10b57cec5SDimitry Andric //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This contains code to emit Expr nodes as LLVM code. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130fca6ea1SDimitry Andric #include "ABIInfoImpl.h" 14fe6060f1SDimitry Andric #include "CGCUDARuntime.h" 150b57cec5SDimitry Andric #include "CGCXXABI.h" 160b57cec5SDimitry Andric #include "CGCall.h" 170b57cec5SDimitry Andric #include "CGCleanup.h" 180b57cec5SDimitry Andric #include "CGDebugInfo.h" 190b57cec5SDimitry Andric #include "CGObjCRuntime.h" 200b57cec5SDimitry Andric #include "CGOpenMPRuntime.h" 210b57cec5SDimitry Andric #include "CGRecordLayout.h" 220b57cec5SDimitry Andric #include "CodeGenFunction.h" 230b57cec5SDimitry Andric #include "CodeGenModule.h" 240b57cec5SDimitry Andric #include "ConstantEmitter.h" 250b57cec5SDimitry Andric #include "TargetInfo.h" 260b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 270b57cec5SDimitry Andric #include "clang/AST/Attr.h" 280b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 290b57cec5SDimitry Andric #include "clang/AST/NSAPI.h" 30297eecfbSDimitry Andric #include "clang/AST/StmtVisitor.h" 310b57cec5SDimitry Andric #include "clang/Basic/Builtins.h" 320b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h" 335ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h" 340b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h" 35297eecfbSDimitry Andric #include "llvm/ADT/STLExtras.h" 360b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h" 370b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 380b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 3906c3fb27SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h" 400b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 410b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h" 42349cc55cSDimitry Andric #include "llvm/IR/MatrixBuilder.h" 4306c3fb27SDimitry Andric #include "llvm/Passes/OptimizationLevel.h" 440b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h" 450b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h" 460b57cec5SDimitry Andric #include "llvm/Support/Path.h" 47fe6060f1SDimitry Andric #include "llvm/Support/SaveAndRestore.h" 4806c3fb27SDimitry Andric #include "llvm/Support/xxhash.h" 490b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SanitizerStats.h" 500b57cec5SDimitry Andric 51bdd1243dSDimitry Andric #include <optional> 520b57cec5SDimitry Andric #include <string> 530b57cec5SDimitry Andric 540b57cec5SDimitry Andric using namespace clang; 550b57cec5SDimitry Andric using namespace CodeGen; 560b57cec5SDimitry Andric 575f757f3fSDimitry Andric // Experiment to make sanitizers easier to debug 585f757f3fSDimitry Andric static llvm::cl::opt<bool> ClSanitizeDebugDeoptimization( 595f757f3fSDimitry Andric "ubsan-unique-traps", llvm::cl::Optional, 600fca6ea1SDimitry Andric llvm::cl::desc("Deoptimize traps for UBSAN so there is 1 trap per check.")); 610fca6ea1SDimitry Andric 620fca6ea1SDimitry Andric // TODO: Introduce frontend options to enabled per sanitizers, similar to 630fca6ea1SDimitry Andric // `fsanitize-trap`. 640fca6ea1SDimitry Andric static llvm::cl::opt<bool> ClSanitizeGuardChecks( 650fca6ea1SDimitry Andric "ubsan-guard-checks", llvm::cl::Optional, 660fca6ea1SDimitry Andric llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`.")); 675f757f3fSDimitry Andric 680b57cec5SDimitry Andric //===--------------------------------------------------------------------===// 690b57cec5SDimitry Andric // Miscellaneous Helper Methods 700b57cec5SDimitry Andric //===--------------------------------------------------------------------===// 710b57cec5SDimitry Andric 720b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry 730b57cec5SDimitry Andric /// block. 740fca6ea1SDimitry Andric RawAddress 750fca6ea1SDimitry Andric CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits Align, 760b57cec5SDimitry Andric const Twine &Name, 770b57cec5SDimitry Andric llvm::Value *ArraySize) { 780b57cec5SDimitry Andric auto Alloca = CreateTempAlloca(Ty, Name, ArraySize); 79a7dea167SDimitry Andric Alloca->setAlignment(Align.getAsAlign()); 800fca6ea1SDimitry Andric return RawAddress(Alloca, Ty, Align, KnownNonNull); 810b57cec5SDimitry Andric } 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry 840b57cec5SDimitry Andric /// block. The alloca is casted to default address space if necessary. 850fca6ea1SDimitry Andric RawAddress CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align, 860b57cec5SDimitry Andric const Twine &Name, 870b57cec5SDimitry Andric llvm::Value *ArraySize, 880fca6ea1SDimitry Andric RawAddress *AllocaAddr) { 890b57cec5SDimitry Andric auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize); 900b57cec5SDimitry Andric if (AllocaAddr) 910b57cec5SDimitry Andric *AllocaAddr = Alloca; 920b57cec5SDimitry Andric llvm::Value *V = Alloca.getPointer(); 930b57cec5SDimitry Andric // Alloca always returns a pointer in alloca address space, which may 940b57cec5SDimitry Andric // be different from the type defined by the language. For example, 950b57cec5SDimitry Andric // in C++ the auto variables are in the default address space. Therefore 960b57cec5SDimitry Andric // cast alloca to the default address space when necessary. 970b57cec5SDimitry Andric if (getASTAllocaAddressSpace() != LangAS::Default) { 980b57cec5SDimitry Andric auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default); 990b57cec5SDimitry Andric llvm::IRBuilderBase::InsertPointGuard IPG(Builder); 1000b57cec5SDimitry Andric // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt, 1010b57cec5SDimitry Andric // otherwise alloca is inserted at the current insertion point of the 1020b57cec5SDimitry Andric // builder. 1030b57cec5SDimitry Andric if (!ArraySize) 104349cc55cSDimitry Andric Builder.SetInsertPoint(getPostAllocaInsertPoint()); 1050b57cec5SDimitry Andric V = getTargetHooks().performAddrSpaceCast( 1060b57cec5SDimitry Andric *this, V, getASTAllocaAddressSpace(), LangAS::Default, 1070b57cec5SDimitry Andric Ty->getPointerTo(DestAddrSpace), /*non-null*/ true); 1080b57cec5SDimitry Andric } 1090b57cec5SDimitry Andric 1100fca6ea1SDimitry Andric return RawAddress(V, Ty, Align, KnownNonNull); 1110b57cec5SDimitry Andric } 1120b57cec5SDimitry Andric 1130b57cec5SDimitry Andric /// CreateTempAlloca - This creates an alloca and inserts it into the entry 1140b57cec5SDimitry Andric /// block if \p ArraySize is nullptr, otherwise inserts it at the current 1150b57cec5SDimitry Andric /// insertion point of the builder. 1160b57cec5SDimitry Andric llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, 1170b57cec5SDimitry Andric const Twine &Name, 1180b57cec5SDimitry Andric llvm::Value *ArraySize) { 1190fca6ea1SDimitry Andric llvm::AllocaInst *Alloca; 1200b57cec5SDimitry Andric if (ArraySize) 1210fca6ea1SDimitry Andric Alloca = Builder.CreateAlloca(Ty, ArraySize, Name); 1220fca6ea1SDimitry Andric else 1230fca6ea1SDimitry Andric Alloca = new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(), 1240fca6ea1SDimitry Andric ArraySize, Name, &*AllocaInsertPt); 1250fca6ea1SDimitry Andric if (Allocas) { 1260fca6ea1SDimitry Andric Allocas->Add(Alloca); 1270fca6ea1SDimitry Andric } 1280fca6ea1SDimitry Andric return Alloca; 1290b57cec5SDimitry Andric } 1300b57cec5SDimitry Andric 1310b57cec5SDimitry Andric /// CreateDefaultAlignTempAlloca - This creates an alloca with the 1320b57cec5SDimitry Andric /// default alignment of the corresponding LLVM type, which is *not* 1330b57cec5SDimitry Andric /// guaranteed to be related in any way to the expected alignment of 1340b57cec5SDimitry Andric /// an AST type that might have been lowered to Ty. 1350fca6ea1SDimitry Andric RawAddress CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty, 1360b57cec5SDimitry Andric const Twine &Name) { 1370b57cec5SDimitry Andric CharUnits Align = 138bdd1243dSDimitry Andric CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty)); 1390b57cec5SDimitry Andric return CreateTempAlloca(Ty, Align, Name); 1400b57cec5SDimitry Andric } 1410b57cec5SDimitry Andric 1420fca6ea1SDimitry Andric RawAddress CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) { 1430b57cec5SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(Ty); 1440b57cec5SDimitry Andric return CreateTempAlloca(ConvertType(Ty), Align, Name); 1450b57cec5SDimitry Andric } 1460b57cec5SDimitry Andric 1470fca6ea1SDimitry Andric RawAddress CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name, 1480fca6ea1SDimitry Andric RawAddress *Alloca) { 1490b57cec5SDimitry Andric // FIXME: Should we prefer the preferred type alignment here? 1500b57cec5SDimitry Andric return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca); 1510b57cec5SDimitry Andric } 1520b57cec5SDimitry Andric 1530fca6ea1SDimitry Andric RawAddress CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align, 1540fca6ea1SDimitry Andric const Twine &Name, 1550fca6ea1SDimitry Andric RawAddress *Alloca) { 1560fca6ea1SDimitry Andric RawAddress Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, 1570b57cec5SDimitry Andric /*ArraySize=*/nullptr, Alloca); 1585ffd83dbSDimitry Andric 1595ffd83dbSDimitry Andric if (Ty->isConstantMatrixType()) { 1600eae32dcSDimitry Andric auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType()); 1615ffd83dbSDimitry Andric auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(), 1625ffd83dbSDimitry Andric ArrayTy->getNumElements()); 1635ffd83dbSDimitry Andric 1645f757f3fSDimitry Andric Result = Address(Result.getPointer(), VectorTy, Result.getAlignment(), 1655f757f3fSDimitry Andric KnownNonNull); 1665ffd83dbSDimitry Andric } 1675ffd83dbSDimitry Andric return Result; 1680b57cec5SDimitry Andric } 1690b57cec5SDimitry Andric 1700fca6ea1SDimitry Andric RawAddress CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, 1710fca6ea1SDimitry Andric CharUnits Align, 1720b57cec5SDimitry Andric const Twine &Name) { 1730b57cec5SDimitry Andric return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name); 1740b57cec5SDimitry Andric } 1750b57cec5SDimitry Andric 1760fca6ea1SDimitry Andric RawAddress CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, 1770b57cec5SDimitry Andric const Twine &Name) { 1780b57cec5SDimitry Andric return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty), 1790b57cec5SDimitry Andric Name); 1800b57cec5SDimitry Andric } 1810b57cec5SDimitry Andric 1820b57cec5SDimitry Andric /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 1830b57cec5SDimitry Andric /// expression and compare the result against zero, returning an Int1Ty value. 1840b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) { 1850b57cec5SDimitry Andric PGO.setCurrentStmt(E); 1860b57cec5SDimitry Andric if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) { 1870b57cec5SDimitry Andric llvm::Value *MemPtr = EmitScalarExpr(E); 1880b57cec5SDimitry Andric return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT); 1890b57cec5SDimitry Andric } 1900b57cec5SDimitry Andric 1910b57cec5SDimitry Andric QualType BoolTy = getContext().BoolTy; 1920b57cec5SDimitry Andric SourceLocation Loc = E->getExprLoc(); 193e8d8bef9SDimitry Andric CGFPOptionsRAII FPOptsRAII(*this, E); 1940b57cec5SDimitry Andric if (!E->getType()->isAnyComplexType()) 1950b57cec5SDimitry Andric return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc); 1960b57cec5SDimitry Andric 1970b57cec5SDimitry Andric return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy, 1980b57cec5SDimitry Andric Loc); 1990b57cec5SDimitry Andric } 2000b57cec5SDimitry Andric 2010b57cec5SDimitry Andric /// EmitIgnoredExpr - Emit code to compute the specified expression, 2020b57cec5SDimitry Andric /// ignoring the result. 2030b57cec5SDimitry Andric void CodeGenFunction::EmitIgnoredExpr(const Expr *E) { 204fe6060f1SDimitry Andric if (E->isPRValue()) 2050b57cec5SDimitry Andric return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true); 2060b57cec5SDimitry Andric 20781ad6265SDimitry Andric // if this is a bitfield-resulting conditional operator, we can special case 20881ad6265SDimitry Andric // emit this. The normal 'EmitLValue' version of this is particularly 20981ad6265SDimitry Andric // difficult to codegen for, since creating a single "LValue" for two 21081ad6265SDimitry Andric // different sized arguments here is not particularly doable. 21181ad6265SDimitry Andric if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>( 21281ad6265SDimitry Andric E->IgnoreParenNoopCasts(getContext()))) { 21381ad6265SDimitry Andric if (CondOp->getObjectKind() == OK_BitField) 21481ad6265SDimitry Andric return EmitIgnoredConditionalOperator(CondOp); 21581ad6265SDimitry Andric } 21681ad6265SDimitry Andric 2170b57cec5SDimitry Andric // Just emit it as an l-value and drop the result. 2180b57cec5SDimitry Andric EmitLValue(E); 2190b57cec5SDimitry Andric } 2200b57cec5SDimitry Andric 2210b57cec5SDimitry Andric /// EmitAnyExpr - Emit code to compute the specified expression which 2220b57cec5SDimitry Andric /// can have any type. The result is returned as an RValue struct. 2230b57cec5SDimitry Andric /// If this is an aggregate expression, AggSlot indicates where the 2240b57cec5SDimitry Andric /// result should be returned. 2250b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExpr(const Expr *E, 2260b57cec5SDimitry Andric AggValueSlot aggSlot, 2270b57cec5SDimitry Andric bool ignoreResult) { 2280b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) { 2290b57cec5SDimitry Andric case TEK_Scalar: 2300b57cec5SDimitry Andric return RValue::get(EmitScalarExpr(E, ignoreResult)); 2310b57cec5SDimitry Andric case TEK_Complex: 2320b57cec5SDimitry Andric return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult)); 2330b57cec5SDimitry Andric case TEK_Aggregate: 2340b57cec5SDimitry Andric if (!ignoreResult && aggSlot.isIgnored()) 2350b57cec5SDimitry Andric aggSlot = CreateAggTemp(E->getType(), "agg-temp"); 2360b57cec5SDimitry Andric EmitAggExpr(E, aggSlot); 2370b57cec5SDimitry Andric return aggSlot.asRValue(); 2380b57cec5SDimitry Andric } 2390b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind"); 2400b57cec5SDimitry Andric } 2410b57cec5SDimitry Andric 2420b57cec5SDimitry Andric /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will 2430b57cec5SDimitry Andric /// always be accessible even if no aggregate location is provided. 2440b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) { 2450b57cec5SDimitry Andric AggValueSlot AggSlot = AggValueSlot::ignored(); 2460b57cec5SDimitry Andric 2470b57cec5SDimitry Andric if (hasAggregateEvaluationKind(E->getType())) 2480b57cec5SDimitry Andric AggSlot = CreateAggTemp(E->getType(), "agg.tmp"); 2490b57cec5SDimitry Andric return EmitAnyExpr(E, AggSlot); 2500b57cec5SDimitry Andric } 2510b57cec5SDimitry Andric 2520b57cec5SDimitry Andric /// EmitAnyExprToMem - Evaluate an expression into a given memory 2530b57cec5SDimitry Andric /// location. 2540b57cec5SDimitry Andric void CodeGenFunction::EmitAnyExprToMem(const Expr *E, 2550b57cec5SDimitry Andric Address Location, 2560b57cec5SDimitry Andric Qualifiers Quals, 2570b57cec5SDimitry Andric bool IsInit) { 2580b57cec5SDimitry Andric // FIXME: This function should take an LValue as an argument. 2590b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) { 2600b57cec5SDimitry Andric case TEK_Complex: 2610b57cec5SDimitry Andric EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()), 2620b57cec5SDimitry Andric /*isInit*/ false); 2630b57cec5SDimitry Andric return; 2640b57cec5SDimitry Andric 2650b57cec5SDimitry Andric case TEK_Aggregate: { 2660b57cec5SDimitry Andric EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals, 2670b57cec5SDimitry Andric AggValueSlot::IsDestructed_t(IsInit), 2680b57cec5SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers, 2690b57cec5SDimitry Andric AggValueSlot::IsAliased_t(!IsInit), 2700b57cec5SDimitry Andric AggValueSlot::MayOverlap)); 2710b57cec5SDimitry Andric return; 2720b57cec5SDimitry Andric } 2730b57cec5SDimitry Andric 2740b57cec5SDimitry Andric case TEK_Scalar: { 2750b57cec5SDimitry Andric RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false)); 2760b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Location, E->getType()); 2770b57cec5SDimitry Andric EmitStoreThroughLValue(RV, LV); 2780b57cec5SDimitry Andric return; 2790b57cec5SDimitry Andric } 2800b57cec5SDimitry Andric } 2810b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind"); 2820b57cec5SDimitry Andric } 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric static void 2850b57cec5SDimitry Andric pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, 2860b57cec5SDimitry Andric const Expr *E, Address ReferenceTemporary) { 2870b57cec5SDimitry Andric // Objective-C++ ARC: 2880b57cec5SDimitry Andric // If we are binding a reference to a temporary that has ownership, we 2890b57cec5SDimitry Andric // need to perform retain/release operations on the temporary. 2900b57cec5SDimitry Andric // 2910b57cec5SDimitry Andric // FIXME: This should be looking at E, not M. 2920b57cec5SDimitry Andric if (auto Lifetime = M->getType().getObjCLifetime()) { 2930b57cec5SDimitry Andric switch (Lifetime) { 2940b57cec5SDimitry Andric case Qualifiers::OCL_None: 2950b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone: 2960b57cec5SDimitry Andric // Carry on to normal cleanup handling. 2970b57cec5SDimitry Andric break; 2980b57cec5SDimitry Andric 2990b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing: 3000b57cec5SDimitry Andric // Nothing to do; cleaned up by an autorelease pool. 3010b57cec5SDimitry Andric return; 3020b57cec5SDimitry Andric 3030b57cec5SDimitry Andric case Qualifiers::OCL_Strong: 3040b57cec5SDimitry Andric case Qualifiers::OCL_Weak: 3050b57cec5SDimitry Andric switch (StorageDuration Duration = M->getStorageDuration()) { 3060b57cec5SDimitry Andric case SD_Static: 3070b57cec5SDimitry Andric // Note: we intentionally do not register a cleanup to release 3080b57cec5SDimitry Andric // the object on program termination. 3090b57cec5SDimitry Andric return; 3100b57cec5SDimitry Andric 3110b57cec5SDimitry Andric case SD_Thread: 3120b57cec5SDimitry Andric // FIXME: We should probably register a cleanup in this case. 3130b57cec5SDimitry Andric return; 3140b57cec5SDimitry Andric 3150b57cec5SDimitry Andric case SD_Automatic: 3160b57cec5SDimitry Andric case SD_FullExpression: 3170b57cec5SDimitry Andric CodeGenFunction::Destroyer *Destroy; 3180b57cec5SDimitry Andric CleanupKind CleanupKind; 3190b57cec5SDimitry Andric if (Lifetime == Qualifiers::OCL_Strong) { 3200b57cec5SDimitry Andric const ValueDecl *VD = M->getExtendingDecl(); 3210fca6ea1SDimitry Andric bool Precise = isa_and_nonnull<VarDecl>(VD) && 3220fca6ea1SDimitry Andric VD->hasAttr<ObjCPreciseLifetimeAttr>(); 3230b57cec5SDimitry Andric CleanupKind = CGF.getARCCleanupKind(); 3240b57cec5SDimitry Andric Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise 3250b57cec5SDimitry Andric : &CodeGenFunction::destroyARCStrongImprecise; 3260b57cec5SDimitry Andric } else { 3270b57cec5SDimitry Andric // __weak objects always get EH cleanups; otherwise, exceptions 3280b57cec5SDimitry Andric // could cause really nasty crashes instead of mere leaks. 3290b57cec5SDimitry Andric CleanupKind = NormalAndEHCleanup; 3300b57cec5SDimitry Andric Destroy = &CodeGenFunction::destroyARCWeak; 3310b57cec5SDimitry Andric } 3320b57cec5SDimitry Andric if (Duration == SD_FullExpression) 3330b57cec5SDimitry Andric CGF.pushDestroy(CleanupKind, ReferenceTemporary, 3340b57cec5SDimitry Andric M->getType(), *Destroy, 3350b57cec5SDimitry Andric CleanupKind & EHCleanup); 3360b57cec5SDimitry Andric else 3370b57cec5SDimitry Andric CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary, 3380b57cec5SDimitry Andric M->getType(), 3390b57cec5SDimitry Andric *Destroy, CleanupKind & EHCleanup); 3400b57cec5SDimitry Andric return; 3410b57cec5SDimitry Andric 3420b57cec5SDimitry Andric case SD_Dynamic: 3430b57cec5SDimitry Andric llvm_unreachable("temporary cannot have dynamic storage duration"); 3440b57cec5SDimitry Andric } 3450b57cec5SDimitry Andric llvm_unreachable("unknown storage duration"); 3460b57cec5SDimitry Andric } 3470b57cec5SDimitry Andric } 3480b57cec5SDimitry Andric 3490b57cec5SDimitry Andric CXXDestructorDecl *ReferenceTemporaryDtor = nullptr; 3500b57cec5SDimitry Andric if (const RecordType *RT = 3510b57cec5SDimitry Andric E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 3520b57cec5SDimitry Andric // Get the destructor for the reference temporary. 3530b57cec5SDimitry Andric auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3540b57cec5SDimitry Andric if (!ClassDecl->hasTrivialDestructor()) 3550b57cec5SDimitry Andric ReferenceTemporaryDtor = ClassDecl->getDestructor(); 3560b57cec5SDimitry Andric } 3570b57cec5SDimitry Andric 3580b57cec5SDimitry Andric if (!ReferenceTemporaryDtor) 3590b57cec5SDimitry Andric return; 3600b57cec5SDimitry Andric 3610b57cec5SDimitry Andric // Call the destructor for the temporary. 3620b57cec5SDimitry Andric switch (M->getStorageDuration()) { 3630b57cec5SDimitry Andric case SD_Static: 3640b57cec5SDimitry Andric case SD_Thread: { 3650b57cec5SDimitry Andric llvm::FunctionCallee CleanupFn; 3660b57cec5SDimitry Andric llvm::Constant *CleanupArg; 3670b57cec5SDimitry Andric if (E->getType()->isArrayType()) { 3680b57cec5SDimitry Andric CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper( 3690b57cec5SDimitry Andric ReferenceTemporary, E->getType(), 3700b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions, 3710b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(M->getExtendingDecl())); 3720b57cec5SDimitry Andric CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy); 3730b57cec5SDimitry Andric } else { 3740b57cec5SDimitry Andric CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor( 3750b57cec5SDimitry Andric GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete)); 3760fca6ea1SDimitry Andric CleanupArg = cast<llvm::Constant>(ReferenceTemporary.emitRawPointer(CGF)); 3770b57cec5SDimitry Andric } 3780b57cec5SDimitry Andric CGF.CGM.getCXXABI().registerGlobalDtor( 3790b57cec5SDimitry Andric CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg); 3800b57cec5SDimitry Andric break; 3810b57cec5SDimitry Andric } 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric case SD_FullExpression: 3840b57cec5SDimitry Andric CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(), 3850b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject, 3860b57cec5SDimitry Andric CGF.getLangOpts().Exceptions); 3870b57cec5SDimitry Andric break; 3880b57cec5SDimitry Andric 3890b57cec5SDimitry Andric case SD_Automatic: 3900b57cec5SDimitry Andric CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup, 3910b57cec5SDimitry Andric ReferenceTemporary, E->getType(), 3920b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject, 3930b57cec5SDimitry Andric CGF.getLangOpts().Exceptions); 3940b57cec5SDimitry Andric break; 3950b57cec5SDimitry Andric 3960b57cec5SDimitry Andric case SD_Dynamic: 3970b57cec5SDimitry Andric llvm_unreachable("temporary cannot have dynamic storage duration"); 3980b57cec5SDimitry Andric } 3990b57cec5SDimitry Andric } 4000b57cec5SDimitry Andric 4010fca6ea1SDimitry Andric static RawAddress createReferenceTemporary(CodeGenFunction &CGF, 4020b57cec5SDimitry Andric const MaterializeTemporaryExpr *M, 4030b57cec5SDimitry Andric const Expr *Inner, 4040fca6ea1SDimitry Andric RawAddress *Alloca = nullptr) { 4050b57cec5SDimitry Andric auto &TCG = CGF.getTargetHooks(); 4060b57cec5SDimitry Andric switch (M->getStorageDuration()) { 4070b57cec5SDimitry Andric case SD_FullExpression: 4080b57cec5SDimitry Andric case SD_Automatic: { 4090b57cec5SDimitry Andric // If we have a constant temporary array or record try to promote it into a 4100b57cec5SDimitry Andric // constant global under the same rules a normal constant would've been 4110b57cec5SDimitry Andric // promoted. This is easier on the optimizer and generally emits fewer 4120b57cec5SDimitry Andric // instructions. 4130b57cec5SDimitry Andric QualType Ty = Inner->getType(); 4140b57cec5SDimitry Andric if (CGF.CGM.getCodeGenOpts().MergeAllConstants && 4150b57cec5SDimitry Andric (Ty->isArrayType() || Ty->isRecordType()) && 4165f757f3fSDimitry Andric Ty.isConstantStorage(CGF.getContext(), true, false)) 4170b57cec5SDimitry Andric if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) { 418fe6060f1SDimitry Andric auto AS = CGF.CGM.GetGlobalConstantAddressSpace(); 4190b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 4200b57cec5SDimitry Andric CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true, 4210b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr, 4220b57cec5SDimitry Andric llvm::GlobalValue::NotThreadLocal, 4230b57cec5SDimitry Andric CGF.getContext().getTargetAddressSpace(AS)); 4240b57cec5SDimitry Andric CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty); 425a7dea167SDimitry Andric GV->setAlignment(alignment.getAsAlign()); 4260b57cec5SDimitry Andric llvm::Constant *C = GV; 4270b57cec5SDimitry Andric if (AS != LangAS::Default) 4280b57cec5SDimitry Andric C = TCG.performAddrSpaceCast( 4290b57cec5SDimitry Andric CGF.CGM, GV, AS, LangAS::Default, 4300b57cec5SDimitry Andric GV->getValueType()->getPointerTo( 4310b57cec5SDimitry Andric CGF.getContext().getTargetAddressSpace(LangAS::Default))); 4320b57cec5SDimitry Andric // FIXME: Should we put the new global into a COMDAT? 4330fca6ea1SDimitry Andric return RawAddress(C, GV->getValueType(), alignment); 4340b57cec5SDimitry Andric } 4350b57cec5SDimitry Andric return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca); 4360b57cec5SDimitry Andric } 4370b57cec5SDimitry Andric case SD_Thread: 4380b57cec5SDimitry Andric case SD_Static: 4390b57cec5SDimitry Andric return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner); 4400b57cec5SDimitry Andric 4410b57cec5SDimitry Andric case SD_Dynamic: 4420b57cec5SDimitry Andric llvm_unreachable("temporary can't have dynamic storage duration"); 4430b57cec5SDimitry Andric } 4440b57cec5SDimitry Andric llvm_unreachable("unknown storage duration"); 4450b57cec5SDimitry Andric } 4460b57cec5SDimitry Andric 4475ffd83dbSDimitry Andric /// Helper method to check if the underlying ABI is AAPCS 4485ffd83dbSDimitry Andric static bool isAAPCS(const TargetInfo &TargetInfo) { 4495f757f3fSDimitry Andric return TargetInfo.getABI().starts_with("aapcs"); 4505ffd83dbSDimitry Andric } 4515ffd83dbSDimitry Andric 4520b57cec5SDimitry Andric LValue CodeGenFunction:: 4530b57cec5SDimitry Andric EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) { 454480093f4SDimitry Andric const Expr *E = M->getSubExpr(); 4550b57cec5SDimitry Andric 4560b57cec5SDimitry Andric assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) || 4570b57cec5SDimitry Andric !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) && 4580b57cec5SDimitry Andric "Reference should never be pseudo-strong!"); 4590b57cec5SDimitry Andric 4600b57cec5SDimitry Andric // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so 4610b57cec5SDimitry Andric // as that will cause the lifetime adjustment to be lost for ARC 4620b57cec5SDimitry Andric auto ownership = M->getType().getObjCLifetime(); 4630b57cec5SDimitry Andric if (ownership != Qualifiers::OCL_None && 4640b57cec5SDimitry Andric ownership != Qualifiers::OCL_ExplicitNone) { 4650fca6ea1SDimitry Andric RawAddress Object = createReferenceTemporary(*this, M, E); 4660b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) { 46781ad6265SDimitry Andric llvm::Type *Ty = ConvertTypeForMem(E->getType()); 4685f757f3fSDimitry Andric Object = Object.withElementType(Ty); 4690b57cec5SDimitry Andric 4700b57cec5SDimitry Andric // createReferenceTemporary will promote the temporary to a global with a 4710b57cec5SDimitry Andric // constant initializer if it can. It can only do this to a value of 4720b57cec5SDimitry Andric // ARC-manageable type if the value is global and therefore "immune" to 4730b57cec5SDimitry Andric // ref-counting operations. Therefore we have no need to emit either a 4740b57cec5SDimitry Andric // dynamic initialization or a cleanup and we can just return the address 4750b57cec5SDimitry Andric // of the temporary. 4760b57cec5SDimitry Andric if (Var->hasInitializer()) 4770b57cec5SDimitry Andric return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl); 4780b57cec5SDimitry Andric 4790b57cec5SDimitry Andric Var->setInitializer(CGM.EmitNullConstant(E->getType())); 4800b57cec5SDimitry Andric } 4810b57cec5SDimitry Andric LValue RefTempDst = MakeAddrLValue(Object, M->getType(), 4820b57cec5SDimitry Andric AlignmentSource::Decl); 4830b57cec5SDimitry Andric 4840b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) { 4850b57cec5SDimitry Andric default: llvm_unreachable("expected scalar or aggregate expression"); 4860b57cec5SDimitry Andric case TEK_Scalar: 4870b57cec5SDimitry Andric EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false); 4880b57cec5SDimitry Andric break; 4890b57cec5SDimitry Andric case TEK_Aggregate: { 4900b57cec5SDimitry Andric EmitAggExpr(E, AggValueSlot::forAddr(Object, 4910b57cec5SDimitry Andric E->getType().getQualifiers(), 4920b57cec5SDimitry Andric AggValueSlot::IsDestructed, 4930b57cec5SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers, 4940b57cec5SDimitry Andric AggValueSlot::IsNotAliased, 4950b57cec5SDimitry Andric AggValueSlot::DoesNotOverlap)); 4960b57cec5SDimitry Andric break; 4970b57cec5SDimitry Andric } 4980b57cec5SDimitry Andric } 4990b57cec5SDimitry Andric 5000b57cec5SDimitry Andric pushTemporaryCleanup(*this, M, E, Object); 5010b57cec5SDimitry Andric return RefTempDst; 5020b57cec5SDimitry Andric } 5030b57cec5SDimitry Andric 5040b57cec5SDimitry Andric SmallVector<const Expr *, 2> CommaLHSs; 5050b57cec5SDimitry Andric SmallVector<SubobjectAdjustment, 2> Adjustments; 5060b57cec5SDimitry Andric E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 5070b57cec5SDimitry Andric 5080b57cec5SDimitry Andric for (const auto &Ignored : CommaLHSs) 5090b57cec5SDimitry Andric EmitIgnoredExpr(Ignored); 5100b57cec5SDimitry Andric 5110b57cec5SDimitry Andric if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) { 5120b57cec5SDimitry Andric if (opaque->getType()->isRecordType()) { 5130b57cec5SDimitry Andric assert(Adjustments.empty()); 5140b57cec5SDimitry Andric return EmitOpaqueValueLValue(opaque); 5150b57cec5SDimitry Andric } 5160b57cec5SDimitry Andric } 5170b57cec5SDimitry Andric 5180b57cec5SDimitry Andric // Create and initialize the reference temporary. 5190fca6ea1SDimitry Andric RawAddress Alloca = Address::invalid(); 5200fca6ea1SDimitry Andric RawAddress Object = createReferenceTemporary(*this, M, E, &Alloca); 5210b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>( 5220b57cec5SDimitry Andric Object.getPointer()->stripPointerCasts())) { 52381ad6265SDimitry Andric llvm::Type *TemporaryType = ConvertTypeForMem(E->getType()); 5245f757f3fSDimitry Andric Object = Object.withElementType(TemporaryType); 5250b57cec5SDimitry Andric // If the temporary is a global and has a constant initializer or is a 5260b57cec5SDimitry Andric // constant temporary that we promoted to a global, we may have already 5270b57cec5SDimitry Andric // initialized it. 5280b57cec5SDimitry Andric if (!Var->hasInitializer()) { 5290b57cec5SDimitry Andric Var->setInitializer(CGM.EmitNullConstant(E->getType())); 5300b57cec5SDimitry Andric EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true); 5310b57cec5SDimitry Andric } 5320b57cec5SDimitry Andric } else { 5330b57cec5SDimitry Andric switch (M->getStorageDuration()) { 5340b57cec5SDimitry Andric case SD_Automatic: 5350b57cec5SDimitry Andric if (auto *Size = EmitLifetimeStart( 5360b57cec5SDimitry Andric CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()), 5370b57cec5SDimitry Andric Alloca.getPointer())) { 5380b57cec5SDimitry Andric pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker, 5390b57cec5SDimitry Andric Alloca, Size); 5400b57cec5SDimitry Andric } 5410b57cec5SDimitry Andric break; 5420b57cec5SDimitry Andric 5430b57cec5SDimitry Andric case SD_FullExpression: { 5440b57cec5SDimitry Andric if (!ShouldEmitLifetimeMarkers) 5450b57cec5SDimitry Andric break; 5460b57cec5SDimitry Andric 5470b57cec5SDimitry Andric // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end 5480b57cec5SDimitry Andric // marker. Instead, start the lifetime of a conditional temporary earlier 549a7dea167SDimitry Andric // so that it's unconditional. Don't do this with sanitizers which need 55006c3fb27SDimitry Andric // more precise lifetime marks. However when inside an "await.suspend" 55106c3fb27SDimitry Andric // block, we should always avoid conditional cleanup because it creates 55206c3fb27SDimitry Andric // boolean marker that lives across await_suspend, which can destroy coro 55306c3fb27SDimitry Andric // frame. 5540b57cec5SDimitry Andric ConditionalEvaluation *OldConditional = nullptr; 5550b57cec5SDimitry Andric CGBuilderTy::InsertPoint OldIP; 5560b57cec5SDimitry Andric if (isInConditionalBranch() && !E->getType().isDestructedType() && 55706c3fb27SDimitry Andric ((!SanOpts.has(SanitizerKind::HWAddress) && 558a7dea167SDimitry Andric !SanOpts.has(SanitizerKind::Memory) && 55906c3fb27SDimitry Andric !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) || 56006c3fb27SDimitry Andric inSuspendBlock())) { 5610b57cec5SDimitry Andric OldConditional = OutermostConditional; 5620b57cec5SDimitry Andric OutermostConditional = nullptr; 5630b57cec5SDimitry Andric 5640b57cec5SDimitry Andric OldIP = Builder.saveIP(); 5650b57cec5SDimitry Andric llvm::BasicBlock *Block = OldConditional->getStartingBlock(); 5660b57cec5SDimitry Andric Builder.restoreIP(CGBuilderTy::InsertPoint( 5670b57cec5SDimitry Andric Block, llvm::BasicBlock::iterator(Block->back()))); 5680b57cec5SDimitry Andric } 5690b57cec5SDimitry Andric 5700b57cec5SDimitry Andric if (auto *Size = EmitLifetimeStart( 5710b57cec5SDimitry Andric CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()), 5720b57cec5SDimitry Andric Alloca.getPointer())) { 5730b57cec5SDimitry Andric pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca, 5740b57cec5SDimitry Andric Size); 5750b57cec5SDimitry Andric } 5760b57cec5SDimitry Andric 5770b57cec5SDimitry Andric if (OldConditional) { 5780b57cec5SDimitry Andric OutermostConditional = OldConditional; 5790b57cec5SDimitry Andric Builder.restoreIP(OldIP); 5800b57cec5SDimitry Andric } 5810b57cec5SDimitry Andric break; 5820b57cec5SDimitry Andric } 5830b57cec5SDimitry Andric 5840b57cec5SDimitry Andric default: 5850b57cec5SDimitry Andric break; 5860b57cec5SDimitry Andric } 5870b57cec5SDimitry Andric EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true); 5880b57cec5SDimitry Andric } 5890b57cec5SDimitry Andric pushTemporaryCleanup(*this, M, E, Object); 5900b57cec5SDimitry Andric 5910b57cec5SDimitry Andric // Perform derived-to-base casts and/or field accesses, to get from the 5920b57cec5SDimitry Andric // temporary object we created (and, potentially, for which we extended 5930b57cec5SDimitry Andric // the lifetime) to the subobject we're binding the reference to. 594349cc55cSDimitry Andric for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) { 5950b57cec5SDimitry Andric switch (Adjustment.Kind) { 5960b57cec5SDimitry Andric case SubobjectAdjustment::DerivedToBaseAdjustment: 5970b57cec5SDimitry Andric Object = 5980b57cec5SDimitry Andric GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass, 5990b57cec5SDimitry Andric Adjustment.DerivedToBase.BasePath->path_begin(), 6000b57cec5SDimitry Andric Adjustment.DerivedToBase.BasePath->path_end(), 6010b57cec5SDimitry Andric /*NullCheckValue=*/ false, E->getExprLoc()); 6020b57cec5SDimitry Andric break; 6030b57cec5SDimitry Andric 6040b57cec5SDimitry Andric case SubobjectAdjustment::FieldAdjustment: { 6050b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl); 6060b57cec5SDimitry Andric LV = EmitLValueForField(LV, Adjustment.Field); 6070b57cec5SDimitry Andric assert(LV.isSimple() && 6080b57cec5SDimitry Andric "materialized temporary field is not a simple lvalue"); 6090fca6ea1SDimitry Andric Object = LV.getAddress(); 6100b57cec5SDimitry Andric break; 6110b57cec5SDimitry Andric } 6120b57cec5SDimitry Andric 6130b57cec5SDimitry Andric case SubobjectAdjustment::MemberPointerAdjustment: { 6140b57cec5SDimitry Andric llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS); 6150b57cec5SDimitry Andric Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr, 6160b57cec5SDimitry Andric Adjustment.Ptr.MPT); 6170b57cec5SDimitry Andric break; 6180b57cec5SDimitry Andric } 6190b57cec5SDimitry Andric } 6200b57cec5SDimitry Andric } 6210b57cec5SDimitry Andric 6220b57cec5SDimitry Andric return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl); 6230b57cec5SDimitry Andric } 6240b57cec5SDimitry Andric 6250b57cec5SDimitry Andric RValue 6260b57cec5SDimitry Andric CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) { 6270b57cec5SDimitry Andric // Emit the expression as an lvalue. 6280b57cec5SDimitry Andric LValue LV = EmitLValue(E); 6290b57cec5SDimitry Andric assert(LV.isSimple()); 630480093f4SDimitry Andric llvm::Value *Value = LV.getPointer(*this); 6310b57cec5SDimitry Andric 6320b57cec5SDimitry Andric if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) { 6330b57cec5SDimitry Andric // C++11 [dcl.ref]p5 (as amended by core issue 453): 6340b57cec5SDimitry Andric // If a glvalue to which a reference is directly bound designates neither 6350b57cec5SDimitry Andric // an existing object or function of an appropriate type nor a region of 6360b57cec5SDimitry Andric // storage of suitable size and alignment to contain an object of the 6370b57cec5SDimitry Andric // reference's type, the behavior is undefined. 6380b57cec5SDimitry Andric QualType Ty = E->getType(); 6390b57cec5SDimitry Andric EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty); 6400b57cec5SDimitry Andric } 6410b57cec5SDimitry Andric 6420b57cec5SDimitry Andric return RValue::get(Value); 6430b57cec5SDimitry Andric } 6440b57cec5SDimitry Andric 6450b57cec5SDimitry Andric 6460b57cec5SDimitry Andric /// getAccessedFieldNo - Given an encoded value and a result number, return the 6470b57cec5SDimitry Andric /// input field number being accessed. 6480b57cec5SDimitry Andric unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx, 6490b57cec5SDimitry Andric const llvm::Constant *Elts) { 6500b57cec5SDimitry Andric return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx)) 6510b57cec5SDimitry Andric ->getZExtValue(); 6520b57cec5SDimitry Andric } 6530b57cec5SDimitry Andric 6540fca6ea1SDimitry Andric static llvm::Value *emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc, 6550fca6ea1SDimitry Andric llvm::Value *Ptr) { 6560fca6ea1SDimitry Andric llvm::Value *A0 = 6570fca6ea1SDimitry Andric Builder.CreateMul(Ptr, Builder.getInt64(0xbf58476d1ce4e5b9u)); 6580fca6ea1SDimitry Andric llvm::Value *A1 = 6590fca6ea1SDimitry Andric Builder.CreateXor(A0, Builder.CreateLShr(A0, Builder.getInt64(31))); 6600fca6ea1SDimitry Andric return Builder.CreateXor(Acc, A1); 6610b57cec5SDimitry Andric } 6620b57cec5SDimitry Andric 6630b57cec5SDimitry Andric bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) { 6640b57cec5SDimitry Andric return TCK == TCK_DowncastPointer || TCK == TCK_Upcast || 6650b57cec5SDimitry Andric TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation; 6660b57cec5SDimitry Andric } 6670b57cec5SDimitry Andric 6680b57cec5SDimitry Andric bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) { 6690b57cec5SDimitry Andric CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 6700b57cec5SDimitry Andric return (RD && RD->hasDefinition() && RD->isDynamicClass()) && 6710b57cec5SDimitry Andric (TCK == TCK_MemberAccess || TCK == TCK_MemberCall || 6720b57cec5SDimitry Andric TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference || 6730b57cec5SDimitry Andric TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation); 6740b57cec5SDimitry Andric } 6750b57cec5SDimitry Andric 6760b57cec5SDimitry Andric bool CodeGenFunction::sanitizePerformTypeCheck() const { 677349cc55cSDimitry Andric return SanOpts.has(SanitizerKind::Null) || 678349cc55cSDimitry Andric SanOpts.has(SanitizerKind::Alignment) || 679349cc55cSDimitry Andric SanOpts.has(SanitizerKind::ObjectSize) || 6800b57cec5SDimitry Andric SanOpts.has(SanitizerKind::Vptr); 6810b57cec5SDimitry Andric } 6820b57cec5SDimitry Andric 6830b57cec5SDimitry Andric void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, 6840b57cec5SDimitry Andric llvm::Value *Ptr, QualType Ty, 6850b57cec5SDimitry Andric CharUnits Alignment, 6860b57cec5SDimitry Andric SanitizerSet SkippedChecks, 6870b57cec5SDimitry Andric llvm::Value *ArraySize) { 6880b57cec5SDimitry Andric if (!sanitizePerformTypeCheck()) 6890b57cec5SDimitry Andric return; 6900b57cec5SDimitry Andric 6910b57cec5SDimitry Andric // Don't check pointers outside the default address space. The null check 6920b57cec5SDimitry Andric // isn't correct, the object-size check isn't supported by LLVM, and we can't 6930b57cec5SDimitry Andric // communicate the addresses to the runtime handler for the vptr check. 6940b57cec5SDimitry Andric if (Ptr->getType()->getPointerAddressSpace()) 6950b57cec5SDimitry Andric return; 6960b57cec5SDimitry Andric 6970b57cec5SDimitry Andric // Don't check pointers to volatile data. The behavior here is implementation- 6980b57cec5SDimitry Andric // defined. 6990b57cec5SDimitry Andric if (Ty.isVolatileQualified()) 7000b57cec5SDimitry Andric return; 7010b57cec5SDimitry Andric 7020b57cec5SDimitry Andric SanitizerScope SanScope(this); 7030b57cec5SDimitry Andric 7040b57cec5SDimitry Andric SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks; 7050b57cec5SDimitry Andric llvm::BasicBlock *Done = nullptr; 7060b57cec5SDimitry Andric 7070b57cec5SDimitry Andric // Quickly determine whether we have a pointer to an alloca. It's possible 7080b57cec5SDimitry Andric // to skip null checks, and some alignment checks, for these pointers. This 7090b57cec5SDimitry Andric // can reduce compile-time significantly. 710a7dea167SDimitry Andric auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts()); 7110b57cec5SDimitry Andric 7120b57cec5SDimitry Andric llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext()); 7130b57cec5SDimitry Andric llvm::Value *IsNonNull = nullptr; 7140b57cec5SDimitry Andric bool IsGuaranteedNonNull = 7150b57cec5SDimitry Andric SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca; 7160b57cec5SDimitry Andric bool AllowNullPointers = isNullPointerAllowed(TCK); 7170b57cec5SDimitry Andric if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) && 7180b57cec5SDimitry Andric !IsGuaranteedNonNull) { 7190b57cec5SDimitry Andric // The glvalue must not be an empty glvalue. 7200b57cec5SDimitry Andric IsNonNull = Builder.CreateIsNotNull(Ptr); 7210b57cec5SDimitry Andric 7220b57cec5SDimitry Andric // The IR builder can constant-fold the null check if the pointer points to 7230b57cec5SDimitry Andric // a constant. 7240b57cec5SDimitry Andric IsGuaranteedNonNull = IsNonNull == True; 7250b57cec5SDimitry Andric 7260b57cec5SDimitry Andric // Skip the null check if the pointer is known to be non-null. 7270b57cec5SDimitry Andric if (!IsGuaranteedNonNull) { 7280b57cec5SDimitry Andric if (AllowNullPointers) { 7290b57cec5SDimitry Andric // When performing pointer casts, it's OK if the value is null. 7300b57cec5SDimitry Andric // Skip the remaining checks in that case. 7310b57cec5SDimitry Andric Done = createBasicBlock("null"); 7320b57cec5SDimitry Andric llvm::BasicBlock *Rest = createBasicBlock("not.null"); 7330b57cec5SDimitry Andric Builder.CreateCondBr(IsNonNull, Rest, Done); 7340b57cec5SDimitry Andric EmitBlock(Rest); 7350b57cec5SDimitry Andric } else { 7360b57cec5SDimitry Andric Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null)); 7370b57cec5SDimitry Andric } 7380b57cec5SDimitry Andric } 7390b57cec5SDimitry Andric } 7400b57cec5SDimitry Andric 7410b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ObjectSize) && 7420b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::ObjectSize) && 7430b57cec5SDimitry Andric !Ty->isIncompleteType()) { 7445ffd83dbSDimitry Andric uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity(); 7450b57cec5SDimitry Andric llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize); 7460b57cec5SDimitry Andric if (ArraySize) 7470b57cec5SDimitry Andric Size = Builder.CreateMul(Size, ArraySize); 7480b57cec5SDimitry Andric 7490b57cec5SDimitry Andric // Degenerate case: new X[0] does not need an objectsize check. 7500b57cec5SDimitry Andric llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size); 7510b57cec5SDimitry Andric if (!ConstantSize || !ConstantSize->isNullValue()) { 7520b57cec5SDimitry Andric // The glvalue must refer to a large enough storage region. 7530b57cec5SDimitry Andric // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation 7540b57cec5SDimitry Andric // to check this. 7550b57cec5SDimitry Andric // FIXME: Get object address space 7560b57cec5SDimitry Andric llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy }; 7570b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys); 7580b57cec5SDimitry Andric llvm::Value *Min = Builder.getFalse(); 7590b57cec5SDimitry Andric llvm::Value *NullIsUnknown = Builder.getFalse(); 7600b57cec5SDimitry Andric llvm::Value *Dynamic = Builder.getFalse(); 7610b57cec5SDimitry Andric llvm::Value *LargeEnough = Builder.CreateICmpUGE( 7625f757f3fSDimitry Andric Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size); 7630b57cec5SDimitry Andric Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize)); 7640b57cec5SDimitry Andric } 7650b57cec5SDimitry Andric } 7660b57cec5SDimitry Andric 76781ad6265SDimitry Andric llvm::MaybeAlign AlignVal; 7680b57cec5SDimitry Andric llvm::Value *PtrAsInt = nullptr; 7690b57cec5SDimitry Andric 7700b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Alignment) && 7710b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::Alignment)) { 77281ad6265SDimitry Andric AlignVal = Alignment.getAsMaybeAlign(); 7730b57cec5SDimitry Andric if (!Ty->isIncompleteType() && !AlignVal) 7745ffd83dbSDimitry Andric AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr, 7755ffd83dbSDimitry Andric /*ForPointeeType=*/true) 77681ad6265SDimitry Andric .getAsMaybeAlign(); 7770b57cec5SDimitry Andric 7780b57cec5SDimitry Andric // The glvalue must be suitably aligned. 77981ad6265SDimitry Andric if (AlignVal && *AlignVal > llvm::Align(1) && 78081ad6265SDimitry Andric (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) { 7810b57cec5SDimitry Andric PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy); 7820b57cec5SDimitry Andric llvm::Value *Align = Builder.CreateAnd( 78381ad6265SDimitry Andric PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1)); 7840b57cec5SDimitry Andric llvm::Value *Aligned = 7850b57cec5SDimitry Andric Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0)); 7860b57cec5SDimitry Andric if (Aligned != True) 7870b57cec5SDimitry Andric Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment)); 7880b57cec5SDimitry Andric } 7890b57cec5SDimitry Andric } 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric if (Checks.size() > 0) { 7920b57cec5SDimitry Andric llvm::Constant *StaticData[] = { 7930b57cec5SDimitry Andric EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty), 79481ad6265SDimitry Andric llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1), 7950b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, TCK)}; 7960b57cec5SDimitry Andric EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, 7970b57cec5SDimitry Andric PtrAsInt ? PtrAsInt : Ptr); 7980b57cec5SDimitry Andric } 7990b57cec5SDimitry Andric 8000b57cec5SDimitry Andric // If possible, check that the vptr indicates that there is a subobject of 8010b57cec5SDimitry Andric // type Ty at offset zero within this object. 8020b57cec5SDimitry Andric // 8030b57cec5SDimitry Andric // C++11 [basic.life]p5,6: 8040b57cec5SDimitry Andric // [For storage which does not refer to an object within its lifetime] 8050b57cec5SDimitry Andric // The program has undefined behavior if: 8060b57cec5SDimitry Andric // -- the [pointer or glvalue] is used to access a non-static data member 8070b57cec5SDimitry Andric // or call a non-static member function 8080b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Vptr) && 8090b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) { 8100b57cec5SDimitry Andric // Ensure that the pointer is non-null before loading it. If there is no 8110b57cec5SDimitry Andric // compile-time guarantee, reuse the run-time null check or emit a new one. 8120b57cec5SDimitry Andric if (!IsGuaranteedNonNull) { 8130b57cec5SDimitry Andric if (!IsNonNull) 8140b57cec5SDimitry Andric IsNonNull = Builder.CreateIsNotNull(Ptr); 8150b57cec5SDimitry Andric if (!Done) 8160b57cec5SDimitry Andric Done = createBasicBlock("vptr.null"); 8170b57cec5SDimitry Andric llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null"); 8180b57cec5SDimitry Andric Builder.CreateCondBr(IsNonNull, VptrNotNull, Done); 8190b57cec5SDimitry Andric EmitBlock(VptrNotNull); 8200b57cec5SDimitry Andric } 8210b57cec5SDimitry Andric 8220fca6ea1SDimitry Andric // Compute a deterministic hash of the mangled name of the type. 8230b57cec5SDimitry Andric SmallString<64> MangledName; 8240b57cec5SDimitry Andric llvm::raw_svector_ostream Out(MangledName); 8250b57cec5SDimitry Andric CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(), 8260b57cec5SDimitry Andric Out); 8270b57cec5SDimitry Andric 828fe6060f1SDimitry Andric // Contained in NoSanitizeList based on the mangled type. 829fe6060f1SDimitry Andric if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr, 830fe6060f1SDimitry Andric Out.str())) { 8310fca6ea1SDimitry Andric // Load the vptr, and mix it with TypeHash. 8320fca6ea1SDimitry Andric llvm::Value *TypeHash = 8330fca6ea1SDimitry Andric llvm::ConstantInt::get(Int64Ty, xxh3_64bits(Out.str())); 8340b57cec5SDimitry Andric 8350fca6ea1SDimitry Andric llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0); 8365f757f3fSDimitry Andric Address VPtrAddr(Ptr, IntPtrTy, getPointerAlign()); 8370fca6ea1SDimitry Andric llvm::Value *VPtrVal = GetVTablePtr(VPtrAddr, VPtrTy, 8380fca6ea1SDimitry Andric Ty->getAsCXXRecordDecl(), 8390fca6ea1SDimitry Andric VTableAuthMode::UnsafeUbsanStrip); 8400fca6ea1SDimitry Andric VPtrVal = Builder.CreateBitOrPointerCast(VPtrVal, IntPtrTy); 8410b57cec5SDimitry Andric 8420fca6ea1SDimitry Andric llvm::Value *Hash = 8430fca6ea1SDimitry Andric emitHashMix(Builder, TypeHash, Builder.CreateZExt(VPtrVal, Int64Ty)); 8440b57cec5SDimitry Andric Hash = Builder.CreateTrunc(Hash, IntPtrTy); 8450b57cec5SDimitry Andric 8460b57cec5SDimitry Andric // Look the hash up in our cache. 8470b57cec5SDimitry Andric const int CacheSize = 128; 8480b57cec5SDimitry Andric llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize); 8490b57cec5SDimitry Andric llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable, 8500b57cec5SDimitry Andric "__ubsan_vptr_type_cache"); 8510b57cec5SDimitry Andric llvm::Value *Slot = Builder.CreateAnd(Hash, 8520b57cec5SDimitry Andric llvm::ConstantInt::get(IntPtrTy, 8530b57cec5SDimitry Andric CacheSize-1)); 8540b57cec5SDimitry Andric llvm::Value *Indices[] = { Builder.getInt32(0), Slot }; 855fe6060f1SDimitry Andric llvm::Value *CacheVal = Builder.CreateAlignedLoad( 856fe6060f1SDimitry Andric IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices), 8570b57cec5SDimitry Andric getPointerAlign()); 8580b57cec5SDimitry Andric 8590b57cec5SDimitry Andric // If the hash isn't in the cache, call a runtime handler to perform the 8600b57cec5SDimitry Andric // hard work of checking whether the vptr is for an object of the right 8610b57cec5SDimitry Andric // type. This will either fill in the cache and return, or produce a 8620b57cec5SDimitry Andric // diagnostic. 8630b57cec5SDimitry Andric llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash); 8640b57cec5SDimitry Andric llvm::Constant *StaticData[] = { 8650b57cec5SDimitry Andric EmitCheckSourceLocation(Loc), 8660b57cec5SDimitry Andric EmitCheckTypeDescriptor(Ty), 8670b57cec5SDimitry Andric CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()), 8680b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, TCK) 8690b57cec5SDimitry Andric }; 8700b57cec5SDimitry Andric llvm::Value *DynamicData[] = { Ptr, Hash }; 8710b57cec5SDimitry Andric EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr), 8720b57cec5SDimitry Andric SanitizerHandler::DynamicTypeCacheMiss, StaticData, 8730b57cec5SDimitry Andric DynamicData); 8740b57cec5SDimitry Andric } 8750b57cec5SDimitry Andric } 8760b57cec5SDimitry Andric 8770b57cec5SDimitry Andric if (Done) { 8780b57cec5SDimitry Andric Builder.CreateBr(Done); 8790b57cec5SDimitry Andric EmitBlock(Done); 8800b57cec5SDimitry Andric } 8810b57cec5SDimitry Andric } 8820b57cec5SDimitry Andric 8830b57cec5SDimitry Andric llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E, 8840b57cec5SDimitry Andric QualType EltTy) { 8850b57cec5SDimitry Andric ASTContext &C = getContext(); 8860b57cec5SDimitry Andric uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity(); 8870b57cec5SDimitry Andric if (!EltSize) 8880b57cec5SDimitry Andric return nullptr; 8890b57cec5SDimitry Andric 8900b57cec5SDimitry Andric auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 8910b57cec5SDimitry Andric if (!ArrayDeclRef) 8920b57cec5SDimitry Andric return nullptr; 8930b57cec5SDimitry Andric 8940b57cec5SDimitry Andric auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl()); 8950b57cec5SDimitry Andric if (!ParamDecl) 8960b57cec5SDimitry Andric return nullptr; 8970b57cec5SDimitry Andric 8980b57cec5SDimitry Andric auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>(); 8990b57cec5SDimitry Andric if (!POSAttr) 9000b57cec5SDimitry Andric return nullptr; 9010b57cec5SDimitry Andric 9020b57cec5SDimitry Andric // Don't load the size if it's a lower bound. 9030b57cec5SDimitry Andric int POSType = POSAttr->getType(); 9040b57cec5SDimitry Andric if (POSType != 0 && POSType != 1) 9050b57cec5SDimitry Andric return nullptr; 9060b57cec5SDimitry Andric 9070b57cec5SDimitry Andric // Find the implicit size parameter. 9080b57cec5SDimitry Andric auto PassedSizeIt = SizeArguments.find(ParamDecl); 9090b57cec5SDimitry Andric if (PassedSizeIt == SizeArguments.end()) 9100b57cec5SDimitry Andric return nullptr; 9110b57cec5SDimitry Andric 9120b57cec5SDimitry Andric const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second; 9130b57cec5SDimitry Andric assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable"); 9140b57cec5SDimitry Andric Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second; 9150b57cec5SDimitry Andric llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false, 9160b57cec5SDimitry Andric C.getSizeType(), E->getExprLoc()); 9170b57cec5SDimitry Andric llvm::Value *SizeOfElement = 9180b57cec5SDimitry Andric llvm::ConstantInt::get(SizeInBytes->getType(), EltSize); 9190b57cec5SDimitry Andric return Builder.CreateUDiv(SizeInBytes, SizeOfElement); 9200b57cec5SDimitry Andric } 9210b57cec5SDimitry Andric 9220b57cec5SDimitry Andric /// If Base is known to point to the start of an array, return the length of 9230b57cec5SDimitry Andric /// that array. Return 0 if the length cannot be determined. 924fcaf7f86SDimitry Andric static llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF, 925fcaf7f86SDimitry Andric const Expr *Base, 926fcaf7f86SDimitry Andric QualType &IndexedType, 927bdd1243dSDimitry Andric LangOptions::StrictFlexArraysLevelKind 928bdd1243dSDimitry Andric StrictFlexArraysLevel) { 9290b57cec5SDimitry Andric // For the vector indexing extension, the bound is the number of elements. 9300b57cec5SDimitry Andric if (const VectorType *VT = Base->getType()->getAs<VectorType>()) { 9310b57cec5SDimitry Andric IndexedType = Base->getType(); 9320b57cec5SDimitry Andric return CGF.Builder.getInt32(VT->getNumElements()); 9330b57cec5SDimitry Andric } 9340b57cec5SDimitry Andric 9350b57cec5SDimitry Andric Base = Base->IgnoreParens(); 9360b57cec5SDimitry Andric 9370b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(Base)) { 9380b57cec5SDimitry Andric if (CE->getCastKind() == CK_ArrayToPointerDecay && 939bdd1243dSDimitry Andric !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(), 940bdd1243dSDimitry Andric StrictFlexArraysLevel)) { 941297eecfbSDimitry Andric CodeGenFunction::SanitizerScope SanScope(&CGF); 942297eecfbSDimitry Andric 9430b57cec5SDimitry Andric IndexedType = CE->getSubExpr()->getType(); 9440b57cec5SDimitry Andric const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe(); 9450b57cec5SDimitry Andric if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 9460b57cec5SDimitry Andric return CGF.Builder.getInt(CAT->getSize()); 947297eecfbSDimitry Andric 948297eecfbSDimitry Andric if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) 9490b57cec5SDimitry Andric return CGF.getVLASize(VAT).NumElts; 9500b57cec5SDimitry Andric // Ignore pass_object_size here. It's not applicable on decayed pointers. 9510b57cec5SDimitry Andric } 9520b57cec5SDimitry Andric } 9530b57cec5SDimitry Andric 954297eecfbSDimitry Andric CodeGenFunction::SanitizerScope SanScope(&CGF); 955297eecfbSDimitry Andric 9560b57cec5SDimitry Andric QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0}; 9570b57cec5SDimitry Andric if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) { 9580b57cec5SDimitry Andric IndexedType = Base->getType(); 9590b57cec5SDimitry Andric return POS; 9600b57cec5SDimitry Andric } 9610b57cec5SDimitry Andric 9620b57cec5SDimitry Andric return nullptr; 9630b57cec5SDimitry Andric } 9640b57cec5SDimitry Andric 965297eecfbSDimitry Andric namespace { 966297eecfbSDimitry Andric 967297eecfbSDimitry Andric /// \p StructAccessBase returns the base \p Expr of a field access. It returns 968297eecfbSDimitry Andric /// either a \p DeclRefExpr, representing the base pointer to the struct, i.e.: 969297eecfbSDimitry Andric /// 970297eecfbSDimitry Andric /// p in p-> a.b.c 971297eecfbSDimitry Andric /// 972297eecfbSDimitry Andric /// or a \p MemberExpr, if the \p MemberExpr has the \p RecordDecl we're 973297eecfbSDimitry Andric /// looking for: 974297eecfbSDimitry Andric /// 975297eecfbSDimitry Andric /// struct s { 976297eecfbSDimitry Andric /// struct s *ptr; 977297eecfbSDimitry Andric /// int count; 978297eecfbSDimitry Andric /// char array[] __attribute__((counted_by(count))); 979297eecfbSDimitry Andric /// }; 980297eecfbSDimitry Andric /// 981297eecfbSDimitry Andric /// If we have an expression like \p p->ptr->array[index], we want the 982297eecfbSDimitry Andric /// \p MemberExpr for \p p->ptr instead of \p p. 983297eecfbSDimitry Andric class StructAccessBase 984297eecfbSDimitry Andric : public ConstStmtVisitor<StructAccessBase, const Expr *> { 985297eecfbSDimitry Andric const RecordDecl *ExpectedRD; 986297eecfbSDimitry Andric 987297eecfbSDimitry Andric bool IsExpectedRecordDecl(const Expr *E) const { 988297eecfbSDimitry Andric QualType Ty = E->getType(); 989297eecfbSDimitry Andric if (Ty->isPointerType()) 990297eecfbSDimitry Andric Ty = Ty->getPointeeType(); 991297eecfbSDimitry Andric return ExpectedRD == Ty->getAsRecordDecl(); 992297eecfbSDimitry Andric } 993297eecfbSDimitry Andric 994297eecfbSDimitry Andric public: 995297eecfbSDimitry Andric StructAccessBase(const RecordDecl *ExpectedRD) : ExpectedRD(ExpectedRD) {} 996297eecfbSDimitry Andric 997297eecfbSDimitry Andric //===--------------------------------------------------------------------===// 998297eecfbSDimitry Andric // Visitor Methods 999297eecfbSDimitry Andric //===--------------------------------------------------------------------===// 1000297eecfbSDimitry Andric 1001297eecfbSDimitry Andric // NOTE: If we build C++ support for counted_by, then we'll have to handle 1002297eecfbSDimitry Andric // horrors like this: 1003297eecfbSDimitry Andric // 1004297eecfbSDimitry Andric // struct S { 1005297eecfbSDimitry Andric // int x, y; 1006297eecfbSDimitry Andric // int blah[] __attribute__((counted_by(x))); 1007297eecfbSDimitry Andric // } s; 1008297eecfbSDimitry Andric // 1009297eecfbSDimitry Andric // int foo(int index, int val) { 1010297eecfbSDimitry Andric // int (S::*IHatePMDs)[] = &S::blah; 1011297eecfbSDimitry Andric // (s.*IHatePMDs)[index] = val; 1012297eecfbSDimitry Andric // } 1013297eecfbSDimitry Andric 1014297eecfbSDimitry Andric const Expr *Visit(const Expr *E) { 1015297eecfbSDimitry Andric return ConstStmtVisitor<StructAccessBase, const Expr *>::Visit(E); 1016297eecfbSDimitry Andric } 1017297eecfbSDimitry Andric 1018297eecfbSDimitry Andric const Expr *VisitStmt(const Stmt *S) { return nullptr; } 1019297eecfbSDimitry Andric 1020297eecfbSDimitry Andric // These are the types we expect to return (in order of most to least 1021297eecfbSDimitry Andric // likely): 1022297eecfbSDimitry Andric // 1023297eecfbSDimitry Andric // 1. DeclRefExpr - This is the expression for the base of the structure. 1024297eecfbSDimitry Andric // It's exactly what we want to build an access to the \p counted_by 1025297eecfbSDimitry Andric // field. 1026297eecfbSDimitry Andric // 2. MemberExpr - This is the expression that has the same \p RecordDecl 1027297eecfbSDimitry Andric // as the flexble array member's lexical enclosing \p RecordDecl. This 1028297eecfbSDimitry Andric // allows us to catch things like: "p->p->array" 1029297eecfbSDimitry Andric // 3. CompoundLiteralExpr - This is for people who create something 1030297eecfbSDimitry Andric // heretical like (struct foo has a flexible array member): 1031297eecfbSDimitry Andric // 1032297eecfbSDimitry Andric // (struct foo){ 1, 2 }.blah[idx]; 1033297eecfbSDimitry Andric const Expr *VisitDeclRefExpr(const DeclRefExpr *E) { 1034297eecfbSDimitry Andric return IsExpectedRecordDecl(E) ? E : nullptr; 1035297eecfbSDimitry Andric } 1036297eecfbSDimitry Andric const Expr *VisitMemberExpr(const MemberExpr *E) { 1037297eecfbSDimitry Andric if (IsExpectedRecordDecl(E) && E->isArrow()) 1038297eecfbSDimitry Andric return E; 1039297eecfbSDimitry Andric const Expr *Res = Visit(E->getBase()); 1040297eecfbSDimitry Andric return !Res && IsExpectedRecordDecl(E) ? E : Res; 1041297eecfbSDimitry Andric } 1042297eecfbSDimitry Andric const Expr *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 1043297eecfbSDimitry Andric return IsExpectedRecordDecl(E) ? E : nullptr; 1044297eecfbSDimitry Andric } 1045297eecfbSDimitry Andric const Expr *VisitCallExpr(const CallExpr *E) { 1046297eecfbSDimitry Andric return IsExpectedRecordDecl(E) ? E : nullptr; 1047297eecfbSDimitry Andric } 1048297eecfbSDimitry Andric 1049297eecfbSDimitry Andric const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 1050297eecfbSDimitry Andric if (IsExpectedRecordDecl(E)) 1051297eecfbSDimitry Andric return E; 1052297eecfbSDimitry Andric return Visit(E->getBase()); 1053297eecfbSDimitry Andric } 1054297eecfbSDimitry Andric const Expr *VisitCastExpr(const CastExpr *E) { 1055*5deeebd8SDimitry Andric if (E->getCastKind() == CK_LValueToRValue) 1056*5deeebd8SDimitry Andric return IsExpectedRecordDecl(E) ? E : nullptr; 1057297eecfbSDimitry Andric return Visit(E->getSubExpr()); 1058297eecfbSDimitry Andric } 1059297eecfbSDimitry Andric const Expr *VisitParenExpr(const ParenExpr *E) { 1060297eecfbSDimitry Andric return Visit(E->getSubExpr()); 1061297eecfbSDimitry Andric } 1062297eecfbSDimitry Andric const Expr *VisitUnaryAddrOf(const UnaryOperator *E) { 1063297eecfbSDimitry Andric return Visit(E->getSubExpr()); 1064297eecfbSDimitry Andric } 1065297eecfbSDimitry Andric const Expr *VisitUnaryDeref(const UnaryOperator *E) { 1066297eecfbSDimitry Andric return Visit(E->getSubExpr()); 1067297eecfbSDimitry Andric } 1068297eecfbSDimitry Andric }; 1069297eecfbSDimitry Andric 1070297eecfbSDimitry Andric } // end anonymous namespace 1071297eecfbSDimitry Andric 1072297eecfbSDimitry Andric using RecIndicesTy = 1073297eecfbSDimitry Andric SmallVector<std::pair<const RecordDecl *, llvm::Value *>, 8>; 1074297eecfbSDimitry Andric 1075297eecfbSDimitry Andric static bool getGEPIndicesToField(CodeGenFunction &CGF, const RecordDecl *RD, 10760fca6ea1SDimitry Andric const FieldDecl *Field, 10770fca6ea1SDimitry Andric RecIndicesTy &Indices) { 1078297eecfbSDimitry Andric const CGRecordLayout &Layout = CGF.CGM.getTypes().getCGRecordLayout(RD); 1079297eecfbSDimitry Andric int64_t FieldNo = -1; 10800fca6ea1SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 10810fca6ea1SDimitry Andric if (!Layout.containsFieldDecl(FD)) 10820fca6ea1SDimitry Andric // This could happen if the field has a struct type that's empty. I don't 10830fca6ea1SDimitry Andric // know why either. 10840fca6ea1SDimitry Andric continue; 10850fca6ea1SDimitry Andric 10860fca6ea1SDimitry Andric FieldNo = Layout.getLLVMFieldNo(FD); 1087297eecfbSDimitry Andric if (FD == Field) { 1088297eecfbSDimitry Andric Indices.emplace_back(std::make_pair(RD, CGF.Builder.getInt32(FieldNo))); 1089297eecfbSDimitry Andric return true; 1090297eecfbSDimitry Andric } 1091297eecfbSDimitry Andric 10920fca6ea1SDimitry Andric QualType Ty = FD->getType(); 10930fca6ea1SDimitry Andric if (Ty->isRecordType()) { 10940fca6ea1SDimitry Andric if (getGEPIndicesToField(CGF, Ty->getAsRecordDecl(), Field, Indices)) { 1095297eecfbSDimitry Andric if (RD->isUnion()) 1096297eecfbSDimitry Andric FieldNo = 0; 1097297eecfbSDimitry Andric Indices.emplace_back(std::make_pair(RD, CGF.Builder.getInt32(FieldNo))); 1098297eecfbSDimitry Andric return true; 1099297eecfbSDimitry Andric } 1100297eecfbSDimitry Andric } 1101297eecfbSDimitry Andric } 1102297eecfbSDimitry Andric 1103297eecfbSDimitry Andric return false; 1104297eecfbSDimitry Andric } 1105297eecfbSDimitry Andric 1106297eecfbSDimitry Andric /// This method is typically called in contexts where we can't generate 1107297eecfbSDimitry Andric /// side-effects, like in __builtin_dynamic_object_size. When finding 1108297eecfbSDimitry Andric /// expressions, only choose those that have either already been emitted or can 1109297eecfbSDimitry Andric /// be loaded without side-effects. 1110297eecfbSDimitry Andric /// 1111297eecfbSDimitry Andric /// - \p FAMDecl: the \p Decl for the flexible array member. It may not be 1112297eecfbSDimitry Andric /// within the top-level struct. 1113297eecfbSDimitry Andric /// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl. 1114297eecfbSDimitry Andric llvm::Value *CodeGenFunction::EmitCountedByFieldExpr( 1115297eecfbSDimitry Andric const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) { 1116297eecfbSDimitry Andric const RecordDecl *RD = CountDecl->getParent()->getOuterLexicalRecordContext(); 1117297eecfbSDimitry Andric 1118297eecfbSDimitry Andric // Find the base struct expr (i.e. p in p->a.b.c.d). 1119297eecfbSDimitry Andric const Expr *StructBase = StructAccessBase(RD).Visit(Base); 1120297eecfbSDimitry Andric if (!StructBase || StructBase->HasSideEffects(getContext())) 1121297eecfbSDimitry Andric return nullptr; 1122297eecfbSDimitry Andric 1123297eecfbSDimitry Andric llvm::Value *Res = nullptr; 1124*5deeebd8SDimitry Andric if (StructBase->getType()->isPointerType()) { 1125297eecfbSDimitry Andric LValueBaseInfo BaseInfo; 1126297eecfbSDimitry Andric TBAAAccessInfo TBAAInfo; 1127297eecfbSDimitry Andric Address Addr = EmitPointerWithAlignment(StructBase, &BaseInfo, &TBAAInfo); 11280fca6ea1SDimitry Andric Res = Addr.emitRawPointer(*this); 1129*5deeebd8SDimitry Andric } else if (StructBase->isLValue()) { 1130*5deeebd8SDimitry Andric LValue LV = EmitLValue(StructBase); 1131*5deeebd8SDimitry Andric Address Addr = LV.getAddress(); 1132*5deeebd8SDimitry Andric Res = Addr.emitRawPointer(*this); 1133297eecfbSDimitry Andric } else { 1134297eecfbSDimitry Andric return nullptr; 1135297eecfbSDimitry Andric } 1136297eecfbSDimitry Andric 1137297eecfbSDimitry Andric llvm::Value *Zero = Builder.getInt32(0); 1138297eecfbSDimitry Andric RecIndicesTy Indices; 1139297eecfbSDimitry Andric 1140297eecfbSDimitry Andric getGEPIndicesToField(*this, RD, CountDecl, Indices); 1141297eecfbSDimitry Andric 1142297eecfbSDimitry Andric for (auto I = Indices.rbegin(), E = Indices.rend(); I != E; ++I) 1143297eecfbSDimitry Andric Res = Builder.CreateInBoundsGEP( 1144297eecfbSDimitry Andric ConvertType(QualType(I->first->getTypeForDecl(), 0)), Res, 1145297eecfbSDimitry Andric {Zero, I->second}, "..counted_by.gep"); 1146297eecfbSDimitry Andric 1147297eecfbSDimitry Andric return Builder.CreateAlignedLoad(ConvertType(CountDecl->getType()), Res, 1148297eecfbSDimitry Andric getIntAlign(), "..counted_by.load"); 1149297eecfbSDimitry Andric } 1150297eecfbSDimitry Andric 1151297eecfbSDimitry Andric const FieldDecl *CodeGenFunction::FindCountedByField(const FieldDecl *FD) { 11520fca6ea1SDimitry Andric if (!FD) 1153297eecfbSDimitry Andric return nullptr; 1154297eecfbSDimitry Andric 11550fca6ea1SDimitry Andric const auto *CAT = FD->getType()->getAs<CountAttributedType>(); 11560fca6ea1SDimitry Andric if (!CAT) 1157297eecfbSDimitry Andric return nullptr; 1158297eecfbSDimitry Andric 11590fca6ea1SDimitry Andric const auto *CountDRE = cast<DeclRefExpr>(CAT->getCountExpr()); 11600fca6ea1SDimitry Andric const auto *CountDecl = CountDRE->getDecl(); 11610fca6ea1SDimitry Andric if (const auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl)) 11620fca6ea1SDimitry Andric CountDecl = IFD->getAnonField(); 1163297eecfbSDimitry Andric 11640fca6ea1SDimitry Andric return dyn_cast<FieldDecl>(CountDecl); 1165297eecfbSDimitry Andric } 1166297eecfbSDimitry Andric 11670b57cec5SDimitry Andric void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base, 11680b57cec5SDimitry Andric llvm::Value *Index, QualType IndexType, 11690b57cec5SDimitry Andric bool Accessed) { 11700b57cec5SDimitry Andric assert(SanOpts.has(SanitizerKind::ArrayBounds) && 11710b57cec5SDimitry Andric "should not be called unless adding bounds checks"); 1172bdd1243dSDimitry Andric const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel = 1173bdd1243dSDimitry Andric getLangOpts().getStrictFlexArraysLevel(); 11740b57cec5SDimitry Andric QualType IndexedType; 1175fcaf7f86SDimitry Andric llvm::Value *Bound = 1176fcaf7f86SDimitry Andric getArrayIndexingBound(*this, Base, IndexedType, StrictFlexArraysLevel); 1177297eecfbSDimitry Andric 1178297eecfbSDimitry Andric EmitBoundsCheckImpl(E, Bound, Index, IndexType, IndexedType, Accessed); 1179297eecfbSDimitry Andric } 1180297eecfbSDimitry Andric 1181297eecfbSDimitry Andric void CodeGenFunction::EmitBoundsCheckImpl(const Expr *E, llvm::Value *Bound, 1182297eecfbSDimitry Andric llvm::Value *Index, 1183297eecfbSDimitry Andric QualType IndexType, 1184297eecfbSDimitry Andric QualType IndexedType, bool Accessed) { 11850b57cec5SDimitry Andric if (!Bound) 11860b57cec5SDimitry Andric return; 11870b57cec5SDimitry Andric 1188297eecfbSDimitry Andric SanitizerScope SanScope(this); 1189297eecfbSDimitry Andric 11900b57cec5SDimitry Andric bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType(); 11910b57cec5SDimitry Andric llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned); 11920b57cec5SDimitry Andric llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false); 11930b57cec5SDimitry Andric 11940b57cec5SDimitry Andric llvm::Constant *StaticData[] = { 11950b57cec5SDimitry Andric EmitCheckSourceLocation(E->getExprLoc()), 11960b57cec5SDimitry Andric EmitCheckTypeDescriptor(IndexedType), 11970b57cec5SDimitry Andric EmitCheckTypeDescriptor(IndexType) 11980b57cec5SDimitry Andric }; 11990b57cec5SDimitry Andric llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal) 12000b57cec5SDimitry Andric : Builder.CreateICmpULE(IndexVal, BoundVal); 12010b57cec5SDimitry Andric EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), 12020b57cec5SDimitry Andric SanitizerHandler::OutOfBounds, StaticData, Index); 12030b57cec5SDimitry Andric } 12040b57cec5SDimitry Andric 12050b57cec5SDimitry Andric CodeGenFunction::ComplexPairTy CodeGenFunction:: 12060b57cec5SDimitry Andric EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 12070b57cec5SDimitry Andric bool isInc, bool isPre) { 12080b57cec5SDimitry Andric ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc()); 12090b57cec5SDimitry Andric 12100b57cec5SDimitry Andric llvm::Value *NextVal; 12110b57cec5SDimitry Andric if (isa<llvm::IntegerType>(InVal.first->getType())) { 12120b57cec5SDimitry Andric uint64_t AmountVal = isInc ? 1 : -1; 12130b57cec5SDimitry Andric NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true); 12140b57cec5SDimitry Andric 12150b57cec5SDimitry Andric // Add the inc/dec to the real part. 12160b57cec5SDimitry Andric NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 12170b57cec5SDimitry Andric } else { 1218a7dea167SDimitry Andric QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 12190b57cec5SDimitry Andric llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1); 12200b57cec5SDimitry Andric if (!isInc) 12210b57cec5SDimitry Andric FVal.changeSign(); 12220b57cec5SDimitry Andric NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal); 12230b57cec5SDimitry Andric 12240b57cec5SDimitry Andric // Add the inc/dec to the real part. 12250b57cec5SDimitry Andric NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec"); 12260b57cec5SDimitry Andric } 12270b57cec5SDimitry Andric 12280b57cec5SDimitry Andric ComplexPairTy IncVal(NextVal, InVal.second); 12290b57cec5SDimitry Andric 12300b57cec5SDimitry Andric // Store the updated result through the lvalue. 12310b57cec5SDimitry Andric EmitStoreOfComplex(IncVal, LV, /*init*/ false); 1232480093f4SDimitry Andric if (getLangOpts().OpenMP) 1233480093f4SDimitry Andric CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this, 1234480093f4SDimitry Andric E->getSubExpr()); 12350b57cec5SDimitry Andric 12360b57cec5SDimitry Andric // If this is a postinc, return the value read from memory, otherwise use the 12370b57cec5SDimitry Andric // updated value. 12380b57cec5SDimitry Andric return isPre ? IncVal : InVal; 12390b57cec5SDimitry Andric } 12400b57cec5SDimitry Andric 12410b57cec5SDimitry Andric void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E, 12420b57cec5SDimitry Andric CodeGenFunction *CGF) { 12430b57cec5SDimitry Andric // Bind VLAs in the cast type. 12440b57cec5SDimitry Andric if (CGF && E->getType()->isVariablyModifiedType()) 12450b57cec5SDimitry Andric CGF->EmitVariablyModifiedType(E->getType()); 12460b57cec5SDimitry Andric 12470b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 12480b57cec5SDimitry Andric DI->EmitExplicitCastType(E->getType()); 12490b57cec5SDimitry Andric } 12500b57cec5SDimitry Andric 12510b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 12520b57cec5SDimitry Andric // LValue Expression Emission 12530b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 12540b57cec5SDimitry Andric 125506c3fb27SDimitry Andric static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, 125606c3fb27SDimitry Andric TBAAAccessInfo *TBAAInfo, 125706c3fb27SDimitry Andric KnownNonNull_t IsKnownNonNull, 125806c3fb27SDimitry Andric CodeGenFunction &CGF) { 12590b57cec5SDimitry Andric // We allow this with ObjC object pointers because of fragile ABIs. 12600b57cec5SDimitry Andric assert(E->getType()->isPointerType() || 12610b57cec5SDimitry Andric E->getType()->isObjCObjectPointerType()); 12620b57cec5SDimitry Andric E = E->IgnoreParens(); 12630b57cec5SDimitry Andric 12640b57cec5SDimitry Andric // Casts: 12650b57cec5SDimitry Andric if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12660b57cec5SDimitry Andric if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE)) 126706c3fb27SDimitry Andric CGF.CGM.EmitExplicitCastExprType(ECE, &CGF); 12680b57cec5SDimitry Andric 12690b57cec5SDimitry Andric switch (CE->getCastKind()) { 12700b57cec5SDimitry Andric // Non-converting casts (but not C's implicit conversion from void*). 12710b57cec5SDimitry Andric case CK_BitCast: 12720b57cec5SDimitry Andric case CK_NoOp: 12730b57cec5SDimitry Andric case CK_AddressSpaceConversion: 12740b57cec5SDimitry Andric if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) { 12750b57cec5SDimitry Andric if (PtrTy->getPointeeType()->isVoidType()) 12760b57cec5SDimitry Andric break; 12770b57cec5SDimitry Andric 12780b57cec5SDimitry Andric LValueBaseInfo InnerBaseInfo; 12790b57cec5SDimitry Andric TBAAAccessInfo InnerTBAAInfo; 128006c3fb27SDimitry Andric Address Addr = CGF.EmitPointerWithAlignment( 128106c3fb27SDimitry Andric CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull); 12820b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = InnerBaseInfo; 12830b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = InnerTBAAInfo; 12840b57cec5SDimitry Andric 12850b57cec5SDimitry Andric if (isa<ExplicitCastExpr>(CE)) { 12860b57cec5SDimitry Andric LValueBaseInfo TargetTypeBaseInfo; 12870b57cec5SDimitry Andric TBAAAccessInfo TargetTypeTBAAInfo; 128806c3fb27SDimitry Andric CharUnits Align = CGF.CGM.getNaturalPointeeTypeAlignment( 12895ffd83dbSDimitry Andric E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo); 12900b57cec5SDimitry Andric if (TBAAInfo) 129106c3fb27SDimitry Andric *TBAAInfo = 129206c3fb27SDimitry Andric CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo); 12930b57cec5SDimitry Andric // If the source l-value is opaque, honor the alignment of the 12940b57cec5SDimitry Andric // casted-to type. 12950b57cec5SDimitry Andric if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) { 12960b57cec5SDimitry Andric if (BaseInfo) 12970b57cec5SDimitry Andric BaseInfo->mergeForCast(TargetTypeBaseInfo); 12980fca6ea1SDimitry Andric Addr.setAlignment(Align); 12990b57cec5SDimitry Andric } 13000b57cec5SDimitry Andric } 13010b57cec5SDimitry Andric 130206c3fb27SDimitry Andric if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) && 13030b57cec5SDimitry Andric CE->getCastKind() == CK_BitCast) { 13040b57cec5SDimitry Andric if (auto PT = E->getType()->getAs<PointerType>()) 130506c3fb27SDimitry Andric CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr, 13060b57cec5SDimitry Andric /*MayBeNull=*/true, 13070b57cec5SDimitry Andric CodeGenFunction::CFITCK_UnrelatedCast, 13080b57cec5SDimitry Andric CE->getBeginLoc()); 13090b57cec5SDimitry Andric } 13100eae32dcSDimitry Andric 131106c3fb27SDimitry Andric llvm::Type *ElemTy = 131206c3fb27SDimitry Andric CGF.ConvertTypeForMem(E->getType()->getPointeeType()); 131306c3fb27SDimitry Andric Addr = Addr.withElementType(ElemTy); 131481ad6265SDimitry Andric if (CE->getCastKind() == CK_AddressSpaceConversion) 13150fca6ea1SDimitry Andric Addr = CGF.Builder.CreateAddrSpaceCast( 13160fca6ea1SDimitry Andric Addr, CGF.ConvertType(E->getType()), ElemTy); 13170fca6ea1SDimitry Andric return CGF.authPointerToPointerCast(Addr, CE->getSubExpr()->getType(), 13180fca6ea1SDimitry Andric CE->getType()); 13190b57cec5SDimitry Andric } 13200b57cec5SDimitry Andric break; 13210b57cec5SDimitry Andric 13220b57cec5SDimitry Andric // Array-to-pointer decay. 13230b57cec5SDimitry Andric case CK_ArrayToPointerDecay: 132406c3fb27SDimitry Andric return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo); 13250b57cec5SDimitry Andric 13260b57cec5SDimitry Andric // Derived-to-base conversions. 13270b57cec5SDimitry Andric case CK_UncheckedDerivedToBase: 13280b57cec5SDimitry Andric case CK_DerivedToBase: { 13290b57cec5SDimitry Andric // TODO: Support accesses to members of base classes in TBAA. For now, we 13300b57cec5SDimitry Andric // conservatively pretend that the complete object is of the base class 13310b57cec5SDimitry Andric // type. 13320b57cec5SDimitry Andric if (TBAAInfo) 133306c3fb27SDimitry Andric *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType()); 133406c3fb27SDimitry Andric Address Addr = CGF.EmitPointerWithAlignment( 133506c3fb27SDimitry Andric CE->getSubExpr(), BaseInfo, nullptr, 133606c3fb27SDimitry Andric (KnownNonNull_t)(IsKnownNonNull || 133706c3fb27SDimitry Andric CE->getCastKind() == CK_UncheckedDerivedToBase)); 13380b57cec5SDimitry Andric auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl(); 133906c3fb27SDimitry Andric return CGF.GetAddressOfBaseClass( 134006c3fb27SDimitry Andric Addr, Derived, CE->path_begin(), CE->path_end(), 134106c3fb27SDimitry Andric CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc()); 13420b57cec5SDimitry Andric } 13430b57cec5SDimitry Andric 13440b57cec5SDimitry Andric // TODO: Is there any reason to treat base-to-derived conversions 13450b57cec5SDimitry Andric // specially? 13460b57cec5SDimitry Andric default: 13470b57cec5SDimitry Andric break; 13480b57cec5SDimitry Andric } 13490b57cec5SDimitry Andric } 13500b57cec5SDimitry Andric 13510b57cec5SDimitry Andric // Unary &. 13520b57cec5SDimitry Andric if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13530b57cec5SDimitry Andric if (UO->getOpcode() == UO_AddrOf) { 135406c3fb27SDimitry Andric LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull); 13550b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 13560b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo(); 13570fca6ea1SDimitry Andric return LV.getAddress(); 13580b57cec5SDimitry Andric } 13590b57cec5SDimitry Andric } 13600b57cec5SDimitry Andric 136181ad6265SDimitry Andric // std::addressof and variants. 136281ad6265SDimitry Andric if (auto *Call = dyn_cast<CallExpr>(E)) { 136381ad6265SDimitry Andric switch (Call->getBuiltinCallee()) { 136481ad6265SDimitry Andric default: 136581ad6265SDimitry Andric break; 136681ad6265SDimitry Andric case Builtin::BIaddressof: 136781ad6265SDimitry Andric case Builtin::BI__addressof: 136881ad6265SDimitry Andric case Builtin::BI__builtin_addressof: { 136906c3fb27SDimitry Andric LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull); 137081ad6265SDimitry Andric if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 137181ad6265SDimitry Andric if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo(); 13720fca6ea1SDimitry Andric return LV.getAddress(); 137381ad6265SDimitry Andric } 137481ad6265SDimitry Andric } 137581ad6265SDimitry Andric } 137681ad6265SDimitry Andric 13770b57cec5SDimitry Andric // TODO: conditional operators, comma. 13780b57cec5SDimitry Andric 13790b57cec5SDimitry Andric // Otherwise, use the alignment of the type. 13800fca6ea1SDimitry Andric return CGF.makeNaturalAddressForPointer( 13810fca6ea1SDimitry Andric CGF.EmitScalarExpr(E), E->getType()->getPointeeType(), CharUnits(), 13820fca6ea1SDimitry Andric /*ForPointeeType=*/true, BaseInfo, TBAAInfo, IsKnownNonNull); 138306c3fb27SDimitry Andric } 138406c3fb27SDimitry Andric 138506c3fb27SDimitry Andric /// EmitPointerWithAlignment - Given an expression of pointer type, try to 138606c3fb27SDimitry Andric /// derive a more accurate bound on the alignment of the pointer. 138706c3fb27SDimitry Andric Address CodeGenFunction::EmitPointerWithAlignment( 138806c3fb27SDimitry Andric const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, 138906c3fb27SDimitry Andric KnownNonNull_t IsKnownNonNull) { 139006c3fb27SDimitry Andric Address Addr = 139106c3fb27SDimitry Andric ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this); 139206c3fb27SDimitry Andric if (IsKnownNonNull && !Addr.isKnownNonNull()) 139306c3fb27SDimitry Andric Addr.setKnownNonNull(); 139406c3fb27SDimitry Andric return Addr; 13950b57cec5SDimitry Andric } 13960b57cec5SDimitry Andric 1397e8d8bef9SDimitry Andric llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) { 1398e8d8bef9SDimitry Andric llvm::Value *V = RV.getScalarVal(); 1399e8d8bef9SDimitry Andric if (auto MPT = T->getAs<MemberPointerType>()) 1400e8d8bef9SDimitry Andric return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT); 1401e8d8bef9SDimitry Andric return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType())); 1402e8d8bef9SDimitry Andric } 1403e8d8bef9SDimitry Andric 14040b57cec5SDimitry Andric RValue CodeGenFunction::GetUndefRValue(QualType Ty) { 14050b57cec5SDimitry Andric if (Ty->isVoidType()) 14060b57cec5SDimitry Andric return RValue::get(nullptr); 14070b57cec5SDimitry Andric 14080b57cec5SDimitry Andric switch (getEvaluationKind(Ty)) { 14090b57cec5SDimitry Andric case TEK_Complex: { 14100b57cec5SDimitry Andric llvm::Type *EltTy = 14110b57cec5SDimitry Andric ConvertType(Ty->castAs<ComplexType>()->getElementType()); 14120b57cec5SDimitry Andric llvm::Value *U = llvm::UndefValue::get(EltTy); 14130b57cec5SDimitry Andric return RValue::getComplex(std::make_pair(U, U)); 14140b57cec5SDimitry Andric } 14150b57cec5SDimitry Andric 14160b57cec5SDimitry Andric // If this is a use of an undefined aggregate type, the aggregate must have an 14170b57cec5SDimitry Andric // identifiable address. Just because the contents of the value are undefined 14180b57cec5SDimitry Andric // doesn't mean that the address can't be taken and compared. 14190b57cec5SDimitry Andric case TEK_Aggregate: { 14200b57cec5SDimitry Andric Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp"); 14210b57cec5SDimitry Andric return RValue::getAggregate(DestPtr); 14220b57cec5SDimitry Andric } 14230b57cec5SDimitry Andric 14240b57cec5SDimitry Andric case TEK_Scalar: 14250b57cec5SDimitry Andric return RValue::get(llvm::UndefValue::get(ConvertType(Ty))); 14260b57cec5SDimitry Andric } 14270b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind"); 14280b57cec5SDimitry Andric } 14290b57cec5SDimitry Andric 14300b57cec5SDimitry Andric RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E, 14310b57cec5SDimitry Andric const char *Name) { 14320b57cec5SDimitry Andric ErrorUnsupported(E, Name); 14330b57cec5SDimitry Andric return GetUndefRValue(E->getType()); 14340b57cec5SDimitry Andric } 14350b57cec5SDimitry Andric 14360b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E, 14370b57cec5SDimitry Andric const char *Name) { 14380b57cec5SDimitry Andric ErrorUnsupported(E, Name); 143981ad6265SDimitry Andric llvm::Type *ElTy = ConvertType(E->getType()); 14405f757f3fSDimitry Andric llvm::Type *Ty = UnqualPtrTy; 144181ad6265SDimitry Andric return MakeAddrLValue( 144281ad6265SDimitry Andric Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType()); 14430b57cec5SDimitry Andric } 14440b57cec5SDimitry Andric 14450b57cec5SDimitry Andric bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) { 14460b57cec5SDimitry Andric const Expr *Base = Obj; 14470b57cec5SDimitry Andric while (!isa<CXXThisExpr>(Base)) { 14480b57cec5SDimitry Andric // The result of a dynamic_cast can be null. 14490b57cec5SDimitry Andric if (isa<CXXDynamicCastExpr>(Base)) 14500b57cec5SDimitry Andric return false; 14510b57cec5SDimitry Andric 14520b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(Base)) { 14530b57cec5SDimitry Andric Base = CE->getSubExpr(); 14540b57cec5SDimitry Andric } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) { 14550b57cec5SDimitry Andric Base = PE->getSubExpr(); 14560b57cec5SDimitry Andric } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) { 14570b57cec5SDimitry Andric if (UO->getOpcode() == UO_Extension) 14580b57cec5SDimitry Andric Base = UO->getSubExpr(); 14590b57cec5SDimitry Andric else 14600b57cec5SDimitry Andric return false; 14610b57cec5SDimitry Andric } else { 14620b57cec5SDimitry Andric return false; 14630b57cec5SDimitry Andric } 14640b57cec5SDimitry Andric } 14650b57cec5SDimitry Andric return true; 14660b57cec5SDimitry Andric } 14670b57cec5SDimitry Andric 14680b57cec5SDimitry Andric LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) { 14690b57cec5SDimitry Andric LValue LV; 14700b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E)) 14710b57cec5SDimitry Andric LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true); 14720b57cec5SDimitry Andric else 14730b57cec5SDimitry Andric LV = EmitLValue(E); 14740b57cec5SDimitry Andric if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) { 14750b57cec5SDimitry Andric SanitizerSet SkippedChecks; 14760b57cec5SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(E)) { 14770b57cec5SDimitry Andric bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase()); 14780b57cec5SDimitry Andric if (IsBaseCXXThis) 14790b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Alignment, true); 14800b57cec5SDimitry Andric if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase())) 14810b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, true); 14820b57cec5SDimitry Andric } 14830fca6ea1SDimitry Andric EmitTypeCheck(TCK, E->getExprLoc(), LV, E->getType(), SkippedChecks); 14840b57cec5SDimitry Andric } 14850b57cec5SDimitry Andric return LV; 14860b57cec5SDimitry Andric } 14870b57cec5SDimitry Andric 14880b57cec5SDimitry Andric /// EmitLValue - Emit code to compute a designator that specifies the location 14890b57cec5SDimitry Andric /// of the expression. 14900b57cec5SDimitry Andric /// 14910b57cec5SDimitry Andric /// This can return one of two things: a simple address or a bitfield reference. 14920b57cec5SDimitry Andric /// In either case, the LLVM Value* in the LValue structure is guaranteed to be 14930b57cec5SDimitry Andric /// an LLVM pointer type. 14940b57cec5SDimitry Andric /// 14950b57cec5SDimitry Andric /// If this returns a bitfield reference, nothing about the pointee type of the 14960b57cec5SDimitry Andric /// LLVM value is known: For example, it may not be a pointer to an integer. 14970b57cec5SDimitry Andric /// 14980b57cec5SDimitry Andric /// If this returns a normal address, and if the lvalue's C type is fixed size, 14990b57cec5SDimitry Andric /// this method guarantees that the returned pointer type will point to an LLVM 15000b57cec5SDimitry Andric /// type of the same size of the lvalue's type. If the lvalue has a variable 15010b57cec5SDimitry Andric /// length type, this is not possible. 15020b57cec5SDimitry Andric /// 150306c3fb27SDimitry Andric LValue CodeGenFunction::EmitLValue(const Expr *E, 150406c3fb27SDimitry Andric KnownNonNull_t IsKnownNonNull) { 150506c3fb27SDimitry Andric LValue LV = EmitLValueHelper(E, IsKnownNonNull); 150606c3fb27SDimitry Andric if (IsKnownNonNull && !LV.isKnownNonNull()) 150706c3fb27SDimitry Andric LV.setKnownNonNull(); 150806c3fb27SDimitry Andric return LV; 150906c3fb27SDimitry Andric } 151006c3fb27SDimitry Andric 15117a6dacacSDimitry Andric static QualType getConstantExprReferredType(const FullExpr *E, 15127a6dacacSDimitry Andric const ASTContext &Ctx) { 15137a6dacacSDimitry Andric const Expr *SE = E->getSubExpr()->IgnoreImplicit(); 15147a6dacacSDimitry Andric if (isa<OpaqueValueExpr>(SE)) 15157a6dacacSDimitry Andric return SE->getType(); 15167a6dacacSDimitry Andric return cast<CallExpr>(SE)->getCallReturnType(Ctx)->getPointeeType(); 15177a6dacacSDimitry Andric } 15187a6dacacSDimitry Andric 151906c3fb27SDimitry Andric LValue CodeGenFunction::EmitLValueHelper(const Expr *E, 152006c3fb27SDimitry Andric KnownNonNull_t IsKnownNonNull) { 15210b57cec5SDimitry Andric ApplyDebugLocation DL(*this, E); 15220b57cec5SDimitry Andric switch (E->getStmtClass()) { 15230b57cec5SDimitry Andric default: return EmitUnsupportedLValue(E, "l-value expression"); 15240b57cec5SDimitry Andric 15250b57cec5SDimitry Andric case Expr::ObjCPropertyRefExprClass: 15260b57cec5SDimitry Andric llvm_unreachable("cannot emit a property reference directly"); 15270b57cec5SDimitry Andric 15280b57cec5SDimitry Andric case Expr::ObjCSelectorExprClass: 15290b57cec5SDimitry Andric return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E)); 15300b57cec5SDimitry Andric case Expr::ObjCIsaExprClass: 15310b57cec5SDimitry Andric return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E)); 15320b57cec5SDimitry Andric case Expr::BinaryOperatorClass: 15330b57cec5SDimitry Andric return EmitBinaryOperatorLValue(cast<BinaryOperator>(E)); 15340b57cec5SDimitry Andric case Expr::CompoundAssignOperatorClass: { 15350b57cec5SDimitry Andric QualType Ty = E->getType(); 15360b57cec5SDimitry Andric if (const AtomicType *AT = Ty->getAs<AtomicType>()) 15370b57cec5SDimitry Andric Ty = AT->getValueType(); 15380b57cec5SDimitry Andric if (!Ty->isAnyComplexType()) 15390b57cec5SDimitry Andric return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 15400b57cec5SDimitry Andric return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E)); 15410b57cec5SDimitry Andric } 15420b57cec5SDimitry Andric case Expr::CallExprClass: 15430b57cec5SDimitry Andric case Expr::CXXMemberCallExprClass: 15440b57cec5SDimitry Andric case Expr::CXXOperatorCallExprClass: 15450b57cec5SDimitry Andric case Expr::UserDefinedLiteralClass: 15460b57cec5SDimitry Andric return EmitCallExprLValue(cast<CallExpr>(E)); 1547a7dea167SDimitry Andric case Expr::CXXRewrittenBinaryOperatorClass: 154806c3fb27SDimitry Andric return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(), 154906c3fb27SDimitry Andric IsKnownNonNull); 15500b57cec5SDimitry Andric case Expr::VAArgExprClass: 15510b57cec5SDimitry Andric return EmitVAArgExprLValue(cast<VAArgExpr>(E)); 15520b57cec5SDimitry Andric case Expr::DeclRefExprClass: 15530b57cec5SDimitry Andric return EmitDeclRefLValue(cast<DeclRefExpr>(E)); 15545ffd83dbSDimitry Andric case Expr::ConstantExprClass: { 15555ffd83dbSDimitry Andric const ConstantExpr *CE = cast<ConstantExpr>(E); 15565ffd83dbSDimitry Andric if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) { 15577a6dacacSDimitry Andric QualType RetType = getConstantExprReferredType(CE, getContext()); 15585ffd83dbSDimitry Andric return MakeNaturalAlignAddrLValue(Result, RetType); 15595ffd83dbSDimitry Andric } 156006c3fb27SDimitry Andric return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull); 15615ffd83dbSDimitry Andric } 15620b57cec5SDimitry Andric case Expr::ParenExprClass: 156306c3fb27SDimitry Andric return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull); 15640b57cec5SDimitry Andric case Expr::GenericSelectionExprClass: 156506c3fb27SDimitry Andric return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(), 156606c3fb27SDimitry Andric IsKnownNonNull); 15670b57cec5SDimitry Andric case Expr::PredefinedExprClass: 15680b57cec5SDimitry Andric return EmitPredefinedLValue(cast<PredefinedExpr>(E)); 15690b57cec5SDimitry Andric case Expr::StringLiteralClass: 15700b57cec5SDimitry Andric return EmitStringLiteralLValue(cast<StringLiteral>(E)); 15710b57cec5SDimitry Andric case Expr::ObjCEncodeExprClass: 15720b57cec5SDimitry Andric return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E)); 15730b57cec5SDimitry Andric case Expr::PseudoObjectExprClass: 15740b57cec5SDimitry Andric return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E)); 15750b57cec5SDimitry Andric case Expr::InitListExprClass: 15760b57cec5SDimitry Andric return EmitInitListLValue(cast<InitListExpr>(E)); 15770b57cec5SDimitry Andric case Expr::CXXTemporaryObjectExprClass: 15780b57cec5SDimitry Andric case Expr::CXXConstructExprClass: 15790b57cec5SDimitry Andric return EmitCXXConstructLValue(cast<CXXConstructExpr>(E)); 15800b57cec5SDimitry Andric case Expr::CXXBindTemporaryExprClass: 15810b57cec5SDimitry Andric return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E)); 15820b57cec5SDimitry Andric case Expr::CXXUuidofExprClass: 15830b57cec5SDimitry Andric return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E)); 15840b57cec5SDimitry Andric case Expr::LambdaExprClass: 15850b57cec5SDimitry Andric return EmitAggExprToLValue(E); 15860b57cec5SDimitry Andric 15870b57cec5SDimitry Andric case Expr::ExprWithCleanupsClass: { 15880b57cec5SDimitry Andric const auto *cleanups = cast<ExprWithCleanups>(E); 15890b57cec5SDimitry Andric RunCleanupsScope Scope(*this); 159006c3fb27SDimitry Andric LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull); 15910b57cec5SDimitry Andric if (LV.isSimple()) { 15920b57cec5SDimitry Andric // Defend against branches out of gnu statement expressions surrounded by 15930b57cec5SDimitry Andric // cleanups. 15940fca6ea1SDimitry Andric Address Addr = LV.getAddress(); 15950fca6ea1SDimitry Andric llvm::Value *V = Addr.getBasePointer(); 15960b57cec5SDimitry Andric Scope.ForceCleanup({&V}); 15970fca6ea1SDimitry Andric Addr.replaceBasePointer(V); 15980fca6ea1SDimitry Andric return LValue::MakeAddr(Addr, LV.getType(), getContext(), 15990fca6ea1SDimitry Andric LV.getBaseInfo(), LV.getTBAAInfo()); 16000b57cec5SDimitry Andric } 16010b57cec5SDimitry Andric // FIXME: Is it possible to create an ExprWithCleanups that produces a 16020b57cec5SDimitry Andric // bitfield lvalue or some other non-simple lvalue? 16030b57cec5SDimitry Andric return LV; 16040b57cec5SDimitry Andric } 16050b57cec5SDimitry Andric 16060b57cec5SDimitry Andric case Expr::CXXDefaultArgExprClass: { 16070b57cec5SDimitry Andric auto *DAE = cast<CXXDefaultArgExpr>(E); 16080b57cec5SDimitry Andric CXXDefaultArgExprScope Scope(*this, DAE); 160906c3fb27SDimitry Andric return EmitLValue(DAE->getExpr(), IsKnownNonNull); 16100b57cec5SDimitry Andric } 16110b57cec5SDimitry Andric case Expr::CXXDefaultInitExprClass: { 16120b57cec5SDimitry Andric auto *DIE = cast<CXXDefaultInitExpr>(E); 16130b57cec5SDimitry Andric CXXDefaultInitExprScope Scope(*this, DIE); 161406c3fb27SDimitry Andric return EmitLValue(DIE->getExpr(), IsKnownNonNull); 16150b57cec5SDimitry Andric } 16160b57cec5SDimitry Andric case Expr::CXXTypeidExprClass: 16170b57cec5SDimitry Andric return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E)); 16180b57cec5SDimitry Andric 16190b57cec5SDimitry Andric case Expr::ObjCMessageExprClass: 16200b57cec5SDimitry Andric return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E)); 16210b57cec5SDimitry Andric case Expr::ObjCIvarRefExprClass: 16220b57cec5SDimitry Andric return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E)); 16230b57cec5SDimitry Andric case Expr::StmtExprClass: 16240b57cec5SDimitry Andric return EmitStmtExprLValue(cast<StmtExpr>(E)); 16250b57cec5SDimitry Andric case Expr::UnaryOperatorClass: 16260b57cec5SDimitry Andric return EmitUnaryOpLValue(cast<UnaryOperator>(E)); 16270b57cec5SDimitry Andric case Expr::ArraySubscriptExprClass: 16280b57cec5SDimitry Andric return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E)); 16295ffd83dbSDimitry Andric case Expr::MatrixSubscriptExprClass: 16305ffd83dbSDimitry Andric return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E)); 16310fca6ea1SDimitry Andric case Expr::ArraySectionExprClass: 16320fca6ea1SDimitry Andric return EmitArraySectionExpr(cast<ArraySectionExpr>(E)); 16330b57cec5SDimitry Andric case Expr::ExtVectorElementExprClass: 16340b57cec5SDimitry Andric return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E)); 1635bdd1243dSDimitry Andric case Expr::CXXThisExprClass: 1636bdd1243dSDimitry Andric return MakeAddrLValue(LoadCXXThisAddress(), E->getType()); 16370b57cec5SDimitry Andric case Expr::MemberExprClass: 16380b57cec5SDimitry Andric return EmitMemberExpr(cast<MemberExpr>(E)); 16390b57cec5SDimitry Andric case Expr::CompoundLiteralExprClass: 16400b57cec5SDimitry Andric return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E)); 16410b57cec5SDimitry Andric case Expr::ConditionalOperatorClass: 16420b57cec5SDimitry Andric return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E)); 16430b57cec5SDimitry Andric case Expr::BinaryConditionalOperatorClass: 16440b57cec5SDimitry Andric return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E)); 16450b57cec5SDimitry Andric case Expr::ChooseExprClass: 164606c3fb27SDimitry Andric return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull); 16470b57cec5SDimitry Andric case Expr::OpaqueValueExprClass: 16480b57cec5SDimitry Andric return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E)); 16490b57cec5SDimitry Andric case Expr::SubstNonTypeTemplateParmExprClass: 165006c3fb27SDimitry Andric return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), 165106c3fb27SDimitry Andric IsKnownNonNull); 16520b57cec5SDimitry Andric case Expr::ImplicitCastExprClass: 16530b57cec5SDimitry Andric case Expr::CStyleCastExprClass: 16540b57cec5SDimitry Andric case Expr::CXXFunctionalCastExprClass: 16550b57cec5SDimitry Andric case Expr::CXXStaticCastExprClass: 16560b57cec5SDimitry Andric case Expr::CXXDynamicCastExprClass: 16570b57cec5SDimitry Andric case Expr::CXXReinterpretCastExprClass: 16580b57cec5SDimitry Andric case Expr::CXXConstCastExprClass: 16595ffd83dbSDimitry Andric case Expr::CXXAddrspaceCastExprClass: 16600b57cec5SDimitry Andric case Expr::ObjCBridgedCastExprClass: 16610b57cec5SDimitry Andric return EmitCastLValue(cast<CastExpr>(E)); 16620b57cec5SDimitry Andric 16630b57cec5SDimitry Andric case Expr::MaterializeTemporaryExprClass: 16640b57cec5SDimitry Andric return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E)); 16650b57cec5SDimitry Andric 16660b57cec5SDimitry Andric case Expr::CoawaitExprClass: 16670b57cec5SDimitry Andric return EmitCoawaitLValue(cast<CoawaitExpr>(E)); 16680b57cec5SDimitry Andric case Expr::CoyieldExprClass: 16690b57cec5SDimitry Andric return EmitCoyieldLValue(cast<CoyieldExpr>(E)); 16700fca6ea1SDimitry Andric case Expr::PackIndexingExprClass: 16710fca6ea1SDimitry Andric return EmitLValue(cast<PackIndexingExpr>(E)->getSelectedExpr()); 16720b57cec5SDimitry Andric } 16730b57cec5SDimitry Andric } 16740b57cec5SDimitry Andric 16750b57cec5SDimitry Andric /// Given an object of the given canonical type, can we safely copy a 16760b57cec5SDimitry Andric /// value out of it based on its initializer? 16770b57cec5SDimitry Andric static bool isConstantEmittableObjectType(QualType type) { 16780b57cec5SDimitry Andric assert(type.isCanonical()); 16790b57cec5SDimitry Andric assert(!type->isReferenceType()); 16800b57cec5SDimitry Andric 16810b57cec5SDimitry Andric // Must be const-qualified but non-volatile. 16820b57cec5SDimitry Andric Qualifiers qs = type.getLocalQualifiers(); 16830b57cec5SDimitry Andric if (!qs.hasConst() || qs.hasVolatile()) return false; 16840b57cec5SDimitry Andric 16850b57cec5SDimitry Andric // Otherwise, all object types satisfy this except C++ classes with 16860b57cec5SDimitry Andric // mutable subobjects or non-trivial copy/destroy behavior. 16870b57cec5SDimitry Andric if (const auto *RT = dyn_cast<RecordType>(type)) 16880b57cec5SDimitry Andric if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 16890b57cec5SDimitry Andric if (RD->hasMutableFields() || !RD->isTrivial()) 16900b57cec5SDimitry Andric return false; 16910b57cec5SDimitry Andric 16920b57cec5SDimitry Andric return true; 16930b57cec5SDimitry Andric } 16940b57cec5SDimitry Andric 16950b57cec5SDimitry Andric /// Can we constant-emit a load of a reference to a variable of the 16960b57cec5SDimitry Andric /// given type? This is different from predicates like 16970b57cec5SDimitry Andric /// Decl::mightBeUsableInConstantExpressions because we do want it to apply 16980b57cec5SDimitry Andric /// in situations that don't necessarily satisfy the language's rules 16990b57cec5SDimitry Andric /// for this (e.g. C++'s ODR-use rules). For example, we want to able 17000b57cec5SDimitry Andric /// to do this with const float variables even if those variables 17010b57cec5SDimitry Andric /// aren't marked 'constexpr'. 17020b57cec5SDimitry Andric enum ConstantEmissionKind { 17030b57cec5SDimitry Andric CEK_None, 17040b57cec5SDimitry Andric CEK_AsReferenceOnly, 17050b57cec5SDimitry Andric CEK_AsValueOrReference, 17060b57cec5SDimitry Andric CEK_AsValueOnly 17070b57cec5SDimitry Andric }; 17080b57cec5SDimitry Andric static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) { 17090b57cec5SDimitry Andric type = type.getCanonicalType(); 17100b57cec5SDimitry Andric if (const auto *ref = dyn_cast<ReferenceType>(type)) { 17110b57cec5SDimitry Andric if (isConstantEmittableObjectType(ref->getPointeeType())) 17120b57cec5SDimitry Andric return CEK_AsValueOrReference; 17130b57cec5SDimitry Andric return CEK_AsReferenceOnly; 17140b57cec5SDimitry Andric } 17150b57cec5SDimitry Andric if (isConstantEmittableObjectType(type)) 17160b57cec5SDimitry Andric return CEK_AsValueOnly; 17170b57cec5SDimitry Andric return CEK_None; 17180b57cec5SDimitry Andric } 17190b57cec5SDimitry Andric 17200b57cec5SDimitry Andric /// Try to emit a reference to the given value without producing it as 17210b57cec5SDimitry Andric /// an l-value. This is just an optimization, but it avoids us needing 17220b57cec5SDimitry Andric /// to emit global copies of variables if they're named without triggering 17230b57cec5SDimitry Andric /// a formal use in a context where we can't emit a direct reference to them, 17240b57cec5SDimitry Andric /// for instance if a block or lambda or a member of a local class uses a 17250b57cec5SDimitry Andric /// const int variable or constexpr variable from an enclosing function. 17260b57cec5SDimitry Andric CodeGenFunction::ConstantEmission 17270b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) { 17280b57cec5SDimitry Andric ValueDecl *value = refExpr->getDecl(); 17290b57cec5SDimitry Andric 17300b57cec5SDimitry Andric // The value needs to be an enum constant or a constant variable. 17310b57cec5SDimitry Andric ConstantEmissionKind CEK; 17320b57cec5SDimitry Andric if (isa<ParmVarDecl>(value)) { 17330b57cec5SDimitry Andric CEK = CEK_None; 17340b57cec5SDimitry Andric } else if (auto *var = dyn_cast<VarDecl>(value)) { 17350b57cec5SDimitry Andric CEK = checkVarTypeForConstantEmission(var->getType()); 17360b57cec5SDimitry Andric } else if (isa<EnumConstantDecl>(value)) { 17370b57cec5SDimitry Andric CEK = CEK_AsValueOnly; 17380b57cec5SDimitry Andric } else { 17390b57cec5SDimitry Andric CEK = CEK_None; 17400b57cec5SDimitry Andric } 17410b57cec5SDimitry Andric if (CEK == CEK_None) return ConstantEmission(); 17420b57cec5SDimitry Andric 17430b57cec5SDimitry Andric Expr::EvalResult result; 17440b57cec5SDimitry Andric bool resultIsReference; 17450b57cec5SDimitry Andric QualType resultType; 17460b57cec5SDimitry Andric 17470b57cec5SDimitry Andric // It's best to evaluate all the way as an r-value if that's permitted. 17480b57cec5SDimitry Andric if (CEK != CEK_AsReferenceOnly && 17490b57cec5SDimitry Andric refExpr->EvaluateAsRValue(result, getContext())) { 17500b57cec5SDimitry Andric resultIsReference = false; 17510b57cec5SDimitry Andric resultType = refExpr->getType(); 17520b57cec5SDimitry Andric 17530b57cec5SDimitry Andric // Otherwise, try to evaluate as an l-value. 17540b57cec5SDimitry Andric } else if (CEK != CEK_AsValueOnly && 17550b57cec5SDimitry Andric refExpr->EvaluateAsLValue(result, getContext())) { 17560b57cec5SDimitry Andric resultIsReference = true; 17570b57cec5SDimitry Andric resultType = value->getType(); 17580b57cec5SDimitry Andric 17590b57cec5SDimitry Andric // Failure. 17600b57cec5SDimitry Andric } else { 17610b57cec5SDimitry Andric return ConstantEmission(); 17620b57cec5SDimitry Andric } 17630b57cec5SDimitry Andric 17640b57cec5SDimitry Andric // In any case, if the initializer has side-effects, abandon ship. 17650b57cec5SDimitry Andric if (result.HasSideEffects) 17660b57cec5SDimitry Andric return ConstantEmission(); 17670b57cec5SDimitry Andric 1768e8d8bef9SDimitry Andric // In CUDA/HIP device compilation, a lambda may capture a reference variable 1769e8d8bef9SDimitry Andric // referencing a global host variable by copy. In this case the lambda should 1770e8d8bef9SDimitry Andric // make a copy of the value of the global host variable. The DRE of the 1771e8d8bef9SDimitry Andric // captured reference variable cannot be emitted as load from the host 1772e8d8bef9SDimitry Andric // global variable as compile time constant, since the host variable is not 1773e8d8bef9SDimitry Andric // accessible on device. The DRE of the captured reference variable has to be 1774e8d8bef9SDimitry Andric // loaded from captures. 1775e8d8bef9SDimitry Andric if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() && 1776e8d8bef9SDimitry Andric refExpr->refersToEnclosingVariableOrCapture()) { 1777e8d8bef9SDimitry Andric auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl); 1778e8d8bef9SDimitry Andric if (MD && MD->getParent()->isLambda() && 1779e8d8bef9SDimitry Andric MD->getOverloadedOperator() == OO_Call) { 1780e8d8bef9SDimitry Andric const APValue::LValueBase &base = result.Val.getLValueBase(); 1781e8d8bef9SDimitry Andric if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) { 1782e8d8bef9SDimitry Andric if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) { 1783e8d8bef9SDimitry Andric if (!VD->hasAttr<CUDADeviceAttr>()) { 1784e8d8bef9SDimitry Andric return ConstantEmission(); 1785e8d8bef9SDimitry Andric } 1786e8d8bef9SDimitry Andric } 1787e8d8bef9SDimitry Andric } 1788e8d8bef9SDimitry Andric } 1789e8d8bef9SDimitry Andric } 1790e8d8bef9SDimitry Andric 17910b57cec5SDimitry Andric // Emit as a constant. 17920b57cec5SDimitry Andric auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(), 17930b57cec5SDimitry Andric result.Val, resultType); 17940b57cec5SDimitry Andric 17950b57cec5SDimitry Andric // Make sure we emit a debug reference to the global variable. 17960b57cec5SDimitry Andric // This should probably fire even for 17970b57cec5SDimitry Andric if (isa<VarDecl>(value)) { 17980b57cec5SDimitry Andric if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value))) 17990b57cec5SDimitry Andric EmitDeclRefExprDbgValue(refExpr, result.Val); 18000b57cec5SDimitry Andric } else { 18010b57cec5SDimitry Andric assert(isa<EnumConstantDecl>(value)); 18020b57cec5SDimitry Andric EmitDeclRefExprDbgValue(refExpr, result.Val); 18030b57cec5SDimitry Andric } 18040b57cec5SDimitry Andric 18050b57cec5SDimitry Andric // If we emitted a reference constant, we need to dereference that. 18060b57cec5SDimitry Andric if (resultIsReference) 18070b57cec5SDimitry Andric return ConstantEmission::forReference(C); 18080b57cec5SDimitry Andric 18090b57cec5SDimitry Andric return ConstantEmission::forValue(C); 18100b57cec5SDimitry Andric } 18110b57cec5SDimitry Andric 18120b57cec5SDimitry Andric static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF, 18130b57cec5SDimitry Andric const MemberExpr *ME) { 18140b57cec5SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) { 18150b57cec5SDimitry Andric // Try to emit static variable member expressions as DREs. 18160b57cec5SDimitry Andric return DeclRefExpr::Create( 18170b57cec5SDimitry Andric CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD, 18180b57cec5SDimitry Andric /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(), 18190b57cec5SDimitry Andric ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse()); 18200b57cec5SDimitry Andric } 18210b57cec5SDimitry Andric return nullptr; 18220b57cec5SDimitry Andric } 18230b57cec5SDimitry Andric 18240b57cec5SDimitry Andric CodeGenFunction::ConstantEmission 18250b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) { 18260b57cec5SDimitry Andric if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME)) 18270b57cec5SDimitry Andric return tryEmitAsConstant(DRE); 18280b57cec5SDimitry Andric return ConstantEmission(); 18290b57cec5SDimitry Andric } 18300b57cec5SDimitry Andric 18310b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitScalarConstant( 18320b57cec5SDimitry Andric const CodeGenFunction::ConstantEmission &Constant, Expr *E) { 18330b57cec5SDimitry Andric assert(Constant && "not a constant"); 18340b57cec5SDimitry Andric if (Constant.isReference()) 18350b57cec5SDimitry Andric return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E), 18360b57cec5SDimitry Andric E->getExprLoc()) 18370b57cec5SDimitry Andric .getScalarVal(); 18380b57cec5SDimitry Andric return Constant.getValue(); 18390b57cec5SDimitry Andric } 18400b57cec5SDimitry Andric 18410b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue, 18420b57cec5SDimitry Andric SourceLocation Loc) { 18430fca6ea1SDimitry Andric return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(), 18440b57cec5SDimitry Andric lvalue.getType(), Loc, lvalue.getBaseInfo(), 18450b57cec5SDimitry Andric lvalue.getTBAAInfo(), lvalue.isNontemporal()); 18460b57cec5SDimitry Andric } 18470b57cec5SDimitry Andric 18480b57cec5SDimitry Andric static bool hasBooleanRepresentation(QualType Ty) { 18490b57cec5SDimitry Andric if (Ty->isBooleanType()) 18500b57cec5SDimitry Andric return true; 18510b57cec5SDimitry Andric 18520b57cec5SDimitry Andric if (const EnumType *ET = Ty->getAs<EnumType>()) 18530b57cec5SDimitry Andric return ET->getDecl()->getIntegerType()->isBooleanType(); 18540b57cec5SDimitry Andric 18550b57cec5SDimitry Andric if (const AtomicType *AT = Ty->getAs<AtomicType>()) 18560b57cec5SDimitry Andric return hasBooleanRepresentation(AT->getValueType()); 18570b57cec5SDimitry Andric 18580b57cec5SDimitry Andric return false; 18590b57cec5SDimitry Andric } 18600b57cec5SDimitry Andric 18610b57cec5SDimitry Andric static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, 18620b57cec5SDimitry Andric llvm::APInt &Min, llvm::APInt &End, 18630b57cec5SDimitry Andric bool StrictEnums, bool IsBool) { 18640b57cec5SDimitry Andric const EnumType *ET = Ty->getAs<EnumType>(); 18650b57cec5SDimitry Andric bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums && 18660b57cec5SDimitry Andric ET && !ET->getDecl()->isFixed(); 18670b57cec5SDimitry Andric if (!IsBool && !IsRegularCPlusPlusEnum) 18680b57cec5SDimitry Andric return false; 18690b57cec5SDimitry Andric 18700b57cec5SDimitry Andric if (IsBool) { 18710b57cec5SDimitry Andric Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0); 18720b57cec5SDimitry Andric End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2); 18730b57cec5SDimitry Andric } else { 18740b57cec5SDimitry Andric const EnumDecl *ED = ET->getDecl(); 1875bdd1243dSDimitry Andric ED->getValueRange(End, Min); 18760b57cec5SDimitry Andric } 18770b57cec5SDimitry Andric return true; 18780b57cec5SDimitry Andric } 18790b57cec5SDimitry Andric 18800b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) { 18810b57cec5SDimitry Andric llvm::APInt Min, End; 18820b57cec5SDimitry Andric if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums, 18830b57cec5SDimitry Andric hasBooleanRepresentation(Ty))) 18840b57cec5SDimitry Andric return nullptr; 18850b57cec5SDimitry Andric 18860b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext()); 18870b57cec5SDimitry Andric return MDHelper.createRange(Min, End); 18880b57cec5SDimitry Andric } 18890b57cec5SDimitry Andric 18900b57cec5SDimitry Andric bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, 18910b57cec5SDimitry Andric SourceLocation Loc) { 18920b57cec5SDimitry Andric bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool); 18930b57cec5SDimitry Andric bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum); 18940b57cec5SDimitry Andric if (!HasBoolCheck && !HasEnumCheck) 18950b57cec5SDimitry Andric return false; 18960b57cec5SDimitry Andric 18970b57cec5SDimitry Andric bool IsBool = hasBooleanRepresentation(Ty) || 18980b57cec5SDimitry Andric NSAPI(CGM.getContext()).isObjCBOOLType(Ty); 18990b57cec5SDimitry Andric bool NeedsBoolCheck = HasBoolCheck && IsBool; 19000b57cec5SDimitry Andric bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>(); 19010b57cec5SDimitry Andric if (!NeedsBoolCheck && !NeedsEnumCheck) 19020b57cec5SDimitry Andric return false; 19030b57cec5SDimitry Andric 19040b57cec5SDimitry Andric // Single-bit booleans don't need to be checked. Special-case this to avoid 19050b57cec5SDimitry Andric // a bit width mismatch when handling bitfield values. This is handled by 19060b57cec5SDimitry Andric // EmitFromMemory for the non-bitfield case. 19070b57cec5SDimitry Andric if (IsBool && 19080b57cec5SDimitry Andric cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1) 19090b57cec5SDimitry Andric return false; 19100b57cec5SDimitry Andric 19110b57cec5SDimitry Andric llvm::APInt Min, End; 19120b57cec5SDimitry Andric if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool)) 19130b57cec5SDimitry Andric return true; 19140b57cec5SDimitry Andric 19150b57cec5SDimitry Andric auto &Ctx = getLLVMContext(); 19160b57cec5SDimitry Andric SanitizerScope SanScope(this); 19170b57cec5SDimitry Andric llvm::Value *Check; 19180b57cec5SDimitry Andric --End; 19190b57cec5SDimitry Andric if (!Min) { 19200b57cec5SDimitry Andric Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End)); 19210b57cec5SDimitry Andric } else { 19220b57cec5SDimitry Andric llvm::Value *Upper = 19230b57cec5SDimitry Andric Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End)); 19240b57cec5SDimitry Andric llvm::Value *Lower = 19250b57cec5SDimitry Andric Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min)); 19260b57cec5SDimitry Andric Check = Builder.CreateAnd(Upper, Lower); 19270b57cec5SDimitry Andric } 19280b57cec5SDimitry Andric llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc), 19290b57cec5SDimitry Andric EmitCheckTypeDescriptor(Ty)}; 19300b57cec5SDimitry Andric SanitizerMask Kind = 19310b57cec5SDimitry Andric NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool; 19320b57cec5SDimitry Andric EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue, 19330b57cec5SDimitry Andric StaticArgs, EmitCheckValue(Value)); 19340b57cec5SDimitry Andric return true; 19350b57cec5SDimitry Andric } 19360b57cec5SDimitry Andric 19370b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile, 19380b57cec5SDimitry Andric QualType Ty, 19390b57cec5SDimitry Andric SourceLocation Loc, 19400b57cec5SDimitry Andric LValueBaseInfo BaseInfo, 19410b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo, 19420b57cec5SDimitry Andric bool isNontemporal) { 19430fca6ea1SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer())) 1944bdd1243dSDimitry Andric if (GV->isThreadLocal()) 194506c3fb27SDimitry Andric Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV), 194606c3fb27SDimitry Andric NotKnownNonNull); 1947bdd1243dSDimitry Andric 194881ad6265SDimitry Andric if (const auto *ClangVecTy = Ty->getAs<VectorType>()) { 194981ad6265SDimitry Andric // Boolean vectors use `iN` as storage type. 195081ad6265SDimitry Andric if (ClangVecTy->isExtVectorBoolType()) { 195181ad6265SDimitry Andric llvm::Type *ValTy = ConvertType(Ty); 195281ad6265SDimitry Andric unsigned ValNumElems = 195381ad6265SDimitry Andric cast<llvm::FixedVectorType>(ValTy)->getNumElements(); 195481ad6265SDimitry Andric // Load the `iP` storage object (P is the padded vector size). 195581ad6265SDimitry Andric auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits"); 195681ad6265SDimitry Andric const auto *RawIntTy = RawIntV->getType(); 195781ad6265SDimitry Andric assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors"); 195881ad6265SDimitry Andric // Bitcast iP --> <P x i1>. 195981ad6265SDimitry Andric auto *PaddedVecTy = llvm::FixedVectorType::get( 196081ad6265SDimitry Andric Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits()); 196181ad6265SDimitry Andric llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy); 196281ad6265SDimitry Andric // Shuffle <P x i1> --> <N x i1> (N is the actual bit size). 196381ad6265SDimitry Andric V = emitBoolVecConversion(V, ValNumElems, "extractvec"); 19640b57cec5SDimitry Andric 196581ad6265SDimitry Andric return EmitFromMemory(V, Ty); 196681ad6265SDimitry Andric } 19670b57cec5SDimitry Andric 19680b57cec5SDimitry Andric // Handle vectors of size 3 like size 4 for better performance. 196981ad6265SDimitry Andric const llvm::Type *EltTy = Addr.getElementType(); 197081ad6265SDimitry Andric const auto *VTy = cast<llvm::FixedVectorType>(EltTy); 197181ad6265SDimitry Andric 197281ad6265SDimitry Andric if (!CGM.getCodeGenOpts().PreserveVec3Type && VTy->getNumElements() == 3) { 19730b57cec5SDimitry Andric 197481ad6265SDimitry Andric llvm::VectorType *vec4Ty = 197581ad6265SDimitry Andric llvm::FixedVectorType::get(VTy->getElementType(), 4); 197606c3fb27SDimitry Andric Address Cast = Addr.withElementType(vec4Ty); 19770b57cec5SDimitry Andric // Now load value. 19780b57cec5SDimitry Andric llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4"); 19790b57cec5SDimitry Andric 19800b57cec5SDimitry Andric // Shuffle vector to get vec3. 198181ad6265SDimitry Andric V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2}, "extractVec"); 19820b57cec5SDimitry Andric return EmitFromMemory(V, Ty); 19830b57cec5SDimitry Andric } 19840b57cec5SDimitry Andric } 19850b57cec5SDimitry Andric 19860b57cec5SDimitry Andric // Atomic operations have to be done on integral types. 19870b57cec5SDimitry Andric LValue AtomicLValue = 19880b57cec5SDimitry Andric LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo); 19890b57cec5SDimitry Andric if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) { 19900b57cec5SDimitry Andric return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal(); 19910b57cec5SDimitry Andric } 19920b57cec5SDimitry Andric 19930fca6ea1SDimitry Andric Addr = 19940fca6ea1SDimitry Andric Addr.withElementType(convertTypeForLoadStore(Ty, Addr.getElementType())); 19950fca6ea1SDimitry Andric 19960b57cec5SDimitry Andric llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile); 19970b57cec5SDimitry Andric if (isNontemporal) { 19980b57cec5SDimitry Andric llvm::MDNode *Node = llvm::MDNode::get( 19990b57cec5SDimitry Andric Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 200006c3fb27SDimitry Andric Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node); 20010b57cec5SDimitry Andric } 20020b57cec5SDimitry Andric 20030b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Load, TBAAInfo); 20040b57cec5SDimitry Andric 20050b57cec5SDimitry Andric if (EmitScalarRangeCheck(Load, Ty, Loc)) { 20060b57cec5SDimitry Andric // In order to prevent the optimizer from throwing away the check, don't 20070b57cec5SDimitry Andric // attach range metadata to the load. 20080b57cec5SDimitry Andric } else if (CGM.getCodeGenOpts().OptimizationLevel > 0) 2009bdd1243dSDimitry Andric if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) { 20100b57cec5SDimitry Andric Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo); 2011bdd1243dSDimitry Andric Load->setMetadata(llvm::LLVMContext::MD_noundef, 2012bdd1243dSDimitry Andric llvm::MDNode::get(getLLVMContext(), std::nullopt)); 2013bdd1243dSDimitry Andric } 20140b57cec5SDimitry Andric 20150b57cec5SDimitry Andric return EmitFromMemory(Load, Ty); 20160b57cec5SDimitry Andric } 20170b57cec5SDimitry Andric 20180fca6ea1SDimitry Andric /// Converts a scalar value from its primary IR type (as returned 20190fca6ea1SDimitry Andric /// by ConvertType) to its load/store type (as returned by 20200fca6ea1SDimitry Andric /// convertTypeForLoadStore). 20210b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) { 20220fca6ea1SDimitry Andric if (hasBooleanRepresentation(Ty) || Ty->isBitIntType()) { 20230fca6ea1SDimitry Andric llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType()); 20240fca6ea1SDimitry Andric bool Signed = Ty->isSignedIntegerOrEnumerationType(); 20250fca6ea1SDimitry Andric return Builder.CreateIntCast(Value, StoreTy, Signed, "storedv"); 20260fca6ea1SDimitry Andric } 20270fca6ea1SDimitry Andric 20280fca6ea1SDimitry Andric if (Ty->isExtVectorBoolType()) { 20290fca6ea1SDimitry Andric llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType()); 20300fca6ea1SDimitry Andric // Expand to the memory bit width. 20310fca6ea1SDimitry Andric unsigned MemNumElems = StoreTy->getPrimitiveSizeInBits(); 20320fca6ea1SDimitry Andric // <N x i1> --> <P x i1>. 20330fca6ea1SDimitry Andric Value = emitBoolVecConversion(Value, MemNumElems, "insertvec"); 20340fca6ea1SDimitry Andric // <P x i1> --> iP. 20350fca6ea1SDimitry Andric Value = Builder.CreateBitCast(Value, StoreTy); 20360b57cec5SDimitry Andric } 20370b57cec5SDimitry Andric 20380b57cec5SDimitry Andric return Value; 20390b57cec5SDimitry Andric } 20400b57cec5SDimitry Andric 20410fca6ea1SDimitry Andric /// Converts a scalar value from its load/store type (as returned 20420fca6ea1SDimitry Andric /// by convertTypeForLoadStore) to its primary IR type (as returned 20430fca6ea1SDimitry Andric /// by ConvertType). 20440b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) { 204581ad6265SDimitry Andric if (Ty->isExtVectorBoolType()) { 204681ad6265SDimitry Andric const auto *RawIntTy = Value->getType(); 204781ad6265SDimitry Andric // Bitcast iP --> <P x i1>. 204881ad6265SDimitry Andric auto *PaddedVecTy = llvm::FixedVectorType::get( 204981ad6265SDimitry Andric Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits()); 205081ad6265SDimitry Andric auto *V = Builder.CreateBitCast(Value, PaddedVecTy); 205181ad6265SDimitry Andric // Shuffle <P x i1> --> <N x i1> (N is the actual bit size). 205281ad6265SDimitry Andric llvm::Type *ValTy = ConvertType(Ty); 205381ad6265SDimitry Andric unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements(); 205481ad6265SDimitry Andric return emitBoolVecConversion(V, ValNumElems, "extractvec"); 205581ad6265SDimitry Andric } 20560b57cec5SDimitry Andric 20570fca6ea1SDimitry Andric if (hasBooleanRepresentation(Ty) || Ty->isBitIntType()) { 20580fca6ea1SDimitry Andric llvm::Type *ResTy = ConvertType(Ty); 20590fca6ea1SDimitry Andric return Builder.CreateTrunc(Value, ResTy, "loadedv"); 20600fca6ea1SDimitry Andric } 20610fca6ea1SDimitry Andric 20620b57cec5SDimitry Andric return Value; 20630b57cec5SDimitry Andric } 20640b57cec5SDimitry Andric 20655ffd83dbSDimitry Andric // Convert the pointer of \p Addr to a pointer to a vector (the value type of 20665ffd83dbSDimitry Andric // MatrixType), if it points to a array (the memory type of MatrixType). 20670fca6ea1SDimitry Andric static RawAddress MaybeConvertMatrixAddress(RawAddress Addr, 20680fca6ea1SDimitry Andric CodeGenFunction &CGF, 20695ffd83dbSDimitry Andric bool IsVector = true) { 20700eae32dcSDimitry Andric auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType()); 20715ffd83dbSDimitry Andric if (ArrayTy && IsVector) { 20725ffd83dbSDimitry Andric auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(), 20735ffd83dbSDimitry Andric ArrayTy->getNumElements()); 20745ffd83dbSDimitry Andric 207506c3fb27SDimitry Andric return Addr.withElementType(VectorTy); 20765ffd83dbSDimitry Andric } 20770eae32dcSDimitry Andric auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType()); 20785ffd83dbSDimitry Andric if (VectorTy && !IsVector) { 2079e8d8bef9SDimitry Andric auto *ArrayTy = llvm::ArrayType::get( 2080e8d8bef9SDimitry Andric VectorTy->getElementType(), 2081e8d8bef9SDimitry Andric cast<llvm::FixedVectorType>(VectorTy)->getNumElements()); 20825ffd83dbSDimitry Andric 208306c3fb27SDimitry Andric return Addr.withElementType(ArrayTy); 20845ffd83dbSDimitry Andric } 20855ffd83dbSDimitry Andric 20865ffd83dbSDimitry Andric return Addr; 20875ffd83dbSDimitry Andric } 20885ffd83dbSDimitry Andric 20895ffd83dbSDimitry Andric // Emit a store of a matrix LValue. This may require casting the original 20905ffd83dbSDimitry Andric // pointer to memory address (ArrayType) to a pointer to the value type 20915ffd83dbSDimitry Andric // (VectorType). 20925ffd83dbSDimitry Andric static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, 20935ffd83dbSDimitry Andric bool isInit, CodeGenFunction &CGF) { 20940fca6ea1SDimitry Andric Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(), CGF, 20955ffd83dbSDimitry Andric value->getType()->isVectorTy()); 20965ffd83dbSDimitry Andric CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(), 20975ffd83dbSDimitry Andric lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit, 20985ffd83dbSDimitry Andric lvalue.isNontemporal()); 20995ffd83dbSDimitry Andric } 21005ffd83dbSDimitry Andric 21010b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr, 21020b57cec5SDimitry Andric bool Volatile, QualType Ty, 21030b57cec5SDimitry Andric LValueBaseInfo BaseInfo, 21040b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo, 21050b57cec5SDimitry Andric bool isInit, bool isNontemporal) { 21060fca6ea1SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer())) 2107bdd1243dSDimitry Andric if (GV->isThreadLocal()) 210806c3fb27SDimitry Andric Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV), 210906c3fb27SDimitry Andric NotKnownNonNull); 2110bdd1243dSDimitry Andric 21110b57cec5SDimitry Andric llvm::Type *SrcTy = Value->getType(); 211281ad6265SDimitry Andric if (const auto *ClangVecTy = Ty->getAs<VectorType>()) { 211381ad6265SDimitry Andric auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy); 21140fca6ea1SDimitry Andric if (!CGM.getCodeGenOpts().PreserveVec3Type) { 21150b57cec5SDimitry Andric // Handle vec3 special. 21160fca6ea1SDimitry Andric if (VecTy && !ClangVecTy->isExtVectorBoolType() && 21170fca6ea1SDimitry Andric cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) { 21180b57cec5SDimitry Andric // Our source is a vec3, do a shuffle vector to make it a vec4. 2119e8d8bef9SDimitry Andric Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1}, 21205ffd83dbSDimitry Andric "extractVec"); 21215ffd83dbSDimitry Andric SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4); 21220b57cec5SDimitry Andric } 21230b57cec5SDimitry Andric if (Addr.getElementType() != SrcTy) { 212406c3fb27SDimitry Andric Addr = Addr.withElementType(SrcTy); 21250b57cec5SDimitry Andric } 21260b57cec5SDimitry Andric } 21270b57cec5SDimitry Andric } 21280b57cec5SDimitry Andric 21290b57cec5SDimitry Andric Value = EmitToMemory(Value, Ty); 21300b57cec5SDimitry Andric 21310b57cec5SDimitry Andric LValue AtomicLValue = 21320b57cec5SDimitry Andric LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo); 21330b57cec5SDimitry Andric if (Ty->isAtomicType() || 21340b57cec5SDimitry Andric (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) { 21350b57cec5SDimitry Andric EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit); 21360b57cec5SDimitry Andric return; 21370b57cec5SDimitry Andric } 21380b57cec5SDimitry Andric 21390b57cec5SDimitry Andric llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile); 21400b57cec5SDimitry Andric if (isNontemporal) { 21410b57cec5SDimitry Andric llvm::MDNode *Node = 21420b57cec5SDimitry Andric llvm::MDNode::get(Store->getContext(), 21430b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(1))); 214406c3fb27SDimitry Andric Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node); 21450b57cec5SDimitry Andric } 21460b57cec5SDimitry Andric 21470b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Store, TBAAInfo); 21480b57cec5SDimitry Andric } 21490b57cec5SDimitry Andric 21500b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue, 21510b57cec5SDimitry Andric bool isInit) { 21525ffd83dbSDimitry Andric if (lvalue.getType()->isConstantMatrixType()) { 21535ffd83dbSDimitry Andric EmitStoreOfMatrixScalar(value, lvalue, isInit, *this); 21545ffd83dbSDimitry Andric return; 21555ffd83dbSDimitry Andric } 21565ffd83dbSDimitry Andric 21570fca6ea1SDimitry Andric EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(), 21580b57cec5SDimitry Andric lvalue.getType(), lvalue.getBaseInfo(), 21590b57cec5SDimitry Andric lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal()); 21600b57cec5SDimitry Andric } 21610b57cec5SDimitry Andric 21625ffd83dbSDimitry Andric // Emit a load of a LValue of matrix type. This may require casting the pointer 21635ffd83dbSDimitry Andric // to memory address (ArrayType) to a pointer to the value type (VectorType). 21645ffd83dbSDimitry Andric static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, 21655ffd83dbSDimitry Andric CodeGenFunction &CGF) { 21665ffd83dbSDimitry Andric assert(LV.getType()->isConstantMatrixType()); 21670fca6ea1SDimitry Andric Address Addr = MaybeConvertMatrixAddress(LV.getAddress(), CGF); 21685ffd83dbSDimitry Andric LV.setAddress(Addr); 21695ffd83dbSDimitry Andric return RValue::get(CGF.EmitLoadOfScalar(LV, Loc)); 21705ffd83dbSDimitry Andric } 21715ffd83dbSDimitry Andric 21720fca6ea1SDimitry Andric RValue CodeGenFunction::EmitLoadOfAnyValue(LValue LV, AggValueSlot Slot, 21730fca6ea1SDimitry Andric SourceLocation Loc) { 21740fca6ea1SDimitry Andric QualType Ty = LV.getType(); 21750fca6ea1SDimitry Andric switch (getEvaluationKind(Ty)) { 21760fca6ea1SDimitry Andric case TEK_Scalar: 21770fca6ea1SDimitry Andric return EmitLoadOfLValue(LV, Loc); 21780fca6ea1SDimitry Andric case TEK_Complex: 21790fca6ea1SDimitry Andric return RValue::getComplex(EmitLoadOfComplex(LV, Loc)); 21800fca6ea1SDimitry Andric case TEK_Aggregate: 21810fca6ea1SDimitry Andric EmitAggFinalDestCopy(Ty, Slot, LV, EVK_NonRValue); 21820fca6ea1SDimitry Andric return Slot.asRValue(); 21830fca6ea1SDimitry Andric } 21840fca6ea1SDimitry Andric llvm_unreachable("bad evaluation kind"); 21850fca6ea1SDimitry Andric } 21860fca6ea1SDimitry Andric 21870b57cec5SDimitry Andric /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this 21880b57cec5SDimitry Andric /// method emits the address of the lvalue, then loads the result as an rvalue, 21890b57cec5SDimitry Andric /// returning the rvalue. 21900b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) { 21910b57cec5SDimitry Andric if (LV.isObjCWeak()) { 21920b57cec5SDimitry Andric // load of a __weak object. 21930fca6ea1SDimitry Andric Address AddrWeakObj = LV.getAddress(); 21940b57cec5SDimitry Andric return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this, 21950b57cec5SDimitry Andric AddrWeakObj)); 21960b57cec5SDimitry Andric } 21970b57cec5SDimitry Andric if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) { 21980b57cec5SDimitry Andric // In MRC mode, we do a load+autorelease. 21990b57cec5SDimitry Andric if (!getLangOpts().ObjCAutoRefCount) { 22000fca6ea1SDimitry Andric return RValue::get(EmitARCLoadWeak(LV.getAddress())); 22010b57cec5SDimitry Andric } 22020b57cec5SDimitry Andric 22030b57cec5SDimitry Andric // In ARC mode, we load retained and then consume the value. 22040fca6ea1SDimitry Andric llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress()); 22050b57cec5SDimitry Andric Object = EmitObjCConsumeObject(LV.getType(), Object); 22060b57cec5SDimitry Andric return RValue::get(Object); 22070b57cec5SDimitry Andric } 22080b57cec5SDimitry Andric 22090b57cec5SDimitry Andric if (LV.isSimple()) { 22100b57cec5SDimitry Andric assert(!LV.getType()->isFunctionType()); 22110b57cec5SDimitry Andric 22125ffd83dbSDimitry Andric if (LV.getType()->isConstantMatrixType()) 22135ffd83dbSDimitry Andric return EmitLoadOfMatrixLValue(LV, Loc, *this); 22145ffd83dbSDimitry Andric 22150b57cec5SDimitry Andric // Everything needs a load. 22160b57cec5SDimitry Andric return RValue::get(EmitLoadOfScalar(LV, Loc)); 22170b57cec5SDimitry Andric } 22180b57cec5SDimitry Andric 22190b57cec5SDimitry Andric if (LV.isVectorElt()) { 22200b57cec5SDimitry Andric llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(), 22210b57cec5SDimitry Andric LV.isVolatileQualified()); 22220b57cec5SDimitry Andric return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(), 22230b57cec5SDimitry Andric "vecext")); 22240b57cec5SDimitry Andric } 22250b57cec5SDimitry Andric 22260b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, either 22270b57cec5SDimitry Andric // shuffle the input or extract/insert them as appropriate. 22285ffd83dbSDimitry Andric if (LV.isExtVectorElt()) { 22290b57cec5SDimitry Andric return EmitLoadOfExtVectorElementLValue(LV); 22305ffd83dbSDimitry Andric } 22310b57cec5SDimitry Andric 22320b57cec5SDimitry Andric // Global Register variables always invoke intrinsics 22330b57cec5SDimitry Andric if (LV.isGlobalReg()) 22340b57cec5SDimitry Andric return EmitLoadOfGlobalRegLValue(LV); 22350b57cec5SDimitry Andric 22365ffd83dbSDimitry Andric if (LV.isMatrixElt()) { 2237349cc55cSDimitry Andric llvm::Value *Idx = LV.getMatrixIdx(); 2238349cc55cSDimitry Andric if (CGM.getCodeGenOpts().OptimizationLevel > 0) { 223904eeddc0SDimitry Andric const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>(); 224081ad6265SDimitry Andric llvm::MatrixBuilder MB(Builder); 2241349cc55cSDimitry Andric MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened()); 2242349cc55cSDimitry Andric } 22435ffd83dbSDimitry Andric llvm::LoadInst *Load = 22445ffd83dbSDimitry Andric Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified()); 2245349cc55cSDimitry Andric return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext")); 22465ffd83dbSDimitry Andric } 22475ffd83dbSDimitry Andric 22480b57cec5SDimitry Andric assert(LV.isBitField() && "Unknown LValue type!"); 22490b57cec5SDimitry Andric return EmitLoadOfBitfieldLValue(LV, Loc); 22500b57cec5SDimitry Andric } 22510b57cec5SDimitry Andric 22520b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV, 22530b57cec5SDimitry Andric SourceLocation Loc) { 22540b57cec5SDimitry Andric const CGBitFieldInfo &Info = LV.getBitFieldInfo(); 22550b57cec5SDimitry Andric 22560b57cec5SDimitry Andric // Get the output type. 22570b57cec5SDimitry Andric llvm::Type *ResLTy = ConvertType(LV.getType()); 22580b57cec5SDimitry Andric 22590b57cec5SDimitry Andric Address Ptr = LV.getBitFieldAddress(); 2260e8d8bef9SDimitry Andric llvm::Value *Val = 2261e8d8bef9SDimitry Andric Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load"); 22620b57cec5SDimitry Andric 2263e8d8bef9SDimitry Andric bool UseVolatile = LV.isVolatileQualified() && 2264e8d8bef9SDimitry Andric Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget()); 2265e8d8bef9SDimitry Andric const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset; 2266e8d8bef9SDimitry Andric const unsigned StorageSize = 2267e8d8bef9SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize; 22680b57cec5SDimitry Andric if (Info.IsSigned) { 2269e8d8bef9SDimitry Andric assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize); 2270e8d8bef9SDimitry Andric unsigned HighBits = StorageSize - Offset - Info.Size; 22710b57cec5SDimitry Andric if (HighBits) 22720b57cec5SDimitry Andric Val = Builder.CreateShl(Val, HighBits, "bf.shl"); 2273e8d8bef9SDimitry Andric if (Offset + HighBits) 2274e8d8bef9SDimitry Andric Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr"); 22750b57cec5SDimitry Andric } else { 2276e8d8bef9SDimitry Andric if (Offset) 2277e8d8bef9SDimitry Andric Val = Builder.CreateLShr(Val, Offset, "bf.lshr"); 2278e8d8bef9SDimitry Andric if (static_cast<unsigned>(Offset) + Info.Size < StorageSize) 2279e8d8bef9SDimitry Andric Val = Builder.CreateAnd( 2280e8d8bef9SDimitry Andric Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear"); 22810b57cec5SDimitry Andric } 22820b57cec5SDimitry Andric Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast"); 22830b57cec5SDimitry Andric EmitScalarRangeCheck(Val, LV.getType(), Loc); 22840b57cec5SDimitry Andric return RValue::get(Val); 22850b57cec5SDimitry Andric } 22860b57cec5SDimitry Andric 22870b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, create an 22880b57cec5SDimitry Andric // appropriate shufflevector. 22890b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) { 22900b57cec5SDimitry Andric llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(), 22910b57cec5SDimitry Andric LV.isVolatileQualified()); 22920b57cec5SDimitry Andric 22935f757f3fSDimitry Andric // HLSL allows treating scalars as one-element vectors. Converting the scalar 22945f757f3fSDimitry Andric // IR value to a vector here allows the rest of codegen to behave as normal. 22955f757f3fSDimitry Andric if (getLangOpts().HLSL && !Vec->getType()->isVectorTy()) { 22965f757f3fSDimitry Andric llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1); 22975f757f3fSDimitry Andric llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty); 22985f757f3fSDimitry Andric Vec = Builder.CreateInsertElement(DstTy, Vec, Zero, "cast.splat"); 22995f757f3fSDimitry Andric } 23005f757f3fSDimitry Andric 23010b57cec5SDimitry Andric const llvm::Constant *Elts = LV.getExtVectorElts(); 23020b57cec5SDimitry Andric 23030b57cec5SDimitry Andric // If the result of the expression is a non-vector type, we must be extracting 23040b57cec5SDimitry Andric // a single element. Just codegen as an extractelement. 23050b57cec5SDimitry Andric const VectorType *ExprVT = LV.getType()->getAs<VectorType>(); 23060b57cec5SDimitry Andric if (!ExprVT) { 23070b57cec5SDimitry Andric unsigned InIdx = getAccessedFieldNo(0, Elts); 23080b57cec5SDimitry Andric llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 23090b57cec5SDimitry Andric return RValue::get(Builder.CreateExtractElement(Vec, Elt)); 23100b57cec5SDimitry Andric } 23110b57cec5SDimitry Andric 23120b57cec5SDimitry Andric // Always use shuffle vector to try to retain the original program structure 23130b57cec5SDimitry Andric unsigned NumResultElts = ExprVT->getNumElements(); 23140b57cec5SDimitry Andric 23155ffd83dbSDimitry Andric SmallVector<int, 4> Mask; 23160b57cec5SDimitry Andric for (unsigned i = 0; i != NumResultElts; ++i) 23175ffd83dbSDimitry Andric Mask.push_back(getAccessedFieldNo(i, Elts)); 23180b57cec5SDimitry Andric 2319e8d8bef9SDimitry Andric Vec = Builder.CreateShuffleVector(Vec, Mask); 23200b57cec5SDimitry Andric return RValue::get(Vec); 23210b57cec5SDimitry Andric } 23220b57cec5SDimitry Andric 23230b57cec5SDimitry Andric /// Generates lvalue for partial ext_vector access. 23240b57cec5SDimitry Andric Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) { 23250b57cec5SDimitry Andric Address VectorAddress = LV.getExtVectorAddress(); 2326480093f4SDimitry Andric QualType EQT = LV.getType()->castAs<VectorType>()->getElementType(); 23270b57cec5SDimitry Andric llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT); 23280b57cec5SDimitry Andric 232906c3fb27SDimitry Andric Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy); 23300b57cec5SDimitry Andric 23310b57cec5SDimitry Andric const llvm::Constant *Elts = LV.getExtVectorElts(); 23320b57cec5SDimitry Andric unsigned ix = getAccessedFieldNo(0, Elts); 23330b57cec5SDimitry Andric 23340b57cec5SDimitry Andric Address VectorBasePtrPlusIx = 23350b57cec5SDimitry Andric Builder.CreateConstInBoundsGEP(CastToPointerElement, ix, 23360b57cec5SDimitry Andric "vector.elt"); 23370b57cec5SDimitry Andric 23380b57cec5SDimitry Andric return VectorBasePtrPlusIx; 23390b57cec5SDimitry Andric } 23400b57cec5SDimitry Andric 23410b57cec5SDimitry Andric /// Load of global gamed gegisters are always calls to intrinsics. 23420b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) { 23430b57cec5SDimitry Andric assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) && 23440b57cec5SDimitry Andric "Bad type for register variable"); 23450b57cec5SDimitry Andric llvm::MDNode *RegName = cast<llvm::MDNode>( 23460b57cec5SDimitry Andric cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata()); 23470b57cec5SDimitry Andric 23480b57cec5SDimitry Andric // We accept integer and pointer types only 23490b57cec5SDimitry Andric llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType()); 23500b57cec5SDimitry Andric llvm::Type *Ty = OrigTy; 23510b57cec5SDimitry Andric if (OrigTy->isPointerTy()) 23520b57cec5SDimitry Andric Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 23530b57cec5SDimitry Andric llvm::Type *Types[] = { Ty }; 23540b57cec5SDimitry Andric 23550b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types); 23560b57cec5SDimitry Andric llvm::Value *Call = Builder.CreateCall( 23570b57cec5SDimitry Andric F, llvm::MetadataAsValue::get(Ty->getContext(), RegName)); 23580b57cec5SDimitry Andric if (OrigTy->isPointerTy()) 23590b57cec5SDimitry Andric Call = Builder.CreateIntToPtr(Call, OrigTy); 23600b57cec5SDimitry Andric return RValue::get(Call); 23610b57cec5SDimitry Andric } 23620b57cec5SDimitry Andric 23630b57cec5SDimitry Andric /// EmitStoreThroughLValue - Store the specified rvalue into the specified 23640b57cec5SDimitry Andric /// lvalue, where both are guaranteed to the have the same type, and that type 23650b57cec5SDimitry Andric /// is 'Ty'. 23660b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, 23670b57cec5SDimitry Andric bool isInit) { 23680b57cec5SDimitry Andric if (!Dst.isSimple()) { 23690b57cec5SDimitry Andric if (Dst.isVectorElt()) { 23700b57cec5SDimitry Andric // Read/modify/write the vector, inserting the new element. 23710b57cec5SDimitry Andric llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(), 23720b57cec5SDimitry Andric Dst.isVolatileQualified()); 237381ad6265SDimitry Andric auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType()); 237481ad6265SDimitry Andric if (IRStoreTy) { 237581ad6265SDimitry Andric auto *IRVecTy = llvm::FixedVectorType::get( 237681ad6265SDimitry Andric Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits()); 237781ad6265SDimitry Andric Vec = Builder.CreateBitCast(Vec, IRVecTy); 237881ad6265SDimitry Andric // iN --> <N x i1>. 237981ad6265SDimitry Andric } 23800b57cec5SDimitry Andric Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(), 23810b57cec5SDimitry Andric Dst.getVectorIdx(), "vecins"); 238281ad6265SDimitry Andric if (IRStoreTy) { 238381ad6265SDimitry Andric // <N x i1> --> <iN>. 238481ad6265SDimitry Andric Vec = Builder.CreateBitCast(Vec, IRStoreTy); 238581ad6265SDimitry Andric } 23860b57cec5SDimitry Andric Builder.CreateStore(Vec, Dst.getVectorAddress(), 23870b57cec5SDimitry Andric Dst.isVolatileQualified()); 23880b57cec5SDimitry Andric return; 23890b57cec5SDimitry Andric } 23900b57cec5SDimitry Andric 23910b57cec5SDimitry Andric // If this is an update of extended vector elements, insert them as 23920b57cec5SDimitry Andric // appropriate. 23930b57cec5SDimitry Andric if (Dst.isExtVectorElt()) 23940b57cec5SDimitry Andric return EmitStoreThroughExtVectorComponentLValue(Src, Dst); 23950b57cec5SDimitry Andric 23960b57cec5SDimitry Andric if (Dst.isGlobalReg()) 23970b57cec5SDimitry Andric return EmitStoreThroughGlobalRegLValue(Src, Dst); 23980b57cec5SDimitry Andric 23995ffd83dbSDimitry Andric if (Dst.isMatrixElt()) { 2400349cc55cSDimitry Andric llvm::Value *Idx = Dst.getMatrixIdx(); 2401349cc55cSDimitry Andric if (CGM.getCodeGenOpts().OptimizationLevel > 0) { 240204eeddc0SDimitry Andric const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>(); 240381ad6265SDimitry Andric llvm::MatrixBuilder MB(Builder); 2404349cc55cSDimitry Andric MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened()); 2405349cc55cSDimitry Andric } 2406349cc55cSDimitry Andric llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress()); 2407349cc55cSDimitry Andric llvm::Value *Vec = 2408349cc55cSDimitry Andric Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins"); 24095ffd83dbSDimitry Andric Builder.CreateStore(Vec, Dst.getMatrixAddress(), 24105ffd83dbSDimitry Andric Dst.isVolatileQualified()); 24115ffd83dbSDimitry Andric return; 24125ffd83dbSDimitry Andric } 24135ffd83dbSDimitry Andric 24140b57cec5SDimitry Andric assert(Dst.isBitField() && "Unknown LValue type"); 24150b57cec5SDimitry Andric return EmitStoreThroughBitfieldLValue(Src, Dst); 24160b57cec5SDimitry Andric } 24170b57cec5SDimitry Andric 24180b57cec5SDimitry Andric // There's special magic for assigning into an ARC-qualified l-value. 24190b57cec5SDimitry Andric if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) { 24200b57cec5SDimitry Andric switch (Lifetime) { 24210b57cec5SDimitry Andric case Qualifiers::OCL_None: 24220b57cec5SDimitry Andric llvm_unreachable("present but none"); 24230b57cec5SDimitry Andric 24240b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone: 24250b57cec5SDimitry Andric // nothing special 24260b57cec5SDimitry Andric break; 24270b57cec5SDimitry Andric 24280b57cec5SDimitry Andric case Qualifiers::OCL_Strong: 24290b57cec5SDimitry Andric if (isInit) { 24300b57cec5SDimitry Andric Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal())); 24310b57cec5SDimitry Andric break; 24320b57cec5SDimitry Andric } 24330b57cec5SDimitry Andric EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true); 24340b57cec5SDimitry Andric return; 24350b57cec5SDimitry Andric 24360b57cec5SDimitry Andric case Qualifiers::OCL_Weak: 24370b57cec5SDimitry Andric if (isInit) 24380b57cec5SDimitry Andric // Initialize and then skip the primitive store. 24390fca6ea1SDimitry Andric EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal()); 24400b57cec5SDimitry Andric else 24410fca6ea1SDimitry Andric EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), 2442480093f4SDimitry Andric /*ignore*/ true); 24430b57cec5SDimitry Andric return; 24440b57cec5SDimitry Andric 24450b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing: 24460b57cec5SDimitry Andric Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(), 24470b57cec5SDimitry Andric Src.getScalarVal())); 24480b57cec5SDimitry Andric // fall into the normal path 24490b57cec5SDimitry Andric break; 24500b57cec5SDimitry Andric } 24510b57cec5SDimitry Andric } 24520b57cec5SDimitry Andric 24530b57cec5SDimitry Andric if (Dst.isObjCWeak() && !Dst.isNonGC()) { 24540b57cec5SDimitry Andric // load of a __weak object. 24550fca6ea1SDimitry Andric Address LvalueDst = Dst.getAddress(); 24560b57cec5SDimitry Andric llvm::Value *src = Src.getScalarVal(); 24570b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst); 24580b57cec5SDimitry Andric return; 24590b57cec5SDimitry Andric } 24600b57cec5SDimitry Andric 24610b57cec5SDimitry Andric if (Dst.isObjCStrong() && !Dst.isNonGC()) { 24620b57cec5SDimitry Andric // load of a __strong object. 24630fca6ea1SDimitry Andric Address LvalueDst = Dst.getAddress(); 24640b57cec5SDimitry Andric llvm::Value *src = Src.getScalarVal(); 24650b57cec5SDimitry Andric if (Dst.isObjCIvar()) { 24660b57cec5SDimitry Andric assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL"); 24670b57cec5SDimitry Andric llvm::Type *ResultType = IntPtrTy; 24680b57cec5SDimitry Andric Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp()); 24690fca6ea1SDimitry Andric llvm::Value *RHS = dst.emitRawPointer(*this); 24700b57cec5SDimitry Andric RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast"); 24710fca6ea1SDimitry Andric llvm::Value *LHS = Builder.CreatePtrToInt(LvalueDst.emitRawPointer(*this), 24720fca6ea1SDimitry Andric ResultType, "sub.ptr.lhs.cast"); 24730b57cec5SDimitry Andric llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset"); 24740fca6ea1SDimitry Andric CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, BytesBetween); 24750b57cec5SDimitry Andric } else if (Dst.isGlobalObjCRef()) { 24760b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst, 24770b57cec5SDimitry Andric Dst.isThreadLocalRef()); 24780b57cec5SDimitry Andric } 24790b57cec5SDimitry Andric else 24800b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst); 24810b57cec5SDimitry Andric return; 24820b57cec5SDimitry Andric } 24830b57cec5SDimitry Andric 24840b57cec5SDimitry Andric assert(Src.isScalar() && "Can't emit an agg store with this method"); 24850b57cec5SDimitry Andric EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit); 24860b57cec5SDimitry Andric } 24870b57cec5SDimitry Andric 24880b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 24890b57cec5SDimitry Andric llvm::Value **Result) { 24900b57cec5SDimitry Andric const CGBitFieldInfo &Info = Dst.getBitFieldInfo(); 24910fca6ea1SDimitry Andric llvm::Type *ResLTy = convertTypeForLoadStore(Dst.getType()); 24920b57cec5SDimitry Andric Address Ptr = Dst.getBitFieldAddress(); 24930b57cec5SDimitry Andric 24940b57cec5SDimitry Andric // Get the source value, truncated to the width of the bit-field. 24950b57cec5SDimitry Andric llvm::Value *SrcVal = Src.getScalarVal(); 24960b57cec5SDimitry Andric 24970b57cec5SDimitry Andric // Cast the source to the storage type and shift it into place. 24980b57cec5SDimitry Andric SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(), 24990b57cec5SDimitry Andric /*isSigned=*/false); 25000b57cec5SDimitry Andric llvm::Value *MaskedVal = SrcVal; 25010b57cec5SDimitry Andric 2502e8d8bef9SDimitry Andric const bool UseVolatile = 2503e8d8bef9SDimitry Andric CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() && 2504e8d8bef9SDimitry Andric Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget()); 2505e8d8bef9SDimitry Andric const unsigned StorageSize = 2506e8d8bef9SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize; 2507e8d8bef9SDimitry Andric const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset; 25080b57cec5SDimitry Andric // See if there are other bits in the bitfield's storage we'll need to load 25090b57cec5SDimitry Andric // and mask together with source before storing. 2510e8d8bef9SDimitry Andric if (StorageSize != Info.Size) { 2511e8d8bef9SDimitry Andric assert(StorageSize > Info.Size && "Invalid bitfield size."); 25120b57cec5SDimitry Andric llvm::Value *Val = 25130b57cec5SDimitry Andric Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load"); 25140b57cec5SDimitry Andric 25150b57cec5SDimitry Andric // Mask the source value as needed. 25160b57cec5SDimitry Andric if (!hasBooleanRepresentation(Dst.getType())) 2517e8d8bef9SDimitry Andric SrcVal = Builder.CreateAnd( 2518e8d8bef9SDimitry Andric SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), 25190b57cec5SDimitry Andric "bf.value"); 25200b57cec5SDimitry Andric MaskedVal = SrcVal; 2521e8d8bef9SDimitry Andric if (Offset) 2522e8d8bef9SDimitry Andric SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl"); 25230b57cec5SDimitry Andric 25240b57cec5SDimitry Andric // Mask out the original value. 2525e8d8bef9SDimitry Andric Val = Builder.CreateAnd( 2526e8d8bef9SDimitry Andric Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size), 25270b57cec5SDimitry Andric "bf.clear"); 25280b57cec5SDimitry Andric 25290b57cec5SDimitry Andric // Or together the unchanged values and the source value. 25300b57cec5SDimitry Andric SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set"); 25310b57cec5SDimitry Andric } else { 2532e8d8bef9SDimitry Andric assert(Offset == 0); 25335ffd83dbSDimitry Andric // According to the AACPS: 25345ffd83dbSDimitry Andric // When a volatile bit-field is written, and its container does not overlap 2535e8d8bef9SDimitry Andric // with any non-bit-field member, its container must be read exactly once 2536e8d8bef9SDimitry Andric // and written exactly once using the access width appropriate to the type 2537e8d8bef9SDimitry Andric // of the container. The two accesses are not atomic. 25385ffd83dbSDimitry Andric if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) && 25395ffd83dbSDimitry Andric CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad) 25405ffd83dbSDimitry Andric Builder.CreateLoad(Ptr, true, "bf.load"); 25410b57cec5SDimitry Andric } 25420b57cec5SDimitry Andric 25430b57cec5SDimitry Andric // Write the new value back out. 25440b57cec5SDimitry Andric Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified()); 25450b57cec5SDimitry Andric 25460b57cec5SDimitry Andric // Return the new value of the bit-field, if requested. 25470b57cec5SDimitry Andric if (Result) { 25480b57cec5SDimitry Andric llvm::Value *ResultVal = MaskedVal; 25490b57cec5SDimitry Andric 25500b57cec5SDimitry Andric // Sign extend the value if needed. 25510b57cec5SDimitry Andric if (Info.IsSigned) { 2552e8d8bef9SDimitry Andric assert(Info.Size <= StorageSize); 2553e8d8bef9SDimitry Andric unsigned HighBits = StorageSize - Info.Size; 25540b57cec5SDimitry Andric if (HighBits) { 25550b57cec5SDimitry Andric ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl"); 25560b57cec5SDimitry Andric ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr"); 25570b57cec5SDimitry Andric } 25580b57cec5SDimitry Andric } 25590b57cec5SDimitry Andric 25600b57cec5SDimitry Andric ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned, 25610b57cec5SDimitry Andric "bf.result.cast"); 25620b57cec5SDimitry Andric *Result = EmitFromMemory(ResultVal, Dst.getType()); 25630b57cec5SDimitry Andric } 25640b57cec5SDimitry Andric } 25650b57cec5SDimitry Andric 25660b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src, 25670b57cec5SDimitry Andric LValue Dst) { 25685f757f3fSDimitry Andric // HLSL allows storing to scalar values through ExtVector component LValues. 25695f757f3fSDimitry Andric // To support this we need to handle the case where the destination address is 25705f757f3fSDimitry Andric // a scalar. 25715f757f3fSDimitry Andric Address DstAddr = Dst.getExtVectorAddress(); 25725f757f3fSDimitry Andric if (!DstAddr.getElementType()->isVectorTy()) { 25735f757f3fSDimitry Andric assert(!Dst.getType()->isVectorType() && 25745f757f3fSDimitry Andric "this should only occur for non-vector l-values"); 25755f757f3fSDimitry Andric Builder.CreateStore(Src.getScalarVal(), DstAddr, Dst.isVolatileQualified()); 25765f757f3fSDimitry Andric return; 25775f757f3fSDimitry Andric } 25785f757f3fSDimitry Andric 25790b57cec5SDimitry Andric // This access turns into a read/modify/write of the vector. Load the input 25800b57cec5SDimitry Andric // value now. 25815f757f3fSDimitry Andric llvm::Value *Vec = Builder.CreateLoad(DstAddr, Dst.isVolatileQualified()); 25820b57cec5SDimitry Andric const llvm::Constant *Elts = Dst.getExtVectorElts(); 25830b57cec5SDimitry Andric 25840b57cec5SDimitry Andric llvm::Value *SrcVal = Src.getScalarVal(); 25850b57cec5SDimitry Andric 25860b57cec5SDimitry Andric if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) { 25870b57cec5SDimitry Andric unsigned NumSrcElts = VTy->getNumElements(); 25885ffd83dbSDimitry Andric unsigned NumDstElts = 2589e8d8bef9SDimitry Andric cast<llvm::FixedVectorType>(Vec->getType())->getNumElements(); 25900b57cec5SDimitry Andric if (NumDstElts == NumSrcElts) { 25910b57cec5SDimitry Andric // Use shuffle vector is the src and destination are the same number of 25920b57cec5SDimitry Andric // elements and restore the vector mask since it is on the side it will be 25930b57cec5SDimitry Andric // stored. 25945ffd83dbSDimitry Andric SmallVector<int, 4> Mask(NumDstElts); 25950b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i) 25965ffd83dbSDimitry Andric Mask[getAccessedFieldNo(i, Elts)] = i; 25970b57cec5SDimitry Andric 2598e8d8bef9SDimitry Andric Vec = Builder.CreateShuffleVector(SrcVal, Mask); 25990b57cec5SDimitry Andric } else if (NumDstElts > NumSrcElts) { 26000b57cec5SDimitry Andric // Extended the source vector to the same length and then shuffle it 26010b57cec5SDimitry Andric // into the destination. 26020b57cec5SDimitry Andric // FIXME: since we're shuffling with undef, can we just use the indices 26030b57cec5SDimitry Andric // into that? This could be simpler. 26045ffd83dbSDimitry Andric SmallVector<int, 4> ExtMask; 26050b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i) 26065ffd83dbSDimitry Andric ExtMask.push_back(i); 26075ffd83dbSDimitry Andric ExtMask.resize(NumDstElts, -1); 2608e8d8bef9SDimitry Andric llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask); 26090b57cec5SDimitry Andric // build identity 26105ffd83dbSDimitry Andric SmallVector<int, 4> Mask; 26110b57cec5SDimitry Andric for (unsigned i = 0; i != NumDstElts; ++i) 26125ffd83dbSDimitry Andric Mask.push_back(i); 26130b57cec5SDimitry Andric 26140b57cec5SDimitry Andric // When the vector size is odd and .odd or .hi is used, the last element 26150b57cec5SDimitry Andric // of the Elts constant array will be one past the size of the vector. 26160b57cec5SDimitry Andric // Ignore the last element here, if it is greater than the mask size. 26170b57cec5SDimitry Andric if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size()) 26180b57cec5SDimitry Andric NumSrcElts--; 26190b57cec5SDimitry Andric 26200b57cec5SDimitry Andric // modify when what gets shuffled in 26210b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i) 26225ffd83dbSDimitry Andric Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts; 26235ffd83dbSDimitry Andric Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask); 26240b57cec5SDimitry Andric } else { 26250b57cec5SDimitry Andric // We should never shorten the vector 26260b57cec5SDimitry Andric llvm_unreachable("unexpected shorten vector length"); 26270b57cec5SDimitry Andric } 26280b57cec5SDimitry Andric } else { 26295f757f3fSDimitry Andric // If the Src is a scalar (not a vector), and the target is a vector it must 26305f757f3fSDimitry Andric // be updating one element. 26310b57cec5SDimitry Andric unsigned InIdx = getAccessedFieldNo(0, Elts); 26320b57cec5SDimitry Andric llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx); 26330b57cec5SDimitry Andric Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt); 26340b57cec5SDimitry Andric } 26350b57cec5SDimitry Andric 26360b57cec5SDimitry Andric Builder.CreateStore(Vec, Dst.getExtVectorAddress(), 26370b57cec5SDimitry Andric Dst.isVolatileQualified()); 26380b57cec5SDimitry Andric } 26390b57cec5SDimitry Andric 26400b57cec5SDimitry Andric /// Store of global named registers are always calls to intrinsics. 26410b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) { 26420b57cec5SDimitry Andric assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) && 26430b57cec5SDimitry Andric "Bad type for register variable"); 26440b57cec5SDimitry Andric llvm::MDNode *RegName = cast<llvm::MDNode>( 26450b57cec5SDimitry Andric cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata()); 26460b57cec5SDimitry Andric assert(RegName && "Register LValue is not metadata"); 26470b57cec5SDimitry Andric 26480b57cec5SDimitry Andric // We accept integer and pointer types only 26490b57cec5SDimitry Andric llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType()); 26500b57cec5SDimitry Andric llvm::Type *Ty = OrigTy; 26510b57cec5SDimitry Andric if (OrigTy->isPointerTy()) 26520b57cec5SDimitry Andric Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy); 26530b57cec5SDimitry Andric llvm::Type *Types[] = { Ty }; 26540b57cec5SDimitry Andric 26550b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types); 26560b57cec5SDimitry Andric llvm::Value *Value = Src.getScalarVal(); 26570b57cec5SDimitry Andric if (OrigTy->isPointerTy()) 26580b57cec5SDimitry Andric Value = Builder.CreatePtrToInt(Value, Ty); 26590b57cec5SDimitry Andric Builder.CreateCall( 26600b57cec5SDimitry Andric F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value}); 26610b57cec5SDimitry Andric } 26620b57cec5SDimitry Andric 26630b57cec5SDimitry Andric // setObjCGCLValueClass - sets class of the lvalue for the purpose of 26640b57cec5SDimitry Andric // generating write-barries API. It is currently a global, ivar, 26650b57cec5SDimitry Andric // or neither. 26660b57cec5SDimitry Andric static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, 26670b57cec5SDimitry Andric LValue &LV, 26680b57cec5SDimitry Andric bool IsMemberAccess=false) { 26690b57cec5SDimitry Andric if (Ctx.getLangOpts().getGC() == LangOptions::NonGC) 26700b57cec5SDimitry Andric return; 26710b57cec5SDimitry Andric 26720b57cec5SDimitry Andric if (isa<ObjCIvarRefExpr>(E)) { 26730b57cec5SDimitry Andric QualType ExpTy = E->getType(); 26740b57cec5SDimitry Andric if (IsMemberAccess && ExpTy->isPointerType()) { 26750b57cec5SDimitry Andric // If ivar is a structure pointer, assigning to field of 26760b57cec5SDimitry Andric // this struct follows gcc's behavior and makes it a non-ivar 26770b57cec5SDimitry Andric // writer-barrier conservatively. 2678a7dea167SDimitry Andric ExpTy = ExpTy->castAs<PointerType>()->getPointeeType(); 26790b57cec5SDimitry Andric if (ExpTy->isRecordType()) { 26800b57cec5SDimitry Andric LV.setObjCIvar(false); 26810b57cec5SDimitry Andric return; 26820b57cec5SDimitry Andric } 26830b57cec5SDimitry Andric } 26840b57cec5SDimitry Andric LV.setObjCIvar(true); 26850b57cec5SDimitry Andric auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E)); 26860b57cec5SDimitry Andric LV.setBaseIvarExp(Exp->getBase()); 26870b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType()); 26880b57cec5SDimitry Andric return; 26890b57cec5SDimitry Andric } 26900b57cec5SDimitry Andric 26910b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) { 26920b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) { 26930b57cec5SDimitry Andric if (VD->hasGlobalStorage()) { 26940b57cec5SDimitry Andric LV.setGlobalObjCRef(true); 26950b57cec5SDimitry Andric LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None); 26960b57cec5SDimitry Andric } 26970b57cec5SDimitry Andric } 26980b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType()); 26990b57cec5SDimitry Andric return; 27000b57cec5SDimitry Andric } 27010b57cec5SDimitry Andric 27020b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<UnaryOperator>(E)) { 27030b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 27040b57cec5SDimitry Andric return; 27050b57cec5SDimitry Andric } 27060b57cec5SDimitry Andric 27070b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ParenExpr>(E)) { 27080b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 27090b57cec5SDimitry Andric if (LV.isObjCIvar()) { 27100b57cec5SDimitry Andric // If cast is to a structure pointer, follow gcc's behavior and make it 27110b57cec5SDimitry Andric // a non-ivar write-barrier. 27120b57cec5SDimitry Andric QualType ExpTy = E->getType(); 27130b57cec5SDimitry Andric if (ExpTy->isPointerType()) 2714a7dea167SDimitry Andric ExpTy = ExpTy->castAs<PointerType>()->getPointeeType(); 27150b57cec5SDimitry Andric if (ExpTy->isRecordType()) 27160b57cec5SDimitry Andric LV.setObjCIvar(false); 27170b57cec5SDimitry Andric } 27180b57cec5SDimitry Andric return; 27190b57cec5SDimitry Andric } 27200b57cec5SDimitry Andric 27210b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) { 27220b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV); 27230b57cec5SDimitry Andric return; 27240b57cec5SDimitry Andric } 27250b57cec5SDimitry Andric 27260b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) { 27270b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 27280b57cec5SDimitry Andric return; 27290b57cec5SDimitry Andric } 27300b57cec5SDimitry Andric 27310b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) { 27320b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 27330b57cec5SDimitry Andric return; 27340b57cec5SDimitry Andric } 27350b57cec5SDimitry Andric 27360b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) { 27370b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess); 27380b57cec5SDimitry Andric return; 27390b57cec5SDimitry Andric } 27400b57cec5SDimitry Andric 27410b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) { 27420b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getBase(), LV); 27430b57cec5SDimitry Andric if (LV.isObjCIvar() && !LV.isObjCArray()) 27440b57cec5SDimitry Andric // Using array syntax to assigning to what an ivar points to is not 27450b57cec5SDimitry Andric // same as assigning to the ivar itself. {id *Names;} Names[i] = 0; 27460b57cec5SDimitry Andric LV.setObjCIvar(false); 27470b57cec5SDimitry Andric else if (LV.isGlobalObjCRef() && !LV.isObjCArray()) 27480b57cec5SDimitry Andric // Using array syntax to assigning to what global points to is not 27490b57cec5SDimitry Andric // same as assigning to the global itself. {id *G;} G[i] = 0; 27500b57cec5SDimitry Andric LV.setGlobalObjCRef(false); 27510b57cec5SDimitry Andric return; 27520b57cec5SDimitry Andric } 27530b57cec5SDimitry Andric 27540b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<MemberExpr>(E)) { 27550b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true); 27560b57cec5SDimitry Andric // We don't know if member is an 'ivar', but this flag is looked at 27570b57cec5SDimitry Andric // only in the context of LV.isObjCIvar(). 27580b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType()); 27590b57cec5SDimitry Andric return; 27600b57cec5SDimitry Andric } 27610b57cec5SDimitry Andric } 27620b57cec5SDimitry Andric 27630b57cec5SDimitry Andric static LValue EmitThreadPrivateVarDeclLValue( 27640b57cec5SDimitry Andric CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, 27650b57cec5SDimitry Andric llvm::Type *RealVarTy, SourceLocation Loc) { 27665ffd83dbSDimitry Andric if (CGF.CGM.getLangOpts().OpenMPIRBuilder) 27675ffd83dbSDimitry Andric Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate( 27685ffd83dbSDimitry Andric CGF, VD, Addr, Loc); 27695ffd83dbSDimitry Andric else 27705ffd83dbSDimitry Andric Addr = 27715ffd83dbSDimitry Andric CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc); 27725ffd83dbSDimitry Andric 277306c3fb27SDimitry Andric Addr = Addr.withElementType(RealVarTy); 27740b57cec5SDimitry Andric return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 27750b57cec5SDimitry Andric } 27760b57cec5SDimitry Andric 27770b57cec5SDimitry Andric static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, 27780b57cec5SDimitry Andric const VarDecl *VD, QualType T) { 2779bdd1243dSDimitry Andric std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 27800b57cec5SDimitry Andric OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2781bdd1243dSDimitry Andric // Return an invalid address if variable is MT_To (or MT_Enter starting with 2782bdd1243dSDimitry Andric // OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link 2783bdd1243dSDimitry Andric // and MT_To (or MT_Enter) with unified memory, return a valid address. 2784bdd1243dSDimitry Andric if (!Res || ((*Res == OMPDeclareTargetDeclAttr::MT_To || 2785bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 27860b57cec5SDimitry Andric !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) 27870b57cec5SDimitry Andric return Address::invalid(); 27880b57cec5SDimitry Andric assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 2789bdd1243dSDimitry Andric ((*Res == OMPDeclareTargetDeclAttr::MT_To || 2790bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 27910b57cec5SDimitry Andric CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) && 27920b57cec5SDimitry Andric "Expected link clause OR to clause with unified memory enabled."); 27930b57cec5SDimitry Andric QualType PtrTy = CGF.getContext().getPointerType(VD->getType()); 27940b57cec5SDimitry Andric Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 27950b57cec5SDimitry Andric return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>()); 27960b57cec5SDimitry Andric } 27970b57cec5SDimitry Andric 27980b57cec5SDimitry Andric Address 27990b57cec5SDimitry Andric CodeGenFunction::EmitLoadOfReference(LValue RefLVal, 28000b57cec5SDimitry Andric LValueBaseInfo *PointeeBaseInfo, 28010b57cec5SDimitry Andric TBAAAccessInfo *PointeeTBAAInfo) { 2802480093f4SDimitry Andric llvm::LoadInst *Load = 28030fca6ea1SDimitry Andric Builder.CreateLoad(RefLVal.getAddress(), RefLVal.isVolatile()); 28040b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo()); 28050fca6ea1SDimitry Andric return makeNaturalAddressForPointer(Load, RefLVal.getType()->getPointeeType(), 28060fca6ea1SDimitry Andric CharUnits(), /*ForPointeeType=*/true, 28070fca6ea1SDimitry Andric PointeeBaseInfo, PointeeTBAAInfo); 28080b57cec5SDimitry Andric } 28090b57cec5SDimitry Andric 28100b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) { 28110b57cec5SDimitry Andric LValueBaseInfo PointeeBaseInfo; 28120b57cec5SDimitry Andric TBAAAccessInfo PointeeTBAAInfo; 28130b57cec5SDimitry Andric Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo, 28140b57cec5SDimitry Andric &PointeeTBAAInfo); 28150b57cec5SDimitry Andric return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(), 28160b57cec5SDimitry Andric PointeeBaseInfo, PointeeTBAAInfo); 28170b57cec5SDimitry Andric } 28180b57cec5SDimitry Andric 28190b57cec5SDimitry Andric Address CodeGenFunction::EmitLoadOfPointer(Address Ptr, 28200b57cec5SDimitry Andric const PointerType *PtrTy, 28210b57cec5SDimitry Andric LValueBaseInfo *BaseInfo, 28220b57cec5SDimitry Andric TBAAAccessInfo *TBAAInfo) { 28230b57cec5SDimitry Andric llvm::Value *Addr = Builder.CreateLoad(Ptr); 28240fca6ea1SDimitry Andric return makeNaturalAddressForPointer(Addr, PtrTy->getPointeeType(), 28250fca6ea1SDimitry Andric CharUnits(), /*ForPointeeType=*/true, 28260fca6ea1SDimitry Andric BaseInfo, TBAAInfo); 28270b57cec5SDimitry Andric } 28280b57cec5SDimitry Andric 28290b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr, 28300b57cec5SDimitry Andric const PointerType *PtrTy) { 28310b57cec5SDimitry Andric LValueBaseInfo BaseInfo; 28320b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo; 28330b57cec5SDimitry Andric Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo); 28340b57cec5SDimitry Andric return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo); 28350b57cec5SDimitry Andric } 28360b57cec5SDimitry Andric 28370b57cec5SDimitry Andric static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, 28380b57cec5SDimitry Andric const Expr *E, const VarDecl *VD) { 28390b57cec5SDimitry Andric QualType T = E->getType(); 28400b57cec5SDimitry Andric 28410b57cec5SDimitry Andric // If it's thread_local, emit a call to its wrapper function instead. 28420b57cec5SDimitry Andric if (VD->getTLSKind() == VarDecl::TLS_Dynamic && 2843a7dea167SDimitry Andric CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD)) 28440b57cec5SDimitry Andric return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T); 28450b57cec5SDimitry Andric // Check if the variable is marked as declare target with link clause in 28460b57cec5SDimitry Andric // device codegen. 284706c3fb27SDimitry Andric if (CGF.getLangOpts().OpenMPIsTargetDevice) { 28480b57cec5SDimitry Andric Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T); 28490b57cec5SDimitry Andric if (Addr.isValid()) 28500b57cec5SDimitry Andric return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 28510b57cec5SDimitry Andric } 28520b57cec5SDimitry Andric 28530b57cec5SDimitry Andric llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD); 2854bdd1243dSDimitry Andric 2855bdd1243dSDimitry Andric if (VD->getTLSKind() != VarDecl::TLS_None) 2856bdd1243dSDimitry Andric V = CGF.Builder.CreateThreadLocalAddress(V); 2857bdd1243dSDimitry Andric 28580b57cec5SDimitry Andric llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType()); 28590b57cec5SDimitry Andric CharUnits Alignment = CGF.getContext().getDeclAlign(VD); 28600eae32dcSDimitry Andric Address Addr(V, RealVarTy, Alignment); 28610b57cec5SDimitry Andric // Emit reference to the private copy of the variable if it is an OpenMP 28620b57cec5SDimitry Andric // threadprivate variable. 28630b57cec5SDimitry Andric if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd && 28640b57cec5SDimitry Andric VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 28650b57cec5SDimitry Andric return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy, 28660b57cec5SDimitry Andric E->getExprLoc()); 28670b57cec5SDimitry Andric } 28680b57cec5SDimitry Andric LValue LV = VD->getType()->isReferenceType() ? 28690b57cec5SDimitry Andric CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(), 28700b57cec5SDimitry Andric AlignmentSource::Decl) : 28710b57cec5SDimitry Andric CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl); 28720b57cec5SDimitry Andric setObjCGCLValueClass(CGF.getContext(), E, LV); 28730b57cec5SDimitry Andric return LV; 28740b57cec5SDimitry Andric } 28750b57cec5SDimitry Andric 28760fca6ea1SDimitry Andric llvm::Constant *CodeGenModule::getRawFunctionPointer(GlobalDecl GD, 28770fca6ea1SDimitry Andric llvm::Type *Ty) { 28785ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 28790b57cec5SDimitry Andric if (FD->hasAttr<WeakRefAttr>()) { 28800fca6ea1SDimitry Andric ConstantAddress aliasee = GetWeakRefReference(FD); 28810b57cec5SDimitry Andric return aliasee.getPointer(); 28820b57cec5SDimitry Andric } 28830b57cec5SDimitry Andric 28840fca6ea1SDimitry Andric llvm::Constant *V = GetAddrOfFunction(GD, Ty); 28850b57cec5SDimitry Andric return V; 28860b57cec5SDimitry Andric } 28870b57cec5SDimitry Andric 28885ffd83dbSDimitry Andric static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, 28895ffd83dbSDimitry Andric GlobalDecl GD) { 28905ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 28910fca6ea1SDimitry Andric llvm::Constant *V = CGF.CGM.getFunctionPointer(GD); 28920b57cec5SDimitry Andric CharUnits Alignment = CGF.getContext().getDeclAlign(FD); 28930b57cec5SDimitry Andric return CGF.MakeAddrLValue(V, E->getType(), Alignment, 28940b57cec5SDimitry Andric AlignmentSource::Decl); 28950b57cec5SDimitry Andric } 28960b57cec5SDimitry Andric 28970b57cec5SDimitry Andric static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, 28980b57cec5SDimitry Andric llvm::Value *ThisValue) { 28995f757f3fSDimitry Andric 29005f757f3fSDimitry Andric return CGF.EmitLValueForLambdaField(FD, ThisValue); 29010b57cec5SDimitry Andric } 29020b57cec5SDimitry Andric 29030b57cec5SDimitry Andric /// Named Registers are named metadata pointing to the register name 29040b57cec5SDimitry Andric /// which will be read from/written to as an argument to the intrinsic 29050b57cec5SDimitry Andric /// @llvm.read/write_register. 29060b57cec5SDimitry Andric /// So far, only the name is being passed down, but other options such as 29070b57cec5SDimitry Andric /// register type, allocation type or even optimization options could be 29080b57cec5SDimitry Andric /// passed down via the metadata node. 29090b57cec5SDimitry Andric static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) { 29100b57cec5SDimitry Andric SmallString<64> Name("llvm.named.register."); 29110b57cec5SDimitry Andric AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>(); 29120b57cec5SDimitry Andric assert(Asm->getLabel().size() < 64-Name.size() && 29130b57cec5SDimitry Andric "Register name too big"); 29140b57cec5SDimitry Andric Name.append(Asm->getLabel()); 29150b57cec5SDimitry Andric llvm::NamedMDNode *M = 29160b57cec5SDimitry Andric CGM.getModule().getOrInsertNamedMetadata(Name); 29170b57cec5SDimitry Andric if (M->getNumOperands() == 0) { 29180b57cec5SDimitry Andric llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(), 29190b57cec5SDimitry Andric Asm->getLabel()); 29200b57cec5SDimitry Andric llvm::Metadata *Ops[] = {Str}; 29210b57cec5SDimitry Andric M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 29220b57cec5SDimitry Andric } 29230b57cec5SDimitry Andric 29240b57cec5SDimitry Andric CharUnits Alignment = CGM.getContext().getDeclAlign(VD); 29250b57cec5SDimitry Andric 29260b57cec5SDimitry Andric llvm::Value *Ptr = 29270b57cec5SDimitry Andric llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)); 29280eae32dcSDimitry Andric return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType()); 29290b57cec5SDimitry Andric } 29300b57cec5SDimitry Andric 29310b57cec5SDimitry Andric /// Determine whether we can emit a reference to \p VD from the current 29320b57cec5SDimitry Andric /// context, despite not necessarily having seen an odr-use of the variable in 29330b57cec5SDimitry Andric /// this context. 29340b57cec5SDimitry Andric static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF, 29350b57cec5SDimitry Andric const DeclRefExpr *E, 29368a4dda33SDimitry Andric const VarDecl *VD) { 29370b57cec5SDimitry Andric // For a variable declared in an enclosing scope, do not emit a spurious 29380b57cec5SDimitry Andric // reference even if we have a capture, as that will emit an unwarranted 29390b57cec5SDimitry Andric // reference to our capture state, and will likely generate worse code than 29400b57cec5SDimitry Andric // emitting a local copy. 29410b57cec5SDimitry Andric if (E->refersToEnclosingVariableOrCapture()) 29420b57cec5SDimitry Andric return false; 29430b57cec5SDimitry Andric 29440b57cec5SDimitry Andric // For a local declaration declared in this function, we can always reference 29450b57cec5SDimitry Andric // it even if we don't have an odr-use. 29460b57cec5SDimitry Andric if (VD->hasLocalStorage()) { 29470b57cec5SDimitry Andric return VD->getDeclContext() == 29480b57cec5SDimitry Andric dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl); 29490b57cec5SDimitry Andric } 29500b57cec5SDimitry Andric 29510b57cec5SDimitry Andric // For a global declaration, we can emit a reference to it if we know 29520b57cec5SDimitry Andric // for sure that we are able to emit a definition of it. 29530b57cec5SDimitry Andric VD = VD->getDefinition(CGF.getContext()); 29540b57cec5SDimitry Andric if (!VD) 29550b57cec5SDimitry Andric return false; 29560b57cec5SDimitry Andric 29570b57cec5SDimitry Andric // Don't emit a spurious reference if it might be to a variable that only 29580b57cec5SDimitry Andric // exists on a different device / target. 29590b57cec5SDimitry Andric // FIXME: This is unnecessarily broad. Check whether this would actually be a 29600b57cec5SDimitry Andric // cross-target reference. 29610b57cec5SDimitry Andric if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA || 29620b57cec5SDimitry Andric CGF.getLangOpts().OpenCL) { 29630b57cec5SDimitry Andric return false; 29640b57cec5SDimitry Andric } 29650b57cec5SDimitry Andric 29660b57cec5SDimitry Andric // We can emit a spurious reference only if the linkage implies that we'll 29670b57cec5SDimitry Andric // be emitting a non-interposable symbol that will be retained until link 29680b57cec5SDimitry Andric // time. 29698a4dda33SDimitry Andric switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) { 29700b57cec5SDimitry Andric case llvm::GlobalValue::ExternalLinkage: 29710b57cec5SDimitry Andric case llvm::GlobalValue::LinkOnceODRLinkage: 29720b57cec5SDimitry Andric case llvm::GlobalValue::WeakODRLinkage: 29730b57cec5SDimitry Andric case llvm::GlobalValue::InternalLinkage: 29740b57cec5SDimitry Andric case llvm::GlobalValue::PrivateLinkage: 29750b57cec5SDimitry Andric return true; 29760b57cec5SDimitry Andric default: 29770b57cec5SDimitry Andric return false; 29780b57cec5SDimitry Andric } 29790b57cec5SDimitry Andric } 29800b57cec5SDimitry Andric 29810b57cec5SDimitry Andric LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) { 29820b57cec5SDimitry Andric const NamedDecl *ND = E->getDecl(); 29830b57cec5SDimitry Andric QualType T = E->getType(); 29840b57cec5SDimitry Andric 29850b57cec5SDimitry Andric assert(E->isNonOdrUse() != NOUR_Unevaluated && 29860b57cec5SDimitry Andric "should not emit an unevaluated operand"); 29870b57cec5SDimitry Andric 29880b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(ND)) { 29890b57cec5SDimitry Andric // Global Named registers access via intrinsics only 29900b57cec5SDimitry Andric if (VD->getStorageClass() == SC_Register && 29910b57cec5SDimitry Andric VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl()) 29920b57cec5SDimitry Andric return EmitGlobalNamedRegister(VD, CGM); 29930b57cec5SDimitry Andric 29940b57cec5SDimitry Andric // If this DeclRefExpr does not constitute an odr-use of the variable, 29950b57cec5SDimitry Andric // we're not permitted to emit a reference to it in general, and it might 29960b57cec5SDimitry Andric // not be captured if capture would be necessary for a use. Emit the 29970b57cec5SDimitry Andric // constant value directly instead. 29980b57cec5SDimitry Andric if (E->isNonOdrUse() == NOUR_Constant && 29990b57cec5SDimitry Andric (VD->getType()->isReferenceType() || 30008a4dda33SDimitry Andric !canEmitSpuriousReferenceToVariable(*this, E, VD))) { 30010b57cec5SDimitry Andric VD->getAnyInitializer(VD); 30020b57cec5SDimitry Andric llvm::Constant *Val = ConstantEmitter(*this).emitAbstract( 30030b57cec5SDimitry Andric E->getLocation(), *VD->evaluateValue(), VD->getType()); 30040b57cec5SDimitry Andric assert(Val && "failed to emit constant expression"); 30050b57cec5SDimitry Andric 30060b57cec5SDimitry Andric Address Addr = Address::invalid(); 30070b57cec5SDimitry Andric if (!VD->getType()->isReferenceType()) { 30080b57cec5SDimitry Andric // Spill the constant value to a global. 30090b57cec5SDimitry Andric Addr = CGM.createUnnamedGlobalFrom(*VD, Val, 30100b57cec5SDimitry Andric getContext().getDeclAlign(VD)); 3011c14a5a88SDimitry Andric llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType()); 3012c14a5a88SDimitry Andric auto *PTy = llvm::PointerType::get( 3013bdd1243dSDimitry Andric VarTy, getTypes().getTargetAddressSpace(VD->getType())); 301481ad6265SDimitry Andric Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy); 30150b57cec5SDimitry Andric } else { 30160b57cec5SDimitry Andric // Should we be using the alignment of the constant pointer we emitted? 30170b57cec5SDimitry Andric CharUnits Alignment = 30185ffd83dbSDimitry Andric CGM.getNaturalTypeAlignment(E->getType(), 30190b57cec5SDimitry Andric /* BaseInfo= */ nullptr, 30200b57cec5SDimitry Andric /* TBAAInfo= */ nullptr, 30210b57cec5SDimitry Andric /* forPointeeType= */ true); 30220fca6ea1SDimitry Andric Addr = makeNaturalAddressForPointer(Val, T, Alignment); 30230b57cec5SDimitry Andric } 30240b57cec5SDimitry Andric return MakeAddrLValue(Addr, T, AlignmentSource::Decl); 30250b57cec5SDimitry Andric } 30260b57cec5SDimitry Andric 30270b57cec5SDimitry Andric // FIXME: Handle other kinds of non-odr-use DeclRefExprs. 30280b57cec5SDimitry Andric 30290b57cec5SDimitry Andric // Check for captured variables. 30300b57cec5SDimitry Andric if (E->refersToEnclosingVariableOrCapture()) { 30310b57cec5SDimitry Andric VD = VD->getCanonicalDecl(); 30320b57cec5SDimitry Andric if (auto *FD = LambdaCaptureFields.lookup(VD)) 30330b57cec5SDimitry Andric return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue); 3034480093f4SDimitry Andric if (CapturedStmtInfo) { 30350b57cec5SDimitry Andric auto I = LocalDeclMap.find(VD); 30360b57cec5SDimitry Andric if (I != LocalDeclMap.end()) { 3037480093f4SDimitry Andric LValue CapLVal; 30380b57cec5SDimitry Andric if (VD->getType()->isReferenceType()) 3039480093f4SDimitry Andric CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(), 30400b57cec5SDimitry Andric AlignmentSource::Decl); 3041480093f4SDimitry Andric else 3042480093f4SDimitry Andric CapLVal = MakeAddrLValue(I->second, T); 3043480093f4SDimitry Andric // Mark lvalue as nontemporal if the variable is marked as nontemporal 3044480093f4SDimitry Andric // in simd context. 3045480093f4SDimitry Andric if (getLangOpts().OpenMP && 3046480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(VD)) 3047480093f4SDimitry Andric CapLVal.setNontemporal(/*Value=*/true); 3048480093f4SDimitry Andric return CapLVal; 30490b57cec5SDimitry Andric } 30500b57cec5SDimitry Andric LValue CapLVal = 30510b57cec5SDimitry Andric EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD), 30520b57cec5SDimitry Andric CapturedStmtInfo->getContextValue()); 30530fca6ea1SDimitry Andric Address LValueAddress = CapLVal.getAddress(); 30540fca6ea1SDimitry Andric CapLVal = MakeAddrLValue(Address(LValueAddress.emitRawPointer(*this), 30550fca6ea1SDimitry Andric LValueAddress.getElementType(), 305681ad6265SDimitry Andric getContext().getDeclAlign(VD)), 30570fca6ea1SDimitry Andric CapLVal.getType(), 30580fca6ea1SDimitry Andric LValueBaseInfo(AlignmentSource::Decl), 30590b57cec5SDimitry Andric CapLVal.getTBAAInfo()); 3060480093f4SDimitry Andric // Mark lvalue as nontemporal if the variable is marked as nontemporal 3061480093f4SDimitry Andric // in simd context. 3062480093f4SDimitry Andric if (getLangOpts().OpenMP && 3063480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(VD)) 3064480093f4SDimitry Andric CapLVal.setNontemporal(/*Value=*/true); 3065480093f4SDimitry Andric return CapLVal; 30660b57cec5SDimitry Andric } 30670b57cec5SDimitry Andric 30680b57cec5SDimitry Andric assert(isa<BlockDecl>(CurCodeDecl)); 30690b57cec5SDimitry Andric Address addr = GetAddrOfBlockDecl(VD); 30700b57cec5SDimitry Andric return MakeAddrLValue(addr, T, AlignmentSource::Decl); 30710b57cec5SDimitry Andric } 30720b57cec5SDimitry Andric } 30730b57cec5SDimitry Andric 30740b57cec5SDimitry Andric // FIXME: We should be able to assert this for FunctionDecls as well! 30750b57cec5SDimitry Andric // FIXME: We should be able to assert this for all DeclRefExprs, not just 30760b57cec5SDimitry Andric // those with a valid source location. 30770b57cec5SDimitry Andric assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() || 30780b57cec5SDimitry Andric !E->getLocation().isValid()) && 30790b57cec5SDimitry Andric "Should not use decl without marking it used!"); 30800b57cec5SDimitry Andric 30810b57cec5SDimitry Andric if (ND->hasAttr<WeakRefAttr>()) { 30820b57cec5SDimitry Andric const auto *VD = cast<ValueDecl>(ND); 30830b57cec5SDimitry Andric ConstantAddress Aliasee = CGM.GetWeakRefReference(VD); 30840b57cec5SDimitry Andric return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl); 30850b57cec5SDimitry Andric } 30860b57cec5SDimitry Andric 30870b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(ND)) { 30880b57cec5SDimitry Andric // Check if this is a global variable. 30890b57cec5SDimitry Andric if (VD->hasLinkage() || VD->isStaticDataMember()) 30900b57cec5SDimitry Andric return EmitGlobalVarDeclLValue(*this, E, VD); 30910b57cec5SDimitry Andric 30920b57cec5SDimitry Andric Address addr = Address::invalid(); 30930b57cec5SDimitry Andric 30940b57cec5SDimitry Andric // The variable should generally be present in the local decl map. 30950b57cec5SDimitry Andric auto iter = LocalDeclMap.find(VD); 30960b57cec5SDimitry Andric if (iter != LocalDeclMap.end()) { 30970b57cec5SDimitry Andric addr = iter->second; 30980b57cec5SDimitry Andric 30990b57cec5SDimitry Andric // Otherwise, it might be static local we haven't emitted yet for 31000b57cec5SDimitry Andric // some reason; most likely, because it's in an outer function. 31010b57cec5SDimitry Andric } else if (VD->isStaticLocal()) { 31020eae32dcSDimitry Andric llvm::Constant *var = CGM.getOrCreateStaticVarDecl( 31038a4dda33SDimitry Andric *VD, CGM.getLLVMLinkageVarDefinition(VD)); 31040eae32dcSDimitry Andric addr = Address( 31050eae32dcSDimitry Andric var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD)); 31060b57cec5SDimitry Andric 31070b57cec5SDimitry Andric // No other cases for now. 31080b57cec5SDimitry Andric } else { 31090b57cec5SDimitry Andric llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?"); 31100b57cec5SDimitry Andric } 31110b57cec5SDimitry Andric 3112bdd1243dSDimitry Andric // Handle threadlocal function locals. 3113bdd1243dSDimitry Andric if (VD->getTLSKind() != VarDecl::TLS_None) 311406c3fb27SDimitry Andric addr = addr.withPointer( 31150fca6ea1SDimitry Andric Builder.CreateThreadLocalAddress(addr.getBasePointer()), 31160fca6ea1SDimitry Andric NotKnownNonNull); 31170b57cec5SDimitry Andric 31180b57cec5SDimitry Andric // Check for OpenMP threadprivate variables. 31190b57cec5SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd && 31200b57cec5SDimitry Andric VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 31210b57cec5SDimitry Andric return EmitThreadPrivateVarDeclLValue( 31220b57cec5SDimitry Andric *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()), 31230b57cec5SDimitry Andric E->getExprLoc()); 31240b57cec5SDimitry Andric } 31250b57cec5SDimitry Andric 31260b57cec5SDimitry Andric // Drill into block byref variables. 31270b57cec5SDimitry Andric bool isBlockByref = VD->isEscapingByref(); 31280b57cec5SDimitry Andric if (isBlockByref) { 31290b57cec5SDimitry Andric addr = emitBlockByrefAddress(addr, VD); 31300b57cec5SDimitry Andric } 31310b57cec5SDimitry Andric 31320b57cec5SDimitry Andric // Drill into reference types. 31330b57cec5SDimitry Andric LValue LV = VD->getType()->isReferenceType() ? 31340b57cec5SDimitry Andric EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) : 31350b57cec5SDimitry Andric MakeAddrLValue(addr, T, AlignmentSource::Decl); 31360b57cec5SDimitry Andric 31370b57cec5SDimitry Andric bool isLocalStorage = VD->hasLocalStorage(); 31380b57cec5SDimitry Andric 31390b57cec5SDimitry Andric bool NonGCable = isLocalStorage && 31400b57cec5SDimitry Andric !VD->getType()->isReferenceType() && 31410b57cec5SDimitry Andric !isBlockByref; 31420b57cec5SDimitry Andric if (NonGCable) { 31430b57cec5SDimitry Andric LV.getQuals().removeObjCGCAttr(); 31440b57cec5SDimitry Andric LV.setNonGC(true); 31450b57cec5SDimitry Andric } 31460b57cec5SDimitry Andric 31470b57cec5SDimitry Andric bool isImpreciseLifetime = 31480b57cec5SDimitry Andric (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>()); 31490b57cec5SDimitry Andric if (isImpreciseLifetime) 31500b57cec5SDimitry Andric LV.setARCPreciseLifetime(ARCImpreciseLifetime); 31510b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV); 31520b57cec5SDimitry Andric return LV; 31530b57cec5SDimitry Andric } 31540b57cec5SDimitry Andric 31550fca6ea1SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 31560fca6ea1SDimitry Andric return EmitFunctionDeclLValue(*this, E, FD); 31570b57cec5SDimitry Andric 31580b57cec5SDimitry Andric // FIXME: While we're emitting a binding from an enclosing scope, all other 31590b57cec5SDimitry Andric // DeclRefExprs we see should be implicitly treated as if they also refer to 31600b57cec5SDimitry Andric // an enclosing scope. 3161bdd1243dSDimitry Andric if (const auto *BD = dyn_cast<BindingDecl>(ND)) { 3162bdd1243dSDimitry Andric if (E->refersToEnclosingVariableOrCapture()) { 3163bdd1243dSDimitry Andric auto *FD = LambdaCaptureFields.lookup(BD); 3164bdd1243dSDimitry Andric return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue); 3165bdd1243dSDimitry Andric } 31660b57cec5SDimitry Andric return EmitLValue(BD->getBinding()); 3167bdd1243dSDimitry Andric } 31680b57cec5SDimitry Andric 31695ffd83dbSDimitry Andric // We can form DeclRefExprs naming GUID declarations when reconstituting 31705ffd83dbSDimitry Andric // non-type template parameters into expressions. 31715ffd83dbSDimitry Andric if (const auto *GD = dyn_cast<MSGuidDecl>(ND)) 31725ffd83dbSDimitry Andric return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T, 31735ffd83dbSDimitry Andric AlignmentSource::Decl); 31745ffd83dbSDimitry Andric 31755f757f3fSDimitry Andric if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) { 31765f757f3fSDimitry Andric auto ATPO = CGM.GetAddrOfTemplateParamObject(TPO); 31775f757f3fSDimitry Andric auto AS = getLangASFromTargetAS(ATPO.getAddressSpace()); 31785f757f3fSDimitry Andric 31795f757f3fSDimitry Andric if (AS != T.getAddressSpace()) { 31805f757f3fSDimitry Andric auto TargetAS = getContext().getTargetAddressSpace(T.getAddressSpace()); 31815f757f3fSDimitry Andric auto PtrTy = ATPO.getElementType()->getPointerTo(TargetAS); 31825f757f3fSDimitry Andric auto ASC = getTargetHooks().performAddrSpaceCast( 31835f757f3fSDimitry Andric CGM, ATPO.getPointer(), AS, T.getAddressSpace(), PtrTy); 31845f757f3fSDimitry Andric ATPO = ConstantAddress(ASC, ATPO.getElementType(), ATPO.getAlignment()); 31855f757f3fSDimitry Andric } 31865f757f3fSDimitry Andric 31875f757f3fSDimitry Andric return MakeAddrLValue(ATPO, T, AlignmentSource::Decl); 31885f757f3fSDimitry Andric } 3189e8d8bef9SDimitry Andric 31900b57cec5SDimitry Andric llvm_unreachable("Unhandled DeclRefExpr"); 31910b57cec5SDimitry Andric } 31920b57cec5SDimitry Andric 31930b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) { 31940b57cec5SDimitry Andric // __extension__ doesn't affect lvalue-ness. 31950b57cec5SDimitry Andric if (E->getOpcode() == UO_Extension) 31960b57cec5SDimitry Andric return EmitLValue(E->getSubExpr()); 31970b57cec5SDimitry Andric 31980b57cec5SDimitry Andric QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType()); 31990b57cec5SDimitry Andric switch (E->getOpcode()) { 32000b57cec5SDimitry Andric default: llvm_unreachable("Unknown unary operator lvalue!"); 32010b57cec5SDimitry Andric case UO_Deref: { 32020b57cec5SDimitry Andric QualType T = E->getSubExpr()->getType()->getPointeeType(); 32030b57cec5SDimitry Andric assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type"); 32040b57cec5SDimitry Andric 32050b57cec5SDimitry Andric LValueBaseInfo BaseInfo; 32060b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo; 32070b57cec5SDimitry Andric Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo, 32080b57cec5SDimitry Andric &TBAAInfo); 32090b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo); 32100b57cec5SDimitry Andric LV.getQuals().setAddressSpace(ExprTy.getAddressSpace()); 32110b57cec5SDimitry Andric 32120b57cec5SDimitry Andric // We should not generate __weak write barrier on indirect reference 32130b57cec5SDimitry Andric // of a pointer to object; as in void foo (__weak id *param); *param = 0; 32140b57cec5SDimitry Andric // But, we continue to generate __strong write barrier on indirect write 32150b57cec5SDimitry Andric // into a pointer to object. 32160b57cec5SDimitry Andric if (getLangOpts().ObjC && 32170b57cec5SDimitry Andric getLangOpts().getGC() != LangOptions::NonGC && 32180b57cec5SDimitry Andric LV.isObjCWeak()) 32190b57cec5SDimitry Andric LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 32200b57cec5SDimitry Andric return LV; 32210b57cec5SDimitry Andric } 32220b57cec5SDimitry Andric case UO_Real: 32230b57cec5SDimitry Andric case UO_Imag: { 32240b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 32250b57cec5SDimitry Andric assert(LV.isSimple() && "real/imag on non-ordinary l-value"); 32260b57cec5SDimitry Andric 32270b57cec5SDimitry Andric // __real is valid on scalars. This is a faster way of testing that. 32280b57cec5SDimitry Andric // __imag can only produce an rvalue on scalars. 32290b57cec5SDimitry Andric if (E->getOpcode() == UO_Real && 32300fca6ea1SDimitry Andric !LV.getAddress().getElementType()->isStructTy()) { 32310b57cec5SDimitry Andric assert(E->getSubExpr()->getType()->isArithmeticType()); 32320b57cec5SDimitry Andric return LV; 32330b57cec5SDimitry Andric } 32340b57cec5SDimitry Andric 32350b57cec5SDimitry Andric QualType T = ExprTy->castAs<ComplexType>()->getElementType(); 32360b57cec5SDimitry Andric 32370b57cec5SDimitry Andric Address Component = 32380b57cec5SDimitry Andric (E->getOpcode() == UO_Real 32390fca6ea1SDimitry Andric ? emitAddrOfRealComponent(LV.getAddress(), LV.getType()) 32400fca6ea1SDimitry Andric : emitAddrOfImagComponent(LV.getAddress(), LV.getType())); 32410b57cec5SDimitry Andric LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(), 32420b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, T)); 32430b57cec5SDimitry Andric ElemLV.getQuals().addQualifiers(LV.getQuals()); 32440b57cec5SDimitry Andric return ElemLV; 32450b57cec5SDimitry Andric } 32460b57cec5SDimitry Andric case UO_PreInc: 32470b57cec5SDimitry Andric case UO_PreDec: { 32480b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 32490b57cec5SDimitry Andric bool isInc = E->getOpcode() == UO_PreInc; 32500b57cec5SDimitry Andric 32510b57cec5SDimitry Andric if (E->getType()->isAnyComplexType()) 32520b57cec5SDimitry Andric EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/); 32530b57cec5SDimitry Andric else 32540b57cec5SDimitry Andric EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/); 32550b57cec5SDimitry Andric return LV; 32560b57cec5SDimitry Andric } 32570b57cec5SDimitry Andric } 32580b57cec5SDimitry Andric } 32590b57cec5SDimitry Andric 32600b57cec5SDimitry Andric LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) { 32610b57cec5SDimitry Andric return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E), 32620b57cec5SDimitry Andric E->getType(), AlignmentSource::Decl); 32630b57cec5SDimitry Andric } 32640b57cec5SDimitry Andric 32650b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) { 32660b57cec5SDimitry Andric return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E), 32670b57cec5SDimitry Andric E->getType(), AlignmentSource::Decl); 32680b57cec5SDimitry Andric } 32690b57cec5SDimitry Andric 32700b57cec5SDimitry Andric LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) { 32710b57cec5SDimitry Andric auto SL = E->getFunctionName(); 32720b57cec5SDimitry Andric assert(SL != nullptr && "No StringLiteral name in PredefinedExpr"); 32730b57cec5SDimitry Andric StringRef FnName = CurFn->getName(); 32745f757f3fSDimitry Andric if (FnName.starts_with("\01")) 32750b57cec5SDimitry Andric FnName = FnName.substr(1); 32760b57cec5SDimitry Andric StringRef NameItems[] = { 32770b57cec5SDimitry Andric PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName}; 32780b57cec5SDimitry Andric std::string GVName = llvm::join(NameItems, NameItems + 2, "."); 32790b57cec5SDimitry Andric if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) { 32805ffd83dbSDimitry Andric std::string Name = std::string(SL->getString()); 32810b57cec5SDimitry Andric if (!Name.empty()) { 32820b57cec5SDimitry Andric unsigned Discriminator = 32830b57cec5SDimitry Andric CGM.getCXXABI().getMangleContext().getBlockId(BD, true); 32840b57cec5SDimitry Andric if (Discriminator) 32850b57cec5SDimitry Andric Name += "_" + Twine(Discriminator + 1).str(); 32860b57cec5SDimitry Andric auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str()); 32870b57cec5SDimitry Andric return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 32880b57cec5SDimitry Andric } else { 32895ffd83dbSDimitry Andric auto C = 32905ffd83dbSDimitry Andric CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str()); 32910b57cec5SDimitry Andric return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 32920b57cec5SDimitry Andric } 32930b57cec5SDimitry Andric } 32940b57cec5SDimitry Andric auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName); 32950b57cec5SDimitry Andric return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl); 32960b57cec5SDimitry Andric } 32970b57cec5SDimitry Andric 32980b57cec5SDimitry Andric /// Emit a type description suitable for use by a runtime sanitizer library. The 32990b57cec5SDimitry Andric /// format of a type descriptor is 33000b57cec5SDimitry Andric /// 33010b57cec5SDimitry Andric /// \code 33020b57cec5SDimitry Andric /// { i16 TypeKind, i16 TypeInfo } 33030b57cec5SDimitry Andric /// \endcode 33040b57cec5SDimitry Andric /// 33050b57cec5SDimitry Andric /// followed by an array of i8 containing the type name. TypeKind is 0 for an 33060b57cec5SDimitry Andric /// integer, 1 for a floating point value, and -1 for anything else. 33070b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) { 33080b57cec5SDimitry Andric // Only emit each type's descriptor once. 33090b57cec5SDimitry Andric if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T)) 33100b57cec5SDimitry Andric return C; 33110b57cec5SDimitry Andric 33120b57cec5SDimitry Andric uint16_t TypeKind = -1; 33130b57cec5SDimitry Andric uint16_t TypeInfo = 0; 33140b57cec5SDimitry Andric 33150b57cec5SDimitry Andric if (T->isIntegerType()) { 33160b57cec5SDimitry Andric TypeKind = 0; 33170b57cec5SDimitry Andric TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) | 33180b57cec5SDimitry Andric (T->isSignedIntegerType() ? 1 : 0); 33190b57cec5SDimitry Andric } else if (T->isFloatingType()) { 33200b57cec5SDimitry Andric TypeKind = 1; 33210b57cec5SDimitry Andric TypeInfo = getContext().getTypeSize(T); 33220b57cec5SDimitry Andric } 33230b57cec5SDimitry Andric 33240b57cec5SDimitry Andric // Format the type name as if for a diagnostic, including quotes and 33250b57cec5SDimitry Andric // optionally an 'aka'. 33260b57cec5SDimitry Andric SmallString<32> Buffer; 3327bdd1243dSDimitry Andric CGM.getDiags().ConvertArgToString( 3328bdd1243dSDimitry Andric DiagnosticsEngine::ak_qualtype, (intptr_t)T.getAsOpaquePtr(), StringRef(), 3329bdd1243dSDimitry Andric StringRef(), std::nullopt, Buffer, std::nullopt); 33300b57cec5SDimitry Andric 33310b57cec5SDimitry Andric llvm::Constant *Components[] = { 33320b57cec5SDimitry Andric Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo), 33330b57cec5SDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), Buffer) 33340b57cec5SDimitry Andric }; 33350b57cec5SDimitry Andric llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components); 33360b57cec5SDimitry Andric 33370b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 33380b57cec5SDimitry Andric CGM.getModule(), Descriptor->getType(), 33390b57cec5SDimitry Andric /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor); 33400b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 33410b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV); 33420b57cec5SDimitry Andric 33430b57cec5SDimitry Andric // Remember the descriptor for this type. 33440b57cec5SDimitry Andric CGM.setTypeDescriptorInMap(T, GV); 33450b57cec5SDimitry Andric 33460b57cec5SDimitry Andric return GV; 33470b57cec5SDimitry Andric } 33480b57cec5SDimitry Andric 33490b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) { 33500b57cec5SDimitry Andric llvm::Type *TargetTy = IntPtrTy; 33510b57cec5SDimitry Andric 33520b57cec5SDimitry Andric if (V->getType() == TargetTy) 33530b57cec5SDimitry Andric return V; 33540b57cec5SDimitry Andric 33550b57cec5SDimitry Andric // Floating-point types which fit into intptr_t are bitcast to integers 33560b57cec5SDimitry Andric // and then passed directly (after zero-extension, if necessary). 33570b57cec5SDimitry Andric if (V->getType()->isFloatingPointTy()) { 3358bdd1243dSDimitry Andric unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue(); 33590b57cec5SDimitry Andric if (Bits <= TargetTy->getIntegerBitWidth()) 33600b57cec5SDimitry Andric V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(), 33610b57cec5SDimitry Andric Bits)); 33620b57cec5SDimitry Andric } 33630b57cec5SDimitry Andric 33640b57cec5SDimitry Andric // Integers which fit in intptr_t are zero-extended and passed directly. 33650b57cec5SDimitry Andric if (V->getType()->isIntegerTy() && 33660b57cec5SDimitry Andric V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()) 33670b57cec5SDimitry Andric return Builder.CreateZExt(V, TargetTy); 33680b57cec5SDimitry Andric 33690b57cec5SDimitry Andric // Pointers are passed directly, everything else is passed by address. 33700b57cec5SDimitry Andric if (!V->getType()->isPointerTy()) { 33710fca6ea1SDimitry Andric RawAddress Ptr = CreateDefaultAlignTempAlloca(V->getType()); 33720b57cec5SDimitry Andric Builder.CreateStore(V, Ptr); 33730b57cec5SDimitry Andric V = Ptr.getPointer(); 33740b57cec5SDimitry Andric } 33750b57cec5SDimitry Andric return Builder.CreatePtrToInt(V, TargetTy); 33760b57cec5SDimitry Andric } 33770b57cec5SDimitry Andric 33780b57cec5SDimitry Andric /// Emit a representation of a SourceLocation for passing to a handler 33790b57cec5SDimitry Andric /// in a sanitizer runtime library. The format for this data is: 33800b57cec5SDimitry Andric /// \code 33810b57cec5SDimitry Andric /// struct SourceLocation { 33820b57cec5SDimitry Andric /// const char *Filename; 33830b57cec5SDimitry Andric /// int32_t Line, Column; 33840b57cec5SDimitry Andric /// }; 33850b57cec5SDimitry Andric /// \endcode 33860b57cec5SDimitry Andric /// For an invalid SourceLocation, the Filename pointer is null. 33870b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) { 33880b57cec5SDimitry Andric llvm::Constant *Filename; 33890b57cec5SDimitry Andric int Line, Column; 33900b57cec5SDimitry Andric 33910b57cec5SDimitry Andric PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc); 33920b57cec5SDimitry Andric if (PLoc.isValid()) { 33930b57cec5SDimitry Andric StringRef FilenameString = PLoc.getFilename(); 33940b57cec5SDimitry Andric 33950b57cec5SDimitry Andric int PathComponentsToStrip = 33960b57cec5SDimitry Andric CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip; 33970b57cec5SDimitry Andric if (PathComponentsToStrip < 0) { 33980b57cec5SDimitry Andric assert(PathComponentsToStrip != INT_MIN); 33990b57cec5SDimitry Andric int PathComponentsToKeep = -PathComponentsToStrip; 34000b57cec5SDimitry Andric auto I = llvm::sys::path::rbegin(FilenameString); 34010b57cec5SDimitry Andric auto E = llvm::sys::path::rend(FilenameString); 34020b57cec5SDimitry Andric while (I != E && --PathComponentsToKeep) 34030b57cec5SDimitry Andric ++I; 34040b57cec5SDimitry Andric 34050b57cec5SDimitry Andric FilenameString = FilenameString.substr(I - E); 34060b57cec5SDimitry Andric } else if (PathComponentsToStrip > 0) { 34070b57cec5SDimitry Andric auto I = llvm::sys::path::begin(FilenameString); 34080b57cec5SDimitry Andric auto E = llvm::sys::path::end(FilenameString); 34090b57cec5SDimitry Andric while (I != E && PathComponentsToStrip--) 34100b57cec5SDimitry Andric ++I; 34110b57cec5SDimitry Andric 34120b57cec5SDimitry Andric if (I != E) 34130b57cec5SDimitry Andric FilenameString = 34140b57cec5SDimitry Andric FilenameString.substr(I - llvm::sys::path::begin(FilenameString)); 34150b57cec5SDimitry Andric else 34160b57cec5SDimitry Andric FilenameString = llvm::sys::path::filename(FilenameString); 34170b57cec5SDimitry Andric } 34180b57cec5SDimitry Andric 34195ffd83dbSDimitry Andric auto FilenameGV = 34205ffd83dbSDimitry Andric CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src"); 34210b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal( 3422bdd1243dSDimitry Andric cast<llvm::GlobalVariable>( 3423bdd1243dSDimitry Andric FilenameGV.getPointer()->stripPointerCasts())); 34240b57cec5SDimitry Andric Filename = FilenameGV.getPointer(); 34250b57cec5SDimitry Andric Line = PLoc.getLine(); 34260b57cec5SDimitry Andric Column = PLoc.getColumn(); 34270b57cec5SDimitry Andric } else { 34280b57cec5SDimitry Andric Filename = llvm::Constant::getNullValue(Int8PtrTy); 34290b57cec5SDimitry Andric Line = Column = 0; 34300b57cec5SDimitry Andric } 34310b57cec5SDimitry Andric 34320b57cec5SDimitry Andric llvm::Constant *Data[] = {Filename, Builder.getInt32(Line), 34330b57cec5SDimitry Andric Builder.getInt32(Column)}; 34340b57cec5SDimitry Andric 34350b57cec5SDimitry Andric return llvm::ConstantStruct::getAnon(Data); 34360b57cec5SDimitry Andric } 34370b57cec5SDimitry Andric 34380b57cec5SDimitry Andric namespace { 34390b57cec5SDimitry Andric /// Specify under what conditions this check can be recovered 34400b57cec5SDimitry Andric enum class CheckRecoverableKind { 34410b57cec5SDimitry Andric /// Always terminate program execution if this check fails. 34420b57cec5SDimitry Andric Unrecoverable, 34430b57cec5SDimitry Andric /// Check supports recovering, runtime has both fatal (noreturn) and 34440b57cec5SDimitry Andric /// non-fatal handlers for this check. 34450b57cec5SDimitry Andric Recoverable, 34460b57cec5SDimitry Andric /// Runtime conditionally aborts, always need to support recovery. 34470b57cec5SDimitry Andric AlwaysRecoverable 34480b57cec5SDimitry Andric }; 34490b57cec5SDimitry Andric } 34500b57cec5SDimitry Andric 34510b57cec5SDimitry Andric static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) { 34520b57cec5SDimitry Andric assert(Kind.countPopulation() == 1); 345306c3fb27SDimitry Andric if (Kind == SanitizerKind::Vptr) 34540b57cec5SDimitry Andric return CheckRecoverableKind::AlwaysRecoverable; 34550b57cec5SDimitry Andric else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable) 34560b57cec5SDimitry Andric return CheckRecoverableKind::Unrecoverable; 34570b57cec5SDimitry Andric else 34580b57cec5SDimitry Andric return CheckRecoverableKind::Recoverable; 34590b57cec5SDimitry Andric } 34600b57cec5SDimitry Andric 34610b57cec5SDimitry Andric namespace { 34620b57cec5SDimitry Andric struct SanitizerHandlerInfo { 34630b57cec5SDimitry Andric char const *const Name; 34640b57cec5SDimitry Andric unsigned Version; 34650b57cec5SDimitry Andric }; 34660b57cec5SDimitry Andric } 34670b57cec5SDimitry Andric 34680b57cec5SDimitry Andric const SanitizerHandlerInfo SanitizerHandlers[] = { 34690b57cec5SDimitry Andric #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version}, 34700b57cec5SDimitry Andric LIST_SANITIZER_CHECKS 34710b57cec5SDimitry Andric #undef SANITIZER_CHECK 34720b57cec5SDimitry Andric }; 34730b57cec5SDimitry Andric 34740b57cec5SDimitry Andric static void emitCheckHandlerCall(CodeGenFunction &CGF, 34750b57cec5SDimitry Andric llvm::FunctionType *FnType, 34760b57cec5SDimitry Andric ArrayRef<llvm::Value *> FnArgs, 34770b57cec5SDimitry Andric SanitizerHandler CheckHandler, 34780b57cec5SDimitry Andric CheckRecoverableKind RecoverKind, bool IsFatal, 34790b57cec5SDimitry Andric llvm::BasicBlock *ContBB) { 34800b57cec5SDimitry Andric assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable); 3481bdd1243dSDimitry Andric std::optional<ApplyDebugLocation> DL; 34820b57cec5SDimitry Andric if (!CGF.Builder.getCurrentDebugLocation()) { 34830b57cec5SDimitry Andric // Ensure that the call has at least an artificial debug location. 34840b57cec5SDimitry Andric DL.emplace(CGF, SourceLocation()); 34850b57cec5SDimitry Andric } 34860b57cec5SDimitry Andric bool NeedsAbortSuffix = 34870b57cec5SDimitry Andric IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable; 34880b57cec5SDimitry Andric bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime; 34890b57cec5SDimitry Andric const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler]; 34900b57cec5SDimitry Andric const StringRef CheckName = CheckInfo.Name; 34910b57cec5SDimitry Andric std::string FnName = "__ubsan_handle_" + CheckName.str(); 34920b57cec5SDimitry Andric if (CheckInfo.Version && !MinimalRuntime) 34930b57cec5SDimitry Andric FnName += "_v" + llvm::utostr(CheckInfo.Version); 34940b57cec5SDimitry Andric if (MinimalRuntime) 34950b57cec5SDimitry Andric FnName += "_minimal"; 34960b57cec5SDimitry Andric if (NeedsAbortSuffix) 34970b57cec5SDimitry Andric FnName += "_abort"; 34980b57cec5SDimitry Andric bool MayReturn = 34990b57cec5SDimitry Andric !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable; 35000b57cec5SDimitry Andric 350104eeddc0SDimitry Andric llvm::AttrBuilder B(CGF.getLLVMContext()); 35020b57cec5SDimitry Andric if (!MayReturn) { 35030b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoReturn) 35040b57cec5SDimitry Andric .addAttribute(llvm::Attribute::NoUnwind); 35050b57cec5SDimitry Andric } 350681ad6265SDimitry Andric B.addUWTableAttr(llvm::UWTableKind::Default); 35070b57cec5SDimitry Andric 35080b57cec5SDimitry Andric llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction( 35090b57cec5SDimitry Andric FnType, FnName, 35100b57cec5SDimitry Andric llvm::AttributeList::get(CGF.getLLVMContext(), 35110b57cec5SDimitry Andric llvm::AttributeList::FunctionIndex, B), 35120b57cec5SDimitry Andric /*Local=*/true); 35130b57cec5SDimitry Andric llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs); 35140b57cec5SDimitry Andric if (!MayReturn) { 35150b57cec5SDimitry Andric HandlerCall->setDoesNotReturn(); 35160b57cec5SDimitry Andric CGF.Builder.CreateUnreachable(); 35170b57cec5SDimitry Andric } else { 35180b57cec5SDimitry Andric CGF.Builder.CreateBr(ContBB); 35190b57cec5SDimitry Andric } 35200b57cec5SDimitry Andric } 35210b57cec5SDimitry Andric 35220b57cec5SDimitry Andric void CodeGenFunction::EmitCheck( 35230b57cec5SDimitry Andric ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 35240b57cec5SDimitry Andric SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs, 35250b57cec5SDimitry Andric ArrayRef<llvm::Value *> DynamicArgs) { 35260b57cec5SDimitry Andric assert(IsSanitizerScope); 35270b57cec5SDimitry Andric assert(Checked.size() > 0); 35280b57cec5SDimitry Andric assert(CheckHandler >= 0 && 3529bdd1243dSDimitry Andric size_t(CheckHandler) < std::size(SanitizerHandlers)); 35300b57cec5SDimitry Andric const StringRef CheckName = SanitizerHandlers[CheckHandler].Name; 35310b57cec5SDimitry Andric 35320b57cec5SDimitry Andric llvm::Value *FatalCond = nullptr; 35330b57cec5SDimitry Andric llvm::Value *RecoverableCond = nullptr; 35340b57cec5SDimitry Andric llvm::Value *TrapCond = nullptr; 35350b57cec5SDimitry Andric for (int i = 0, n = Checked.size(); i < n; ++i) { 35360b57cec5SDimitry Andric llvm::Value *Check = Checked[i].first; 35370b57cec5SDimitry Andric // -fsanitize-trap= overrides -fsanitize-recover=. 35380b57cec5SDimitry Andric llvm::Value *&Cond = 35390b57cec5SDimitry Andric CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second) 35400b57cec5SDimitry Andric ? TrapCond 35410b57cec5SDimitry Andric : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second) 35420b57cec5SDimitry Andric ? RecoverableCond 35430b57cec5SDimitry Andric : FatalCond; 35440b57cec5SDimitry Andric Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check; 35450b57cec5SDimitry Andric } 35460b57cec5SDimitry Andric 35470fca6ea1SDimitry Andric if (ClSanitizeGuardChecks) { 35480fca6ea1SDimitry Andric llvm::Value *Allow = 35490fca6ea1SDimitry Andric Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::allow_ubsan_check), 35500fca6ea1SDimitry Andric llvm::ConstantInt::get(CGM.Int8Ty, CheckHandler)); 35510fca6ea1SDimitry Andric 35520fca6ea1SDimitry Andric for (llvm::Value **Cond : {&FatalCond, &RecoverableCond, &TrapCond}) { 35530fca6ea1SDimitry Andric if (*Cond) 35540fca6ea1SDimitry Andric *Cond = Builder.CreateOr(*Cond, Builder.CreateNot(Allow)); 35550fca6ea1SDimitry Andric } 35560fca6ea1SDimitry Andric } 35570fca6ea1SDimitry Andric 35580b57cec5SDimitry Andric if (TrapCond) 3559e8d8bef9SDimitry Andric EmitTrapCheck(TrapCond, CheckHandler); 35600b57cec5SDimitry Andric if (!FatalCond && !RecoverableCond) 35610b57cec5SDimitry Andric return; 35620b57cec5SDimitry Andric 35630b57cec5SDimitry Andric llvm::Value *JointCond; 35640b57cec5SDimitry Andric if (FatalCond && RecoverableCond) 35650b57cec5SDimitry Andric JointCond = Builder.CreateAnd(FatalCond, RecoverableCond); 35660b57cec5SDimitry Andric else 35670b57cec5SDimitry Andric JointCond = FatalCond ? FatalCond : RecoverableCond; 35680b57cec5SDimitry Andric assert(JointCond); 35690b57cec5SDimitry Andric 35700b57cec5SDimitry Andric CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second); 35710b57cec5SDimitry Andric assert(SanOpts.has(Checked[0].second)); 35720b57cec5SDimitry Andric #ifndef NDEBUG 35730b57cec5SDimitry Andric for (int i = 1, n = Checked.size(); i < n; ++i) { 35740b57cec5SDimitry Andric assert(RecoverKind == getRecoverableKind(Checked[i].second) && 35750b57cec5SDimitry Andric "All recoverable kinds in a single check must be same!"); 35760b57cec5SDimitry Andric assert(SanOpts.has(Checked[i].second)); 35770b57cec5SDimitry Andric } 35780b57cec5SDimitry Andric #endif 35790b57cec5SDimitry Andric 35800b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont"); 35810b57cec5SDimitry Andric llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName); 35820b57cec5SDimitry Andric llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers); 35830b57cec5SDimitry Andric // Give hint that we very much don't expect to execute the handler 35840b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext()); 35850fca6ea1SDimitry Andric llvm::MDNode *Node = MDHelper.createLikelyBranchWeights(); 35860b57cec5SDimitry Andric Branch->setMetadata(llvm::LLVMContext::MD_prof, Node); 35870b57cec5SDimitry Andric EmitBlock(Handlers); 35880b57cec5SDimitry Andric 35890b57cec5SDimitry Andric // Handler functions take an i8* pointing to the (handler-specific) static 35900b57cec5SDimitry Andric // information block, followed by a sequence of intptr_t arguments 35910b57cec5SDimitry Andric // representing operand values. 35920b57cec5SDimitry Andric SmallVector<llvm::Value *, 4> Args; 35930b57cec5SDimitry Andric SmallVector<llvm::Type *, 4> ArgTypes; 35940b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) { 35950b57cec5SDimitry Andric Args.reserve(DynamicArgs.size() + 1); 35960b57cec5SDimitry Andric ArgTypes.reserve(DynamicArgs.size() + 1); 35970b57cec5SDimitry Andric 35980b57cec5SDimitry Andric // Emit handler arguments and create handler function type. 35990b57cec5SDimitry Andric if (!StaticArgs.empty()) { 36000b57cec5SDimitry Andric llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 3601bdd1243dSDimitry Andric auto *InfoPtr = new llvm::GlobalVariable( 3602bdd1243dSDimitry Andric CGM.getModule(), Info->getType(), false, 3603bdd1243dSDimitry Andric llvm::GlobalVariable::PrivateLinkage, Info, "", nullptr, 3604bdd1243dSDimitry Andric llvm::GlobalVariable::NotThreadLocal, 3605bdd1243dSDimitry Andric CGM.getDataLayout().getDefaultGlobalsAddressSpace()); 36060b57cec5SDimitry Andric InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 36070b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 360806c3fb27SDimitry Andric Args.push_back(InfoPtr); 3609bdd1243dSDimitry Andric ArgTypes.push_back(Args.back()->getType()); 36100b57cec5SDimitry Andric } 36110b57cec5SDimitry Andric 36120b57cec5SDimitry Andric for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) { 36130b57cec5SDimitry Andric Args.push_back(EmitCheckValue(DynamicArgs[i])); 36140b57cec5SDimitry Andric ArgTypes.push_back(IntPtrTy); 36150b57cec5SDimitry Andric } 36160b57cec5SDimitry Andric } 36170b57cec5SDimitry Andric 36180b57cec5SDimitry Andric llvm::FunctionType *FnType = 36190b57cec5SDimitry Andric llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false); 36200b57cec5SDimitry Andric 36210b57cec5SDimitry Andric if (!FatalCond || !RecoverableCond) { 36220b57cec5SDimitry Andric // Simple case: we need to generate a single handler call, either 36230b57cec5SDimitry Andric // fatal, or non-fatal. 36240b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, 36250b57cec5SDimitry Andric (FatalCond != nullptr), Cont); 36260b57cec5SDimitry Andric } else { 36270b57cec5SDimitry Andric // Emit two handler calls: first one for set of unrecoverable checks, 36280b57cec5SDimitry Andric // another one for recoverable. 36290b57cec5SDimitry Andric llvm::BasicBlock *NonFatalHandlerBB = 36300b57cec5SDimitry Andric createBasicBlock("non_fatal." + CheckName); 36310b57cec5SDimitry Andric llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName); 36320b57cec5SDimitry Andric Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB); 36330b57cec5SDimitry Andric EmitBlock(FatalHandlerBB); 36340b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true, 36350b57cec5SDimitry Andric NonFatalHandlerBB); 36360b57cec5SDimitry Andric EmitBlock(NonFatalHandlerBB); 36370b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false, 36380b57cec5SDimitry Andric Cont); 36390b57cec5SDimitry Andric } 36400b57cec5SDimitry Andric 36410b57cec5SDimitry Andric EmitBlock(Cont); 36420b57cec5SDimitry Andric } 36430b57cec5SDimitry Andric 36440b57cec5SDimitry Andric void CodeGenFunction::EmitCfiSlowPathCheck( 36450b57cec5SDimitry Andric SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId, 36460b57cec5SDimitry Andric llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) { 36470b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cfi.cont"); 36480b57cec5SDimitry Andric 36490b57cec5SDimitry Andric llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath"); 36500b57cec5SDimitry Andric llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB); 36510b57cec5SDimitry Andric 36520b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext()); 36530fca6ea1SDimitry Andric llvm::MDNode *Node = MDHelper.createLikelyBranchWeights(); 36540b57cec5SDimitry Andric BI->setMetadata(llvm::LLVMContext::MD_prof, Node); 36550b57cec5SDimitry Andric 36560b57cec5SDimitry Andric EmitBlock(CheckBB); 36570b57cec5SDimitry Andric 36580b57cec5SDimitry Andric bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind); 36590b57cec5SDimitry Andric 36600b57cec5SDimitry Andric llvm::CallInst *CheckCall; 36610b57cec5SDimitry Andric llvm::FunctionCallee SlowPathFn; 36620b57cec5SDimitry Andric if (WithDiag) { 36630b57cec5SDimitry Andric llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs); 36640b57cec5SDimitry Andric auto *InfoPtr = 36650b57cec5SDimitry Andric new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false, 36660b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage, Info); 36670b57cec5SDimitry Andric InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 36680b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr); 36690b57cec5SDimitry Andric 36700b57cec5SDimitry Andric SlowPathFn = CGM.getModule().getOrInsertFunction( 36710b57cec5SDimitry Andric "__cfi_slowpath_diag", 36720b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, 36730b57cec5SDimitry Andric false)); 36745f757f3fSDimitry Andric CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr}); 36750b57cec5SDimitry Andric } else { 36760b57cec5SDimitry Andric SlowPathFn = CGM.getModule().getOrInsertFunction( 36770b57cec5SDimitry Andric "__cfi_slowpath", 36780b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false)); 36790b57cec5SDimitry Andric CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr}); 36800b57cec5SDimitry Andric } 36810b57cec5SDimitry Andric 36820b57cec5SDimitry Andric CGM.setDSOLocal( 36830b57cec5SDimitry Andric cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts())); 36840b57cec5SDimitry Andric CheckCall->setDoesNotThrow(); 36850b57cec5SDimitry Andric 36860b57cec5SDimitry Andric EmitBlock(Cont); 36870b57cec5SDimitry Andric } 36880b57cec5SDimitry Andric 36890b57cec5SDimitry Andric // Emit a stub for __cfi_check function so that the linker knows about this 36900b57cec5SDimitry Andric // symbol in LTO mode. 36910b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckStub() { 36920b57cec5SDimitry Andric llvm::Module *M = &CGM.getModule(); 36930fca6ea1SDimitry Andric ASTContext &C = getContext(); 36940fca6ea1SDimitry Andric QualType QInt64Ty = C.getIntTypeForBitwidth(64, false); 36950fca6ea1SDimitry Andric 36960fca6ea1SDimitry Andric FunctionArgList FnArgs; 36970fca6ea1SDimitry Andric ImplicitParamDecl ArgCallsiteTypeId(C, QInt64Ty, ImplicitParamKind::Other); 36980fca6ea1SDimitry Andric ImplicitParamDecl ArgAddr(C, C.VoidPtrTy, ImplicitParamKind::Other); 36990fca6ea1SDimitry Andric ImplicitParamDecl ArgCFICheckFailData(C, C.VoidPtrTy, 37000fca6ea1SDimitry Andric ImplicitParamKind::Other); 37010fca6ea1SDimitry Andric FnArgs.push_back(&ArgCallsiteTypeId); 37020fca6ea1SDimitry Andric FnArgs.push_back(&ArgAddr); 37030fca6ea1SDimitry Andric FnArgs.push_back(&ArgCFICheckFailData); 37040fca6ea1SDimitry Andric const CGFunctionInfo &FI = 37050fca6ea1SDimitry Andric CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, FnArgs); 37060fca6ea1SDimitry Andric 37070b57cec5SDimitry Andric llvm::Function *F = llvm::Function::Create( 37080fca6ea1SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy, VoidPtrTy}, false), 37090b57cec5SDimitry Andric llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M); 37100fca6ea1SDimitry Andric CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false); 37110fca6ea1SDimitry Andric CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F); 37125f757f3fSDimitry Andric F->setAlignment(llvm::Align(4096)); 37130b57cec5SDimitry Andric CGM.setDSOLocal(F); 37140fca6ea1SDimitry Andric 37150fca6ea1SDimitry Andric llvm::LLVMContext &Ctx = M->getContext(); 37160b57cec5SDimitry Andric llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F); 37175f757f3fSDimitry Andric // CrossDSOCFI pass is not executed if there is no executable code. 37185f757f3fSDimitry Andric SmallVector<llvm::Value*> Args{F->getArg(2), F->getArg(1)}; 37195f757f3fSDimitry Andric llvm::CallInst::Create(M->getFunction("__cfi_check_fail"), Args, "", BB); 37200b57cec5SDimitry Andric llvm::ReturnInst::Create(Ctx, nullptr, BB); 37210b57cec5SDimitry Andric } 37220b57cec5SDimitry Andric 37230b57cec5SDimitry Andric // This function is basically a switch over the CFI failure kind, which is 37240b57cec5SDimitry Andric // extracted from CFICheckFailData (1st function argument). Each case is either 37250b57cec5SDimitry Andric // llvm.trap or a call to one of the two runtime handlers, based on 37260b57cec5SDimitry Andric // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid 37270b57cec5SDimitry Andric // failure kind) traps, but this should really never happen. CFICheckFailData 37280b57cec5SDimitry Andric // can be nullptr if the calling module has -fsanitize-trap behavior for this 37290b57cec5SDimitry Andric // check kind; in this case __cfi_check_fail traps as well. 37300b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckFail() { 37310b57cec5SDimitry Andric SanitizerScope SanScope(this); 37320b57cec5SDimitry Andric FunctionArgList Args; 37330b57cec5SDimitry Andric ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy, 37345f757f3fSDimitry Andric ImplicitParamKind::Other); 37350b57cec5SDimitry Andric ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy, 37365f757f3fSDimitry Andric ImplicitParamKind::Other); 37370b57cec5SDimitry Andric Args.push_back(&ArgData); 37380b57cec5SDimitry Andric Args.push_back(&ArgAddr); 37390b57cec5SDimitry Andric 37400b57cec5SDimitry Andric const CGFunctionInfo &FI = 37410b57cec5SDimitry Andric CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args); 37420b57cec5SDimitry Andric 37430b57cec5SDimitry Andric llvm::Function *F = llvm::Function::Create( 37440b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false), 37450b57cec5SDimitry Andric llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule()); 3746480093f4SDimitry Andric 3747fe6060f1SDimitry Andric CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false); 3748480093f4SDimitry Andric CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F); 37490b57cec5SDimitry Andric F->setVisibility(llvm::GlobalValue::HiddenVisibility); 37500b57cec5SDimitry Andric 37510b57cec5SDimitry Andric StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args, 37520b57cec5SDimitry Andric SourceLocation()); 37530b57cec5SDimitry Andric 3754fe6060f1SDimitry Andric // This function is not affected by NoSanitizeList. This function does 37550b57cec5SDimitry Andric // not have a source location, but "src:*" would still apply. Revert any 37560b57cec5SDimitry Andric // changes to SanOpts made in StartFunction. 37570b57cec5SDimitry Andric SanOpts = CGM.getLangOpts().Sanitize; 37580b57cec5SDimitry Andric 37590b57cec5SDimitry Andric llvm::Value *Data = 37600b57cec5SDimitry Andric EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false, 37610b57cec5SDimitry Andric CGM.getContext().VoidPtrTy, ArgData.getLocation()); 37620b57cec5SDimitry Andric llvm::Value *Addr = 37630b57cec5SDimitry Andric EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false, 37640b57cec5SDimitry Andric CGM.getContext().VoidPtrTy, ArgAddr.getLocation()); 37650b57cec5SDimitry Andric 37660b57cec5SDimitry Andric // Data == nullptr means the calling module has trap behaviour for this check. 37670b57cec5SDimitry Andric llvm::Value *DataIsNotNullPtr = 37680b57cec5SDimitry Andric Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy)); 3769e8d8bef9SDimitry Andric EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail); 37700b57cec5SDimitry Andric 37710b57cec5SDimitry Andric llvm::StructType *SourceLocationTy = 37720b57cec5SDimitry Andric llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty); 37730b57cec5SDimitry Andric llvm::StructType *CfiCheckFailDataTy = 37740b57cec5SDimitry Andric llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy); 37750b57cec5SDimitry Andric 37760b57cec5SDimitry Andric llvm::Value *V = Builder.CreateConstGEP2_32( 37770b57cec5SDimitry Andric CfiCheckFailDataTy, 37780b57cec5SDimitry Andric Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0, 37790b57cec5SDimitry Andric 0); 378081ad6265SDimitry Andric 378181ad6265SDimitry Andric Address CheckKindAddr(V, Int8Ty, getIntAlign()); 37820b57cec5SDimitry Andric llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr); 37830b57cec5SDimitry Andric 37840b57cec5SDimitry Andric llvm::Value *AllVtables = llvm::MetadataAsValue::get( 37850b57cec5SDimitry Andric CGM.getLLVMContext(), 37860b57cec5SDimitry Andric llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 37870b57cec5SDimitry Andric llvm::Value *ValidVtable = Builder.CreateZExt( 37880b57cec5SDimitry Andric Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), 37890b57cec5SDimitry Andric {Addr, AllVtables}), 37900b57cec5SDimitry Andric IntPtrTy); 37910b57cec5SDimitry Andric 37920b57cec5SDimitry Andric const std::pair<int, SanitizerMask> CheckKinds[] = { 37930b57cec5SDimitry Andric {CFITCK_VCall, SanitizerKind::CFIVCall}, 37940b57cec5SDimitry Andric {CFITCK_NVCall, SanitizerKind::CFINVCall}, 37950b57cec5SDimitry Andric {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast}, 37960b57cec5SDimitry Andric {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast}, 37970b57cec5SDimitry Andric {CFITCK_ICall, SanitizerKind::CFIICall}}; 37980b57cec5SDimitry Andric 37990b57cec5SDimitry Andric SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks; 38000b57cec5SDimitry Andric for (auto CheckKindMaskPair : CheckKinds) { 38010b57cec5SDimitry Andric int Kind = CheckKindMaskPair.first; 38020b57cec5SDimitry Andric SanitizerMask Mask = CheckKindMaskPair.second; 38030b57cec5SDimitry Andric llvm::Value *Cond = 38040b57cec5SDimitry Andric Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind)); 38050b57cec5SDimitry Andric if (CGM.getLangOpts().Sanitize.has(Mask)) 38060b57cec5SDimitry Andric EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {}, 38070b57cec5SDimitry Andric {Data, Addr, ValidVtable}); 38080b57cec5SDimitry Andric else 3809e8d8bef9SDimitry Andric EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail); 38100b57cec5SDimitry Andric } 38110b57cec5SDimitry Andric 38120b57cec5SDimitry Andric FinishFunction(); 38130b57cec5SDimitry Andric // The only reference to this function will be created during LTO link. 38140b57cec5SDimitry Andric // Make sure it survives until then. 38150b57cec5SDimitry Andric CGM.addUsedGlobal(F); 38160b57cec5SDimitry Andric } 38170b57cec5SDimitry Andric 38180b57cec5SDimitry Andric void CodeGenFunction::EmitUnreachable(SourceLocation Loc) { 38190b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Unreachable)) { 38200b57cec5SDimitry Andric SanitizerScope SanScope(this); 38210b57cec5SDimitry Andric EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()), 38220b57cec5SDimitry Andric SanitizerKind::Unreachable), 38230b57cec5SDimitry Andric SanitizerHandler::BuiltinUnreachable, 3824bdd1243dSDimitry Andric EmitCheckSourceLocation(Loc), std::nullopt); 38250b57cec5SDimitry Andric } 38260b57cec5SDimitry Andric Builder.CreateUnreachable(); 38270b57cec5SDimitry Andric } 38280b57cec5SDimitry Andric 3829e8d8bef9SDimitry Andric void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked, 3830e8d8bef9SDimitry Andric SanitizerHandler CheckHandlerID) { 38310b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont"); 38320b57cec5SDimitry Andric 38330b57cec5SDimitry Andric // If we're optimizing, collapse all calls to trap down to just one per 3834e8d8bef9SDimitry Andric // check-type per function to save on code size. 38350fca6ea1SDimitry Andric if ((int)TrapBBs.size() <= CheckHandlerID) 3836e8d8bef9SDimitry Andric TrapBBs.resize(CheckHandlerID + 1); 38375f757f3fSDimitry Andric 3838e8d8bef9SDimitry Andric llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID]; 3839e8d8bef9SDimitry Andric 38405f757f3fSDimitry Andric if (!ClSanitizeDebugDeoptimization && 38415f757f3fSDimitry Andric CGM.getCodeGenOpts().OptimizationLevel && TrapBB && 38425f757f3fSDimitry Andric (!CurCodeDecl || !CurCodeDecl->hasAttr<OptimizeNoneAttr>())) { 38435f757f3fSDimitry Andric auto Call = TrapBB->begin(); 38445f757f3fSDimitry Andric assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB"); 38455f757f3fSDimitry Andric 38465f757f3fSDimitry Andric Call->applyMergedLocation(Call->getDebugLoc(), 38475f757f3fSDimitry Andric Builder.getCurrentDebugLocation()); 38485f757f3fSDimitry Andric Builder.CreateCondBr(Checked, Cont, TrapBB); 38495f757f3fSDimitry Andric } else { 38500b57cec5SDimitry Andric TrapBB = createBasicBlock("trap"); 38510b57cec5SDimitry Andric Builder.CreateCondBr(Checked, Cont, TrapBB); 38520b57cec5SDimitry Andric EmitBlock(TrapBB); 3853e8d8bef9SDimitry Andric 38545f757f3fSDimitry Andric llvm::CallInst *TrapCall = Builder.CreateCall( 38555f757f3fSDimitry Andric CGM.getIntrinsic(llvm::Intrinsic::ubsantrap), 38560fca6ea1SDimitry Andric llvm::ConstantInt::get(CGM.Int8Ty, 38570fca6ea1SDimitry Andric ClSanitizeDebugDeoptimization 38585f757f3fSDimitry Andric ? TrapBB->getParent()->size() 38590fca6ea1SDimitry Andric : static_cast<uint64_t>(CheckHandlerID))); 3860e8d8bef9SDimitry Andric 3861e8d8bef9SDimitry Andric if (!CGM.getCodeGenOpts().TrapFuncName.empty()) { 3862e8d8bef9SDimitry Andric auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name", 3863e8d8bef9SDimitry Andric CGM.getCodeGenOpts().TrapFuncName); 3864349cc55cSDimitry Andric TrapCall->addFnAttr(A); 3865e8d8bef9SDimitry Andric } 38660b57cec5SDimitry Andric TrapCall->setDoesNotReturn(); 38670b57cec5SDimitry Andric TrapCall->setDoesNotThrow(); 38680b57cec5SDimitry Andric Builder.CreateUnreachable(); 38690b57cec5SDimitry Andric } 38700b57cec5SDimitry Andric 38710b57cec5SDimitry Andric EmitBlock(Cont); 38720b57cec5SDimitry Andric } 38730b57cec5SDimitry Andric 38740b57cec5SDimitry Andric llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) { 3875e8d8bef9SDimitry Andric llvm::CallInst *TrapCall = 3876e8d8bef9SDimitry Andric Builder.CreateCall(CGM.getIntrinsic(IntrID)); 38770b57cec5SDimitry Andric 38780b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().TrapFuncName.empty()) { 38790b57cec5SDimitry Andric auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name", 38800b57cec5SDimitry Andric CGM.getCodeGenOpts().TrapFuncName); 3881349cc55cSDimitry Andric TrapCall->addFnAttr(A); 38820b57cec5SDimitry Andric } 38830b57cec5SDimitry Andric 38840b57cec5SDimitry Andric return TrapCall; 38850b57cec5SDimitry Andric } 38860b57cec5SDimitry Andric 38870b57cec5SDimitry Andric Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E, 38880b57cec5SDimitry Andric LValueBaseInfo *BaseInfo, 38890b57cec5SDimitry Andric TBAAAccessInfo *TBAAInfo) { 38900b57cec5SDimitry Andric assert(E->getType()->isArrayType() && 38910b57cec5SDimitry Andric "Array to pointer decay must have array source type!"); 38920b57cec5SDimitry Andric 38930b57cec5SDimitry Andric // Expressions of array type can't be bitfields or vector elements. 38940b57cec5SDimitry Andric LValue LV = EmitLValue(E); 38950fca6ea1SDimitry Andric Address Addr = LV.getAddress(); 38960b57cec5SDimitry Andric 38970b57cec5SDimitry Andric // If the array type was an incomplete type, we need to make sure 38980b57cec5SDimitry Andric // the decay ends up being the right type. 38990b57cec5SDimitry Andric llvm::Type *NewTy = ConvertType(E->getType()); 390006c3fb27SDimitry Andric Addr = Addr.withElementType(NewTy); 39010b57cec5SDimitry Andric 39020b57cec5SDimitry Andric // Note that VLA pointers are always decayed, so we don't need to do 39030b57cec5SDimitry Andric // anything here. 39040b57cec5SDimitry Andric if (!E->getType()->isVariableArrayType()) { 39050b57cec5SDimitry Andric assert(isa<llvm::ArrayType>(Addr.getElementType()) && 39060b57cec5SDimitry Andric "Expected pointer to array"); 39070b57cec5SDimitry Andric Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay"); 39080b57cec5SDimitry Andric } 39090b57cec5SDimitry Andric 39100b57cec5SDimitry Andric // The result of this decay conversion points to an array element within the 39110b57cec5SDimitry Andric // base lvalue. However, since TBAA currently does not support representing 39120b57cec5SDimitry Andric // accesses to elements of member arrays, we conservatively represent accesses 39130b57cec5SDimitry Andric // to the pointee object as if it had no any base lvalue specified. 39140b57cec5SDimitry Andric // TODO: Support TBAA for member arrays. 39150b57cec5SDimitry Andric QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType(); 39160b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = LV.getBaseInfo(); 39170b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType); 39180b57cec5SDimitry Andric 391906c3fb27SDimitry Andric return Addr.withElementType(ConvertTypeForMem(EltType)); 39200b57cec5SDimitry Andric } 39210b57cec5SDimitry Andric 39220b57cec5SDimitry Andric /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an 39230b57cec5SDimitry Andric /// array to pointer, return the array subexpression. 39240b57cec5SDimitry Andric static const Expr *isSimpleArrayDecayOperand(const Expr *E) { 39250b57cec5SDimitry Andric // If this isn't just an array->pointer decay, bail out. 39260b57cec5SDimitry Andric const auto *CE = dyn_cast<CastExpr>(E); 39270b57cec5SDimitry Andric if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay) 39280b57cec5SDimitry Andric return nullptr; 39290b57cec5SDimitry Andric 39300b57cec5SDimitry Andric // If this is a decay from variable width array, bail out. 39310b57cec5SDimitry Andric const Expr *SubExpr = CE->getSubExpr(); 39320b57cec5SDimitry Andric if (SubExpr->getType()->isVariableArrayType()) 39330b57cec5SDimitry Andric return nullptr; 39340b57cec5SDimitry Andric 39350b57cec5SDimitry Andric return SubExpr; 39360b57cec5SDimitry Andric } 39370b57cec5SDimitry Andric 39380b57cec5SDimitry Andric static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF, 3939fe6060f1SDimitry Andric llvm::Type *elemType, 39400b57cec5SDimitry Andric llvm::Value *ptr, 39410b57cec5SDimitry Andric ArrayRef<llvm::Value*> indices, 39420b57cec5SDimitry Andric bool inbounds, 39430b57cec5SDimitry Andric bool signedIndices, 39440b57cec5SDimitry Andric SourceLocation loc, 39450b57cec5SDimitry Andric const llvm::Twine &name = "arrayidx") { 39460b57cec5SDimitry Andric if (inbounds) { 39470eae32dcSDimitry Andric return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices, 39480b57cec5SDimitry Andric CodeGenFunction::NotSubtraction, loc, 39490b57cec5SDimitry Andric name); 39500b57cec5SDimitry Andric } else { 3951fe6060f1SDimitry Andric return CGF.Builder.CreateGEP(elemType, ptr, indices, name); 39520b57cec5SDimitry Andric } 39530b57cec5SDimitry Andric } 39540b57cec5SDimitry Andric 39550fca6ea1SDimitry Andric static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, 39560fca6ea1SDimitry Andric ArrayRef<llvm::Value *> indices, 39570fca6ea1SDimitry Andric llvm::Type *elementType, bool inbounds, 39580fca6ea1SDimitry Andric bool signedIndices, SourceLocation loc, 39590fca6ea1SDimitry Andric CharUnits align, 39600fca6ea1SDimitry Andric const llvm::Twine &name = "arrayidx") { 39610fca6ea1SDimitry Andric if (inbounds) { 39620fca6ea1SDimitry Andric return CGF.EmitCheckedInBoundsGEP(addr, indices, elementType, signedIndices, 39630fca6ea1SDimitry Andric CodeGenFunction::NotSubtraction, loc, 39640fca6ea1SDimitry Andric align, name); 39650fca6ea1SDimitry Andric } else { 39660fca6ea1SDimitry Andric return CGF.Builder.CreateGEP(addr, indices, elementType, align, name); 39670fca6ea1SDimitry Andric } 39680fca6ea1SDimitry Andric } 39690fca6ea1SDimitry Andric 39700b57cec5SDimitry Andric static CharUnits getArrayElementAlign(CharUnits arrayAlign, 39710b57cec5SDimitry Andric llvm::Value *idx, 39720b57cec5SDimitry Andric CharUnits eltSize) { 39730b57cec5SDimitry Andric // If we have a constant index, we can use the exact offset of the 39740b57cec5SDimitry Andric // element we're accessing. 39750b57cec5SDimitry Andric if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) { 39760b57cec5SDimitry Andric CharUnits offset = constantIdx->getZExtValue() * eltSize; 39770b57cec5SDimitry Andric return arrayAlign.alignmentAtOffset(offset); 39780b57cec5SDimitry Andric 39790b57cec5SDimitry Andric // Otherwise, use the worst-case alignment for any element. 39800b57cec5SDimitry Andric } else { 39810b57cec5SDimitry Andric return arrayAlign.alignmentOfArrayElement(eltSize); 39820b57cec5SDimitry Andric } 39830b57cec5SDimitry Andric } 39840b57cec5SDimitry Andric 39850b57cec5SDimitry Andric static QualType getFixedSizeElementType(const ASTContext &ctx, 39860b57cec5SDimitry Andric const VariableArrayType *vla) { 39870b57cec5SDimitry Andric QualType eltType; 39880b57cec5SDimitry Andric do { 39890b57cec5SDimitry Andric eltType = vla->getElementType(); 39900b57cec5SDimitry Andric } while ((vla = ctx.getAsVariableArrayType(eltType))); 39910b57cec5SDimitry Andric return eltType; 39920b57cec5SDimitry Andric } 39930b57cec5SDimitry Andric 39945f757f3fSDimitry Andric static bool hasBPFPreserveStaticOffset(const RecordDecl *D) { 39955f757f3fSDimitry Andric return D && D->hasAttr<BPFPreserveStaticOffsetAttr>(); 39965f757f3fSDimitry Andric } 39975f757f3fSDimitry Andric 39985f757f3fSDimitry Andric static bool hasBPFPreserveStaticOffset(const Expr *E) { 39995f757f3fSDimitry Andric if (!E) 40005f757f3fSDimitry Andric return false; 40015f757f3fSDimitry Andric QualType PointeeType = E->getType()->getPointeeType(); 40025f757f3fSDimitry Andric if (PointeeType.isNull()) 40035f757f3fSDimitry Andric return false; 40045f757f3fSDimitry Andric if (const auto *BaseDecl = PointeeType->getAsRecordDecl()) 40055f757f3fSDimitry Andric return hasBPFPreserveStaticOffset(BaseDecl); 40065f757f3fSDimitry Andric return false; 40075f757f3fSDimitry Andric } 40085f757f3fSDimitry Andric 40095f757f3fSDimitry Andric // Wraps Addr with a call to llvm.preserve.static.offset intrinsic. 40105f757f3fSDimitry Andric static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF, 40115f757f3fSDimitry Andric Address &Addr) { 40125f757f3fSDimitry Andric if (!CGF.getTarget().getTriple().isBPF()) 40135f757f3fSDimitry Andric return Addr; 40145f757f3fSDimitry Andric 40155f757f3fSDimitry Andric llvm::Function *Fn = 40165f757f3fSDimitry Andric CGF.CGM.getIntrinsic(llvm::Intrinsic::preserve_static_offset); 40170fca6ea1SDimitry Andric llvm::CallInst *Call = CGF.Builder.CreateCall(Fn, {Addr.emitRawPointer(CGF)}); 40185f757f3fSDimitry Andric return Address(Call, Addr.getElementType(), Addr.getAlignment()); 40195f757f3fSDimitry Andric } 40205f757f3fSDimitry Andric 4021480093f4SDimitry Andric /// Given an array base, check whether its member access belongs to a record 4022480093f4SDimitry Andric /// with preserve_access_index attribute or not. 4023480093f4SDimitry Andric static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) { 4024480093f4SDimitry Andric if (!ArrayBase || !CGF.getDebugInfo()) 4025480093f4SDimitry Andric return false; 4026480093f4SDimitry Andric 4027480093f4SDimitry Andric // Only support base as either a MemberExpr or DeclRefExpr. 4028480093f4SDimitry Andric // DeclRefExpr to cover cases like: 4029480093f4SDimitry Andric // struct s { int a; int b[10]; }; 4030480093f4SDimitry Andric // struct s *p; 4031480093f4SDimitry Andric // p[1].a 4032480093f4SDimitry Andric // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr. 4033480093f4SDimitry Andric // p->b[5] is a MemberExpr example. 4034480093f4SDimitry Andric const Expr *E = ArrayBase->IgnoreImpCasts(); 4035480093f4SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(E)) 4036480093f4SDimitry Andric return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>(); 4037480093f4SDimitry Andric 4038480093f4SDimitry Andric if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 4039480093f4SDimitry Andric const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl()); 4040480093f4SDimitry Andric if (!VarDef) 4041480093f4SDimitry Andric return false; 4042480093f4SDimitry Andric 4043480093f4SDimitry Andric const auto *PtrT = VarDef->getType()->getAs<PointerType>(); 4044480093f4SDimitry Andric if (!PtrT) 4045480093f4SDimitry Andric return false; 4046480093f4SDimitry Andric 4047480093f4SDimitry Andric const auto *PointeeT = PtrT->getPointeeType() 4048480093f4SDimitry Andric ->getUnqualifiedDesugaredType(); 4049480093f4SDimitry Andric if (const auto *RecT = dyn_cast<RecordType>(PointeeT)) 4050480093f4SDimitry Andric return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>(); 4051480093f4SDimitry Andric return false; 4052480093f4SDimitry Andric } 4053480093f4SDimitry Andric 4054480093f4SDimitry Andric return false; 4055480093f4SDimitry Andric } 4056480093f4SDimitry Andric 40570b57cec5SDimitry Andric static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr, 40580b57cec5SDimitry Andric ArrayRef<llvm::Value *> indices, 40590b57cec5SDimitry Andric QualType eltType, bool inbounds, 40600b57cec5SDimitry Andric bool signedIndices, SourceLocation loc, 4061a7dea167SDimitry Andric QualType *arrayType = nullptr, 4062480093f4SDimitry Andric const Expr *Base = nullptr, 40630b57cec5SDimitry Andric const llvm::Twine &name = "arrayidx") { 40640b57cec5SDimitry Andric // All the indices except that last must be zero. 40650b57cec5SDimitry Andric #ifndef NDEBUG 4066bdd1243dSDimitry Andric for (auto *idx : indices.drop_back()) 40670b57cec5SDimitry Andric assert(isa<llvm::ConstantInt>(idx) && 40680b57cec5SDimitry Andric cast<llvm::ConstantInt>(idx)->isZero()); 40690b57cec5SDimitry Andric #endif 40700b57cec5SDimitry Andric 40710b57cec5SDimitry Andric // Determine the element size of the statically-sized base. This is 40720b57cec5SDimitry Andric // the thing that the indices are expressed in terms of. 40730b57cec5SDimitry Andric if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) { 40740b57cec5SDimitry Andric eltType = getFixedSizeElementType(CGF.getContext(), vla); 40750b57cec5SDimitry Andric } 40760b57cec5SDimitry Andric 40770b57cec5SDimitry Andric // We can use that to compute the best alignment of the element. 40780b57cec5SDimitry Andric CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType); 40790b57cec5SDimitry Andric CharUnits eltAlign = 40800b57cec5SDimitry Andric getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize); 40810b57cec5SDimitry Andric 40825f757f3fSDimitry Andric if (hasBPFPreserveStaticOffset(Base)) 40835f757f3fSDimitry Andric addr = wrapWithBPFPreserveStaticOffset(CGF, addr); 40845f757f3fSDimitry Andric 40850b57cec5SDimitry Andric llvm::Value *eltPtr; 40860b57cec5SDimitry Andric auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back()); 4087480093f4SDimitry Andric if (!LastIndex || 4088480093f4SDimitry Andric (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) { 40890fca6ea1SDimitry Andric addr = emitArraySubscriptGEP(CGF, addr, indices, 40900fca6ea1SDimitry Andric CGF.ConvertTypeForMem(eltType), inbounds, 40910fca6ea1SDimitry Andric signedIndices, loc, eltAlign, name); 40920fca6ea1SDimitry Andric return addr; 40930b57cec5SDimitry Andric } else { 40940b57cec5SDimitry Andric // Remember the original array subscript for bpf target 40950b57cec5SDimitry Andric unsigned idx = LastIndex->getZExtValue(); 4096a7dea167SDimitry Andric llvm::DIType *DbgInfo = nullptr; 4097a7dea167SDimitry Andric if (arrayType) 4098a7dea167SDimitry Andric DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc); 40990fca6ea1SDimitry Andric eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex( 41000fca6ea1SDimitry Andric addr.getElementType(), addr.emitRawPointer(CGF), indices.size() - 1, 4101a7dea167SDimitry Andric idx, DbgInfo); 41020b57cec5SDimitry Andric } 41030b57cec5SDimitry Andric 41040eae32dcSDimitry Andric return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign); 41050b57cec5SDimitry Andric } 41060b57cec5SDimitry Andric 4107297eecfbSDimitry Andric /// The offset of a field from the beginning of the record. 4108297eecfbSDimitry Andric static bool getFieldOffsetInBits(CodeGenFunction &CGF, const RecordDecl *RD, 4109297eecfbSDimitry Andric const FieldDecl *FD, int64_t &Offset) { 4110297eecfbSDimitry Andric ASTContext &Ctx = CGF.getContext(); 4111297eecfbSDimitry Andric const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD); 4112297eecfbSDimitry Andric unsigned FieldNo = 0; 4113297eecfbSDimitry Andric 4114297eecfbSDimitry Andric for (const Decl *D : RD->decls()) { 4115297eecfbSDimitry Andric if (const auto *Record = dyn_cast<RecordDecl>(D)) 4116297eecfbSDimitry Andric if (getFieldOffsetInBits(CGF, Record, FD, Offset)) { 4117297eecfbSDimitry Andric Offset += Layout.getFieldOffset(FieldNo); 4118297eecfbSDimitry Andric return true; 4119297eecfbSDimitry Andric } 4120297eecfbSDimitry Andric 4121297eecfbSDimitry Andric if (const auto *Field = dyn_cast<FieldDecl>(D)) 4122297eecfbSDimitry Andric if (FD == Field) { 4123297eecfbSDimitry Andric Offset += Layout.getFieldOffset(FieldNo); 4124297eecfbSDimitry Andric return true; 4125297eecfbSDimitry Andric } 4126297eecfbSDimitry Andric 4127297eecfbSDimitry Andric if (isa<FieldDecl>(D)) 4128297eecfbSDimitry Andric ++FieldNo; 4129297eecfbSDimitry Andric } 4130297eecfbSDimitry Andric 4131297eecfbSDimitry Andric return false; 4132297eecfbSDimitry Andric } 4133297eecfbSDimitry Andric 4134297eecfbSDimitry Andric /// Returns the relative offset difference between \p FD1 and \p FD2. 4135297eecfbSDimitry Andric /// \code 4136297eecfbSDimitry Andric /// offsetof(struct foo, FD1) - offsetof(struct foo, FD2) 4137297eecfbSDimitry Andric /// \endcode 4138297eecfbSDimitry Andric /// Both fields must be within the same struct. 4139297eecfbSDimitry Andric static std::optional<int64_t> getOffsetDifferenceInBits(CodeGenFunction &CGF, 4140297eecfbSDimitry Andric const FieldDecl *FD1, 4141297eecfbSDimitry Andric const FieldDecl *FD2) { 4142297eecfbSDimitry Andric const RecordDecl *FD1OuterRec = 4143297eecfbSDimitry Andric FD1->getParent()->getOuterLexicalRecordContext(); 4144297eecfbSDimitry Andric const RecordDecl *FD2OuterRec = 4145297eecfbSDimitry Andric FD2->getParent()->getOuterLexicalRecordContext(); 4146297eecfbSDimitry Andric 4147297eecfbSDimitry Andric if (FD1OuterRec != FD2OuterRec) 4148297eecfbSDimitry Andric // Fields must be within the same RecordDecl. 4149297eecfbSDimitry Andric return std::optional<int64_t>(); 4150297eecfbSDimitry Andric 4151297eecfbSDimitry Andric int64_t FD1Offset = 0; 4152297eecfbSDimitry Andric if (!getFieldOffsetInBits(CGF, FD1OuterRec, FD1, FD1Offset)) 4153297eecfbSDimitry Andric return std::optional<int64_t>(); 4154297eecfbSDimitry Andric 4155297eecfbSDimitry Andric int64_t FD2Offset = 0; 4156297eecfbSDimitry Andric if (!getFieldOffsetInBits(CGF, FD2OuterRec, FD2, FD2Offset)) 4157297eecfbSDimitry Andric return std::optional<int64_t>(); 4158297eecfbSDimitry Andric 4159297eecfbSDimitry Andric return std::make_optional<int64_t>(FD1Offset - FD2Offset); 4160297eecfbSDimitry Andric } 4161297eecfbSDimitry Andric 41620b57cec5SDimitry Andric LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 41630b57cec5SDimitry Andric bool Accessed) { 41640b57cec5SDimitry Andric // The index must always be an integer, which is not an aggregate. Emit it 41650b57cec5SDimitry Andric // in lexical order (this complexity is, sadly, required by C++17). 41660b57cec5SDimitry Andric llvm::Value *IdxPre = 41670b57cec5SDimitry Andric (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr; 41680b57cec5SDimitry Andric bool SignedIndices = false; 41690b57cec5SDimitry Andric auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * { 41700b57cec5SDimitry Andric auto *Idx = IdxPre; 41710b57cec5SDimitry Andric if (E->getLHS() != E->getIdx()) { 41720b57cec5SDimitry Andric assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS"); 41730b57cec5SDimitry Andric Idx = EmitScalarExpr(E->getIdx()); 41740b57cec5SDimitry Andric } 41750b57cec5SDimitry Andric 41760b57cec5SDimitry Andric QualType IdxTy = E->getIdx()->getType(); 41770b57cec5SDimitry Andric bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType(); 41780b57cec5SDimitry Andric SignedIndices |= IdxSigned; 41790b57cec5SDimitry Andric 41800b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ArrayBounds)) 41810b57cec5SDimitry Andric EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed); 41820b57cec5SDimitry Andric 41830b57cec5SDimitry Andric // Extend or truncate the index type to 32 or 64-bits. 41840b57cec5SDimitry Andric if (Promote && Idx->getType() != IntPtrTy) 41850b57cec5SDimitry Andric Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom"); 41860b57cec5SDimitry Andric 41870b57cec5SDimitry Andric return Idx; 41880b57cec5SDimitry Andric }; 41890b57cec5SDimitry Andric IdxPre = nullptr; 41900b57cec5SDimitry Andric 41910b57cec5SDimitry Andric // If the base is a vector type, then we are forming a vector element lvalue 41920b57cec5SDimitry Andric // with this subscript. 41930fca6ea1SDimitry Andric if (E->getBase()->getType()->isSubscriptableVectorType() && 41940b57cec5SDimitry Andric !isa<ExtVectorElementExpr>(E->getBase())) { 41950b57cec5SDimitry Andric // Emit the vector as an lvalue to get its address. 41960b57cec5SDimitry Andric LValue LHS = EmitLValue(E->getBase()); 41970b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/false); 41980b57cec5SDimitry Andric assert(LHS.isSimple() && "Can only subscript lvalue vectors here!"); 41990fca6ea1SDimitry Andric return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(), 42000fca6ea1SDimitry Andric LHS.getBaseInfo(), TBAAAccessInfo()); 42010b57cec5SDimitry Andric } 42020b57cec5SDimitry Andric 42030b57cec5SDimitry Andric // All the other cases basically behave like simple offsetting. 42040b57cec5SDimitry Andric 42050b57cec5SDimitry Andric // Handle the extvector case we ignored above. 42060b57cec5SDimitry Andric if (isa<ExtVectorElementExpr>(E->getBase())) { 42070b57cec5SDimitry Andric LValue LV = EmitLValue(E->getBase()); 42080b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true); 42090b57cec5SDimitry Andric Address Addr = EmitExtVectorElementLValue(LV); 42100b57cec5SDimitry Andric 42110b57cec5SDimitry Andric QualType EltType = LV.getType()->castAs<VectorType>()->getElementType(); 42120b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true, 42130b57cec5SDimitry Andric SignedIndices, E->getExprLoc()); 42140b57cec5SDimitry Andric return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(), 42150b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, EltType)); 42160b57cec5SDimitry Andric } 42170b57cec5SDimitry Andric 42180b57cec5SDimitry Andric LValueBaseInfo EltBaseInfo; 42190b57cec5SDimitry Andric TBAAAccessInfo EltTBAAInfo; 42200b57cec5SDimitry Andric Address Addr = Address::invalid(); 42210b57cec5SDimitry Andric if (const VariableArrayType *vla = 42220b57cec5SDimitry Andric getContext().getAsVariableArrayType(E->getType())) { 42230b57cec5SDimitry Andric // The base must be a pointer, which is not an aggregate. Emit 42240b57cec5SDimitry Andric // it. It needs to be emitted first in case it's what captures 42250b57cec5SDimitry Andric // the VLA bounds. 42260b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 42270b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true); 42280b57cec5SDimitry Andric 42290b57cec5SDimitry Andric // The element count here is the total number of non-VLA elements. 42300b57cec5SDimitry Andric llvm::Value *numElements = getVLASize(vla).NumElts; 42310b57cec5SDimitry Andric 42320b57cec5SDimitry Andric // Effectively, the multiply by the VLA size is part of the GEP. 42330b57cec5SDimitry Andric // GEP indexes are signed, and scaling an index isn't permitted to 42340b57cec5SDimitry Andric // signed-overflow, so we use the same semantics for our explicit 42350b57cec5SDimitry Andric // multiply. We suppress this if overflow is not undefined behavior. 42360b57cec5SDimitry Andric if (getLangOpts().isSignedOverflowDefined()) { 42370b57cec5SDimitry Andric Idx = Builder.CreateMul(Idx, numElements); 42380b57cec5SDimitry Andric } else { 42390b57cec5SDimitry Andric Idx = Builder.CreateNSWMul(Idx, numElements); 42400b57cec5SDimitry Andric } 42410b57cec5SDimitry Andric 42420b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(), 42430b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(), 42440b57cec5SDimitry Andric SignedIndices, E->getExprLoc()); 42450b57cec5SDimitry Andric 42460b57cec5SDimitry Andric } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){ 42470b57cec5SDimitry Andric // Indexing over an interface, as in "NSString *P; P[4];" 42480b57cec5SDimitry Andric 42490b57cec5SDimitry Andric // Emit the base pointer. 42500b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 42510b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true); 42520b57cec5SDimitry Andric 42530b57cec5SDimitry Andric CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT); 42540b57cec5SDimitry Andric llvm::Value *InterfaceSizeVal = 42550b57cec5SDimitry Andric llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity()); 42560b57cec5SDimitry Andric 42570b57cec5SDimitry Andric llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal); 42580b57cec5SDimitry Andric 42590b57cec5SDimitry Andric // We don't necessarily build correct LLVM struct types for ObjC 42600b57cec5SDimitry Andric // interfaces, so we can't rely on GEP to do this scaling 42610b57cec5SDimitry Andric // correctly, so we need to cast to i8*. FIXME: is this actually 42620b57cec5SDimitry Andric // true? A lot of other things in the fragile ABI would break... 426381ad6265SDimitry Andric llvm::Type *OrigBaseElemTy = Addr.getElementType(); 42640b57cec5SDimitry Andric 42650b57cec5SDimitry Andric // Do the GEP. 42660b57cec5SDimitry Andric CharUnits EltAlign = 42670b57cec5SDimitry Andric getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize); 42680b57cec5SDimitry Andric llvm::Value *EltPtr = 42690fca6ea1SDimitry Andric emitArraySubscriptGEP(*this, Int8Ty, Addr.emitRawPointer(*this), 42700fca6ea1SDimitry Andric ScaledIdx, false, SignedIndices, E->getExprLoc()); 427106c3fb27SDimitry Andric Addr = Address(EltPtr, OrigBaseElemTy, EltAlign); 42720b57cec5SDimitry Andric } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 42730b57cec5SDimitry Andric // If this is A[i] where A is an array, the frontend will have decayed the 42740b57cec5SDimitry Andric // base to be a ArrayToPointerDecay implicit cast. While correct, it is 42750b57cec5SDimitry Andric // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 42760b57cec5SDimitry Andric // "gep x, i" here. Emit one "gep A, 0, i". 42770b57cec5SDimitry Andric assert(Array->getType()->isArrayType() && 42780b57cec5SDimitry Andric "Array to pointer decay must have array source type!"); 42790b57cec5SDimitry Andric LValue ArrayLV; 42800b57cec5SDimitry Andric // For simple multidimensional array indexing, set the 'accessed' flag for 42810b57cec5SDimitry Andric // better bounds-checking of the base expression. 42820b57cec5SDimitry Andric if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 42830b57cec5SDimitry Andric ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 42840b57cec5SDimitry Andric else 42850b57cec5SDimitry Andric ArrayLV = EmitLValue(Array); 42860b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true); 42870b57cec5SDimitry Andric 4288297eecfbSDimitry Andric if (SanOpts.has(SanitizerKind::ArrayBounds)) { 4289297eecfbSDimitry Andric // If the array being accessed has a "counted_by" attribute, generate 4290297eecfbSDimitry Andric // bounds checking code. The "count" field is at the top level of the 4291297eecfbSDimitry Andric // struct or in an anonymous struct, that's also at the top level. Future 4292297eecfbSDimitry Andric // expansions may allow the "count" to reside at any place in the struct, 4293297eecfbSDimitry Andric // but the value of "counted_by" will be a "simple" path to the count, 4294297eecfbSDimitry Andric // i.e. "a.b.count", so we shouldn't need the full force of EmitLValue or 4295297eecfbSDimitry Andric // similar to emit the correct GEP. 4296297eecfbSDimitry Andric const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel = 4297297eecfbSDimitry Andric getLangOpts().getStrictFlexArraysLevel(); 4298297eecfbSDimitry Andric 4299297eecfbSDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(Array); 4300297eecfbSDimitry Andric ME && 4301297eecfbSDimitry Andric ME->isFlexibleArrayMemberLike(getContext(), StrictFlexArraysLevel) && 43020fca6ea1SDimitry Andric ME->getMemberDecl()->getType()->isCountAttributedType()) { 4303297eecfbSDimitry Andric const FieldDecl *FAMDecl = dyn_cast<FieldDecl>(ME->getMemberDecl()); 4304297eecfbSDimitry Andric if (const FieldDecl *CountFD = FindCountedByField(FAMDecl)) { 4305297eecfbSDimitry Andric if (std::optional<int64_t> Diff = 4306297eecfbSDimitry Andric getOffsetDifferenceInBits(*this, CountFD, FAMDecl)) { 4307297eecfbSDimitry Andric CharUnits OffsetDiff = CGM.getContext().toCharUnitsFromBits(*Diff); 4308297eecfbSDimitry Andric 4309297eecfbSDimitry Andric // Create a GEP with a byte offset between the FAM and count and 4310297eecfbSDimitry Andric // use that to load the count value. 4311297eecfbSDimitry Andric Addr = Builder.CreatePointerBitCastOrAddrSpaceCast( 43120fca6ea1SDimitry Andric ArrayLV.getAddress(), Int8PtrTy, Int8Ty); 4313297eecfbSDimitry Andric 4314297eecfbSDimitry Andric llvm::Type *CountTy = ConvertType(CountFD->getType()); 4315297eecfbSDimitry Andric llvm::Value *Res = Builder.CreateInBoundsGEP( 43160fca6ea1SDimitry Andric Int8Ty, Addr.emitRawPointer(*this), 4317297eecfbSDimitry Andric Builder.getInt32(OffsetDiff.getQuantity()), ".counted_by.gep"); 4318297eecfbSDimitry Andric Res = Builder.CreateAlignedLoad(CountTy, Res, getIntAlign(), 4319297eecfbSDimitry Andric ".counted_by.load"); 4320297eecfbSDimitry Andric 4321297eecfbSDimitry Andric // Now emit the bounds checking. 4322297eecfbSDimitry Andric EmitBoundsCheckImpl(E, Res, Idx, E->getIdx()->getType(), 4323297eecfbSDimitry Andric Array->getType(), Accessed); 4324297eecfbSDimitry Andric } 4325297eecfbSDimitry Andric } 4326297eecfbSDimitry Andric } 4327297eecfbSDimitry Andric } 4328297eecfbSDimitry Andric 43290b57cec5SDimitry Andric // Propagate the alignment from the array itself to the result. 4330a7dea167SDimitry Andric QualType arrayType = Array->getType(); 43310b57cec5SDimitry Andric Addr = emitArraySubscriptGEP( 43320fca6ea1SDimitry Andric *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx}, 43330b57cec5SDimitry Andric E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices, 4334480093f4SDimitry Andric E->getExprLoc(), &arrayType, E->getBase()); 43350b57cec5SDimitry Andric EltBaseInfo = ArrayLV.getBaseInfo(); 43360b57cec5SDimitry Andric EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType()); 43370b57cec5SDimitry Andric } else { 43380b57cec5SDimitry Andric // The base must be a pointer; emit it with an estimate of its alignment. 43390b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo); 43400b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true); 4341a7dea167SDimitry Andric QualType ptrType = E->getBase()->getType(); 43420b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(), 43430b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(), 4344480093f4SDimitry Andric SignedIndices, E->getExprLoc(), &ptrType, 4345480093f4SDimitry Andric E->getBase()); 43460b57cec5SDimitry Andric } 43470b57cec5SDimitry Andric 43480b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo); 43490b57cec5SDimitry Andric 43500b57cec5SDimitry Andric if (getLangOpts().ObjC && 43510b57cec5SDimitry Andric getLangOpts().getGC() != LangOptions::NonGC) { 43520b57cec5SDimitry Andric LV.setNonGC(!E->isOBJCGCCandidate(getContext())); 43530b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV); 43540b57cec5SDimitry Andric } 43550b57cec5SDimitry Andric return LV; 43560b57cec5SDimitry Andric } 43570b57cec5SDimitry Andric 43585ffd83dbSDimitry Andric LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) { 43595ffd83dbSDimitry Andric assert( 43605ffd83dbSDimitry Andric !E->isIncomplete() && 43615ffd83dbSDimitry Andric "incomplete matrix subscript expressions should be rejected during Sema"); 43625ffd83dbSDimitry Andric LValue Base = EmitLValue(E->getBase()); 43635ffd83dbSDimitry Andric llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx()); 43645ffd83dbSDimitry Andric llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx()); 43655ffd83dbSDimitry Andric llvm::Value *NumRows = Builder.getIntN( 43665ffd83dbSDimitry Andric RowIdx->getType()->getScalarSizeInBits(), 4367e8d8bef9SDimitry Andric E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows()); 43685ffd83dbSDimitry Andric llvm::Value *FinalIdx = 43695ffd83dbSDimitry Andric Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx); 43705ffd83dbSDimitry Andric return LValue::MakeMatrixElt( 43710fca6ea1SDimitry Andric MaybeConvertMatrixAddress(Base.getAddress(), *this), FinalIdx, 43725ffd83dbSDimitry Andric E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo()); 43735ffd83dbSDimitry Andric } 43745ffd83dbSDimitry Andric 43750b57cec5SDimitry Andric static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, 43760b57cec5SDimitry Andric LValueBaseInfo &BaseInfo, 43770b57cec5SDimitry Andric TBAAAccessInfo &TBAAInfo, 43780b57cec5SDimitry Andric QualType BaseTy, QualType ElTy, 43790b57cec5SDimitry Andric bool IsLowerBound) { 43800b57cec5SDimitry Andric LValue BaseLVal; 43810fca6ea1SDimitry Andric if (auto *ASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParenImpCasts())) { 43820fca6ea1SDimitry Andric BaseLVal = CGF.EmitArraySectionExpr(ASE, IsLowerBound); 43830b57cec5SDimitry Andric if (BaseTy->isArrayType()) { 43840fca6ea1SDimitry Andric Address Addr = BaseLVal.getAddress(); 43850b57cec5SDimitry Andric BaseInfo = BaseLVal.getBaseInfo(); 43860b57cec5SDimitry Andric 43870b57cec5SDimitry Andric // If the array type was an incomplete type, we need to make sure 43880b57cec5SDimitry Andric // the decay ends up being the right type. 43890b57cec5SDimitry Andric llvm::Type *NewTy = CGF.ConvertType(BaseTy); 439006c3fb27SDimitry Andric Addr = Addr.withElementType(NewTy); 43910b57cec5SDimitry Andric 43920b57cec5SDimitry Andric // Note that VLA pointers are always decayed, so we don't need to do 43930b57cec5SDimitry Andric // anything here. 43940b57cec5SDimitry Andric if (!BaseTy->isVariableArrayType()) { 43950b57cec5SDimitry Andric assert(isa<llvm::ArrayType>(Addr.getElementType()) && 43960b57cec5SDimitry Andric "Expected pointer to array"); 43970b57cec5SDimitry Andric Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay"); 43980b57cec5SDimitry Andric } 43990b57cec5SDimitry Andric 440006c3fb27SDimitry Andric return Addr.withElementType(CGF.ConvertTypeForMem(ElTy)); 44010b57cec5SDimitry Andric } 44020b57cec5SDimitry Andric LValueBaseInfo TypeBaseInfo; 44030b57cec5SDimitry Andric TBAAAccessInfo TypeTBAAInfo; 44045ffd83dbSDimitry Andric CharUnits Align = 44055ffd83dbSDimitry Andric CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo); 44060b57cec5SDimitry Andric BaseInfo.mergeForCast(TypeBaseInfo); 44070b57cec5SDimitry Andric TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo); 44080fca6ea1SDimitry Andric return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), 440981ad6265SDimitry Andric CGF.ConvertTypeForMem(ElTy), Align); 44100b57cec5SDimitry Andric } 44110b57cec5SDimitry Andric return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo); 44120b57cec5SDimitry Andric } 44130b57cec5SDimitry Andric 44140fca6ea1SDimitry Andric LValue CodeGenFunction::EmitArraySectionExpr(const ArraySectionExpr *E, 44150b57cec5SDimitry Andric bool IsLowerBound) { 44160fca6ea1SDimitry Andric 44170fca6ea1SDimitry Andric assert(!E->isOpenACCArraySection() && 44180fca6ea1SDimitry Andric "OpenACC Array section codegen not implemented"); 44190fca6ea1SDimitry Andric 44200fca6ea1SDimitry Andric QualType BaseTy = ArraySectionExpr::getBaseOriginalType(E->getBase()); 44210b57cec5SDimitry Andric QualType ResultExprTy; 44220b57cec5SDimitry Andric if (auto *AT = getContext().getAsArrayType(BaseTy)) 44230b57cec5SDimitry Andric ResultExprTy = AT->getElementType(); 44240b57cec5SDimitry Andric else 44250b57cec5SDimitry Andric ResultExprTy = BaseTy->getPointeeType(); 44260b57cec5SDimitry Andric llvm::Value *Idx = nullptr; 44275ffd83dbSDimitry Andric if (IsLowerBound || E->getColonLocFirst().isInvalid()) { 44280b57cec5SDimitry Andric // Requesting lower bound or upper bound, but without provided length and 44290b57cec5SDimitry Andric // without ':' symbol for the default length -> length = 1. 44300b57cec5SDimitry Andric // Idx = LowerBound ?: 0; 44310b57cec5SDimitry Andric if (auto *LowerBound = E->getLowerBound()) { 44320b57cec5SDimitry Andric Idx = Builder.CreateIntCast( 44330b57cec5SDimitry Andric EmitScalarExpr(LowerBound), IntPtrTy, 44340b57cec5SDimitry Andric LowerBound->getType()->hasSignedIntegerRepresentation()); 44350b57cec5SDimitry Andric } else 44360b57cec5SDimitry Andric Idx = llvm::ConstantInt::getNullValue(IntPtrTy); 44370b57cec5SDimitry Andric } else { 44380b57cec5SDimitry Andric // Try to emit length or lower bound as constant. If this is possible, 1 44390b57cec5SDimitry Andric // is subtracted from constant length or lower bound. Otherwise, emit LLVM 44400b57cec5SDimitry Andric // IR (LB + Len) - 1. 44410b57cec5SDimitry Andric auto &C = CGM.getContext(); 44420b57cec5SDimitry Andric auto *Length = E->getLength(); 44430b57cec5SDimitry Andric llvm::APSInt ConstLength; 44440b57cec5SDimitry Andric if (Length) { 44450b57cec5SDimitry Andric // Idx = LowerBound + Length - 1; 4446bdd1243dSDimitry Andric if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) { 4447e8d8bef9SDimitry Andric ConstLength = CL->zextOrTrunc(PointerWidthInBits); 44480b57cec5SDimitry Andric Length = nullptr; 44490b57cec5SDimitry Andric } 44500b57cec5SDimitry Andric auto *LowerBound = E->getLowerBound(); 44510b57cec5SDimitry Andric llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false); 4452e8d8bef9SDimitry Andric if (LowerBound) { 4453bdd1243dSDimitry Andric if (std::optional<llvm::APSInt> LB = 4454bdd1243dSDimitry Andric LowerBound->getIntegerConstantExpr(C)) { 4455e8d8bef9SDimitry Andric ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits); 44560b57cec5SDimitry Andric LowerBound = nullptr; 44570b57cec5SDimitry Andric } 4458e8d8bef9SDimitry Andric } 44590b57cec5SDimitry Andric if (!Length) 44600b57cec5SDimitry Andric --ConstLength; 44610b57cec5SDimitry Andric else if (!LowerBound) 44620b57cec5SDimitry Andric --ConstLowerBound; 44630b57cec5SDimitry Andric 44640b57cec5SDimitry Andric if (Length || LowerBound) { 44650b57cec5SDimitry Andric auto *LowerBoundVal = 44660b57cec5SDimitry Andric LowerBound 44670b57cec5SDimitry Andric ? Builder.CreateIntCast( 44680b57cec5SDimitry Andric EmitScalarExpr(LowerBound), IntPtrTy, 44690b57cec5SDimitry Andric LowerBound->getType()->hasSignedIntegerRepresentation()) 44700b57cec5SDimitry Andric : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound); 44710b57cec5SDimitry Andric auto *LengthVal = 44720b57cec5SDimitry Andric Length 44730b57cec5SDimitry Andric ? Builder.CreateIntCast( 44740b57cec5SDimitry Andric EmitScalarExpr(Length), IntPtrTy, 44750b57cec5SDimitry Andric Length->getType()->hasSignedIntegerRepresentation()) 44760b57cec5SDimitry Andric : llvm::ConstantInt::get(IntPtrTy, ConstLength); 44770b57cec5SDimitry Andric Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len", 44780b57cec5SDimitry Andric /*HasNUW=*/false, 44790b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined()); 44800b57cec5SDimitry Andric if (Length && LowerBound) { 44810b57cec5SDimitry Andric Idx = Builder.CreateSub( 44820b57cec5SDimitry Andric Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1", 44830b57cec5SDimitry Andric /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 44840b57cec5SDimitry Andric } 44850b57cec5SDimitry Andric } else 44860b57cec5SDimitry Andric Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound); 44870b57cec5SDimitry Andric } else { 44880b57cec5SDimitry Andric // Idx = ArraySize - 1; 44890b57cec5SDimitry Andric QualType ArrayTy = BaseTy->isPointerType() 44900b57cec5SDimitry Andric ? E->getBase()->IgnoreParenImpCasts()->getType() 44910b57cec5SDimitry Andric : BaseTy; 44920b57cec5SDimitry Andric if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) { 44930b57cec5SDimitry Andric Length = VAT->getSizeExpr(); 4494bdd1243dSDimitry Andric if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) { 4495e8d8bef9SDimitry Andric ConstLength = *L; 44960b57cec5SDimitry Andric Length = nullptr; 4497e8d8bef9SDimitry Andric } 44980b57cec5SDimitry Andric } else { 44990b57cec5SDimitry Andric auto *CAT = C.getAsConstantArrayType(ArrayTy); 450006c3fb27SDimitry Andric assert(CAT && "unexpected type for array initializer"); 45010b57cec5SDimitry Andric ConstLength = CAT->getSize(); 45020b57cec5SDimitry Andric } 45030b57cec5SDimitry Andric if (Length) { 45040b57cec5SDimitry Andric auto *LengthVal = Builder.CreateIntCast( 45050b57cec5SDimitry Andric EmitScalarExpr(Length), IntPtrTy, 45060b57cec5SDimitry Andric Length->getType()->hasSignedIntegerRepresentation()); 45070b57cec5SDimitry Andric Idx = Builder.CreateSub( 45080b57cec5SDimitry Andric LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1", 45090b57cec5SDimitry Andric /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined()); 45100b57cec5SDimitry Andric } else { 45110b57cec5SDimitry Andric ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits); 45120b57cec5SDimitry Andric --ConstLength; 45130b57cec5SDimitry Andric Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength); 45140b57cec5SDimitry Andric } 45150b57cec5SDimitry Andric } 45160b57cec5SDimitry Andric } 45170b57cec5SDimitry Andric assert(Idx); 45180b57cec5SDimitry Andric 45190b57cec5SDimitry Andric Address EltPtr = Address::invalid(); 45200b57cec5SDimitry Andric LValueBaseInfo BaseInfo; 45210b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo; 45220b57cec5SDimitry Andric if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) { 45230b57cec5SDimitry Andric // The base must be a pointer, which is not an aggregate. Emit 45240b57cec5SDimitry Andric // it. It needs to be emitted first in case it's what captures 45250b57cec5SDimitry Andric // the VLA bounds. 45260b57cec5SDimitry Andric Address Base = 45270b57cec5SDimitry Andric emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, 45280b57cec5SDimitry Andric BaseTy, VLA->getElementType(), IsLowerBound); 45290b57cec5SDimitry Andric // The element count here is the total number of non-VLA elements. 45300b57cec5SDimitry Andric llvm::Value *NumElements = getVLASize(VLA).NumElts; 45310b57cec5SDimitry Andric 45320b57cec5SDimitry Andric // Effectively, the multiply by the VLA size is part of the GEP. 45330b57cec5SDimitry Andric // GEP indexes are signed, and scaling an index isn't permitted to 45340b57cec5SDimitry Andric // signed-overflow, so we use the same semantics for our explicit 45350b57cec5SDimitry Andric // multiply. We suppress this if overflow is not undefined behavior. 45360b57cec5SDimitry Andric if (getLangOpts().isSignedOverflowDefined()) 45370b57cec5SDimitry Andric Idx = Builder.CreateMul(Idx, NumElements); 45380b57cec5SDimitry Andric else 45390b57cec5SDimitry Andric Idx = Builder.CreateNSWMul(Idx, NumElements); 45400b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(), 45410b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(), 45420b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc()); 45430b57cec5SDimitry Andric } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) { 45440b57cec5SDimitry Andric // If this is A[i] where A is an array, the frontend will have decayed the 45450b57cec5SDimitry Andric // base to be a ArrayToPointerDecay implicit cast. While correct, it is 45460b57cec5SDimitry Andric // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a 45470b57cec5SDimitry Andric // "gep x, i" here. Emit one "gep A, 0, i". 45480b57cec5SDimitry Andric assert(Array->getType()->isArrayType() && 45490b57cec5SDimitry Andric "Array to pointer decay must have array source type!"); 45500b57cec5SDimitry Andric LValue ArrayLV; 45510b57cec5SDimitry Andric // For simple multidimensional array indexing, set the 'accessed' flag for 45520b57cec5SDimitry Andric // better bounds-checking of the base expression. 45530b57cec5SDimitry Andric if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array)) 45540b57cec5SDimitry Andric ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true); 45550b57cec5SDimitry Andric else 45560b57cec5SDimitry Andric ArrayLV = EmitLValue(Array); 45570b57cec5SDimitry Andric 45580b57cec5SDimitry Andric // Propagate the alignment from the array itself to the result. 45590b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP( 45600fca6ea1SDimitry Andric *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx}, 45610b57cec5SDimitry Andric ResultExprTy, !getLangOpts().isSignedOverflowDefined(), 45620b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc()); 45630b57cec5SDimitry Andric BaseInfo = ArrayLV.getBaseInfo(); 45640b57cec5SDimitry Andric TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy); 45650b57cec5SDimitry Andric } else { 45660fca6ea1SDimitry Andric Address Base = 45670fca6ea1SDimitry Andric emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, BaseTy, 45680fca6ea1SDimitry Andric ResultExprTy, IsLowerBound); 45690b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy, 45700b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(), 45710b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc()); 45720b57cec5SDimitry Andric } 45730b57cec5SDimitry Andric 45740b57cec5SDimitry Andric return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo); 45750b57cec5SDimitry Andric } 45760b57cec5SDimitry Andric 45770b57cec5SDimitry Andric LValue CodeGenFunction:: 45780b57cec5SDimitry Andric EmitExtVectorElementExpr(const ExtVectorElementExpr *E) { 45790b57cec5SDimitry Andric // Emit the base vector as an l-value. 45800b57cec5SDimitry Andric LValue Base; 45810b57cec5SDimitry Andric 45820b57cec5SDimitry Andric // ExtVectorElementExpr's base can either be a vector or pointer to vector. 45830b57cec5SDimitry Andric if (E->isArrow()) { 45840b57cec5SDimitry Andric // If it is a pointer to a vector, emit the address and form an lvalue with 45850b57cec5SDimitry Andric // it. 45860b57cec5SDimitry Andric LValueBaseInfo BaseInfo; 45870b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo; 45880b57cec5SDimitry Andric Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo); 4589480093f4SDimitry Andric const auto *PT = E->getBase()->getType()->castAs<PointerType>(); 45900b57cec5SDimitry Andric Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo); 45910b57cec5SDimitry Andric Base.getQuals().removeObjCGCAttr(); 45920b57cec5SDimitry Andric } else if (E->getBase()->isGLValue()) { 45930b57cec5SDimitry Andric // Otherwise, if the base is an lvalue ( as in the case of foo.x.x), 45940b57cec5SDimitry Andric // emit the base as an lvalue. 45950b57cec5SDimitry Andric assert(E->getBase()->getType()->isVectorType()); 45960b57cec5SDimitry Andric Base = EmitLValue(E->getBase()); 45970b57cec5SDimitry Andric } else { 45980b57cec5SDimitry Andric // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such. 45990b57cec5SDimitry Andric assert(E->getBase()->getType()->isVectorType() && 46000b57cec5SDimitry Andric "Result must be a vector"); 46010b57cec5SDimitry Andric llvm::Value *Vec = EmitScalarExpr(E->getBase()); 46020b57cec5SDimitry Andric 46030b57cec5SDimitry Andric // Store the vector to memory (because LValue wants an address). 46040b57cec5SDimitry Andric Address VecMem = CreateMemTemp(E->getBase()->getType()); 46050b57cec5SDimitry Andric Builder.CreateStore(Vec, VecMem); 46060b57cec5SDimitry Andric Base = MakeAddrLValue(VecMem, E->getBase()->getType(), 46070b57cec5SDimitry Andric AlignmentSource::Decl); 46080b57cec5SDimitry Andric } 46090b57cec5SDimitry Andric 46100b57cec5SDimitry Andric QualType type = 46110b57cec5SDimitry Andric E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers()); 46120b57cec5SDimitry Andric 46130b57cec5SDimitry Andric // Encode the element access list into a vector of unsigned indices. 46140b57cec5SDimitry Andric SmallVector<uint32_t, 4> Indices; 46150b57cec5SDimitry Andric E->getEncodedElementAccess(Indices); 46160b57cec5SDimitry Andric 46170b57cec5SDimitry Andric if (Base.isSimple()) { 46180b57cec5SDimitry Andric llvm::Constant *CV = 46190b57cec5SDimitry Andric llvm::ConstantDataVector::get(getLLVMContext(), Indices); 46200fca6ea1SDimitry Andric return LValue::MakeExtVectorElt(Base.getAddress(), CV, type, 46210b57cec5SDimitry Andric Base.getBaseInfo(), TBAAAccessInfo()); 46220b57cec5SDimitry Andric } 46230b57cec5SDimitry Andric assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!"); 46240b57cec5SDimitry Andric 46250b57cec5SDimitry Andric llvm::Constant *BaseElts = Base.getExtVectorElts(); 46260b57cec5SDimitry Andric SmallVector<llvm::Constant *, 4> CElts; 46270b57cec5SDimitry Andric 46280b57cec5SDimitry Andric for (unsigned i = 0, e = Indices.size(); i != e; ++i) 46290b57cec5SDimitry Andric CElts.push_back(BaseElts->getAggregateElement(Indices[i])); 46300b57cec5SDimitry Andric llvm::Constant *CV = llvm::ConstantVector::get(CElts); 46310b57cec5SDimitry Andric return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type, 46320b57cec5SDimitry Andric Base.getBaseInfo(), TBAAAccessInfo()); 46330b57cec5SDimitry Andric } 46340b57cec5SDimitry Andric 46350b57cec5SDimitry Andric LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) { 46360b57cec5SDimitry Andric if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) { 46370b57cec5SDimitry Andric EmitIgnoredExpr(E->getBase()); 46380b57cec5SDimitry Andric return EmitDeclRefLValue(DRE); 46390b57cec5SDimitry Andric } 46400b57cec5SDimitry Andric 46410b57cec5SDimitry Andric Expr *BaseExpr = E->getBase(); 46420b57cec5SDimitry Andric // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 46430b57cec5SDimitry Andric LValue BaseLV; 46440b57cec5SDimitry Andric if (E->isArrow()) { 46450b57cec5SDimitry Andric LValueBaseInfo BaseInfo; 46460b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo; 46470b57cec5SDimitry Andric Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo); 46480b57cec5SDimitry Andric QualType PtrTy = BaseExpr->getType()->getPointeeType(); 46490b57cec5SDimitry Andric SanitizerSet SkippedChecks; 46500b57cec5SDimitry Andric bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr); 46510b57cec5SDimitry Andric if (IsBaseCXXThis) 46520b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Alignment, true); 46530b57cec5SDimitry Andric if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr)) 46540b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, true); 46550fca6ea1SDimitry Andric EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr, PtrTy, 46560b57cec5SDimitry Andric /*Alignment=*/CharUnits::Zero(), SkippedChecks); 46570b57cec5SDimitry Andric BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo); 46580b57cec5SDimitry Andric } else 46590b57cec5SDimitry Andric BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess); 46600b57cec5SDimitry Andric 46610b57cec5SDimitry Andric NamedDecl *ND = E->getMemberDecl(); 46620b57cec5SDimitry Andric if (auto *Field = dyn_cast<FieldDecl>(ND)) { 46630b57cec5SDimitry Andric LValue LV = EmitLValueForField(BaseLV, Field); 46640b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV); 4665480093f4SDimitry Andric if (getLangOpts().OpenMP) { 4666480093f4SDimitry Andric // If the member was explicitly marked as nontemporal, mark it as 4667480093f4SDimitry Andric // nontemporal. If the base lvalue is marked as nontemporal, mark access 4668480093f4SDimitry Andric // to children as nontemporal too. 4669480093f4SDimitry Andric if ((IsWrappedCXXThis(BaseExpr) && 4670480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(Field)) || 4671480093f4SDimitry Andric BaseLV.isNontemporal()) 4672480093f4SDimitry Andric LV.setNontemporal(/*Value=*/true); 4673480093f4SDimitry Andric } 46740b57cec5SDimitry Andric return LV; 46750b57cec5SDimitry Andric } 46760b57cec5SDimitry Andric 46770b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 46780b57cec5SDimitry Andric return EmitFunctionDeclLValue(*this, E, FD); 46790b57cec5SDimitry Andric 46800b57cec5SDimitry Andric llvm_unreachable("Unhandled member declaration!"); 46810b57cec5SDimitry Andric } 46820b57cec5SDimitry Andric 46830b57cec5SDimitry Andric /// Given that we are currently emitting a lambda, emit an l-value for 46840b57cec5SDimitry Andric /// one of its members. 46855f757f3fSDimitry Andric /// 46865f757f3fSDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field, 46875f757f3fSDimitry Andric llvm::Value *ThisValue) { 46885f757f3fSDimitry Andric bool HasExplicitObjectParameter = false; 46890fca6ea1SDimitry Andric const auto *MD = dyn_cast_if_present<CXXMethodDecl>(CurCodeDecl); 46900fca6ea1SDimitry Andric if (MD) { 46915f757f3fSDimitry Andric HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction(); 46925f757f3fSDimitry Andric assert(MD->getParent()->isLambda()); 46935f757f3fSDimitry Andric assert(MD->getParent() == Field->getParent()); 4694fe6060f1SDimitry Andric } 46955f757f3fSDimitry Andric LValue LambdaLV; 46965f757f3fSDimitry Andric if (HasExplicitObjectParameter) { 46975f757f3fSDimitry Andric const VarDecl *D = cast<CXXMethodDecl>(CurCodeDecl)->getParamDecl(0); 46985f757f3fSDimitry Andric auto It = LocalDeclMap.find(D); 46995f757f3fSDimitry Andric assert(It != LocalDeclMap.end() && "explicit parameter not loaded?"); 47005f757f3fSDimitry Andric Address AddrOfExplicitObject = It->getSecond(); 47015f757f3fSDimitry Andric if (D->getType()->isReferenceType()) 47025f757f3fSDimitry Andric LambdaLV = EmitLoadOfReferenceLValue(AddrOfExplicitObject, D->getType(), 47035f757f3fSDimitry Andric AlignmentSource::Decl); 47045f757f3fSDimitry Andric else 47050fca6ea1SDimitry Andric LambdaLV = MakeAddrLValue(AddrOfExplicitObject, 47065f757f3fSDimitry Andric D->getType().getNonReferenceType()); 47070fca6ea1SDimitry Andric 47080fca6ea1SDimitry Andric // Make sure we have an lvalue to the lambda itself and not a derived class. 47090fca6ea1SDimitry Andric auto *ThisTy = D->getType().getNonReferenceType()->getAsCXXRecordDecl(); 47100fca6ea1SDimitry Andric auto *LambdaTy = cast<CXXRecordDecl>(Field->getParent()); 47110fca6ea1SDimitry Andric if (ThisTy != LambdaTy) { 47120fca6ea1SDimitry Andric const CXXCastPath &BasePathArray = getContext().LambdaCastPaths.at(MD); 47130fca6ea1SDimitry Andric Address Base = GetAddressOfBaseClass( 47140fca6ea1SDimitry Andric LambdaLV.getAddress(), ThisTy, BasePathArray.begin(), 47150fca6ea1SDimitry Andric BasePathArray.end(), /*NullCheckValue=*/false, SourceLocation()); 47160fca6ea1SDimitry Andric LambdaLV = MakeAddrLValue(Base, QualType{LambdaTy->getTypeForDecl(), 0}); 47170fca6ea1SDimitry Andric } 47185f757f3fSDimitry Andric } else { 47195f757f3fSDimitry Andric QualType LambdaTagType = getContext().getTagDeclType(Field->getParent()); 47205f757f3fSDimitry Andric LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType); 47215f757f3fSDimitry Andric } 47220b57cec5SDimitry Andric return EmitLValueForField(LambdaLV, Field); 47230b57cec5SDimitry Andric } 47240b57cec5SDimitry Andric 47255f757f3fSDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) { 47265f757f3fSDimitry Andric return EmitLValueForLambdaField(Field, CXXABIThisValue); 47275f757f3fSDimitry Andric } 47285f757f3fSDimitry Andric 47290b57cec5SDimitry Andric /// Get the field index in the debug info. The debug info structure/union 47300b57cec5SDimitry Andric /// will ignore the unnamed bitfields. 47310b57cec5SDimitry Andric unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec, 47320b57cec5SDimitry Andric unsigned FieldIndex) { 47330b57cec5SDimitry Andric unsigned I = 0, Skipped = 0; 47340b57cec5SDimitry Andric 4735bdd1243dSDimitry Andric for (auto *F : Rec->getDefinition()->fields()) { 47360b57cec5SDimitry Andric if (I == FieldIndex) 47370b57cec5SDimitry Andric break; 47380fca6ea1SDimitry Andric if (F->isUnnamedBitField()) 47390b57cec5SDimitry Andric Skipped++; 47400b57cec5SDimitry Andric I++; 47410b57cec5SDimitry Andric } 47420b57cec5SDimitry Andric 47430b57cec5SDimitry Andric return FieldIndex - Skipped; 47440b57cec5SDimitry Andric } 47450b57cec5SDimitry Andric 47460b57cec5SDimitry Andric /// Get the address of a zero-sized field within a record. The resulting 47470b57cec5SDimitry Andric /// address doesn't necessarily have the right type. 47480b57cec5SDimitry Andric static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base, 47490b57cec5SDimitry Andric const FieldDecl *Field) { 47500b57cec5SDimitry Andric CharUnits Offset = CGF.getContext().toCharUnitsFromBits( 47510b57cec5SDimitry Andric CGF.getContext().getFieldOffset(Field)); 47520b57cec5SDimitry Andric if (Offset.isZero()) 47530b57cec5SDimitry Andric return Base; 475406c3fb27SDimitry Andric Base = Base.withElementType(CGF.Int8Ty); 47550b57cec5SDimitry Andric return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset); 47560b57cec5SDimitry Andric } 47570b57cec5SDimitry Andric 47580b57cec5SDimitry Andric /// Drill down to the storage of a field without walking into 47590b57cec5SDimitry Andric /// reference types. 47600b57cec5SDimitry Andric /// 47610b57cec5SDimitry Andric /// The resulting address doesn't necessarily have the right type. 47620b57cec5SDimitry Andric static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, 47630b57cec5SDimitry Andric const FieldDecl *field) { 47640fca6ea1SDimitry Andric if (isEmptyFieldForLayout(CGF.getContext(), field)) 47650b57cec5SDimitry Andric return emitAddrOfZeroSizeField(CGF, base, field); 47660b57cec5SDimitry Andric 47670b57cec5SDimitry Andric const RecordDecl *rec = field->getParent(); 47680b57cec5SDimitry Andric 47690b57cec5SDimitry Andric unsigned idx = 47700b57cec5SDimitry Andric CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 47710b57cec5SDimitry Andric 47720b57cec5SDimitry Andric return CGF.Builder.CreateStructGEP(base, idx, field->getName()); 47730b57cec5SDimitry Andric } 47740b57cec5SDimitry Andric 47755ffd83dbSDimitry Andric static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, 47765ffd83dbSDimitry Andric Address addr, const FieldDecl *field) { 47770b57cec5SDimitry Andric const RecordDecl *rec = field->getParent(); 47785ffd83dbSDimitry Andric llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType( 47795ffd83dbSDimitry Andric base.getType(), rec->getLocation()); 47800b57cec5SDimitry Andric 47810b57cec5SDimitry Andric unsigned idx = 47820b57cec5SDimitry Andric CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); 47830b57cec5SDimitry Andric 47840b57cec5SDimitry Andric return CGF.Builder.CreatePreserveStructAccessIndex( 47855ffd83dbSDimitry Andric addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo); 47860b57cec5SDimitry Andric } 47870b57cec5SDimitry Andric 47880b57cec5SDimitry Andric static bool hasAnyVptr(const QualType Type, const ASTContext &Context) { 47890b57cec5SDimitry Andric const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl(); 47900b57cec5SDimitry Andric if (!RD) 47910b57cec5SDimitry Andric return false; 47920b57cec5SDimitry Andric 47930b57cec5SDimitry Andric if (RD->isDynamicClass()) 47940b57cec5SDimitry Andric return true; 47950b57cec5SDimitry Andric 47960b57cec5SDimitry Andric for (const auto &Base : RD->bases()) 47970b57cec5SDimitry Andric if (hasAnyVptr(Base.getType(), Context)) 47980b57cec5SDimitry Andric return true; 47990b57cec5SDimitry Andric 48000b57cec5SDimitry Andric for (const FieldDecl *Field : RD->fields()) 48010b57cec5SDimitry Andric if (hasAnyVptr(Field->getType(), Context)) 48020b57cec5SDimitry Andric return true; 48030b57cec5SDimitry Andric 48040b57cec5SDimitry Andric return false; 48050b57cec5SDimitry Andric } 48060b57cec5SDimitry Andric 48070b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForField(LValue base, 48080b57cec5SDimitry Andric const FieldDecl *field) { 48090b57cec5SDimitry Andric LValueBaseInfo BaseInfo = base.getBaseInfo(); 48100b57cec5SDimitry Andric 48110b57cec5SDimitry Andric if (field->isBitField()) { 48120b57cec5SDimitry Andric const CGRecordLayout &RL = 48130b57cec5SDimitry Andric CGM.getTypes().getCGRecordLayout(field->getParent()); 48140b57cec5SDimitry Andric const CGBitFieldInfo &Info = RL.getBitFieldInfo(field); 4815e8d8bef9SDimitry Andric const bool UseVolatile = isAAPCS(CGM.getTarget()) && 4816e8d8bef9SDimitry Andric CGM.getCodeGenOpts().AAPCSBitfieldWidth && 4817e8d8bef9SDimitry Andric Info.VolatileStorageSize != 0 && 4818e8d8bef9SDimitry Andric field->getType() 4819e8d8bef9SDimitry Andric .withCVRQualifiers(base.getVRQualifiers()) 4820e8d8bef9SDimitry Andric .isVolatileQualified(); 48210fca6ea1SDimitry Andric Address Addr = base.getAddress(); 48220b57cec5SDimitry Andric unsigned Idx = RL.getLLVMFieldNo(field); 4823480093f4SDimitry Andric const RecordDecl *rec = field->getParent(); 48245f757f3fSDimitry Andric if (hasBPFPreserveStaticOffset(rec)) 48255f757f3fSDimitry Andric Addr = wrapWithBPFPreserveStaticOffset(*this, Addr); 4826e8d8bef9SDimitry Andric if (!UseVolatile) { 4827480093f4SDimitry Andric if (!IsInPreservedAIRegion && 4828480093f4SDimitry Andric (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) { 48290b57cec5SDimitry Andric if (Idx != 0) 48300b57cec5SDimitry Andric // For structs, we GEP to the field that the record layout suggests. 48310b57cec5SDimitry Andric Addr = Builder.CreateStructGEP(Addr, Idx, field->getName()); 4832a7dea167SDimitry Andric } else { 4833a7dea167SDimitry Andric llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType( 4834a7dea167SDimitry Andric getContext().getRecordType(rec), rec->getLocation()); 4835e8d8bef9SDimitry Andric Addr = Builder.CreatePreserveStructAccessIndex( 4836e8d8bef9SDimitry Andric Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()), 4837a7dea167SDimitry Andric DbgInfo); 4838a7dea167SDimitry Andric } 4839e8d8bef9SDimitry Andric } 4840e8d8bef9SDimitry Andric const unsigned SS = 4841e8d8bef9SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize; 48420b57cec5SDimitry Andric // Get the access type. 4843e8d8bef9SDimitry Andric llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS); 484406c3fb27SDimitry Andric Addr = Addr.withElementType(FieldIntTy); 4845e8d8bef9SDimitry Andric if (UseVolatile) { 4846e8d8bef9SDimitry Andric const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity(); 4847e8d8bef9SDimitry Andric if (VolatileOffset) 4848e8d8bef9SDimitry Andric Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset); 4849e8d8bef9SDimitry Andric } 48500b57cec5SDimitry Andric 48510b57cec5SDimitry Andric QualType fieldType = 48520b57cec5SDimitry Andric field->getType().withCVRQualifiers(base.getVRQualifiers()); 48530b57cec5SDimitry Andric // TODO: Support TBAA for bit fields. 48540b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource()); 48550b57cec5SDimitry Andric return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo, 48560b57cec5SDimitry Andric TBAAAccessInfo()); 48570b57cec5SDimitry Andric } 48580b57cec5SDimitry Andric 48590b57cec5SDimitry Andric // Fields of may-alias structures are may-alias themselves. 48600b57cec5SDimitry Andric // FIXME: this should get propagated down through anonymous structs 48610b57cec5SDimitry Andric // and unions. 48620b57cec5SDimitry Andric QualType FieldType = field->getType(); 48630b57cec5SDimitry Andric const RecordDecl *rec = field->getParent(); 48640b57cec5SDimitry Andric AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource(); 48650b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource)); 48660b57cec5SDimitry Andric TBAAAccessInfo FieldTBAAInfo; 48670b57cec5SDimitry Andric if (base.getTBAAInfo().isMayAlias() || 48680b57cec5SDimitry Andric rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) { 48690b57cec5SDimitry Andric FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo(); 48700b57cec5SDimitry Andric } else if (rec->isUnion()) { 48710b57cec5SDimitry Andric // TODO: Support TBAA for unions. 48720b57cec5SDimitry Andric FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo(); 48730b57cec5SDimitry Andric } else { 48740b57cec5SDimitry Andric // If no base type been assigned for the base access, then try to generate 48750b57cec5SDimitry Andric // one for this base lvalue. 48760b57cec5SDimitry Andric FieldTBAAInfo = base.getTBAAInfo(); 48770b57cec5SDimitry Andric if (!FieldTBAAInfo.BaseType) { 48780b57cec5SDimitry Andric FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType()); 48790b57cec5SDimitry Andric assert(!FieldTBAAInfo.Offset && 48800b57cec5SDimitry Andric "Nonzero offset for an access with no base type!"); 48810b57cec5SDimitry Andric } 48820b57cec5SDimitry Andric 48830b57cec5SDimitry Andric // Adjust offset to be relative to the base type. 48840b57cec5SDimitry Andric const ASTRecordLayout &Layout = 48850b57cec5SDimitry Andric getContext().getASTRecordLayout(field->getParent()); 48860b57cec5SDimitry Andric unsigned CharWidth = getContext().getCharWidth(); 48870b57cec5SDimitry Andric if (FieldTBAAInfo.BaseType) 48880b57cec5SDimitry Andric FieldTBAAInfo.Offset += 48890b57cec5SDimitry Andric Layout.getFieldOffset(field->getFieldIndex()) / CharWidth; 48900b57cec5SDimitry Andric 48910b57cec5SDimitry Andric // Update the final access type and size. 48920b57cec5SDimitry Andric FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType); 48930b57cec5SDimitry Andric FieldTBAAInfo.Size = 48940b57cec5SDimitry Andric getContext().getTypeSizeInChars(FieldType).getQuantity(); 48950b57cec5SDimitry Andric } 48960b57cec5SDimitry Andric 48970fca6ea1SDimitry Andric Address addr = base.getAddress(); 48985f757f3fSDimitry Andric if (hasBPFPreserveStaticOffset(rec)) 48995f757f3fSDimitry Andric addr = wrapWithBPFPreserveStaticOffset(*this, addr); 49000b57cec5SDimitry Andric if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) { 49010b57cec5SDimitry Andric if (CGM.getCodeGenOpts().StrictVTablePointers && 49020b57cec5SDimitry Andric ClassDef->isDynamicClass()) { 49030b57cec5SDimitry Andric // Getting to any field of dynamic object requires stripping dynamic 49040b57cec5SDimitry Andric // information provided by invariant.group. This is because accessing 49050b57cec5SDimitry Andric // fields may leak the real address of dynamic object, which could result 49060b57cec5SDimitry Andric // in miscompilation when leaked pointer would be compared. 49070fca6ea1SDimitry Andric auto *stripped = 49080fca6ea1SDimitry Andric Builder.CreateStripInvariantGroup(addr.emitRawPointer(*this)); 490981ad6265SDimitry Andric addr = Address(stripped, addr.getElementType(), addr.getAlignment()); 49100b57cec5SDimitry Andric } 49110b57cec5SDimitry Andric } 49120b57cec5SDimitry Andric 49130b57cec5SDimitry Andric unsigned RecordCVR = base.getVRQualifiers(); 49140b57cec5SDimitry Andric if (rec->isUnion()) { 49150b57cec5SDimitry Andric // For unions, there is no pointer adjustment. 49160b57cec5SDimitry Andric if (CGM.getCodeGenOpts().StrictVTablePointers && 49170b57cec5SDimitry Andric hasAnyVptr(FieldType, getContext())) 49180b57cec5SDimitry Andric // Because unions can easily skip invariant.barriers, we need to add 49190b57cec5SDimitry Andric // a barrier every time CXXRecord field with vptr is referenced. 49200eae32dcSDimitry Andric addr = Builder.CreateLaunderInvariantGroup(addr); 49210b57cec5SDimitry Andric 4922480093f4SDimitry Andric if (IsInPreservedAIRegion || 4923480093f4SDimitry Andric (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) { 49240b57cec5SDimitry Andric // Remember the original union field index 49255ffd83dbSDimitry Andric llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(), 49265ffd83dbSDimitry Andric rec->getLocation()); 49270fca6ea1SDimitry Andric addr = 49280fca6ea1SDimitry Andric Address(Builder.CreatePreserveUnionAccessIndex( 49290fca6ea1SDimitry Andric addr.emitRawPointer(*this), 49300fca6ea1SDimitry Andric getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo), 493181ad6265SDimitry Andric addr.getElementType(), addr.getAlignment()); 49320b57cec5SDimitry Andric } 49330b57cec5SDimitry Andric 4934a7dea167SDimitry Andric if (FieldType->isReferenceType()) 493506c3fb27SDimitry Andric addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType)); 4936a7dea167SDimitry Andric } else { 4937480093f4SDimitry Andric if (!IsInPreservedAIRegion && 4938480093f4SDimitry Andric (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) 49390b57cec5SDimitry Andric // For structs, we GEP to the field that the record layout suggests. 49400b57cec5SDimitry Andric addr = emitAddrOfFieldStorage(*this, addr, field); 49410b57cec5SDimitry Andric else 49420b57cec5SDimitry Andric // Remember the original struct field index 49435ffd83dbSDimitry Andric addr = emitPreserveStructAccess(*this, base, addr, field); 4944a7dea167SDimitry Andric } 49450b57cec5SDimitry Andric 49460b57cec5SDimitry Andric // If this is a reference field, load the reference right now. 49470b57cec5SDimitry Andric if (FieldType->isReferenceType()) { 4948a7dea167SDimitry Andric LValue RefLVal = 4949a7dea167SDimitry Andric MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo); 49500b57cec5SDimitry Andric if (RecordCVR & Qualifiers::Volatile) 49510b57cec5SDimitry Andric RefLVal.getQuals().addVolatile(); 49520b57cec5SDimitry Andric addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo); 49530b57cec5SDimitry Andric 49540b57cec5SDimitry Andric // Qualifiers on the struct don't apply to the referencee. 49550b57cec5SDimitry Andric RecordCVR = 0; 49560b57cec5SDimitry Andric FieldType = FieldType->getPointeeType(); 49570b57cec5SDimitry Andric } 49580b57cec5SDimitry Andric 49590b57cec5SDimitry Andric // Make sure that the address is pointing to the right type. This is critical 496006c3fb27SDimitry Andric // for both unions and structs. 496106c3fb27SDimitry Andric addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType)); 49620b57cec5SDimitry Andric 49630b57cec5SDimitry Andric if (field->hasAttr<AnnotateAttr>()) 49640b57cec5SDimitry Andric addr = EmitFieldAnnotations(field, addr); 49650b57cec5SDimitry Andric 49660b57cec5SDimitry Andric LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo); 49670b57cec5SDimitry Andric LV.getQuals().addCVRQualifiers(RecordCVR); 49680b57cec5SDimitry Andric 49690b57cec5SDimitry Andric // __weak attribute on a field is ignored. 49700b57cec5SDimitry Andric if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak) 49710b57cec5SDimitry Andric LV.getQuals().removeObjCGCAttr(); 49720b57cec5SDimitry Andric 49730b57cec5SDimitry Andric return LV; 49740b57cec5SDimitry Andric } 49750b57cec5SDimitry Andric 49760b57cec5SDimitry Andric LValue 49770b57cec5SDimitry Andric CodeGenFunction::EmitLValueForFieldInitialization(LValue Base, 49780b57cec5SDimitry Andric const FieldDecl *Field) { 49790b57cec5SDimitry Andric QualType FieldType = Field->getType(); 49800b57cec5SDimitry Andric 49810b57cec5SDimitry Andric if (!FieldType->isReferenceType()) 49820b57cec5SDimitry Andric return EmitLValueForField(Base, Field); 49830b57cec5SDimitry Andric 49840fca6ea1SDimitry Andric Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field); 49850b57cec5SDimitry Andric 49860b57cec5SDimitry Andric // Make sure that the address is pointing to the right type. 49870b57cec5SDimitry Andric llvm::Type *llvmType = ConvertTypeForMem(FieldType); 498806c3fb27SDimitry Andric V = V.withElementType(llvmType); 49890b57cec5SDimitry Andric 49900b57cec5SDimitry Andric // TODO: Generate TBAA information that describes this access as a structure 49910b57cec5SDimitry Andric // member access and not just an access to an object of the field's type. This 49920b57cec5SDimitry Andric // should be similar to what we do in EmitLValueForField(). 49930b57cec5SDimitry Andric LValueBaseInfo BaseInfo = Base.getBaseInfo(); 49940b57cec5SDimitry Andric AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource(); 49950b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource)); 49960b57cec5SDimitry Andric return MakeAddrLValue(V, FieldType, FieldBaseInfo, 49970b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(Base, FieldType)); 49980b57cec5SDimitry Andric } 49990b57cec5SDimitry Andric 50000b57cec5SDimitry Andric LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){ 50010b57cec5SDimitry Andric if (E->isFileScope()) { 50020b57cec5SDimitry Andric ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E); 50030b57cec5SDimitry Andric return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl); 50040b57cec5SDimitry Andric } 50050b57cec5SDimitry Andric if (E->getType()->isVariablyModifiedType()) 50060b57cec5SDimitry Andric // make sure to emit the VLA size. 50070b57cec5SDimitry Andric EmitVariablyModifiedType(E->getType()); 50080b57cec5SDimitry Andric 50090b57cec5SDimitry Andric Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral"); 50100b57cec5SDimitry Andric const Expr *InitExpr = E->getInitializer(); 50110b57cec5SDimitry Andric LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl); 50120b57cec5SDimitry Andric 50130b57cec5SDimitry Andric EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(), 50140b57cec5SDimitry Andric /*Init*/ true); 50150b57cec5SDimitry Andric 50165ffd83dbSDimitry Andric // Block-scope compound literals are destroyed at the end of the enclosing 50175ffd83dbSDimitry Andric // scope in C. 50185ffd83dbSDimitry Andric if (!getLangOpts().CPlusPlus) 50195ffd83dbSDimitry Andric if (QualType::DestructionKind DtorKind = E->getType().isDestructedType()) 50205ffd83dbSDimitry Andric pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr, 50215ffd83dbSDimitry Andric E->getType(), getDestroyer(DtorKind), 50225ffd83dbSDimitry Andric DtorKind & EHCleanup); 50235ffd83dbSDimitry Andric 50240b57cec5SDimitry Andric return Result; 50250b57cec5SDimitry Andric } 50260b57cec5SDimitry Andric 50270b57cec5SDimitry Andric LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) { 50280b57cec5SDimitry Andric if (!E->isGLValue()) 50290b57cec5SDimitry Andric // Initializing an aggregate temporary in C++11: T{...}. 50300b57cec5SDimitry Andric return EmitAggExprToLValue(E); 50310b57cec5SDimitry Andric 50320b57cec5SDimitry Andric // An lvalue initializer list must be initializing a reference. 50330b57cec5SDimitry Andric assert(E->isTransparent() && "non-transparent glvalue init list"); 50340b57cec5SDimitry Andric return EmitLValue(E->getInit(0)); 50350b57cec5SDimitry Andric } 50360b57cec5SDimitry Andric 50370b57cec5SDimitry Andric /// Emit the operand of a glvalue conditional operator. This is either a glvalue 50380b57cec5SDimitry Andric /// or a (possibly-parenthesized) throw-expression. If this is a throw, no 50390b57cec5SDimitry Andric /// LValue is returned and the current block has been terminated. 5040bdd1243dSDimitry Andric static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF, 50410b57cec5SDimitry Andric const Expr *Operand) { 50420b57cec5SDimitry Andric if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) { 50430b57cec5SDimitry Andric CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false); 5044bdd1243dSDimitry Andric return std::nullopt; 50450b57cec5SDimitry Andric } 50460b57cec5SDimitry Andric 50470b57cec5SDimitry Andric return CGF.EmitLValue(Operand); 50480b57cec5SDimitry Andric } 50490b57cec5SDimitry Andric 505081ad6265SDimitry Andric namespace { 505181ad6265SDimitry Andric // Handle the case where the condition is a constant evaluatable simple integer, 505281ad6265SDimitry Andric // which means we don't have to separately handle the true/false blocks. 5053bdd1243dSDimitry Andric std::optional<LValue> HandleConditionalOperatorLValueSimpleCase( 505481ad6265SDimitry Andric CodeGenFunction &CGF, const AbstractConditionalOperator *E) { 505581ad6265SDimitry Andric const Expr *condExpr = E->getCond(); 505681ad6265SDimitry Andric bool CondExprBool; 505781ad6265SDimitry Andric if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) { 505881ad6265SDimitry Andric const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr(); 505981ad6265SDimitry Andric if (!CondExprBool) 506081ad6265SDimitry Andric std::swap(Live, Dead); 506181ad6265SDimitry Andric 506281ad6265SDimitry Andric if (!CGF.ContainsLabel(Dead)) { 506381ad6265SDimitry Andric // If the true case is live, we need to track its region. 506481ad6265SDimitry Andric if (CondExprBool) 506581ad6265SDimitry Andric CGF.incrementProfileCounter(E); 506681ad6265SDimitry Andric // If a throw expression we emit it and return an undefined lvalue 506781ad6265SDimitry Andric // because it can't be used. 506881ad6265SDimitry Andric if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) { 506981ad6265SDimitry Andric CGF.EmitCXXThrowExpr(ThrowExpr); 507081ad6265SDimitry Andric llvm::Type *ElemTy = CGF.ConvertType(Dead->getType()); 50715f757f3fSDimitry Andric llvm::Type *Ty = CGF.UnqualPtrTy; 507281ad6265SDimitry Andric return CGF.MakeAddrLValue( 507381ad6265SDimitry Andric Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()), 507481ad6265SDimitry Andric Dead->getType()); 507581ad6265SDimitry Andric } 507681ad6265SDimitry Andric return CGF.EmitLValue(Live); 507781ad6265SDimitry Andric } 507881ad6265SDimitry Andric } 5079bdd1243dSDimitry Andric return std::nullopt; 508081ad6265SDimitry Andric } 508181ad6265SDimitry Andric struct ConditionalInfo { 508281ad6265SDimitry Andric llvm::BasicBlock *lhsBlock, *rhsBlock; 5083bdd1243dSDimitry Andric std::optional<LValue> LHS, RHS; 508481ad6265SDimitry Andric }; 508581ad6265SDimitry Andric 508681ad6265SDimitry Andric // Create and generate the 3 blocks for a conditional operator. 508781ad6265SDimitry Andric // Leaves the 'current block' in the continuation basic block. 508881ad6265SDimitry Andric template<typename FuncTy> 508981ad6265SDimitry Andric ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF, 509081ad6265SDimitry Andric const AbstractConditionalOperator *E, 509181ad6265SDimitry Andric const FuncTy &BranchGenFunc) { 509281ad6265SDimitry Andric ConditionalInfo Info{CGF.createBasicBlock("cond.true"), 5093bdd1243dSDimitry Andric CGF.createBasicBlock("cond.false"), std::nullopt, 5094bdd1243dSDimitry Andric std::nullopt}; 509581ad6265SDimitry Andric llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end"); 509681ad6265SDimitry Andric 509781ad6265SDimitry Andric CodeGenFunction::ConditionalEvaluation eval(CGF); 509881ad6265SDimitry Andric CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock, 509981ad6265SDimitry Andric CGF.getProfileCount(E)); 510081ad6265SDimitry Andric 510181ad6265SDimitry Andric // Any temporaries created here are conditional. 510281ad6265SDimitry Andric CGF.EmitBlock(Info.lhsBlock); 510381ad6265SDimitry Andric CGF.incrementProfileCounter(E); 510481ad6265SDimitry Andric eval.begin(CGF); 510581ad6265SDimitry Andric Info.LHS = BranchGenFunc(CGF, E->getTrueExpr()); 510681ad6265SDimitry Andric eval.end(CGF); 510781ad6265SDimitry Andric Info.lhsBlock = CGF.Builder.GetInsertBlock(); 510881ad6265SDimitry Andric 510981ad6265SDimitry Andric if (Info.LHS) 511081ad6265SDimitry Andric CGF.Builder.CreateBr(endBlock); 511181ad6265SDimitry Andric 511281ad6265SDimitry Andric // Any temporaries created here are conditional. 511381ad6265SDimitry Andric CGF.EmitBlock(Info.rhsBlock); 511481ad6265SDimitry Andric eval.begin(CGF); 511581ad6265SDimitry Andric Info.RHS = BranchGenFunc(CGF, E->getFalseExpr()); 511681ad6265SDimitry Andric eval.end(CGF); 511781ad6265SDimitry Andric Info.rhsBlock = CGF.Builder.GetInsertBlock(); 511881ad6265SDimitry Andric CGF.EmitBlock(endBlock); 511981ad6265SDimitry Andric 512081ad6265SDimitry Andric return Info; 512181ad6265SDimitry Andric } 512281ad6265SDimitry Andric } // namespace 512381ad6265SDimitry Andric 512481ad6265SDimitry Andric void CodeGenFunction::EmitIgnoredConditionalOperator( 512581ad6265SDimitry Andric const AbstractConditionalOperator *E) { 512681ad6265SDimitry Andric if (!E->isGLValue()) { 512781ad6265SDimitry Andric // ?: here should be an aggregate. 512881ad6265SDimitry Andric assert(hasAggregateEvaluationKind(E->getType()) && 512981ad6265SDimitry Andric "Unexpected conditional operator!"); 513081ad6265SDimitry Andric return (void)EmitAggExprToLValue(E); 513181ad6265SDimitry Andric } 513281ad6265SDimitry Andric 513381ad6265SDimitry Andric OpaqueValueMapping binding(*this, E); 513481ad6265SDimitry Andric if (HandleConditionalOperatorLValueSimpleCase(*this, E)) 513581ad6265SDimitry Andric return; 513681ad6265SDimitry Andric 513781ad6265SDimitry Andric EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) { 513881ad6265SDimitry Andric CGF.EmitIgnoredExpr(E); 513981ad6265SDimitry Andric return LValue{}; 514081ad6265SDimitry Andric }); 514181ad6265SDimitry Andric } 514281ad6265SDimitry Andric LValue CodeGenFunction::EmitConditionalOperatorLValue( 514381ad6265SDimitry Andric const AbstractConditionalOperator *expr) { 51440b57cec5SDimitry Andric if (!expr->isGLValue()) { 51450b57cec5SDimitry Andric // ?: here should be an aggregate. 51460b57cec5SDimitry Andric assert(hasAggregateEvaluationKind(expr->getType()) && 51470b57cec5SDimitry Andric "Unexpected conditional operator!"); 51480b57cec5SDimitry Andric return EmitAggExprToLValue(expr); 51490b57cec5SDimitry Andric } 51500b57cec5SDimitry Andric 51510b57cec5SDimitry Andric OpaqueValueMapping binding(*this, expr); 5152bdd1243dSDimitry Andric if (std::optional<LValue> Res = 515381ad6265SDimitry Andric HandleConditionalOperatorLValueSimpleCase(*this, expr)) 515481ad6265SDimitry Andric return *Res; 51550b57cec5SDimitry Andric 515681ad6265SDimitry Andric ConditionalInfo Info = EmitConditionalBlocks( 515781ad6265SDimitry Andric *this, expr, [](CodeGenFunction &CGF, const Expr *E) { 515881ad6265SDimitry Andric return EmitLValueOrThrowExpression(CGF, E); 515981ad6265SDimitry Andric }); 51600b57cec5SDimitry Andric 516181ad6265SDimitry Andric if ((Info.LHS && !Info.LHS->isSimple()) || 516281ad6265SDimitry Andric (Info.RHS && !Info.RHS->isSimple())) 51630b57cec5SDimitry Andric return EmitUnsupportedLValue(expr, "conditional operator"); 51640b57cec5SDimitry Andric 516581ad6265SDimitry Andric if (Info.LHS && Info.RHS) { 51660fca6ea1SDimitry Andric Address lhsAddr = Info.LHS->getAddress(); 51670fca6ea1SDimitry Andric Address rhsAddr = Info.RHS->getAddress(); 51680fca6ea1SDimitry Andric Address result = mergeAddressesInConditionalExpr( 51690fca6ea1SDimitry Andric lhsAddr, rhsAddr, Info.lhsBlock, Info.rhsBlock, 51700fca6ea1SDimitry Andric Builder.GetInsertBlock(), expr->getType()); 51710b57cec5SDimitry Andric AlignmentSource alignSource = 517281ad6265SDimitry Andric std::max(Info.LHS->getBaseInfo().getAlignmentSource(), 517381ad6265SDimitry Andric Info.RHS->getBaseInfo().getAlignmentSource()); 51740b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator( 517581ad6265SDimitry Andric Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo()); 51760b57cec5SDimitry Andric return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource), 51770b57cec5SDimitry Andric TBAAInfo); 51780b57cec5SDimitry Andric } else { 517981ad6265SDimitry Andric assert((Info.LHS || Info.RHS) && 51800b57cec5SDimitry Andric "both operands of glvalue conditional are throw-expressions?"); 518181ad6265SDimitry Andric return Info.LHS ? *Info.LHS : *Info.RHS; 51820b57cec5SDimitry Andric } 51830b57cec5SDimitry Andric } 51840b57cec5SDimitry Andric 51850b57cec5SDimitry Andric /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference 51860b57cec5SDimitry Andric /// type. If the cast is to a reference, we can have the usual lvalue result, 51870b57cec5SDimitry Andric /// otherwise if a cast is needed by the code generator in an lvalue context, 51880b57cec5SDimitry Andric /// then it must mean that we need the address of an aggregate in order to 51890b57cec5SDimitry Andric /// access one of its members. This can happen for all the reasons that casts 51900b57cec5SDimitry Andric /// are permitted with aggregate result, including noop aggregate casts, and 51910b57cec5SDimitry Andric /// cast from scalar to union. 51920b57cec5SDimitry Andric LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) { 51930b57cec5SDimitry Andric switch (E->getCastKind()) { 51940b57cec5SDimitry Andric case CK_ToVoid: 51950b57cec5SDimitry Andric case CK_BitCast: 51960b57cec5SDimitry Andric case CK_LValueToRValueBitCast: 51970b57cec5SDimitry Andric case CK_ArrayToPointerDecay: 51980b57cec5SDimitry Andric case CK_FunctionToPointerDecay: 51990b57cec5SDimitry Andric case CK_NullToMemberPointer: 52000b57cec5SDimitry Andric case CK_NullToPointer: 52010b57cec5SDimitry Andric case CK_IntegralToPointer: 52020b57cec5SDimitry Andric case CK_PointerToIntegral: 52030b57cec5SDimitry Andric case CK_PointerToBoolean: 52040b57cec5SDimitry Andric case CK_IntegralCast: 52050b57cec5SDimitry Andric case CK_BooleanToSignedIntegral: 52060b57cec5SDimitry Andric case CK_IntegralToBoolean: 52070b57cec5SDimitry Andric case CK_IntegralToFloating: 52080b57cec5SDimitry Andric case CK_FloatingToIntegral: 52090b57cec5SDimitry Andric case CK_FloatingToBoolean: 52100b57cec5SDimitry Andric case CK_FloatingCast: 52110b57cec5SDimitry Andric case CK_FloatingRealToComplex: 52120b57cec5SDimitry Andric case CK_FloatingComplexToReal: 52130b57cec5SDimitry Andric case CK_FloatingComplexToBoolean: 52140b57cec5SDimitry Andric case CK_FloatingComplexCast: 52150b57cec5SDimitry Andric case CK_FloatingComplexToIntegralComplex: 52160b57cec5SDimitry Andric case CK_IntegralRealToComplex: 52170b57cec5SDimitry Andric case CK_IntegralComplexToReal: 52180b57cec5SDimitry Andric case CK_IntegralComplexToBoolean: 52190b57cec5SDimitry Andric case CK_IntegralComplexCast: 52200b57cec5SDimitry Andric case CK_IntegralComplexToFloatingComplex: 52210b57cec5SDimitry Andric case CK_DerivedToBaseMemberPointer: 52220b57cec5SDimitry Andric case CK_BaseToDerivedMemberPointer: 52230b57cec5SDimitry Andric case CK_MemberPointerToBoolean: 52240b57cec5SDimitry Andric case CK_ReinterpretMemberPointer: 52250b57cec5SDimitry Andric case CK_AnyPointerToBlockPointerCast: 52260b57cec5SDimitry Andric case CK_ARCProduceObject: 52270b57cec5SDimitry Andric case CK_ARCConsumeObject: 52280b57cec5SDimitry Andric case CK_ARCReclaimReturnedObject: 52290b57cec5SDimitry Andric case CK_ARCExtendBlockObject: 52300b57cec5SDimitry Andric case CK_CopyAndAutoreleaseBlockObject: 52310b57cec5SDimitry Andric case CK_IntToOCLSampler: 5232e8d8bef9SDimitry Andric case CK_FloatingToFixedPoint: 5233e8d8bef9SDimitry Andric case CK_FixedPointToFloating: 52340b57cec5SDimitry Andric case CK_FixedPointCast: 52350b57cec5SDimitry Andric case CK_FixedPointToBoolean: 52360b57cec5SDimitry Andric case CK_FixedPointToIntegral: 52370b57cec5SDimitry Andric case CK_IntegralToFixedPoint: 5238fe6060f1SDimitry Andric case CK_MatrixCast: 52390fca6ea1SDimitry Andric case CK_HLSLVectorTruncation: 52400fca6ea1SDimitry Andric case CK_HLSLArrayRValue: 52410b57cec5SDimitry Andric return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 52420b57cec5SDimitry Andric 52430b57cec5SDimitry Andric case CK_Dependent: 52440b57cec5SDimitry Andric llvm_unreachable("dependent cast kind in IR gen!"); 52450b57cec5SDimitry Andric 52460b57cec5SDimitry Andric case CK_BuiltinFnToFnPtr: 52470b57cec5SDimitry Andric llvm_unreachable("builtin functions are handled elsewhere"); 52480b57cec5SDimitry Andric 52490b57cec5SDimitry Andric // These are never l-values; just use the aggregate emission code. 52500b57cec5SDimitry Andric case CK_NonAtomicToAtomic: 52510b57cec5SDimitry Andric case CK_AtomicToNonAtomic: 52520b57cec5SDimitry Andric return EmitAggExprToLValue(E); 52530b57cec5SDimitry Andric 52540b57cec5SDimitry Andric case CK_Dynamic: { 52550b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 52560fca6ea1SDimitry Andric Address V = LV.getAddress(); 52570b57cec5SDimitry Andric const auto *DCE = cast<CXXDynamicCastExpr>(E); 52580fca6ea1SDimitry Andric return MakeNaturalAlignRawAddrLValue(EmitDynamicCast(V, DCE), E->getType()); 52590b57cec5SDimitry Andric } 52600b57cec5SDimitry Andric 52610b57cec5SDimitry Andric case CK_ConstructorConversion: 52620b57cec5SDimitry Andric case CK_UserDefinedConversion: 52630b57cec5SDimitry Andric case CK_CPointerToObjCPointerCast: 52640b57cec5SDimitry Andric case CK_BlockPointerToObjCPointerCast: 52650b57cec5SDimitry Andric case CK_LValueToRValue: 52660b57cec5SDimitry Andric return EmitLValue(E->getSubExpr()); 52670b57cec5SDimitry Andric 5268349cc55cSDimitry Andric case CK_NoOp: { 5269349cc55cSDimitry Andric // CK_NoOp can model a qualification conversion, which can remove an array 5270349cc55cSDimitry Andric // bound and change the IR type. 5271349cc55cSDimitry Andric // FIXME: Once pointee types are removed from IR, remove this. 5272349cc55cSDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 52735f757f3fSDimitry Andric // Propagate the volatile qualifer to LValue, if exist in E. 52745f757f3fSDimitry Andric if (E->changesVolatileQualification()) 52755f757f3fSDimitry Andric LV.getQuals() = E->getType().getQualifiers(); 5276349cc55cSDimitry Andric if (LV.isSimple()) { 52770fca6ea1SDimitry Andric Address V = LV.getAddress(); 5278349cc55cSDimitry Andric if (V.isValid()) { 527904eeddc0SDimitry Andric llvm::Type *T = ConvertTypeForMem(E->getType()); 528004eeddc0SDimitry Andric if (V.getElementType() != T) 528106c3fb27SDimitry Andric LV.setAddress(V.withElementType(T)); 5282349cc55cSDimitry Andric } 5283349cc55cSDimitry Andric } 5284349cc55cSDimitry Andric return LV; 5285349cc55cSDimitry Andric } 5286349cc55cSDimitry Andric 52870b57cec5SDimitry Andric case CK_UncheckedDerivedToBase: 52880b57cec5SDimitry Andric case CK_DerivedToBase: { 5289480093f4SDimitry Andric const auto *DerivedClassTy = 5290480093f4SDimitry Andric E->getSubExpr()->getType()->castAs<RecordType>(); 52910b57cec5SDimitry Andric auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 52920b57cec5SDimitry Andric 52930b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 52940fca6ea1SDimitry Andric Address This = LV.getAddress(); 52950b57cec5SDimitry Andric 52960b57cec5SDimitry Andric // Perform the derived-to-base conversion 52970b57cec5SDimitry Andric Address Base = GetAddressOfBaseClass( 52980b57cec5SDimitry Andric This, DerivedClassDecl, E->path_begin(), E->path_end(), 52990b57cec5SDimitry Andric /*NullCheckValue=*/false, E->getExprLoc()); 53000b57cec5SDimitry Andric 53010b57cec5SDimitry Andric // TODO: Support accesses to members of base classes in TBAA. For now, we 53020b57cec5SDimitry Andric // conservatively pretend that the complete object is of the base class 53030b57cec5SDimitry Andric // type. 53040b57cec5SDimitry Andric return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(), 53050b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType())); 53060b57cec5SDimitry Andric } 53070b57cec5SDimitry Andric case CK_ToUnion: 53080b57cec5SDimitry Andric return EmitAggExprToLValue(E); 53090b57cec5SDimitry Andric case CK_BaseToDerived: { 5310480093f4SDimitry Andric const auto *DerivedClassTy = E->getType()->castAs<RecordType>(); 53110b57cec5SDimitry Andric auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl()); 53120b57cec5SDimitry Andric 53130b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 53140b57cec5SDimitry Andric 53150b57cec5SDimitry Andric // Perform the base-to-derived conversion 5316480093f4SDimitry Andric Address Derived = GetAddressOfDerivedClass( 53170fca6ea1SDimitry Andric LV.getAddress(), DerivedClassDecl, E->path_begin(), E->path_end(), 53180b57cec5SDimitry Andric /*NullCheckValue=*/false); 53190b57cec5SDimitry Andric 53200b57cec5SDimitry Andric // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is 53210b57cec5SDimitry Andric // performed and the object is not of the derived type. 53220b57cec5SDimitry Andric if (sanitizePerformTypeCheck()) 53230fca6ea1SDimitry Andric EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(), Derived, 53240fca6ea1SDimitry Andric E->getType()); 53250b57cec5SDimitry Andric 53260b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIDerivedCast)) 532781ad6265SDimitry Andric EmitVTablePtrCheckForCast(E->getType(), Derived, 53280b57cec5SDimitry Andric /*MayBeNull=*/false, CFITCK_DerivedCast, 53290b57cec5SDimitry Andric E->getBeginLoc()); 53300b57cec5SDimitry Andric 53310b57cec5SDimitry Andric return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(), 53320b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType())); 53330b57cec5SDimitry Andric } 53340b57cec5SDimitry Andric case CK_LValueBitCast: { 53350b57cec5SDimitry Andric // This must be a reinterpret_cast (or c-style equivalent). 53360b57cec5SDimitry Andric const auto *CE = cast<ExplicitCastExpr>(E); 53370b57cec5SDimitry Andric 53380b57cec5SDimitry Andric CGM.EmitExplicitCastExprType(CE, this); 53390b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 53400fca6ea1SDimitry Andric Address V = LV.getAddress().withElementType( 534104eeddc0SDimitry Andric ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType())); 53420b57cec5SDimitry Andric 53430b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) 534481ad6265SDimitry Andric EmitVTablePtrCheckForCast(E->getType(), V, 53450b57cec5SDimitry Andric /*MayBeNull=*/false, CFITCK_UnrelatedCast, 53460b57cec5SDimitry Andric E->getBeginLoc()); 53470b57cec5SDimitry Andric 53480b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(), 53490b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType())); 53500b57cec5SDimitry Andric } 53510b57cec5SDimitry Andric case CK_AddressSpaceConversion: { 53520b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 53530b57cec5SDimitry Andric QualType DestTy = getContext().getPointerType(E->getType()); 53540b57cec5SDimitry Andric llvm::Value *V = getTargetHooks().performAddrSpaceCast( 5355480093f4SDimitry Andric *this, LV.getPointer(*this), 5356480093f4SDimitry Andric E->getSubExpr()->getType().getAddressSpace(), 53570b57cec5SDimitry Andric E->getType().getAddressSpace(), ConvertType(DestTy)); 535881ad6265SDimitry Andric return MakeAddrLValue(Address(V, ConvertTypeForMem(E->getType()), 53590fca6ea1SDimitry Andric LV.getAddress().getAlignment()), 53600b57cec5SDimitry Andric E->getType(), LV.getBaseInfo(), LV.getTBAAInfo()); 53610b57cec5SDimitry Andric } 53620b57cec5SDimitry Andric case CK_ObjCObjectLValueCast: { 53630b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr()); 53640fca6ea1SDimitry Andric Address V = LV.getAddress().withElementType(ConvertType(E->getType())); 53650b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(), 53660b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType())); 53670b57cec5SDimitry Andric } 53680b57cec5SDimitry Andric case CK_ZeroToOCLOpaqueType: 53690b57cec5SDimitry Andric llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid"); 53705f757f3fSDimitry Andric 53715f757f3fSDimitry Andric case CK_VectorSplat: { 53725f757f3fSDimitry Andric // LValue results of vector splats are only supported in HLSL. 53735f757f3fSDimitry Andric if (!getLangOpts().HLSL) 53745f757f3fSDimitry Andric return EmitUnsupportedLValue(E, "unexpected cast lvalue"); 53755f757f3fSDimitry Andric return EmitLValue(E->getSubExpr()); 53765f757f3fSDimitry Andric } 53770b57cec5SDimitry Andric } 53780b57cec5SDimitry Andric 53790b57cec5SDimitry Andric llvm_unreachable("Unhandled lvalue cast kind?"); 53800b57cec5SDimitry Andric } 53810b57cec5SDimitry Andric 53820b57cec5SDimitry Andric LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) { 53830b57cec5SDimitry Andric assert(OpaqueValueMappingData::shouldBindAsLValue(e)); 53840b57cec5SDimitry Andric return getOrCreateOpaqueLValueMapping(e); 53850b57cec5SDimitry Andric } 53860b57cec5SDimitry Andric 53870b57cec5SDimitry Andric LValue 53880b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) { 53890b57cec5SDimitry Andric assert(OpaqueValueMapping::shouldBindAsLValue(e)); 53900b57cec5SDimitry Andric 53910b57cec5SDimitry Andric llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 53920b57cec5SDimitry Andric it = OpaqueLValues.find(e); 53930b57cec5SDimitry Andric 53940b57cec5SDimitry Andric if (it != OpaqueLValues.end()) 53950b57cec5SDimitry Andric return it->second; 53960b57cec5SDimitry Andric 53970b57cec5SDimitry Andric assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted"); 53980b57cec5SDimitry Andric return EmitLValue(e->getSourceExpr()); 53990b57cec5SDimitry Andric } 54000b57cec5SDimitry Andric 54010b57cec5SDimitry Andric RValue 54020b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) { 54030b57cec5SDimitry Andric assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 54040b57cec5SDimitry Andric 54050b57cec5SDimitry Andric llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 54060b57cec5SDimitry Andric it = OpaqueRValues.find(e); 54070b57cec5SDimitry Andric 54080b57cec5SDimitry Andric if (it != OpaqueRValues.end()) 54090b57cec5SDimitry Andric return it->second; 54100b57cec5SDimitry Andric 54110b57cec5SDimitry Andric assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted"); 54120b57cec5SDimitry Andric return EmitAnyExpr(e->getSourceExpr()); 54130b57cec5SDimitry Andric } 54140b57cec5SDimitry Andric 54150b57cec5SDimitry Andric RValue CodeGenFunction::EmitRValueForField(LValue LV, 54160b57cec5SDimitry Andric const FieldDecl *FD, 54170b57cec5SDimitry Andric SourceLocation Loc) { 54180b57cec5SDimitry Andric QualType FT = FD->getType(); 54190b57cec5SDimitry Andric LValue FieldLV = EmitLValueForField(LV, FD); 54200b57cec5SDimitry Andric switch (getEvaluationKind(FT)) { 54210b57cec5SDimitry Andric case TEK_Complex: 54220b57cec5SDimitry Andric return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc)); 54230b57cec5SDimitry Andric case TEK_Aggregate: 54240fca6ea1SDimitry Andric return FieldLV.asAggregateRValue(); 54250b57cec5SDimitry Andric case TEK_Scalar: 54260b57cec5SDimitry Andric // This routine is used to load fields one-by-one to perform a copy, so 54270b57cec5SDimitry Andric // don't load reference fields. 54280b57cec5SDimitry Andric if (FD->getType()->isReferenceType()) 5429480093f4SDimitry Andric return RValue::get(FieldLV.getPointer(*this)); 5430480093f4SDimitry Andric // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a 5431480093f4SDimitry Andric // primitive load. 5432480093f4SDimitry Andric if (FieldLV.isBitField()) 54330b57cec5SDimitry Andric return EmitLoadOfLValue(FieldLV, Loc); 5434480093f4SDimitry Andric return RValue::get(EmitLoadOfScalar(FieldLV, Loc)); 54350b57cec5SDimitry Andric } 54360b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind"); 54370b57cec5SDimitry Andric } 54380b57cec5SDimitry Andric 54390b57cec5SDimitry Andric //===--------------------------------------------------------------------===// 54400b57cec5SDimitry Andric // Expression Emission 54410b57cec5SDimitry Andric //===--------------------------------------------------------------------===// 54420b57cec5SDimitry Andric 54430b57cec5SDimitry Andric RValue CodeGenFunction::EmitCallExpr(const CallExpr *E, 54440b57cec5SDimitry Andric ReturnValueSlot ReturnValue) { 54450b57cec5SDimitry Andric // Builtins never have block type. 54460b57cec5SDimitry Andric if (E->getCallee()->getType()->isBlockPointerType()) 54470b57cec5SDimitry Andric return EmitBlockCallExpr(E, ReturnValue); 54480b57cec5SDimitry Andric 54490b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E)) 54500b57cec5SDimitry Andric return EmitCXXMemberCallExpr(CE, ReturnValue); 54510b57cec5SDimitry Andric 54520b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E)) 54530b57cec5SDimitry Andric return EmitCUDAKernelCallExpr(CE, ReturnValue); 54540b57cec5SDimitry Andric 54555f757f3fSDimitry Andric // A CXXOperatorCallExpr is created even for explicit object methods, but 54565f757f3fSDimitry Andric // these should be treated like static function call. 54570b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E)) 54585f757f3fSDimitry Andric if (const auto *MD = 54595f757f3fSDimitry Andric dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl()); 54605f757f3fSDimitry Andric MD && MD->isImplicitObjectMemberFunction()) 54610b57cec5SDimitry Andric return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue); 54620b57cec5SDimitry Andric 54630b57cec5SDimitry Andric CGCallee callee = EmitCallee(E->getCallee()); 54640b57cec5SDimitry Andric 54650b57cec5SDimitry Andric if (callee.isBuiltin()) { 54660b57cec5SDimitry Andric return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(), 54670b57cec5SDimitry Andric E, ReturnValue); 54680b57cec5SDimitry Andric } 54690b57cec5SDimitry Andric 54700b57cec5SDimitry Andric if (callee.isPseudoDestructor()) { 54710b57cec5SDimitry Andric return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr()); 54720b57cec5SDimitry Andric } 54730b57cec5SDimitry Andric 54740b57cec5SDimitry Andric return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue); 54750b57cec5SDimitry Andric } 54760b57cec5SDimitry Andric 54770b57cec5SDimitry Andric /// Emit a CallExpr without considering whether it might be a subclass. 54780b57cec5SDimitry Andric RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E, 54790b57cec5SDimitry Andric ReturnValueSlot ReturnValue) { 54800b57cec5SDimitry Andric CGCallee Callee = EmitCallee(E->getCallee()); 54810b57cec5SDimitry Andric return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue); 54820b57cec5SDimitry Andric } 54830b57cec5SDimitry Andric 54843a9a9c0cSDimitry Andric // Detect the unusual situation where an inline version is shadowed by a 54853a9a9c0cSDimitry Andric // non-inline version. In that case we should pick the external one 54863a9a9c0cSDimitry Andric // everywhere. That's GCC behavior too. 54873a9a9c0cSDimitry Andric static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD) { 54883a9a9c0cSDimitry Andric for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl()) 54893a9a9c0cSDimitry Andric if (!PD->isInlineBuiltinDeclaration()) 54903a9a9c0cSDimitry Andric return false; 54913a9a9c0cSDimitry Andric return true; 54923a9a9c0cSDimitry Andric } 54933a9a9c0cSDimitry Andric 54945ffd83dbSDimitry Andric static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) { 54955ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 5496480093f4SDimitry Andric 54970b57cec5SDimitry Andric if (auto builtinID = FD->getBuiltinID()) { 549881ad6265SDimitry Andric std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str(); 549981ad6265SDimitry Andric std::string NoBuiltins = "no-builtins"; 5500bdd1243dSDimitry Andric 5501bdd1243dSDimitry Andric StringRef Ident = CGF.CGM.getMangledName(GD); 5502bdd1243dSDimitry Andric std::string FDInlineName = (Ident + ".inline").str(); 550381ad6265SDimitry Andric 550481ad6265SDimitry Andric bool IsPredefinedLibFunction = 550581ad6265SDimitry Andric CGF.getContext().BuiltinInfo.isPredefinedLibFunction(builtinID); 550681ad6265SDimitry Andric bool HasAttributeNoBuiltin = 550781ad6265SDimitry Andric CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) || 550881ad6265SDimitry Andric CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins); 550981ad6265SDimitry Andric 5510349cc55cSDimitry Andric // When directing calling an inline builtin, call it through it's mangled 5511349cc55cSDimitry Andric // name to make it clear it's not the actual builtin. 55123a9a9c0cSDimitry Andric if (CGF.CurFn->getName() != FDInlineName && 55133a9a9c0cSDimitry Andric OnlyHasInlineBuiltinDeclaration(FD)) { 55140fca6ea1SDimitry Andric llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD); 5515349cc55cSDimitry Andric llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr); 5516349cc55cSDimitry Andric llvm::Module *M = Fn->getParent(); 5517349cc55cSDimitry Andric llvm::Function *Clone = M->getFunction(FDInlineName); 5518349cc55cSDimitry Andric if (!Clone) { 5519349cc55cSDimitry Andric Clone = llvm::Function::Create(Fn->getFunctionType(), 5520349cc55cSDimitry Andric llvm::GlobalValue::InternalLinkage, 5521349cc55cSDimitry Andric Fn->getAddressSpace(), FDInlineName, M); 5522349cc55cSDimitry Andric Clone->addFnAttr(llvm::Attribute::AlwaysInline); 5523349cc55cSDimitry Andric } 5524349cc55cSDimitry Andric return CGCallee::forDirect(Clone, GD); 5525349cc55cSDimitry Andric } 5526349cc55cSDimitry Andric 5527349cc55cSDimitry Andric // Replaceable builtins provide their own implementation of a builtin. If we 5528349cc55cSDimitry Andric // are in an inline builtin implementation, avoid trivial infinite 552981ad6265SDimitry Andric // recursion. Honor __attribute__((no_builtin("foo"))) or 553081ad6265SDimitry Andric // __attribute__((no_builtin)) on the current function unless foo is 553181ad6265SDimitry Andric // not a predefined library function which means we must generate the 553281ad6265SDimitry Andric // builtin no matter what. 553381ad6265SDimitry Andric else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin) 55340b57cec5SDimitry Andric return CGCallee::forBuiltin(builtinID, FD); 55350b57cec5SDimitry Andric } 55360b57cec5SDimitry Andric 55370fca6ea1SDimitry Andric llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD); 5538fe6060f1SDimitry Andric if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice && 5539fe6060f1SDimitry Andric FD->hasAttr<CUDAGlobalAttr>()) 5540fe6060f1SDimitry Andric CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub( 5541fe6060f1SDimitry Andric cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts())); 5542349cc55cSDimitry Andric 5543fe6060f1SDimitry Andric return CGCallee::forDirect(CalleePtr, GD); 55440b57cec5SDimitry Andric } 55450b57cec5SDimitry Andric 55460b57cec5SDimitry Andric CGCallee CodeGenFunction::EmitCallee(const Expr *E) { 55470b57cec5SDimitry Andric E = E->IgnoreParens(); 55480b57cec5SDimitry Andric 55490b57cec5SDimitry Andric // Look through function-to-pointer decay. 55500b57cec5SDimitry Andric if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) { 55510b57cec5SDimitry Andric if (ICE->getCastKind() == CK_FunctionToPointerDecay || 55520b57cec5SDimitry Andric ICE->getCastKind() == CK_BuiltinFnToFnPtr) { 55530b57cec5SDimitry Andric return EmitCallee(ICE->getSubExpr()); 55540b57cec5SDimitry Andric } 55550b57cec5SDimitry Andric 55560b57cec5SDimitry Andric // Resolve direct calls. 55570b57cec5SDimitry Andric } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) { 55580b57cec5SDimitry Andric if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 55590b57cec5SDimitry Andric return EmitDirectCallee(*this, FD); 55600b57cec5SDimitry Andric } 55610b57cec5SDimitry Andric } else if (auto ME = dyn_cast<MemberExpr>(E)) { 55620b57cec5SDimitry Andric if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) { 55630b57cec5SDimitry Andric EmitIgnoredExpr(ME->getBase()); 55640b57cec5SDimitry Andric return EmitDirectCallee(*this, FD); 55650b57cec5SDimitry Andric } 55660b57cec5SDimitry Andric 55670b57cec5SDimitry Andric // Look through template substitutions. 55680b57cec5SDimitry Andric } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) { 55690b57cec5SDimitry Andric return EmitCallee(NTTP->getReplacement()); 55700b57cec5SDimitry Andric 55710b57cec5SDimitry Andric // Treat pseudo-destructor calls differently. 55720b57cec5SDimitry Andric } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) { 55730b57cec5SDimitry Andric return CGCallee::forPseudoDestructor(PDE); 55740b57cec5SDimitry Andric } 55750b57cec5SDimitry Andric 55760b57cec5SDimitry Andric // Otherwise, we have an indirect reference. 55770b57cec5SDimitry Andric llvm::Value *calleePtr; 55780b57cec5SDimitry Andric QualType functionType; 55790b57cec5SDimitry Andric if (auto ptrType = E->getType()->getAs<PointerType>()) { 55800b57cec5SDimitry Andric calleePtr = EmitScalarExpr(E); 55810b57cec5SDimitry Andric functionType = ptrType->getPointeeType(); 55820b57cec5SDimitry Andric } else { 55830b57cec5SDimitry Andric functionType = E->getType(); 558406c3fb27SDimitry Andric calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this); 55850b57cec5SDimitry Andric } 55860b57cec5SDimitry Andric assert(functionType->isFunctionType()); 55870b57cec5SDimitry Andric 55880b57cec5SDimitry Andric GlobalDecl GD; 55890b57cec5SDimitry Andric if (const auto *VD = 55900b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee())) 55910b57cec5SDimitry Andric GD = GlobalDecl(VD); 55920b57cec5SDimitry Andric 55930b57cec5SDimitry Andric CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD); 55940fca6ea1SDimitry Andric CGPointerAuthInfo pointerAuth = CGM.getFunctionPointerAuthInfo(functionType); 55950fca6ea1SDimitry Andric CGCallee callee(calleeInfo, calleePtr, pointerAuth); 55960b57cec5SDimitry Andric return callee; 55970b57cec5SDimitry Andric } 55980b57cec5SDimitry Andric 55990b57cec5SDimitry Andric LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) { 56000b57cec5SDimitry Andric // Comma expressions just emit their LHS then their RHS as an l-value. 56010b57cec5SDimitry Andric if (E->getOpcode() == BO_Comma) { 56020b57cec5SDimitry Andric EmitIgnoredExpr(E->getLHS()); 56030b57cec5SDimitry Andric EnsureInsertPoint(); 56040b57cec5SDimitry Andric return EmitLValue(E->getRHS()); 56050b57cec5SDimitry Andric } 56060b57cec5SDimitry Andric 56070b57cec5SDimitry Andric if (E->getOpcode() == BO_PtrMemD || 56080b57cec5SDimitry Andric E->getOpcode() == BO_PtrMemI) 56090b57cec5SDimitry Andric return EmitPointerToDataMemberBinaryExpr(E); 56100b57cec5SDimitry Andric 56110b57cec5SDimitry Andric assert(E->getOpcode() == BO_Assign && "unexpected binary l-value"); 56120b57cec5SDimitry Andric 56130b57cec5SDimitry Andric // Note that in all of these cases, __block variables need the RHS 56140b57cec5SDimitry Andric // evaluated first just in case the variable gets moved by the RHS. 56150b57cec5SDimitry Andric 56160b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) { 56170b57cec5SDimitry Andric case TEK_Scalar: { 56180b57cec5SDimitry Andric switch (E->getLHS()->getType().getObjCLifetime()) { 56190b57cec5SDimitry Andric case Qualifiers::OCL_Strong: 56200b57cec5SDimitry Andric return EmitARCStoreStrong(E, /*ignored*/ false).first; 56210b57cec5SDimitry Andric 56220b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing: 56230b57cec5SDimitry Andric return EmitARCStoreAutoreleasing(E).first; 56240b57cec5SDimitry Andric 56250b57cec5SDimitry Andric // No reason to do any of these differently. 56260b57cec5SDimitry Andric case Qualifiers::OCL_None: 56270b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone: 56280b57cec5SDimitry Andric case Qualifiers::OCL_Weak: 56290b57cec5SDimitry Andric break; 56300b57cec5SDimitry Andric } 56310b57cec5SDimitry Andric 56320fca6ea1SDimitry Andric // TODO: Can we de-duplicate this code with the corresponding code in 56330fca6ea1SDimitry Andric // CGExprScalar, similar to the way EmitCompoundAssignmentLValue works? 56340fca6ea1SDimitry Andric RValue RV; 56350fca6ea1SDimitry Andric llvm::Value *Previous = nullptr; 56360fca6ea1SDimitry Andric QualType SrcType = E->getRHS()->getType(); 56370fca6ea1SDimitry Andric // Check if LHS is a bitfield, if RHS contains an implicit cast expression 56380fca6ea1SDimitry Andric // we want to extract that value and potentially (if the bitfield sanitizer 56390fca6ea1SDimitry Andric // is enabled) use it to check for an implicit conversion. 56400fca6ea1SDimitry Andric if (E->getLHS()->refersToBitField()) { 56410fca6ea1SDimitry Andric llvm::Value *RHS = 56420fca6ea1SDimitry Andric EmitWithOriginalRHSBitfieldAssignment(E, &Previous, &SrcType); 56430fca6ea1SDimitry Andric RV = RValue::get(RHS); 56440fca6ea1SDimitry Andric } else 56450fca6ea1SDimitry Andric RV = EmitAnyExpr(E->getRHS()); 56460fca6ea1SDimitry Andric 56470b57cec5SDimitry Andric LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store); 56480fca6ea1SDimitry Andric 56490b57cec5SDimitry Andric if (RV.isScalar()) 56500b57cec5SDimitry Andric EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc()); 56510fca6ea1SDimitry Andric 56520fca6ea1SDimitry Andric if (LV.isBitField()) { 56530fca6ea1SDimitry Andric llvm::Value *Result = nullptr; 56540fca6ea1SDimitry Andric // If bitfield sanitizers are enabled we want to use the result 56550fca6ea1SDimitry Andric // to check whether a truncation or sign change has occurred. 56560fca6ea1SDimitry Andric if (SanOpts.has(SanitizerKind::ImplicitBitfieldConversion)) 56570fca6ea1SDimitry Andric EmitStoreThroughBitfieldLValue(RV, LV, &Result); 56580fca6ea1SDimitry Andric else 56590fca6ea1SDimitry Andric EmitStoreThroughBitfieldLValue(RV, LV); 56600fca6ea1SDimitry Andric 56610fca6ea1SDimitry Andric // If the expression contained an implicit conversion, make sure 56620fca6ea1SDimitry Andric // to use the value before the scalar conversion. 56630fca6ea1SDimitry Andric llvm::Value *Src = Previous ? Previous : RV.getScalarVal(); 56640fca6ea1SDimitry Andric QualType DstType = E->getLHS()->getType(); 56650fca6ea1SDimitry Andric EmitBitfieldConversionCheck(Src, SrcType, Result, DstType, 56660fca6ea1SDimitry Andric LV.getBitFieldInfo(), E->getExprLoc()); 56670fca6ea1SDimitry Andric } else 56680b57cec5SDimitry Andric EmitStoreThroughLValue(RV, LV); 56690fca6ea1SDimitry Andric 5670480093f4SDimitry Andric if (getLangOpts().OpenMP) 5671480093f4SDimitry Andric CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this, 5672480093f4SDimitry Andric E->getLHS()); 56730b57cec5SDimitry Andric return LV; 56740b57cec5SDimitry Andric } 56750b57cec5SDimitry Andric 56760b57cec5SDimitry Andric case TEK_Complex: 56770b57cec5SDimitry Andric return EmitComplexAssignmentLValue(E); 56780b57cec5SDimitry Andric 56790b57cec5SDimitry Andric case TEK_Aggregate: 56800b57cec5SDimitry Andric return EmitAggExprToLValue(E); 56810b57cec5SDimitry Andric } 56820b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind"); 56830b57cec5SDimitry Andric } 56840b57cec5SDimitry Andric 56850b57cec5SDimitry Andric LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) { 56860b57cec5SDimitry Andric RValue RV = EmitCallExpr(E); 56870b57cec5SDimitry Andric 56880b57cec5SDimitry Andric if (!RV.isScalar()) 56890b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 56900b57cec5SDimitry Andric AlignmentSource::Decl); 56910b57cec5SDimitry Andric 56920b57cec5SDimitry Andric assert(E->getCallReturnType(getContext())->isReferenceType() && 56930b57cec5SDimitry Andric "Can't have a scalar return unless the return type is a " 56940b57cec5SDimitry Andric "reference type!"); 56950b57cec5SDimitry Andric 56960b57cec5SDimitry Andric return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 56970b57cec5SDimitry Andric } 56980b57cec5SDimitry Andric 56990b57cec5SDimitry Andric LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) { 57000b57cec5SDimitry Andric // FIXME: This shouldn't require another copy. 57010b57cec5SDimitry Andric return EmitAggExprToLValue(E); 57020b57cec5SDimitry Andric } 57030b57cec5SDimitry Andric 57040b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) { 57050b57cec5SDimitry Andric assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor() 57060b57cec5SDimitry Andric && "binding l-value to type which needs a temporary"); 57070b57cec5SDimitry Andric AggValueSlot Slot = CreateAggTemp(E->getType()); 57080b57cec5SDimitry Andric EmitCXXConstructExpr(E, Slot); 57090b57cec5SDimitry Andric return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl); 57100b57cec5SDimitry Andric } 57110b57cec5SDimitry Andric 57120b57cec5SDimitry Andric LValue 57130b57cec5SDimitry Andric CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) { 57140fca6ea1SDimitry Andric return MakeNaturalAlignRawAddrLValue(EmitCXXTypeidExpr(E), E->getType()); 57150b57cec5SDimitry Andric } 57160b57cec5SDimitry Andric 57170b57cec5SDimitry Andric Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) { 571806c3fb27SDimitry Andric return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()) 571906c3fb27SDimitry Andric .withElementType(ConvertType(E->getType())); 57200b57cec5SDimitry Andric } 57210b57cec5SDimitry Andric 57220b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) { 57230b57cec5SDimitry Andric return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(), 57240b57cec5SDimitry Andric AlignmentSource::Decl); 57250b57cec5SDimitry Andric } 57260b57cec5SDimitry Andric 57270b57cec5SDimitry Andric LValue 57280b57cec5SDimitry Andric CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) { 57290b57cec5SDimitry Andric AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue"); 57300b57cec5SDimitry Andric Slot.setExternallyDestructed(); 57310b57cec5SDimitry Andric EmitAggExpr(E->getSubExpr(), Slot); 57320b57cec5SDimitry Andric EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress()); 57330b57cec5SDimitry Andric return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl); 57340b57cec5SDimitry Andric } 57350b57cec5SDimitry Andric 57360b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) { 57370b57cec5SDimitry Andric RValue RV = EmitObjCMessageExpr(E); 57380b57cec5SDimitry Andric 57390b57cec5SDimitry Andric if (!RV.isScalar()) 57400b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 57410b57cec5SDimitry Andric AlignmentSource::Decl); 57420b57cec5SDimitry Andric 57430b57cec5SDimitry Andric assert(E->getMethodDecl()->getReturnType()->isReferenceType() && 57440b57cec5SDimitry Andric "Can't have a scalar return unless the return type is a " 57450b57cec5SDimitry Andric "reference type!"); 57460b57cec5SDimitry Andric 57470b57cec5SDimitry Andric return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType()); 57480b57cec5SDimitry Andric } 57490b57cec5SDimitry Andric 57500b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) { 57510b57cec5SDimitry Andric Address V = 57520b57cec5SDimitry Andric CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector()); 57530b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl); 57540b57cec5SDimitry Andric } 57550b57cec5SDimitry Andric 57560b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface, 57570b57cec5SDimitry Andric const ObjCIvarDecl *Ivar) { 57580b57cec5SDimitry Andric return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar); 57590b57cec5SDimitry Andric } 57600b57cec5SDimitry Andric 5761bdd1243dSDimitry Andric llvm::Value * 5762bdd1243dSDimitry Andric CodeGenFunction::EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface, 5763bdd1243dSDimitry Andric const ObjCIvarDecl *Ivar) { 5764bdd1243dSDimitry Andric llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar); 5765bdd1243dSDimitry Andric QualType PointerDiffType = getContext().getPointerDiffType(); 5766bdd1243dSDimitry Andric return Builder.CreateZExtOrTrunc(OffsetValue, 5767bdd1243dSDimitry Andric getTypes().ConvertType(PointerDiffType)); 5768bdd1243dSDimitry Andric } 5769bdd1243dSDimitry Andric 57700b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy, 57710b57cec5SDimitry Andric llvm::Value *BaseValue, 57720b57cec5SDimitry Andric const ObjCIvarDecl *Ivar, 57730b57cec5SDimitry Andric unsigned CVRQualifiers) { 57740b57cec5SDimitry Andric return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue, 57750b57cec5SDimitry Andric Ivar, CVRQualifiers); 57760b57cec5SDimitry Andric } 57770b57cec5SDimitry Andric 57780b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) { 57790b57cec5SDimitry Andric // FIXME: A lot of the code below could be shared with EmitMemberExpr. 57800b57cec5SDimitry Andric llvm::Value *BaseValue = nullptr; 57810b57cec5SDimitry Andric const Expr *BaseExpr = E->getBase(); 57820b57cec5SDimitry Andric Qualifiers BaseQuals; 57830b57cec5SDimitry Andric QualType ObjectTy; 57840b57cec5SDimitry Andric if (E->isArrow()) { 57850b57cec5SDimitry Andric BaseValue = EmitScalarExpr(BaseExpr); 57860b57cec5SDimitry Andric ObjectTy = BaseExpr->getType()->getPointeeType(); 57870b57cec5SDimitry Andric BaseQuals = ObjectTy.getQualifiers(); 57880b57cec5SDimitry Andric } else { 57890b57cec5SDimitry Andric LValue BaseLV = EmitLValue(BaseExpr); 5790480093f4SDimitry Andric BaseValue = BaseLV.getPointer(*this); 57910b57cec5SDimitry Andric ObjectTy = BaseExpr->getType(); 57920b57cec5SDimitry Andric BaseQuals = ObjectTy.getQualifiers(); 57930b57cec5SDimitry Andric } 57940b57cec5SDimitry Andric 57950b57cec5SDimitry Andric LValue LV = 57960b57cec5SDimitry Andric EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(), 57970b57cec5SDimitry Andric BaseQuals.getCVRQualifiers()); 57980b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV); 57990b57cec5SDimitry Andric return LV; 58000b57cec5SDimitry Andric } 58010b57cec5SDimitry Andric 58020b57cec5SDimitry Andric LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) { 58030b57cec5SDimitry Andric // Can only get l-value for message expression returning aggregate type 58040b57cec5SDimitry Andric RValue RV = EmitAnyExprToTemp(E); 58050b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(), 58060b57cec5SDimitry Andric AlignmentSource::Decl); 58070b57cec5SDimitry Andric } 58080b57cec5SDimitry Andric 58090b57cec5SDimitry Andric RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee, 58100b57cec5SDimitry Andric const CallExpr *E, ReturnValueSlot ReturnValue, 58110b57cec5SDimitry Andric llvm::Value *Chain) { 58120b57cec5SDimitry Andric // Get the actual function type. The callee type will always be a pointer to 58130b57cec5SDimitry Andric // function type or a block pointer type. 58140b57cec5SDimitry Andric assert(CalleeType->isFunctionPointerType() && 58150b57cec5SDimitry Andric "Call must have function pointer type!"); 58160b57cec5SDimitry Andric 58170b57cec5SDimitry Andric const Decl *TargetDecl = 58180b57cec5SDimitry Andric OrigCallee.getAbstractInfo().getCalleeDecl().getDecl(); 58190b57cec5SDimitry Andric 582006c3fb27SDimitry Andric assert((!isa_and_present<FunctionDecl>(TargetDecl) || 582106c3fb27SDimitry Andric !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) && 582206c3fb27SDimitry Andric "trying to emit a call to an immediate function"); 582306c3fb27SDimitry Andric 58240b57cec5SDimitry Andric CalleeType = getContext().getCanonicalType(CalleeType); 58250b57cec5SDimitry Andric 58260b57cec5SDimitry Andric auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType(); 58270b57cec5SDimitry Andric 58280b57cec5SDimitry Andric CGCallee Callee = OrigCallee; 58290b57cec5SDimitry Andric 583006c3fb27SDimitry Andric if (SanOpts.has(SanitizerKind::Function) && 583106c3fb27SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) && 583206c3fb27SDimitry Andric !isa<FunctionNoProtoType>(PointeeType)) { 58330b57cec5SDimitry Andric if (llvm::Constant *PrefixSig = 58340b57cec5SDimitry Andric CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 58350b57cec5SDimitry Andric SanitizerScope SanScope(this); 583606c3fb27SDimitry Andric auto *TypeHash = getUBSanFunctionTypeHash(PointeeType); 583706c3fb27SDimitry Andric 5838fe6060f1SDimitry Andric llvm::Type *PrefixSigType = PrefixSig->getType(); 58390b57cec5SDimitry Andric llvm::StructType *PrefixStructTy = llvm::StructType::get( 5840fe6060f1SDimitry Andric CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true); 58410b57cec5SDimitry Andric 58420b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer(); 58430fca6ea1SDimitry Andric if (CGM.getCodeGenOpts().PointerAuth.FunctionPointers) { 58440fca6ea1SDimitry Andric // Use raw pointer since we are using the callee pointer as data here. 58450fca6ea1SDimitry Andric Address Addr = 58460fca6ea1SDimitry Andric Address(CalleePtr, CalleePtr->getType(), 58470fca6ea1SDimitry Andric CharUnits::fromQuantity( 58480fca6ea1SDimitry Andric CalleePtr->getPointerAlignment(CGM.getDataLayout())), 58490fca6ea1SDimitry Andric Callee.getPointerAuthInfo(), nullptr); 58500fca6ea1SDimitry Andric CalleePtr = Addr.emitRawPointer(*this); 58510fca6ea1SDimitry Andric } 58520b57cec5SDimitry Andric 585306c3fb27SDimitry Andric // On 32-bit Arm, the low bit of a function pointer indicates whether 585406c3fb27SDimitry Andric // it's using the Arm or Thumb instruction set. The actual first 585506c3fb27SDimitry Andric // instruction lives at the same address either way, so we must clear 585606c3fb27SDimitry Andric // that low bit before using the function address to find the prefix 585706c3fb27SDimitry Andric // structure. 585806c3fb27SDimitry Andric // 585906c3fb27SDimitry Andric // This applies to both Arm and Thumb target triples, because 586006c3fb27SDimitry Andric // either one could be used in an interworking context where it 586106c3fb27SDimitry Andric // might be passed function pointers of both types. 586206c3fb27SDimitry Andric llvm::Value *AlignedCalleePtr; 586306c3fb27SDimitry Andric if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) { 586406c3fb27SDimitry Andric llvm::Value *CalleeAddress = 586506c3fb27SDimitry Andric Builder.CreatePtrToInt(CalleePtr, IntPtrTy); 586606c3fb27SDimitry Andric llvm::Value *Mask = llvm::ConstantInt::get(IntPtrTy, ~1); 586706c3fb27SDimitry Andric llvm::Value *AlignedCalleeAddress = 586806c3fb27SDimitry Andric Builder.CreateAnd(CalleeAddress, Mask); 586906c3fb27SDimitry Andric AlignedCalleePtr = 587006c3fb27SDimitry Andric Builder.CreateIntToPtr(AlignedCalleeAddress, CalleePtr->getType()); 587106c3fb27SDimitry Andric } else { 587206c3fb27SDimitry Andric AlignedCalleePtr = CalleePtr; 587306c3fb27SDimitry Andric } 587406c3fb27SDimitry Andric 58755f757f3fSDimitry Andric llvm::Value *CalleePrefixStruct = AlignedCalleePtr; 58760b57cec5SDimitry Andric llvm::Value *CalleeSigPtr = 587706c3fb27SDimitry Andric Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0); 58780b57cec5SDimitry Andric llvm::Value *CalleeSig = 5879fe6060f1SDimitry Andric Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign()); 58800b57cec5SDimitry Andric llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig); 58810b57cec5SDimitry Andric 58820b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont"); 58830b57cec5SDimitry Andric llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck"); 58840b57cec5SDimitry Andric Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont); 58850b57cec5SDimitry Andric 58860b57cec5SDimitry Andric EmitBlock(TypeCheck); 588706c3fb27SDimitry Andric llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad( 588806c3fb27SDimitry Andric Int32Ty, 588906c3fb27SDimitry Andric Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1), 589006c3fb27SDimitry Andric getPointerAlign()); 589106c3fb27SDimitry Andric llvm::Value *CalleeTypeHashMatch = 589206c3fb27SDimitry Andric Builder.CreateICmpEQ(CalleeTypeHash, TypeHash); 58930b57cec5SDimitry Andric llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()), 58940b57cec5SDimitry Andric EmitCheckTypeDescriptor(CalleeType)}; 589506c3fb27SDimitry Andric EmitCheck(std::make_pair(CalleeTypeHashMatch, SanitizerKind::Function), 58960b57cec5SDimitry Andric SanitizerHandler::FunctionTypeMismatch, StaticData, 589706c3fb27SDimitry Andric {CalleePtr}); 58980b57cec5SDimitry Andric 58990b57cec5SDimitry Andric Builder.CreateBr(Cont); 59000b57cec5SDimitry Andric EmitBlock(Cont); 59010b57cec5SDimitry Andric } 59020b57cec5SDimitry Andric } 59030b57cec5SDimitry Andric 59040b57cec5SDimitry Andric const auto *FnType = cast<FunctionType>(PointeeType); 59050b57cec5SDimitry Andric 59060b57cec5SDimitry Andric // If we are checking indirect calls and this call is indirect, check that the 59070b57cec5SDimitry Andric // function pointer is a member of the bit set for the function type. 59080b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIICall) && 59090b57cec5SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 59100b57cec5SDimitry Andric SanitizerScope SanScope(this); 59110b57cec5SDimitry Andric EmitSanitizerStatReport(llvm::SanStat_CFI_ICall); 59120b57cec5SDimitry Andric 59130b57cec5SDimitry Andric llvm::Metadata *MD; 59140b57cec5SDimitry Andric if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers) 59150b57cec5SDimitry Andric MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0)); 59160b57cec5SDimitry Andric else 59170b57cec5SDimitry Andric MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)); 59180b57cec5SDimitry Andric 59190b57cec5SDimitry Andric llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD); 59200b57cec5SDimitry Andric 59210b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer(); 59220b57cec5SDimitry Andric llvm::Value *TypeTest = Builder.CreateCall( 59235f757f3fSDimitry Andric CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId}); 59240b57cec5SDimitry Andric 59250b57cec5SDimitry Andric auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD); 59260b57cec5SDimitry Andric llvm::Constant *StaticData[] = { 59270b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, CFITCK_ICall), 59280b57cec5SDimitry Andric EmitCheckSourceLocation(E->getBeginLoc()), 59290b57cec5SDimitry Andric EmitCheckTypeDescriptor(QualType(FnType, 0)), 59300b57cec5SDimitry Andric }; 59310b57cec5SDimitry Andric if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) { 59320b57cec5SDimitry Andric EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId, 59335f757f3fSDimitry Andric CalleePtr, StaticData); 59340b57cec5SDimitry Andric } else { 59350b57cec5SDimitry Andric EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall), 59360b57cec5SDimitry Andric SanitizerHandler::CFICheckFail, StaticData, 59375f757f3fSDimitry Andric {CalleePtr, llvm::UndefValue::get(IntPtrTy)}); 59380b57cec5SDimitry Andric } 59390b57cec5SDimitry Andric } 59400b57cec5SDimitry Andric 59410b57cec5SDimitry Andric CallArgList Args; 59420b57cec5SDimitry Andric if (Chain) 59435f757f3fSDimitry Andric Args.add(RValue::get(Chain), CGM.getContext().VoidPtrTy); 59440b57cec5SDimitry Andric 59450b57cec5SDimitry Andric // C++17 requires that we evaluate arguments to a call using assignment syntax 59460b57cec5SDimitry Andric // right-to-left, and that we evaluate arguments to certain other operators 59470b57cec5SDimitry Andric // left-to-right. Note that we allow this to override the order dictated by 59480b57cec5SDimitry Andric // the calling convention on the MS ABI, which means that parameter 59490b57cec5SDimitry Andric // destruction order is not necessarily reverse construction order. 59500b57cec5SDimitry Andric // FIXME: Revisit this based on C++ committee response to unimplementability. 59510b57cec5SDimitry Andric EvaluationOrder Order = EvaluationOrder::Default; 5952b3edf446SDimitry Andric bool StaticOperator = false; 59530b57cec5SDimitry Andric if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 59540b57cec5SDimitry Andric if (OCE->isAssignmentOp()) 59550b57cec5SDimitry Andric Order = EvaluationOrder::ForceRightToLeft; 59560b57cec5SDimitry Andric else { 59570b57cec5SDimitry Andric switch (OCE->getOperator()) { 59580b57cec5SDimitry Andric case OO_LessLess: 59590b57cec5SDimitry Andric case OO_GreaterGreater: 59600b57cec5SDimitry Andric case OO_AmpAmp: 59610b57cec5SDimitry Andric case OO_PipePipe: 59620b57cec5SDimitry Andric case OO_Comma: 59630b57cec5SDimitry Andric case OO_ArrowStar: 59640b57cec5SDimitry Andric Order = EvaluationOrder::ForceLeftToRight; 59650b57cec5SDimitry Andric break; 59660b57cec5SDimitry Andric default: 59670b57cec5SDimitry Andric break; 59680b57cec5SDimitry Andric } 59690b57cec5SDimitry Andric } 5970b3edf446SDimitry Andric 5971b3edf446SDimitry Andric if (const auto *MD = 5972b3edf446SDimitry Andric dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl()); 5973b3edf446SDimitry Andric MD && MD->isStatic()) 5974b3edf446SDimitry Andric StaticOperator = true; 59750b57cec5SDimitry Andric } 59760b57cec5SDimitry Andric 5977b3edf446SDimitry Andric auto Arguments = E->arguments(); 5978b3edf446SDimitry Andric if (StaticOperator) { 5979b3edf446SDimitry Andric // If we're calling a static operator, we need to emit the object argument 5980b3edf446SDimitry Andric // and ignore it. 5981b3edf446SDimitry Andric EmitIgnoredExpr(E->getArg(0)); 5982b3edf446SDimitry Andric Arguments = drop_begin(Arguments, 1); 5983b3edf446SDimitry Andric } 5984b3edf446SDimitry Andric EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments, 5985b3edf446SDimitry Andric E->getDirectCallee(), /*ParamsToSkip=*/0, Order); 59860b57cec5SDimitry Andric 59870b57cec5SDimitry Andric const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall( 59880b57cec5SDimitry Andric Args, FnType, /*ChainCall=*/Chain); 59890b57cec5SDimitry Andric 59900b57cec5SDimitry Andric // C99 6.5.2.2p6: 59910b57cec5SDimitry Andric // If the expression that denotes the called function has a type 59920b57cec5SDimitry Andric // that does not include a prototype, [the default argument 59930b57cec5SDimitry Andric // promotions are performed]. If the number of arguments does not 59940b57cec5SDimitry Andric // equal the number of parameters, the behavior is undefined. If 59950b57cec5SDimitry Andric // the function is defined with a type that includes a prototype, 59960b57cec5SDimitry Andric // and either the prototype ends with an ellipsis (, ...) or the 59970b57cec5SDimitry Andric // types of the arguments after promotion are not compatible with 59980b57cec5SDimitry Andric // the types of the parameters, the behavior is undefined. If the 59990b57cec5SDimitry Andric // function is defined with a type that does not include a 60000b57cec5SDimitry Andric // prototype, and the types of the arguments after promotion are 60010b57cec5SDimitry Andric // not compatible with those of the parameters after promotion, 60020b57cec5SDimitry Andric // the behavior is undefined [except in some trivial cases]. 60030b57cec5SDimitry Andric // That is, in the general case, we should assume that a call 60040b57cec5SDimitry Andric // through an unprototyped function type works like a *non-variadic* 60050b57cec5SDimitry Andric // call. The way we make this work is to cast to the exact type 60060b57cec5SDimitry Andric // of the promoted arguments. 60070b57cec5SDimitry Andric // 60080b57cec5SDimitry Andric // Chain calls use this same code path to add the invisible chain parameter 60090b57cec5SDimitry Andric // to the function type. 60100b57cec5SDimitry Andric if (isa<FunctionNoProtoType>(FnType) || Chain) { 60110b57cec5SDimitry Andric llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo); 60125ffd83dbSDimitry Andric int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace(); 60135ffd83dbSDimitry Andric CalleeTy = CalleeTy->getPointerTo(AS); 60140b57cec5SDimitry Andric 60150b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer(); 60160b57cec5SDimitry Andric CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast"); 60170b57cec5SDimitry Andric Callee.setFunctionPointer(CalleePtr); 60180b57cec5SDimitry Andric } 60190b57cec5SDimitry Andric 6020fe6060f1SDimitry Andric // HIP function pointer contains kernel handle when it is used in triple 6021fe6060f1SDimitry Andric // chevron. The kernel stub needs to be loaded from kernel handle and used 6022fe6060f1SDimitry Andric // as callee. 6023fe6060f1SDimitry Andric if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice && 6024fe6060f1SDimitry Andric isa<CUDAKernelCallExpr>(E) && 6025fe6060f1SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) { 6026fe6060f1SDimitry Andric llvm::Value *Handle = Callee.getFunctionPointer(); 602781ad6265SDimitry Andric auto *Stub = Builder.CreateLoad( 60285f757f3fSDimitry Andric Address(Handle, Handle->getType(), CGM.getPointerAlign())); 6029fe6060f1SDimitry Andric Callee.setFunctionPointer(Stub); 6030fe6060f1SDimitry Andric } 60310b57cec5SDimitry Andric llvm::CallBase *CallOrInvoke = nullptr; 60320b57cec5SDimitry Andric RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke, 6033fe6060f1SDimitry Andric E == MustTailCall, E->getExprLoc()); 60340b57cec5SDimitry Andric 60350b57cec5SDimitry Andric // Generate function declaration DISuprogram in order to be used 60360b57cec5SDimitry Andric // in debug info about call sites. 60370b57cec5SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) { 6038349cc55cSDimitry Andric if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) { 6039349cc55cSDimitry Andric FunctionArgList Args; 6040349cc55cSDimitry Andric QualType ResTy = BuildFunctionArgList(CalleeDecl, Args); 6041349cc55cSDimitry Andric DI->EmitFuncDeclForCallSite(CallOrInvoke, 6042349cc55cSDimitry Andric DI->getFunctionType(CalleeDecl, ResTy, Args), 60430b57cec5SDimitry Andric CalleeDecl); 60440b57cec5SDimitry Andric } 6045349cc55cSDimitry Andric } 60460b57cec5SDimitry Andric 60470b57cec5SDimitry Andric return Call; 60480b57cec5SDimitry Andric } 60490b57cec5SDimitry Andric 60500b57cec5SDimitry Andric LValue CodeGenFunction:: 60510b57cec5SDimitry Andric EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) { 60520b57cec5SDimitry Andric Address BaseAddr = Address::invalid(); 60530b57cec5SDimitry Andric if (E->getOpcode() == BO_PtrMemI) { 60540b57cec5SDimitry Andric BaseAddr = EmitPointerWithAlignment(E->getLHS()); 60550b57cec5SDimitry Andric } else { 60560fca6ea1SDimitry Andric BaseAddr = EmitLValue(E->getLHS()).getAddress(); 60570b57cec5SDimitry Andric } 60580b57cec5SDimitry Andric 60590b57cec5SDimitry Andric llvm::Value *OffsetV = EmitScalarExpr(E->getRHS()); 6060480093f4SDimitry Andric const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>(); 60610b57cec5SDimitry Andric 60620b57cec5SDimitry Andric LValueBaseInfo BaseInfo; 60630b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo; 60640b57cec5SDimitry Andric Address MemberAddr = 60650b57cec5SDimitry Andric EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo, 60660b57cec5SDimitry Andric &TBAAInfo); 60670b57cec5SDimitry Andric 60680b57cec5SDimitry Andric return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo); 60690b57cec5SDimitry Andric } 60700b57cec5SDimitry Andric 60710b57cec5SDimitry Andric /// Given the address of a temporary variable, produce an r-value of 60720b57cec5SDimitry Andric /// its type. 60730b57cec5SDimitry Andric RValue CodeGenFunction::convertTempToRValue(Address addr, 60740b57cec5SDimitry Andric QualType type, 60750b57cec5SDimitry Andric SourceLocation loc) { 60760b57cec5SDimitry Andric LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl); 60770b57cec5SDimitry Andric switch (getEvaluationKind(type)) { 60780b57cec5SDimitry Andric case TEK_Complex: 60790b57cec5SDimitry Andric return RValue::getComplex(EmitLoadOfComplex(lvalue, loc)); 60800b57cec5SDimitry Andric case TEK_Aggregate: 60810fca6ea1SDimitry Andric return lvalue.asAggregateRValue(); 60820b57cec5SDimitry Andric case TEK_Scalar: 60830b57cec5SDimitry Andric return RValue::get(EmitLoadOfScalar(lvalue, loc)); 60840b57cec5SDimitry Andric } 60850b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind"); 60860b57cec5SDimitry Andric } 60870b57cec5SDimitry Andric 60880b57cec5SDimitry Andric void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) { 60890b57cec5SDimitry Andric assert(Val->getType()->isFPOrFPVectorTy()); 60900b57cec5SDimitry Andric if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val)) 60910b57cec5SDimitry Andric return; 60920b57cec5SDimitry Andric 60930b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext()); 60940b57cec5SDimitry Andric llvm::MDNode *Node = MDHelper.createFPMath(Accuracy); 60950b57cec5SDimitry Andric 60960b57cec5SDimitry Andric cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node); 60970b57cec5SDimitry Andric } 60980b57cec5SDimitry Andric 609906c3fb27SDimitry Andric void CodeGenFunction::SetSqrtFPAccuracy(llvm::Value *Val) { 610006c3fb27SDimitry Andric llvm::Type *EltTy = Val->getType()->getScalarType(); 610106c3fb27SDimitry Andric if (!EltTy->isFloatTy()) 610206c3fb27SDimitry Andric return; 610306c3fb27SDimitry Andric 610406c3fb27SDimitry Andric if ((getLangOpts().OpenCL && 610506c3fb27SDimitry Andric !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) || 610606c3fb27SDimitry Andric (getLangOpts().HIP && getLangOpts().CUDAIsDevice && 610706c3fb27SDimitry Andric !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) { 610806c3fb27SDimitry Andric // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 3ulp 610906c3fb27SDimitry Andric // 611006c3fb27SDimitry Andric // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt 611106c3fb27SDimitry Andric // build option allows an application to specify that single precision 611206c3fb27SDimitry Andric // floating-point divide (x/y and 1/x) and sqrt used in the program 611306c3fb27SDimitry Andric // source are correctly rounded. 611406c3fb27SDimitry Andric // 611506c3fb27SDimitry Andric // TODO: CUDA has a prec-sqrt flag 611606c3fb27SDimitry Andric SetFPAccuracy(Val, 3.0f); 611706c3fb27SDimitry Andric } 611806c3fb27SDimitry Andric } 611906c3fb27SDimitry Andric 612006c3fb27SDimitry Andric void CodeGenFunction::SetDivFPAccuracy(llvm::Value *Val) { 612106c3fb27SDimitry Andric llvm::Type *EltTy = Val->getType()->getScalarType(); 612206c3fb27SDimitry Andric if (!EltTy->isFloatTy()) 612306c3fb27SDimitry Andric return; 612406c3fb27SDimitry Andric 612506c3fb27SDimitry Andric if ((getLangOpts().OpenCL && 612606c3fb27SDimitry Andric !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) || 612706c3fb27SDimitry Andric (getLangOpts().HIP && getLangOpts().CUDAIsDevice && 612806c3fb27SDimitry Andric !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) { 612906c3fb27SDimitry Andric // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp 613006c3fb27SDimitry Andric // 613106c3fb27SDimitry Andric // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt 613206c3fb27SDimitry Andric // build option allows an application to specify that single precision 613306c3fb27SDimitry Andric // floating-point divide (x/y and 1/x) and sqrt used in the program 613406c3fb27SDimitry Andric // source are correctly rounded. 613506c3fb27SDimitry Andric // 613606c3fb27SDimitry Andric // TODO: CUDA has a prec-div flag 613706c3fb27SDimitry Andric SetFPAccuracy(Val, 2.5f); 613806c3fb27SDimitry Andric } 613906c3fb27SDimitry Andric } 614006c3fb27SDimitry Andric 61410b57cec5SDimitry Andric namespace { 61420b57cec5SDimitry Andric struct LValueOrRValue { 61430b57cec5SDimitry Andric LValue LV; 61440b57cec5SDimitry Andric RValue RV; 61450b57cec5SDimitry Andric }; 61460b57cec5SDimitry Andric } 61470b57cec5SDimitry Andric 61480b57cec5SDimitry Andric static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, 61490b57cec5SDimitry Andric const PseudoObjectExpr *E, 61500b57cec5SDimitry Andric bool forLValue, 61510b57cec5SDimitry Andric AggValueSlot slot) { 61520b57cec5SDimitry Andric SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques; 61530b57cec5SDimitry Andric 61540b57cec5SDimitry Andric // Find the result expression, if any. 61550b57cec5SDimitry Andric const Expr *resultExpr = E->getResultExpr(); 61560b57cec5SDimitry Andric LValueOrRValue result; 61570b57cec5SDimitry Andric 61580b57cec5SDimitry Andric for (PseudoObjectExpr::const_semantics_iterator 61590b57cec5SDimitry Andric i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) { 61600b57cec5SDimitry Andric const Expr *semantic = *i; 61610b57cec5SDimitry Andric 61620b57cec5SDimitry Andric // If this semantic expression is an opaque value, bind it 61630b57cec5SDimitry Andric // to the result of its source expression. 61640b57cec5SDimitry Andric if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) { 61650b57cec5SDimitry Andric // Skip unique OVEs. 61660b57cec5SDimitry Andric if (ov->isUnique()) { 61670b57cec5SDimitry Andric assert(ov != resultExpr && 61680b57cec5SDimitry Andric "A unique OVE cannot be used as the result expression"); 61690b57cec5SDimitry Andric continue; 61700b57cec5SDimitry Andric } 61710b57cec5SDimitry Andric 61720b57cec5SDimitry Andric // If this is the result expression, we may need to evaluate 61730b57cec5SDimitry Andric // directly into the slot. 61740b57cec5SDimitry Andric typedef CodeGenFunction::OpaqueValueMappingData OVMA; 61750b57cec5SDimitry Andric OVMA opaqueData; 6176fe6060f1SDimitry Andric if (ov == resultExpr && ov->isPRValue() && !forLValue && 61770b57cec5SDimitry Andric CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) { 61780b57cec5SDimitry Andric CGF.EmitAggExpr(ov->getSourceExpr(), slot); 61790b57cec5SDimitry Andric LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(), 61800b57cec5SDimitry Andric AlignmentSource::Decl); 61810b57cec5SDimitry Andric opaqueData = OVMA::bind(CGF, ov, LV); 61820b57cec5SDimitry Andric result.RV = slot.asRValue(); 61830b57cec5SDimitry Andric 61840b57cec5SDimitry Andric // Otherwise, emit as normal. 61850b57cec5SDimitry Andric } else { 61860b57cec5SDimitry Andric opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr()); 61870b57cec5SDimitry Andric 61880b57cec5SDimitry Andric // If this is the result, also evaluate the result now. 61890b57cec5SDimitry Andric if (ov == resultExpr) { 61900b57cec5SDimitry Andric if (forLValue) 61910b57cec5SDimitry Andric result.LV = CGF.EmitLValue(ov); 61920b57cec5SDimitry Andric else 61930b57cec5SDimitry Andric result.RV = CGF.EmitAnyExpr(ov, slot); 61940b57cec5SDimitry Andric } 61950b57cec5SDimitry Andric } 61960b57cec5SDimitry Andric 61970b57cec5SDimitry Andric opaques.push_back(opaqueData); 61980b57cec5SDimitry Andric 61990b57cec5SDimitry Andric // Otherwise, if the expression is the result, evaluate it 62000b57cec5SDimitry Andric // and remember the result. 62010b57cec5SDimitry Andric } else if (semantic == resultExpr) { 62020b57cec5SDimitry Andric if (forLValue) 62030b57cec5SDimitry Andric result.LV = CGF.EmitLValue(semantic); 62040b57cec5SDimitry Andric else 62050b57cec5SDimitry Andric result.RV = CGF.EmitAnyExpr(semantic, slot); 62060b57cec5SDimitry Andric 62070b57cec5SDimitry Andric // Otherwise, evaluate the expression in an ignored context. 62080b57cec5SDimitry Andric } else { 62090b57cec5SDimitry Andric CGF.EmitIgnoredExpr(semantic); 62100b57cec5SDimitry Andric } 62110b57cec5SDimitry Andric } 62120b57cec5SDimitry Andric 62130b57cec5SDimitry Andric // Unbind all the opaques now. 62140b57cec5SDimitry Andric for (unsigned i = 0, e = opaques.size(); i != e; ++i) 62150b57cec5SDimitry Andric opaques[i].unbind(CGF); 62160b57cec5SDimitry Andric 62170b57cec5SDimitry Andric return result; 62180b57cec5SDimitry Andric } 62190b57cec5SDimitry Andric 62200b57cec5SDimitry Andric RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E, 62210b57cec5SDimitry Andric AggValueSlot slot) { 62220b57cec5SDimitry Andric return emitPseudoObjectExpr(*this, E, false, slot).RV; 62230b57cec5SDimitry Andric } 62240b57cec5SDimitry Andric 62250b57cec5SDimitry Andric LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) { 62260b57cec5SDimitry Andric return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV; 62270b57cec5SDimitry Andric } 6228