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
13fe6060f1SDimitry Andric #include "CGCUDARuntime.h"
140b57cec5SDimitry Andric #include "CGCXXABI.h"
150b57cec5SDimitry Andric #include "CGCall.h"
160b57cec5SDimitry Andric #include "CGCleanup.h"
170b57cec5SDimitry Andric #include "CGDebugInfo.h"
180b57cec5SDimitry Andric #include "CGObjCRuntime.h"
190b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
200b57cec5SDimitry Andric #include "CGRecordLayout.h"
210b57cec5SDimitry Andric #include "CodeGenFunction.h"
220b57cec5SDimitry Andric #include "CodeGenModule.h"
230b57cec5SDimitry Andric #include "ConstantEmitter.h"
240b57cec5SDimitry Andric #include "TargetInfo.h"
250b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
260b57cec5SDimitry Andric #include "clang/AST/Attr.h"
270b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
280b57cec5SDimitry Andric #include "clang/AST/NSAPI.h"
296c20abcdSDimitry Andric #include "clang/AST/StmtVisitor.h"
300b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
310b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
325ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
330b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
346c20abcdSDimitry Andric #include "llvm/ADT/STLExtras.h"
350b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
360b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
370b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
38fe013be4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
390b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
400b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
41349cc55cSDimitry Andric #include "llvm/IR/MatrixBuilder.h"
42fe013be4SDimitry Andric #include "llvm/Passes/OptimizationLevel.h"
430b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
440b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
450b57cec5SDimitry Andric #include "llvm/Support/Path.h"
46fe6060f1SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
47fe013be4SDimitry Andric #include "llvm/Support/xxhash.h"
480b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SanitizerStats.h"
490b57cec5SDimitry Andric
50bdd1243dSDimitry Andric #include <optional>
510b57cec5SDimitry Andric #include <string>
520b57cec5SDimitry Andric
530b57cec5SDimitry Andric using namespace clang;
540b57cec5SDimitry Andric using namespace CodeGen;
550b57cec5SDimitry Andric
56c9157d92SDimitry Andric // Experiment to make sanitizers easier to debug
57c9157d92SDimitry Andric static llvm::cl::opt<bool> ClSanitizeDebugDeoptimization(
58c9157d92SDimitry Andric "ubsan-unique-traps", llvm::cl::Optional,
59c9157d92SDimitry Andric llvm::cl::desc("Deoptimize traps for UBSAN so there is 1 trap per check"),
60c9157d92SDimitry Andric llvm::cl::init(false));
61c9157d92SDimitry Andric
620b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
630b57cec5SDimitry Andric // Miscellaneous Helper Methods
640b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
650b57cec5SDimitry Andric
660b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
670b57cec5SDimitry Andric /// block.
CreateTempAllocaWithoutCast(llvm::Type * Ty,CharUnits Align,const Twine & Name,llvm::Value * ArraySize)680b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
690b57cec5SDimitry Andric CharUnits Align,
700b57cec5SDimitry Andric const Twine &Name,
710b57cec5SDimitry Andric llvm::Value *ArraySize) {
720b57cec5SDimitry Andric auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
73a7dea167SDimitry Andric Alloca->setAlignment(Align.getAsAlign());
74fe013be4SDimitry Andric return Address(Alloca, Ty, Align, KnownNonNull);
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric
770b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
780b57cec5SDimitry Andric /// block. The alloca is casted to default address space if necessary.
CreateTempAlloca(llvm::Type * Ty,CharUnits Align,const Twine & Name,llvm::Value * ArraySize,Address * AllocaAddr)790b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
800b57cec5SDimitry Andric const Twine &Name,
810b57cec5SDimitry Andric llvm::Value *ArraySize,
820b57cec5SDimitry Andric Address *AllocaAddr) {
830b57cec5SDimitry Andric auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
840b57cec5SDimitry Andric if (AllocaAddr)
850b57cec5SDimitry Andric *AllocaAddr = Alloca;
860b57cec5SDimitry Andric llvm::Value *V = Alloca.getPointer();
870b57cec5SDimitry Andric // Alloca always returns a pointer in alloca address space, which may
880b57cec5SDimitry Andric // be different from the type defined by the language. For example,
890b57cec5SDimitry Andric // in C++ the auto variables are in the default address space. Therefore
900b57cec5SDimitry Andric // cast alloca to the default address space when necessary.
910b57cec5SDimitry Andric if (getASTAllocaAddressSpace() != LangAS::Default) {
920b57cec5SDimitry Andric auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
930b57cec5SDimitry Andric llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
940b57cec5SDimitry Andric // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
950b57cec5SDimitry Andric // otherwise alloca is inserted at the current insertion point of the
960b57cec5SDimitry Andric // builder.
970b57cec5SDimitry Andric if (!ArraySize)
98349cc55cSDimitry Andric Builder.SetInsertPoint(getPostAllocaInsertPoint());
990b57cec5SDimitry Andric V = getTargetHooks().performAddrSpaceCast(
1000b57cec5SDimitry Andric *this, V, getASTAllocaAddressSpace(), LangAS::Default,
1010b57cec5SDimitry Andric Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
1020b57cec5SDimitry Andric }
1030b57cec5SDimitry Andric
104fe013be4SDimitry Andric return Address(V, Ty, Align, KnownNonNull);
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric
1070b57cec5SDimitry Andric /// CreateTempAlloca - This creates an alloca and inserts it into the entry
1080b57cec5SDimitry Andric /// block if \p ArraySize is nullptr, otherwise inserts it at the current
1090b57cec5SDimitry Andric /// insertion point of the builder.
CreateTempAlloca(llvm::Type * Ty,const Twine & Name,llvm::Value * ArraySize)1100b57cec5SDimitry Andric llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
1110b57cec5SDimitry Andric const Twine &Name,
1120b57cec5SDimitry Andric llvm::Value *ArraySize) {
1130b57cec5SDimitry Andric if (ArraySize)
1140b57cec5SDimitry Andric return Builder.CreateAlloca(Ty, ArraySize, Name);
1150b57cec5SDimitry Andric return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
1160b57cec5SDimitry Andric ArraySize, Name, AllocaInsertPt);
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric /// CreateDefaultAlignTempAlloca - This creates an alloca with the
1200b57cec5SDimitry Andric /// default alignment of the corresponding LLVM type, which is *not*
1210b57cec5SDimitry Andric /// guaranteed to be related in any way to the expected alignment of
1220b57cec5SDimitry Andric /// an AST type that might have been lowered to Ty.
CreateDefaultAlignTempAlloca(llvm::Type * Ty,const Twine & Name)1230b57cec5SDimitry Andric Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1240b57cec5SDimitry Andric const Twine &Name) {
1250b57cec5SDimitry Andric CharUnits Align =
126bdd1243dSDimitry Andric CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty));
1270b57cec5SDimitry Andric return CreateTempAlloca(Ty, Align, Name);
1280b57cec5SDimitry Andric }
1290b57cec5SDimitry Andric
CreateIRTemp(QualType Ty,const Twine & Name)1300b57cec5SDimitry Andric Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
1310b57cec5SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(Ty);
1320b57cec5SDimitry Andric return CreateTempAlloca(ConvertType(Ty), Align, Name);
1330b57cec5SDimitry Andric }
1340b57cec5SDimitry Andric
CreateMemTemp(QualType Ty,const Twine & Name,Address * Alloca)1350b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
1360b57cec5SDimitry Andric Address *Alloca) {
1370b57cec5SDimitry Andric // FIXME: Should we prefer the preferred type alignment here?
1380b57cec5SDimitry Andric return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
1390b57cec5SDimitry Andric }
1400b57cec5SDimitry Andric
CreateMemTemp(QualType Ty,CharUnits Align,const Twine & Name,Address * Alloca)1410b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
1420b57cec5SDimitry Andric const Twine &Name, Address *Alloca) {
1435ffd83dbSDimitry Andric Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
1440b57cec5SDimitry Andric /*ArraySize=*/nullptr, Alloca);
1455ffd83dbSDimitry Andric
1465ffd83dbSDimitry Andric if (Ty->isConstantMatrixType()) {
1470eae32dcSDimitry Andric auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
1485ffd83dbSDimitry Andric auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1495ffd83dbSDimitry Andric ArrayTy->getNumElements());
1505ffd83dbSDimitry Andric
151c9157d92SDimitry Andric Result = Address(Result.getPointer(), VectorTy, Result.getAlignment(),
152c9157d92SDimitry Andric KnownNonNull);
1535ffd83dbSDimitry Andric }
1545ffd83dbSDimitry Andric return Result;
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric
CreateMemTempWithoutCast(QualType Ty,CharUnits Align,const Twine & Name)1570b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
1580b57cec5SDimitry Andric const Twine &Name) {
1590b57cec5SDimitry Andric return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric
CreateMemTempWithoutCast(QualType Ty,const Twine & Name)1620b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
1630b57cec5SDimitry Andric const Twine &Name) {
1640b57cec5SDimitry Andric return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
1650b57cec5SDimitry Andric Name);
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric
1680b57cec5SDimitry Andric /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1690b57cec5SDimitry Andric /// expression and compare the result against zero, returning an Int1Ty value.
EvaluateExprAsBool(const Expr * E)1700b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
1710b57cec5SDimitry Andric PGO.setCurrentStmt(E);
1720b57cec5SDimitry Andric if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
1730b57cec5SDimitry Andric llvm::Value *MemPtr = EmitScalarExpr(E);
1740b57cec5SDimitry Andric return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
1750b57cec5SDimitry Andric }
1760b57cec5SDimitry Andric
1770b57cec5SDimitry Andric QualType BoolTy = getContext().BoolTy;
1780b57cec5SDimitry Andric SourceLocation Loc = E->getExprLoc();
179e8d8bef9SDimitry Andric CGFPOptionsRAII FPOptsRAII(*this, E);
1800b57cec5SDimitry Andric if (!E->getType()->isAnyComplexType())
1810b57cec5SDimitry Andric return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
1820b57cec5SDimitry Andric
1830b57cec5SDimitry Andric return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
1840b57cec5SDimitry Andric Loc);
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric
1870b57cec5SDimitry Andric /// EmitIgnoredExpr - Emit code to compute the specified expression,
1880b57cec5SDimitry Andric /// ignoring the result.
EmitIgnoredExpr(const Expr * E)1890b57cec5SDimitry Andric void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
190fe6060f1SDimitry Andric if (E->isPRValue())
1910b57cec5SDimitry Andric return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
1920b57cec5SDimitry Andric
19381ad6265SDimitry Andric // if this is a bitfield-resulting conditional operator, we can special case
19481ad6265SDimitry Andric // emit this. The normal 'EmitLValue' version of this is particularly
19581ad6265SDimitry Andric // difficult to codegen for, since creating a single "LValue" for two
19681ad6265SDimitry Andric // different sized arguments here is not particularly doable.
19781ad6265SDimitry Andric if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
19881ad6265SDimitry Andric E->IgnoreParenNoopCasts(getContext()))) {
19981ad6265SDimitry Andric if (CondOp->getObjectKind() == OK_BitField)
20081ad6265SDimitry Andric return EmitIgnoredConditionalOperator(CondOp);
20181ad6265SDimitry Andric }
20281ad6265SDimitry Andric
2030b57cec5SDimitry Andric // Just emit it as an l-value and drop the result.
2040b57cec5SDimitry Andric EmitLValue(E);
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric
2070b57cec5SDimitry Andric /// EmitAnyExpr - Emit code to compute the specified expression which
2080b57cec5SDimitry Andric /// can have any type. The result is returned as an RValue struct.
2090b57cec5SDimitry Andric /// If this is an aggregate expression, AggSlot indicates where the
2100b57cec5SDimitry Andric /// result should be returned.
EmitAnyExpr(const Expr * E,AggValueSlot aggSlot,bool ignoreResult)2110b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
2120b57cec5SDimitry Andric AggValueSlot aggSlot,
2130b57cec5SDimitry Andric bool ignoreResult) {
2140b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) {
2150b57cec5SDimitry Andric case TEK_Scalar:
2160b57cec5SDimitry Andric return RValue::get(EmitScalarExpr(E, ignoreResult));
2170b57cec5SDimitry Andric case TEK_Complex:
2180b57cec5SDimitry Andric return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
2190b57cec5SDimitry Andric case TEK_Aggregate:
2200b57cec5SDimitry Andric if (!ignoreResult && aggSlot.isIgnored())
2210b57cec5SDimitry Andric aggSlot = CreateAggTemp(E->getType(), "agg-temp");
2220b57cec5SDimitry Andric EmitAggExpr(E, aggSlot);
2230b57cec5SDimitry Andric return aggSlot.asRValue();
2240b57cec5SDimitry Andric }
2250b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric
2280b57cec5SDimitry Andric /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
2290b57cec5SDimitry Andric /// always be accessible even if no aggregate location is provided.
EmitAnyExprToTemp(const Expr * E)2300b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
2310b57cec5SDimitry Andric AggValueSlot AggSlot = AggValueSlot::ignored();
2320b57cec5SDimitry Andric
2330b57cec5SDimitry Andric if (hasAggregateEvaluationKind(E->getType()))
2340b57cec5SDimitry Andric AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
2350b57cec5SDimitry Andric return EmitAnyExpr(E, AggSlot);
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric
2380b57cec5SDimitry Andric /// EmitAnyExprToMem - Evaluate an expression into a given memory
2390b57cec5SDimitry Andric /// location.
EmitAnyExprToMem(const Expr * E,Address Location,Qualifiers Quals,bool IsInit)2400b57cec5SDimitry Andric void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
2410b57cec5SDimitry Andric Address Location,
2420b57cec5SDimitry Andric Qualifiers Quals,
2430b57cec5SDimitry Andric bool IsInit) {
2440b57cec5SDimitry Andric // FIXME: This function should take an LValue as an argument.
2450b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) {
2460b57cec5SDimitry Andric case TEK_Complex:
2470b57cec5SDimitry Andric EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
2480b57cec5SDimitry Andric /*isInit*/ false);
2490b57cec5SDimitry Andric return;
2500b57cec5SDimitry Andric
2510b57cec5SDimitry Andric case TEK_Aggregate: {
2520b57cec5SDimitry Andric EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
2530b57cec5SDimitry Andric AggValueSlot::IsDestructed_t(IsInit),
2540b57cec5SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
2550b57cec5SDimitry Andric AggValueSlot::IsAliased_t(!IsInit),
2560b57cec5SDimitry Andric AggValueSlot::MayOverlap));
2570b57cec5SDimitry Andric return;
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric
2600b57cec5SDimitry Andric case TEK_Scalar: {
2610b57cec5SDimitry Andric RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
2620b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Location, E->getType());
2630b57cec5SDimitry Andric EmitStoreThroughLValue(RV, LV);
2640b57cec5SDimitry Andric return;
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
2680b57cec5SDimitry Andric }
2690b57cec5SDimitry Andric
2700b57cec5SDimitry Andric static void
pushTemporaryCleanup(CodeGenFunction & CGF,const MaterializeTemporaryExpr * M,const Expr * E,Address ReferenceTemporary)2710b57cec5SDimitry Andric pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
2720b57cec5SDimitry Andric const Expr *E, Address ReferenceTemporary) {
2730b57cec5SDimitry Andric // Objective-C++ ARC:
2740b57cec5SDimitry Andric // If we are binding a reference to a temporary that has ownership, we
2750b57cec5SDimitry Andric // need to perform retain/release operations on the temporary.
2760b57cec5SDimitry Andric //
2770b57cec5SDimitry Andric // FIXME: This should be looking at E, not M.
2780b57cec5SDimitry Andric if (auto Lifetime = M->getType().getObjCLifetime()) {
2790b57cec5SDimitry Andric switch (Lifetime) {
2800b57cec5SDimitry Andric case Qualifiers::OCL_None:
2810b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone:
2820b57cec5SDimitry Andric // Carry on to normal cleanup handling.
2830b57cec5SDimitry Andric break;
2840b57cec5SDimitry Andric
2850b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing:
2860b57cec5SDimitry Andric // Nothing to do; cleaned up by an autorelease pool.
2870b57cec5SDimitry Andric return;
2880b57cec5SDimitry Andric
2890b57cec5SDimitry Andric case Qualifiers::OCL_Strong:
2900b57cec5SDimitry Andric case Qualifiers::OCL_Weak:
2910b57cec5SDimitry Andric switch (StorageDuration Duration = M->getStorageDuration()) {
2920b57cec5SDimitry Andric case SD_Static:
2930b57cec5SDimitry Andric // Note: we intentionally do not register a cleanup to release
2940b57cec5SDimitry Andric // the object on program termination.
2950b57cec5SDimitry Andric return;
2960b57cec5SDimitry Andric
2970b57cec5SDimitry Andric case SD_Thread:
2980b57cec5SDimitry Andric // FIXME: We should probably register a cleanup in this case.
2990b57cec5SDimitry Andric return;
3000b57cec5SDimitry Andric
3010b57cec5SDimitry Andric case SD_Automatic:
3020b57cec5SDimitry Andric case SD_FullExpression:
3030b57cec5SDimitry Andric CodeGenFunction::Destroyer *Destroy;
3040b57cec5SDimitry Andric CleanupKind CleanupKind;
3050b57cec5SDimitry Andric if (Lifetime == Qualifiers::OCL_Strong) {
3060b57cec5SDimitry Andric const ValueDecl *VD = M->getExtendingDecl();
3070b57cec5SDimitry Andric bool Precise =
3080b57cec5SDimitry Andric VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
3090b57cec5SDimitry Andric CleanupKind = CGF.getARCCleanupKind();
3100b57cec5SDimitry Andric Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
3110b57cec5SDimitry Andric : &CodeGenFunction::destroyARCStrongImprecise;
3120b57cec5SDimitry Andric } else {
3130b57cec5SDimitry Andric // __weak objects always get EH cleanups; otherwise, exceptions
3140b57cec5SDimitry Andric // could cause really nasty crashes instead of mere leaks.
3150b57cec5SDimitry Andric CleanupKind = NormalAndEHCleanup;
3160b57cec5SDimitry Andric Destroy = &CodeGenFunction::destroyARCWeak;
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric if (Duration == SD_FullExpression)
3190b57cec5SDimitry Andric CGF.pushDestroy(CleanupKind, ReferenceTemporary,
3200b57cec5SDimitry Andric M->getType(), *Destroy,
3210b57cec5SDimitry Andric CleanupKind & EHCleanup);
3220b57cec5SDimitry Andric else
3230b57cec5SDimitry Andric CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
3240b57cec5SDimitry Andric M->getType(),
3250b57cec5SDimitry Andric *Destroy, CleanupKind & EHCleanup);
3260b57cec5SDimitry Andric return;
3270b57cec5SDimitry Andric
3280b57cec5SDimitry Andric case SD_Dynamic:
3290b57cec5SDimitry Andric llvm_unreachable("temporary cannot have dynamic storage duration");
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric llvm_unreachable("unknown storage duration");
3320b57cec5SDimitry Andric }
3330b57cec5SDimitry Andric }
3340b57cec5SDimitry Andric
3350b57cec5SDimitry Andric CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
3360b57cec5SDimitry Andric if (const RecordType *RT =
3370b57cec5SDimitry Andric E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
3380b57cec5SDimitry Andric // Get the destructor for the reference temporary.
3390b57cec5SDimitry Andric auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3400b57cec5SDimitry Andric if (!ClassDecl->hasTrivialDestructor())
3410b57cec5SDimitry Andric ReferenceTemporaryDtor = ClassDecl->getDestructor();
3420b57cec5SDimitry Andric }
3430b57cec5SDimitry Andric
3440b57cec5SDimitry Andric if (!ReferenceTemporaryDtor)
3450b57cec5SDimitry Andric return;
3460b57cec5SDimitry Andric
3470b57cec5SDimitry Andric // Call the destructor for the temporary.
3480b57cec5SDimitry Andric switch (M->getStorageDuration()) {
3490b57cec5SDimitry Andric case SD_Static:
3500b57cec5SDimitry Andric case SD_Thread: {
3510b57cec5SDimitry Andric llvm::FunctionCallee CleanupFn;
3520b57cec5SDimitry Andric llvm::Constant *CleanupArg;
3530b57cec5SDimitry Andric if (E->getType()->isArrayType()) {
3540b57cec5SDimitry Andric CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
3550b57cec5SDimitry Andric ReferenceTemporary, E->getType(),
3560b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
3570b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
3580b57cec5SDimitry Andric CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
3590b57cec5SDimitry Andric } else {
3600b57cec5SDimitry Andric CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
3610b57cec5SDimitry Andric GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
3620b57cec5SDimitry Andric CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
3630b57cec5SDimitry Andric }
3640b57cec5SDimitry Andric CGF.CGM.getCXXABI().registerGlobalDtor(
3650b57cec5SDimitry Andric CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
3660b57cec5SDimitry Andric break;
3670b57cec5SDimitry Andric }
3680b57cec5SDimitry Andric
3690b57cec5SDimitry Andric case SD_FullExpression:
3700b57cec5SDimitry Andric CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
3710b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject,
3720b57cec5SDimitry Andric CGF.getLangOpts().Exceptions);
3730b57cec5SDimitry Andric break;
3740b57cec5SDimitry Andric
3750b57cec5SDimitry Andric case SD_Automatic:
3760b57cec5SDimitry Andric CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
3770b57cec5SDimitry Andric ReferenceTemporary, E->getType(),
3780b57cec5SDimitry Andric CodeGenFunction::destroyCXXObject,
3790b57cec5SDimitry Andric CGF.getLangOpts().Exceptions);
3800b57cec5SDimitry Andric break;
3810b57cec5SDimitry Andric
3820b57cec5SDimitry Andric case SD_Dynamic:
3830b57cec5SDimitry Andric llvm_unreachable("temporary cannot have dynamic storage duration");
3840b57cec5SDimitry Andric }
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric
createReferenceTemporary(CodeGenFunction & CGF,const MaterializeTemporaryExpr * M,const Expr * Inner,Address * Alloca=nullptr)3870b57cec5SDimitry Andric static Address createReferenceTemporary(CodeGenFunction &CGF,
3880b57cec5SDimitry Andric const MaterializeTemporaryExpr *M,
3890b57cec5SDimitry Andric const Expr *Inner,
3900b57cec5SDimitry Andric Address *Alloca = nullptr) {
3910b57cec5SDimitry Andric auto &TCG = CGF.getTargetHooks();
3920b57cec5SDimitry Andric switch (M->getStorageDuration()) {
3930b57cec5SDimitry Andric case SD_FullExpression:
3940b57cec5SDimitry Andric case SD_Automatic: {
3950b57cec5SDimitry Andric // If we have a constant temporary array or record try to promote it into a
3960b57cec5SDimitry Andric // constant global under the same rules a normal constant would've been
3970b57cec5SDimitry Andric // promoted. This is easier on the optimizer and generally emits fewer
3980b57cec5SDimitry Andric // instructions.
3990b57cec5SDimitry Andric QualType Ty = Inner->getType();
4000b57cec5SDimitry Andric if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
4010b57cec5SDimitry Andric (Ty->isArrayType() || Ty->isRecordType()) &&
402c9157d92SDimitry Andric Ty.isConstantStorage(CGF.getContext(), true, false))
4030b57cec5SDimitry Andric if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
404fe6060f1SDimitry Andric auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
4050b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable(
4060b57cec5SDimitry Andric CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
4070b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
4080b57cec5SDimitry Andric llvm::GlobalValue::NotThreadLocal,
4090b57cec5SDimitry Andric CGF.getContext().getTargetAddressSpace(AS));
4100b57cec5SDimitry Andric CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
411a7dea167SDimitry Andric GV->setAlignment(alignment.getAsAlign());
4120b57cec5SDimitry Andric llvm::Constant *C = GV;
4130b57cec5SDimitry Andric if (AS != LangAS::Default)
4140b57cec5SDimitry Andric C = TCG.performAddrSpaceCast(
4150b57cec5SDimitry Andric CGF.CGM, GV, AS, LangAS::Default,
4160b57cec5SDimitry Andric GV->getValueType()->getPointerTo(
4170b57cec5SDimitry Andric CGF.getContext().getTargetAddressSpace(LangAS::Default)));
4180b57cec5SDimitry Andric // FIXME: Should we put the new global into a COMDAT?
41981ad6265SDimitry Andric return Address(C, GV->getValueType(), alignment);
4200b57cec5SDimitry Andric }
4210b57cec5SDimitry Andric return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
4220b57cec5SDimitry Andric }
4230b57cec5SDimitry Andric case SD_Thread:
4240b57cec5SDimitry Andric case SD_Static:
4250b57cec5SDimitry Andric return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
4260b57cec5SDimitry Andric
4270b57cec5SDimitry Andric case SD_Dynamic:
4280b57cec5SDimitry Andric llvm_unreachable("temporary can't have dynamic storage duration");
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric llvm_unreachable("unknown storage duration");
4310b57cec5SDimitry Andric }
4320b57cec5SDimitry Andric
4335ffd83dbSDimitry Andric /// Helper method to check if the underlying ABI is AAPCS
isAAPCS(const TargetInfo & TargetInfo)4345ffd83dbSDimitry Andric static bool isAAPCS(const TargetInfo &TargetInfo) {
435c9157d92SDimitry Andric return TargetInfo.getABI().starts_with("aapcs");
4365ffd83dbSDimitry Andric }
4375ffd83dbSDimitry Andric
4380b57cec5SDimitry Andric LValue CodeGenFunction::
EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * M)4390b57cec5SDimitry Andric EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
440480093f4SDimitry Andric const Expr *E = M->getSubExpr();
4410b57cec5SDimitry Andric
4420b57cec5SDimitry Andric assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
4430b57cec5SDimitry Andric !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
4440b57cec5SDimitry Andric "Reference should never be pseudo-strong!");
4450b57cec5SDimitry Andric
4460b57cec5SDimitry Andric // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
4470b57cec5SDimitry Andric // as that will cause the lifetime adjustment to be lost for ARC
4480b57cec5SDimitry Andric auto ownership = M->getType().getObjCLifetime();
4490b57cec5SDimitry Andric if (ownership != Qualifiers::OCL_None &&
4500b57cec5SDimitry Andric ownership != Qualifiers::OCL_ExplicitNone) {
4510b57cec5SDimitry Andric Address Object = createReferenceTemporary(*this, M, E);
4520b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
45381ad6265SDimitry Andric llvm::Type *Ty = ConvertTypeForMem(E->getType());
454c9157d92SDimitry Andric Object = Object.withElementType(Ty);
4550b57cec5SDimitry Andric
4560b57cec5SDimitry Andric // createReferenceTemporary will promote the temporary to a global with a
4570b57cec5SDimitry Andric // constant initializer if it can. It can only do this to a value of
4580b57cec5SDimitry Andric // ARC-manageable type if the value is global and therefore "immune" to
4590b57cec5SDimitry Andric // ref-counting operations. Therefore we have no need to emit either a
4600b57cec5SDimitry Andric // dynamic initialization or a cleanup and we can just return the address
4610b57cec5SDimitry Andric // of the temporary.
4620b57cec5SDimitry Andric if (Var->hasInitializer())
4630b57cec5SDimitry Andric return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
4640b57cec5SDimitry Andric
4650b57cec5SDimitry Andric Var->setInitializer(CGM.EmitNullConstant(E->getType()));
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
4680b57cec5SDimitry Andric AlignmentSource::Decl);
4690b57cec5SDimitry Andric
4700b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) {
4710b57cec5SDimitry Andric default: llvm_unreachable("expected scalar or aggregate expression");
4720b57cec5SDimitry Andric case TEK_Scalar:
4730b57cec5SDimitry Andric EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
4740b57cec5SDimitry Andric break;
4750b57cec5SDimitry Andric case TEK_Aggregate: {
4760b57cec5SDimitry Andric EmitAggExpr(E, AggValueSlot::forAddr(Object,
4770b57cec5SDimitry Andric E->getType().getQualifiers(),
4780b57cec5SDimitry Andric AggValueSlot::IsDestructed,
4790b57cec5SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
4800b57cec5SDimitry Andric AggValueSlot::IsNotAliased,
4810b57cec5SDimitry Andric AggValueSlot::DoesNotOverlap));
4820b57cec5SDimitry Andric break;
4830b57cec5SDimitry Andric }
4840b57cec5SDimitry Andric }
4850b57cec5SDimitry Andric
4860b57cec5SDimitry Andric pushTemporaryCleanup(*this, M, E, Object);
4870b57cec5SDimitry Andric return RefTempDst;
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric
4900b57cec5SDimitry Andric SmallVector<const Expr *, 2> CommaLHSs;
4910b57cec5SDimitry Andric SmallVector<SubobjectAdjustment, 2> Adjustments;
4920b57cec5SDimitry Andric E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4930b57cec5SDimitry Andric
4940b57cec5SDimitry Andric for (const auto &Ignored : CommaLHSs)
4950b57cec5SDimitry Andric EmitIgnoredExpr(Ignored);
4960b57cec5SDimitry Andric
4970b57cec5SDimitry Andric if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
4980b57cec5SDimitry Andric if (opaque->getType()->isRecordType()) {
4990b57cec5SDimitry Andric assert(Adjustments.empty());
5000b57cec5SDimitry Andric return EmitOpaqueValueLValue(opaque);
5010b57cec5SDimitry Andric }
5020b57cec5SDimitry Andric }
5030b57cec5SDimitry Andric
5040b57cec5SDimitry Andric // Create and initialize the reference temporary.
5050b57cec5SDimitry Andric Address Alloca = Address::invalid();
5060b57cec5SDimitry Andric Address Object = createReferenceTemporary(*this, M, E, &Alloca);
5070b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(
5080b57cec5SDimitry Andric Object.getPointer()->stripPointerCasts())) {
50981ad6265SDimitry Andric llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
510c9157d92SDimitry Andric Object = Object.withElementType(TemporaryType);
5110b57cec5SDimitry Andric // If the temporary is a global and has a constant initializer or is a
5120b57cec5SDimitry Andric // constant temporary that we promoted to a global, we may have already
5130b57cec5SDimitry Andric // initialized it.
5140b57cec5SDimitry Andric if (!Var->hasInitializer()) {
5150b57cec5SDimitry Andric Var->setInitializer(CGM.EmitNullConstant(E->getType()));
5160b57cec5SDimitry Andric EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric } else {
5190b57cec5SDimitry Andric switch (M->getStorageDuration()) {
5200b57cec5SDimitry Andric case SD_Automatic:
5210b57cec5SDimitry Andric if (auto *Size = EmitLifetimeStart(
5220b57cec5SDimitry Andric CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
5230b57cec5SDimitry Andric Alloca.getPointer())) {
5240b57cec5SDimitry Andric pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
5250b57cec5SDimitry Andric Alloca, Size);
5260b57cec5SDimitry Andric }
5270b57cec5SDimitry Andric break;
5280b57cec5SDimitry Andric
5290b57cec5SDimitry Andric case SD_FullExpression: {
5300b57cec5SDimitry Andric if (!ShouldEmitLifetimeMarkers)
5310b57cec5SDimitry Andric break;
5320b57cec5SDimitry Andric
5330b57cec5SDimitry Andric // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
5340b57cec5SDimitry Andric // marker. Instead, start the lifetime of a conditional temporary earlier
535a7dea167SDimitry Andric // so that it's unconditional. Don't do this with sanitizers which need
536fe013be4SDimitry Andric // more precise lifetime marks. However when inside an "await.suspend"
537fe013be4SDimitry Andric // block, we should always avoid conditional cleanup because it creates
538fe013be4SDimitry Andric // boolean marker that lives across await_suspend, which can destroy coro
539fe013be4SDimitry Andric // frame.
5400b57cec5SDimitry Andric ConditionalEvaluation *OldConditional = nullptr;
5410b57cec5SDimitry Andric CGBuilderTy::InsertPoint OldIP;
5420b57cec5SDimitry Andric if (isInConditionalBranch() && !E->getType().isDestructedType() &&
543fe013be4SDimitry Andric ((!SanOpts.has(SanitizerKind::HWAddress) &&
544a7dea167SDimitry Andric !SanOpts.has(SanitizerKind::Memory) &&
545fe013be4SDimitry Andric !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
546fe013be4SDimitry Andric inSuspendBlock())) {
5470b57cec5SDimitry Andric OldConditional = OutermostConditional;
5480b57cec5SDimitry Andric OutermostConditional = nullptr;
5490b57cec5SDimitry Andric
5500b57cec5SDimitry Andric OldIP = Builder.saveIP();
5510b57cec5SDimitry Andric llvm::BasicBlock *Block = OldConditional->getStartingBlock();
5520b57cec5SDimitry Andric Builder.restoreIP(CGBuilderTy::InsertPoint(
5530b57cec5SDimitry Andric Block, llvm::BasicBlock::iterator(Block->back())));
5540b57cec5SDimitry Andric }
5550b57cec5SDimitry Andric
5560b57cec5SDimitry Andric if (auto *Size = EmitLifetimeStart(
5570b57cec5SDimitry Andric CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
5580b57cec5SDimitry Andric Alloca.getPointer())) {
5590b57cec5SDimitry Andric pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
5600b57cec5SDimitry Andric Size);
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric
5630b57cec5SDimitry Andric if (OldConditional) {
5640b57cec5SDimitry Andric OutermostConditional = OldConditional;
5650b57cec5SDimitry Andric Builder.restoreIP(OldIP);
5660b57cec5SDimitry Andric }
5670b57cec5SDimitry Andric break;
5680b57cec5SDimitry Andric }
5690b57cec5SDimitry Andric
5700b57cec5SDimitry Andric default:
5710b57cec5SDimitry Andric break;
5720b57cec5SDimitry Andric }
5730b57cec5SDimitry Andric EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
5740b57cec5SDimitry Andric }
5750b57cec5SDimitry Andric pushTemporaryCleanup(*this, M, E, Object);
5760b57cec5SDimitry Andric
5770b57cec5SDimitry Andric // Perform derived-to-base casts and/or field accesses, to get from the
5780b57cec5SDimitry Andric // temporary object we created (and, potentially, for which we extended
5790b57cec5SDimitry Andric // the lifetime) to the subobject we're binding the reference to.
580349cc55cSDimitry Andric for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
5810b57cec5SDimitry Andric switch (Adjustment.Kind) {
5820b57cec5SDimitry Andric case SubobjectAdjustment::DerivedToBaseAdjustment:
5830b57cec5SDimitry Andric Object =
5840b57cec5SDimitry Andric GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
5850b57cec5SDimitry Andric Adjustment.DerivedToBase.BasePath->path_begin(),
5860b57cec5SDimitry Andric Adjustment.DerivedToBase.BasePath->path_end(),
5870b57cec5SDimitry Andric /*NullCheckValue=*/ false, E->getExprLoc());
5880b57cec5SDimitry Andric break;
5890b57cec5SDimitry Andric
5900b57cec5SDimitry Andric case SubobjectAdjustment::FieldAdjustment: {
5910b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
5920b57cec5SDimitry Andric LV = EmitLValueForField(LV, Adjustment.Field);
5930b57cec5SDimitry Andric assert(LV.isSimple() &&
5940b57cec5SDimitry Andric "materialized temporary field is not a simple lvalue");
595480093f4SDimitry Andric Object = LV.getAddress(*this);
5960b57cec5SDimitry Andric break;
5970b57cec5SDimitry Andric }
5980b57cec5SDimitry Andric
5990b57cec5SDimitry Andric case SubobjectAdjustment::MemberPointerAdjustment: {
6000b57cec5SDimitry Andric llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
6010b57cec5SDimitry Andric Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
6020b57cec5SDimitry Andric Adjustment.Ptr.MPT);
6030b57cec5SDimitry Andric break;
6040b57cec5SDimitry Andric }
6050b57cec5SDimitry Andric }
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric
6080b57cec5SDimitry Andric return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
6090b57cec5SDimitry Andric }
6100b57cec5SDimitry Andric
6110b57cec5SDimitry Andric RValue
EmitReferenceBindingToExpr(const Expr * E)6120b57cec5SDimitry Andric CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
6130b57cec5SDimitry Andric // Emit the expression as an lvalue.
6140b57cec5SDimitry Andric LValue LV = EmitLValue(E);
6150b57cec5SDimitry Andric assert(LV.isSimple());
616480093f4SDimitry Andric llvm::Value *Value = LV.getPointer(*this);
6170b57cec5SDimitry Andric
6180b57cec5SDimitry Andric if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
6190b57cec5SDimitry Andric // C++11 [dcl.ref]p5 (as amended by core issue 453):
6200b57cec5SDimitry Andric // If a glvalue to which a reference is directly bound designates neither
6210b57cec5SDimitry Andric // an existing object or function of an appropriate type nor a region of
6220b57cec5SDimitry Andric // storage of suitable size and alignment to contain an object of the
6230b57cec5SDimitry Andric // reference's type, the behavior is undefined.
6240b57cec5SDimitry Andric QualType Ty = E->getType();
6250b57cec5SDimitry Andric EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
6260b57cec5SDimitry Andric }
6270b57cec5SDimitry Andric
6280b57cec5SDimitry Andric return RValue::get(Value);
6290b57cec5SDimitry Andric }
6300b57cec5SDimitry Andric
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric /// getAccessedFieldNo - Given an encoded value and a result number, return the
6330b57cec5SDimitry Andric /// input field number being accessed.
getAccessedFieldNo(unsigned Idx,const llvm::Constant * Elts)6340b57cec5SDimitry Andric unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
6350b57cec5SDimitry Andric const llvm::Constant *Elts) {
6360b57cec5SDimitry Andric return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
6370b57cec5SDimitry Andric ->getZExtValue();
6380b57cec5SDimitry Andric }
6390b57cec5SDimitry Andric
6400b57cec5SDimitry Andric /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
emitHash16Bytes(CGBuilderTy & Builder,llvm::Value * Low,llvm::Value * High)6410b57cec5SDimitry Andric static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
6420b57cec5SDimitry Andric llvm::Value *High) {
6430b57cec5SDimitry Andric llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
6440b57cec5SDimitry Andric llvm::Value *K47 = Builder.getInt64(47);
6450b57cec5SDimitry Andric llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
6460b57cec5SDimitry Andric llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
6470b57cec5SDimitry Andric llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
6480b57cec5SDimitry Andric llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
6490b57cec5SDimitry Andric return Builder.CreateMul(B1, KMul);
6500b57cec5SDimitry Andric }
6510b57cec5SDimitry Andric
isNullPointerAllowed(TypeCheckKind TCK)6520b57cec5SDimitry Andric bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
6530b57cec5SDimitry Andric return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
6540b57cec5SDimitry Andric TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
6550b57cec5SDimitry Andric }
6560b57cec5SDimitry Andric
isVptrCheckRequired(TypeCheckKind TCK,QualType Ty)6570b57cec5SDimitry Andric bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
6580b57cec5SDimitry Andric CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6590b57cec5SDimitry Andric return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
6600b57cec5SDimitry Andric (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
6610b57cec5SDimitry Andric TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
6620b57cec5SDimitry Andric TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric
sanitizePerformTypeCheck() const6650b57cec5SDimitry Andric bool CodeGenFunction::sanitizePerformTypeCheck() const {
666349cc55cSDimitry Andric return SanOpts.has(SanitizerKind::Null) ||
667349cc55cSDimitry Andric SanOpts.has(SanitizerKind::Alignment) ||
668349cc55cSDimitry Andric SanOpts.has(SanitizerKind::ObjectSize) ||
6690b57cec5SDimitry Andric SanOpts.has(SanitizerKind::Vptr);
6700b57cec5SDimitry Andric }
6710b57cec5SDimitry Andric
EmitTypeCheck(TypeCheckKind TCK,SourceLocation Loc,llvm::Value * Ptr,QualType Ty,CharUnits Alignment,SanitizerSet SkippedChecks,llvm::Value * ArraySize)6720b57cec5SDimitry Andric void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
6730b57cec5SDimitry Andric llvm::Value *Ptr, QualType Ty,
6740b57cec5SDimitry Andric CharUnits Alignment,
6750b57cec5SDimitry Andric SanitizerSet SkippedChecks,
6760b57cec5SDimitry Andric llvm::Value *ArraySize) {
6770b57cec5SDimitry Andric if (!sanitizePerformTypeCheck())
6780b57cec5SDimitry Andric return;
6790b57cec5SDimitry Andric
6800b57cec5SDimitry Andric // Don't check pointers outside the default address space. The null check
6810b57cec5SDimitry Andric // isn't correct, the object-size check isn't supported by LLVM, and we can't
6820b57cec5SDimitry Andric // communicate the addresses to the runtime handler for the vptr check.
6830b57cec5SDimitry Andric if (Ptr->getType()->getPointerAddressSpace())
6840b57cec5SDimitry Andric return;
6850b57cec5SDimitry Andric
6860b57cec5SDimitry Andric // Don't check pointers to volatile data. The behavior here is implementation-
6870b57cec5SDimitry Andric // defined.
6880b57cec5SDimitry Andric if (Ty.isVolatileQualified())
6890b57cec5SDimitry Andric return;
6900b57cec5SDimitry Andric
6910b57cec5SDimitry Andric SanitizerScope SanScope(this);
6920b57cec5SDimitry Andric
6930b57cec5SDimitry Andric SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
6940b57cec5SDimitry Andric llvm::BasicBlock *Done = nullptr;
6950b57cec5SDimitry Andric
6960b57cec5SDimitry Andric // Quickly determine whether we have a pointer to an alloca. It's possible
6970b57cec5SDimitry Andric // to skip null checks, and some alignment checks, for these pointers. This
6980b57cec5SDimitry Andric // can reduce compile-time significantly.
699a7dea167SDimitry Andric auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
7000b57cec5SDimitry Andric
7010b57cec5SDimitry Andric llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
7020b57cec5SDimitry Andric llvm::Value *IsNonNull = nullptr;
7030b57cec5SDimitry Andric bool IsGuaranteedNonNull =
7040b57cec5SDimitry Andric SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
7050b57cec5SDimitry Andric bool AllowNullPointers = isNullPointerAllowed(TCK);
7060b57cec5SDimitry Andric if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
7070b57cec5SDimitry Andric !IsGuaranteedNonNull) {
7080b57cec5SDimitry Andric // The glvalue must not be an empty glvalue.
7090b57cec5SDimitry Andric IsNonNull = Builder.CreateIsNotNull(Ptr);
7100b57cec5SDimitry Andric
7110b57cec5SDimitry Andric // The IR builder can constant-fold the null check if the pointer points to
7120b57cec5SDimitry Andric // a constant.
7130b57cec5SDimitry Andric IsGuaranteedNonNull = IsNonNull == True;
7140b57cec5SDimitry Andric
7150b57cec5SDimitry Andric // Skip the null check if the pointer is known to be non-null.
7160b57cec5SDimitry Andric if (!IsGuaranteedNonNull) {
7170b57cec5SDimitry Andric if (AllowNullPointers) {
7180b57cec5SDimitry Andric // When performing pointer casts, it's OK if the value is null.
7190b57cec5SDimitry Andric // Skip the remaining checks in that case.
7200b57cec5SDimitry Andric Done = createBasicBlock("null");
7210b57cec5SDimitry Andric llvm::BasicBlock *Rest = createBasicBlock("not.null");
7220b57cec5SDimitry Andric Builder.CreateCondBr(IsNonNull, Rest, Done);
7230b57cec5SDimitry Andric EmitBlock(Rest);
7240b57cec5SDimitry Andric } else {
7250b57cec5SDimitry Andric Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
7260b57cec5SDimitry Andric }
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric }
7290b57cec5SDimitry Andric
7300b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ObjectSize) &&
7310b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::ObjectSize) &&
7320b57cec5SDimitry Andric !Ty->isIncompleteType()) {
7335ffd83dbSDimitry Andric uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
7340b57cec5SDimitry Andric llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
7350b57cec5SDimitry Andric if (ArraySize)
7360b57cec5SDimitry Andric Size = Builder.CreateMul(Size, ArraySize);
7370b57cec5SDimitry Andric
7380b57cec5SDimitry Andric // Degenerate case: new X[0] does not need an objectsize check.
7390b57cec5SDimitry Andric llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
7400b57cec5SDimitry Andric if (!ConstantSize || !ConstantSize->isNullValue()) {
7410b57cec5SDimitry Andric // The glvalue must refer to a large enough storage region.
7420b57cec5SDimitry Andric // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
7430b57cec5SDimitry Andric // to check this.
7440b57cec5SDimitry Andric // FIXME: Get object address space
7450b57cec5SDimitry Andric llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
7460b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
7470b57cec5SDimitry Andric llvm::Value *Min = Builder.getFalse();
7480b57cec5SDimitry Andric llvm::Value *NullIsUnknown = Builder.getFalse();
7490b57cec5SDimitry Andric llvm::Value *Dynamic = Builder.getFalse();
7500b57cec5SDimitry Andric llvm::Value *LargeEnough = Builder.CreateICmpUGE(
751c9157d92SDimitry Andric Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size);
7520b57cec5SDimitry Andric Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
7530b57cec5SDimitry Andric }
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric
75681ad6265SDimitry Andric llvm::MaybeAlign AlignVal;
7570b57cec5SDimitry Andric llvm::Value *PtrAsInt = nullptr;
7580b57cec5SDimitry Andric
7590b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Alignment) &&
7600b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::Alignment)) {
76181ad6265SDimitry Andric AlignVal = Alignment.getAsMaybeAlign();
7620b57cec5SDimitry Andric if (!Ty->isIncompleteType() && !AlignVal)
7635ffd83dbSDimitry Andric AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
7645ffd83dbSDimitry Andric /*ForPointeeType=*/true)
76581ad6265SDimitry Andric .getAsMaybeAlign();
7660b57cec5SDimitry Andric
7670b57cec5SDimitry Andric // The glvalue must be suitably aligned.
76881ad6265SDimitry Andric if (AlignVal && *AlignVal > llvm::Align(1) &&
76981ad6265SDimitry Andric (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
7700b57cec5SDimitry Andric PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
7710b57cec5SDimitry Andric llvm::Value *Align = Builder.CreateAnd(
77281ad6265SDimitry Andric PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
7730b57cec5SDimitry Andric llvm::Value *Aligned =
7740b57cec5SDimitry Andric Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
7750b57cec5SDimitry Andric if (Aligned != True)
7760b57cec5SDimitry Andric Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
7770b57cec5SDimitry Andric }
7780b57cec5SDimitry Andric }
7790b57cec5SDimitry Andric
7800b57cec5SDimitry Andric if (Checks.size() > 0) {
7810b57cec5SDimitry Andric llvm::Constant *StaticData[] = {
7820b57cec5SDimitry Andric EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
78381ad6265SDimitry Andric llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
7840b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, TCK)};
7850b57cec5SDimitry Andric EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
7860b57cec5SDimitry Andric PtrAsInt ? PtrAsInt : Ptr);
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric
7890b57cec5SDimitry Andric // If possible, check that the vptr indicates that there is a subobject of
7900b57cec5SDimitry Andric // type Ty at offset zero within this object.
7910b57cec5SDimitry Andric //
7920b57cec5SDimitry Andric // C++11 [basic.life]p5,6:
7930b57cec5SDimitry Andric // [For storage which does not refer to an object within its lifetime]
7940b57cec5SDimitry Andric // The program has undefined behavior if:
7950b57cec5SDimitry Andric // -- the [pointer or glvalue] is used to access a non-static data member
7960b57cec5SDimitry Andric // or call a non-static member function
7970b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Vptr) &&
7980b57cec5SDimitry Andric !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
7990b57cec5SDimitry Andric // Ensure that the pointer is non-null before loading it. If there is no
8000b57cec5SDimitry Andric // compile-time guarantee, reuse the run-time null check or emit a new one.
8010b57cec5SDimitry Andric if (!IsGuaranteedNonNull) {
8020b57cec5SDimitry Andric if (!IsNonNull)
8030b57cec5SDimitry Andric IsNonNull = Builder.CreateIsNotNull(Ptr);
8040b57cec5SDimitry Andric if (!Done)
8050b57cec5SDimitry Andric Done = createBasicBlock("vptr.null");
8060b57cec5SDimitry Andric llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
8070b57cec5SDimitry Andric Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
8080b57cec5SDimitry Andric EmitBlock(VptrNotNull);
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric
8110b57cec5SDimitry Andric // Compute a hash of the mangled name of the type.
8120b57cec5SDimitry Andric //
8130b57cec5SDimitry Andric // FIXME: This is not guaranteed to be deterministic! Move to a
8140b57cec5SDimitry Andric // fingerprinting mechanism once LLVM provides one. For the time
8150b57cec5SDimitry Andric // being the implementation happens to be deterministic.
8160b57cec5SDimitry Andric SmallString<64> MangledName;
8170b57cec5SDimitry Andric llvm::raw_svector_ostream Out(MangledName);
8180b57cec5SDimitry Andric CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
8190b57cec5SDimitry Andric Out);
8200b57cec5SDimitry Andric
821fe6060f1SDimitry Andric // Contained in NoSanitizeList based on the mangled type.
822fe6060f1SDimitry Andric if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
823fe6060f1SDimitry Andric Out.str())) {
8240b57cec5SDimitry Andric llvm::hash_code TypeHash = hash_value(Out.str());
8250b57cec5SDimitry Andric
8260b57cec5SDimitry Andric // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
8270b57cec5SDimitry Andric llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
828c9157d92SDimitry Andric Address VPtrAddr(Ptr, IntPtrTy, getPointerAlign());
8290b57cec5SDimitry Andric llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
8300b57cec5SDimitry Andric llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
8310b57cec5SDimitry Andric
8320b57cec5SDimitry Andric llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
8330b57cec5SDimitry Andric Hash = Builder.CreateTrunc(Hash, IntPtrTy);
8340b57cec5SDimitry Andric
8350b57cec5SDimitry Andric // Look the hash up in our cache.
8360b57cec5SDimitry Andric const int CacheSize = 128;
8370b57cec5SDimitry Andric llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
8380b57cec5SDimitry Andric llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
8390b57cec5SDimitry Andric "__ubsan_vptr_type_cache");
8400b57cec5SDimitry Andric llvm::Value *Slot = Builder.CreateAnd(Hash,
8410b57cec5SDimitry Andric llvm::ConstantInt::get(IntPtrTy,
8420b57cec5SDimitry Andric CacheSize-1));
8430b57cec5SDimitry Andric llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
844fe6060f1SDimitry Andric llvm::Value *CacheVal = Builder.CreateAlignedLoad(
845fe6060f1SDimitry Andric IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
8460b57cec5SDimitry Andric getPointerAlign());
8470b57cec5SDimitry Andric
8480b57cec5SDimitry Andric // If the hash isn't in the cache, call a runtime handler to perform the
8490b57cec5SDimitry Andric // hard work of checking whether the vptr is for an object of the right
8500b57cec5SDimitry Andric // type. This will either fill in the cache and return, or produce a
8510b57cec5SDimitry Andric // diagnostic.
8520b57cec5SDimitry Andric llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
8530b57cec5SDimitry Andric llvm::Constant *StaticData[] = {
8540b57cec5SDimitry Andric EmitCheckSourceLocation(Loc),
8550b57cec5SDimitry Andric EmitCheckTypeDescriptor(Ty),
8560b57cec5SDimitry Andric CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
8570b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, TCK)
8580b57cec5SDimitry Andric };
8590b57cec5SDimitry Andric llvm::Value *DynamicData[] = { Ptr, Hash };
8600b57cec5SDimitry Andric EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
8610b57cec5SDimitry Andric SanitizerHandler::DynamicTypeCacheMiss, StaticData,
8620b57cec5SDimitry Andric DynamicData);
8630b57cec5SDimitry Andric }
8640b57cec5SDimitry Andric }
8650b57cec5SDimitry Andric
8660b57cec5SDimitry Andric if (Done) {
8670b57cec5SDimitry Andric Builder.CreateBr(Done);
8680b57cec5SDimitry Andric EmitBlock(Done);
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric
LoadPassedObjectSize(const Expr * E,QualType EltTy)8720b57cec5SDimitry Andric llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
8730b57cec5SDimitry Andric QualType EltTy) {
8740b57cec5SDimitry Andric ASTContext &C = getContext();
8750b57cec5SDimitry Andric uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
8760b57cec5SDimitry Andric if (!EltSize)
8770b57cec5SDimitry Andric return nullptr;
8780b57cec5SDimitry Andric
8790b57cec5SDimitry Andric auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
8800b57cec5SDimitry Andric if (!ArrayDeclRef)
8810b57cec5SDimitry Andric return nullptr;
8820b57cec5SDimitry Andric
8830b57cec5SDimitry Andric auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
8840b57cec5SDimitry Andric if (!ParamDecl)
8850b57cec5SDimitry Andric return nullptr;
8860b57cec5SDimitry Andric
8870b57cec5SDimitry Andric auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
8880b57cec5SDimitry Andric if (!POSAttr)
8890b57cec5SDimitry Andric return nullptr;
8900b57cec5SDimitry Andric
8910b57cec5SDimitry Andric // Don't load the size if it's a lower bound.
8920b57cec5SDimitry Andric int POSType = POSAttr->getType();
8930b57cec5SDimitry Andric if (POSType != 0 && POSType != 1)
8940b57cec5SDimitry Andric return nullptr;
8950b57cec5SDimitry Andric
8960b57cec5SDimitry Andric // Find the implicit size parameter.
8970b57cec5SDimitry Andric auto PassedSizeIt = SizeArguments.find(ParamDecl);
8980b57cec5SDimitry Andric if (PassedSizeIt == SizeArguments.end())
8990b57cec5SDimitry Andric return nullptr;
9000b57cec5SDimitry Andric
9010b57cec5SDimitry Andric const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
9020b57cec5SDimitry Andric assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
9030b57cec5SDimitry Andric Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
9040b57cec5SDimitry Andric llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
9050b57cec5SDimitry Andric C.getSizeType(), E->getExprLoc());
9060b57cec5SDimitry Andric llvm::Value *SizeOfElement =
9070b57cec5SDimitry Andric llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
9080b57cec5SDimitry Andric return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
9090b57cec5SDimitry Andric }
9100b57cec5SDimitry Andric
9110b57cec5SDimitry Andric /// If Base is known to point to the start of an array, return the length of
9120b57cec5SDimitry Andric /// that array. Return 0 if the length cannot be determined.
getArrayIndexingBound(CodeGenFunction & CGF,const Expr * Base,QualType & IndexedType,LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel)913fcaf7f86SDimitry Andric static llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF,
914fcaf7f86SDimitry Andric const Expr *Base,
915fcaf7f86SDimitry Andric QualType &IndexedType,
916bdd1243dSDimitry Andric LangOptions::StrictFlexArraysLevelKind
917bdd1243dSDimitry Andric StrictFlexArraysLevel) {
9180b57cec5SDimitry Andric // For the vector indexing extension, the bound is the number of elements.
9190b57cec5SDimitry Andric if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
9200b57cec5SDimitry Andric IndexedType = Base->getType();
9210b57cec5SDimitry Andric return CGF.Builder.getInt32(VT->getNumElements());
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric
9240b57cec5SDimitry Andric Base = Base->IgnoreParens();
9250b57cec5SDimitry Andric
9260b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(Base)) {
9270b57cec5SDimitry Andric if (CE->getCastKind() == CK_ArrayToPointerDecay &&
928bdd1243dSDimitry Andric !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(),
929bdd1243dSDimitry Andric StrictFlexArraysLevel)) {
9306c20abcdSDimitry Andric CodeGenFunction::SanitizerScope SanScope(&CGF);
9316c20abcdSDimitry Andric
9320b57cec5SDimitry Andric IndexedType = CE->getSubExpr()->getType();
9330b57cec5SDimitry Andric const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
9340b57cec5SDimitry Andric if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9350b57cec5SDimitry Andric return CGF.Builder.getInt(CAT->getSize());
9366c20abcdSDimitry Andric
9376c20abcdSDimitry Andric if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
9380b57cec5SDimitry Andric return CGF.getVLASize(VAT).NumElts;
9390b57cec5SDimitry Andric // Ignore pass_object_size here. It's not applicable on decayed pointers.
9400b57cec5SDimitry Andric }
9410b57cec5SDimitry Andric }
9420b57cec5SDimitry Andric
9436c20abcdSDimitry Andric CodeGenFunction::SanitizerScope SanScope(&CGF);
9446c20abcdSDimitry Andric
9450b57cec5SDimitry Andric QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
9460b57cec5SDimitry Andric if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
9470b57cec5SDimitry Andric IndexedType = Base->getType();
9480b57cec5SDimitry Andric return POS;
9490b57cec5SDimitry Andric }
9500b57cec5SDimitry Andric
9510b57cec5SDimitry Andric return nullptr;
9520b57cec5SDimitry Andric }
9530b57cec5SDimitry Andric
9546c20abcdSDimitry Andric namespace {
9556c20abcdSDimitry Andric
9566c20abcdSDimitry Andric /// \p StructAccessBase returns the base \p Expr of a field access. It returns
9576c20abcdSDimitry Andric /// either a \p DeclRefExpr, representing the base pointer to the struct, i.e.:
9586c20abcdSDimitry Andric ///
9596c20abcdSDimitry Andric /// p in p-> a.b.c
9606c20abcdSDimitry Andric ///
9616c20abcdSDimitry Andric /// or a \p MemberExpr, if the \p MemberExpr has the \p RecordDecl we're
9626c20abcdSDimitry Andric /// looking for:
9636c20abcdSDimitry Andric ///
9646c20abcdSDimitry Andric /// struct s {
9656c20abcdSDimitry Andric /// struct s *ptr;
9666c20abcdSDimitry Andric /// int count;
9676c20abcdSDimitry Andric /// char array[] __attribute__((counted_by(count)));
9686c20abcdSDimitry Andric /// };
9696c20abcdSDimitry Andric ///
9706c20abcdSDimitry Andric /// If we have an expression like \p p->ptr->array[index], we want the
9716c20abcdSDimitry Andric /// \p MemberExpr for \p p->ptr instead of \p p.
9726c20abcdSDimitry Andric class StructAccessBase
9736c20abcdSDimitry Andric : public ConstStmtVisitor<StructAccessBase, const Expr *> {
9746c20abcdSDimitry Andric const RecordDecl *ExpectedRD;
9756c20abcdSDimitry Andric
IsExpectedRecordDecl(const Expr * E) const9766c20abcdSDimitry Andric bool IsExpectedRecordDecl(const Expr *E) const {
9776c20abcdSDimitry Andric QualType Ty = E->getType();
9786c20abcdSDimitry Andric if (Ty->isPointerType())
9796c20abcdSDimitry Andric Ty = Ty->getPointeeType();
9806c20abcdSDimitry Andric return ExpectedRD == Ty->getAsRecordDecl();
9816c20abcdSDimitry Andric }
9826c20abcdSDimitry Andric
9836c20abcdSDimitry Andric public:
StructAccessBase(const RecordDecl * ExpectedRD)9846c20abcdSDimitry Andric StructAccessBase(const RecordDecl *ExpectedRD) : ExpectedRD(ExpectedRD) {}
9856c20abcdSDimitry Andric
9866c20abcdSDimitry Andric //===--------------------------------------------------------------------===//
9876c20abcdSDimitry Andric // Visitor Methods
9886c20abcdSDimitry Andric //===--------------------------------------------------------------------===//
9896c20abcdSDimitry Andric
9906c20abcdSDimitry Andric // NOTE: If we build C++ support for counted_by, then we'll have to handle
9916c20abcdSDimitry Andric // horrors like this:
9926c20abcdSDimitry Andric //
9936c20abcdSDimitry Andric // struct S {
9946c20abcdSDimitry Andric // int x, y;
9956c20abcdSDimitry Andric // int blah[] __attribute__((counted_by(x)));
9966c20abcdSDimitry Andric // } s;
9976c20abcdSDimitry Andric //
9986c20abcdSDimitry Andric // int foo(int index, int val) {
9996c20abcdSDimitry Andric // int (S::*IHatePMDs)[] = &S::blah;
10006c20abcdSDimitry Andric // (s.*IHatePMDs)[index] = val;
10016c20abcdSDimitry Andric // }
10026c20abcdSDimitry Andric
Visit(const Expr * E)10036c20abcdSDimitry Andric const Expr *Visit(const Expr *E) {
10046c20abcdSDimitry Andric return ConstStmtVisitor<StructAccessBase, const Expr *>::Visit(E);
10056c20abcdSDimitry Andric }
10066c20abcdSDimitry Andric
VisitStmt(const Stmt * S)10076c20abcdSDimitry Andric const Expr *VisitStmt(const Stmt *S) { return nullptr; }
10086c20abcdSDimitry Andric
10096c20abcdSDimitry Andric // These are the types we expect to return (in order of most to least
10106c20abcdSDimitry Andric // likely):
10116c20abcdSDimitry Andric //
10126c20abcdSDimitry Andric // 1. DeclRefExpr - This is the expression for the base of the structure.
10136c20abcdSDimitry Andric // It's exactly what we want to build an access to the \p counted_by
10146c20abcdSDimitry Andric // field.
10156c20abcdSDimitry Andric // 2. MemberExpr - This is the expression that has the same \p RecordDecl
10166c20abcdSDimitry Andric // as the flexble array member's lexical enclosing \p RecordDecl. This
10176c20abcdSDimitry Andric // allows us to catch things like: "p->p->array"
10186c20abcdSDimitry Andric // 3. CompoundLiteralExpr - This is for people who create something
10196c20abcdSDimitry Andric // heretical like (struct foo has a flexible array member):
10206c20abcdSDimitry Andric //
10216c20abcdSDimitry Andric // (struct foo){ 1, 2 }.blah[idx];
VisitDeclRefExpr(const DeclRefExpr * E)10226c20abcdSDimitry Andric const Expr *VisitDeclRefExpr(const DeclRefExpr *E) {
10236c20abcdSDimitry Andric return IsExpectedRecordDecl(E) ? E : nullptr;
10246c20abcdSDimitry Andric }
VisitMemberExpr(const MemberExpr * E)10256c20abcdSDimitry Andric const Expr *VisitMemberExpr(const MemberExpr *E) {
10266c20abcdSDimitry Andric if (IsExpectedRecordDecl(E) && E->isArrow())
10276c20abcdSDimitry Andric return E;
10286c20abcdSDimitry Andric const Expr *Res = Visit(E->getBase());
10296c20abcdSDimitry Andric return !Res && IsExpectedRecordDecl(E) ? E : Res;
10306c20abcdSDimitry Andric }
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)10316c20abcdSDimitry Andric const Expr *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
10326c20abcdSDimitry Andric return IsExpectedRecordDecl(E) ? E : nullptr;
10336c20abcdSDimitry Andric }
VisitCallExpr(const CallExpr * E)10346c20abcdSDimitry Andric const Expr *VisitCallExpr(const CallExpr *E) {
10356c20abcdSDimitry Andric return IsExpectedRecordDecl(E) ? E : nullptr;
10366c20abcdSDimitry Andric }
10376c20abcdSDimitry Andric
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)10386c20abcdSDimitry Andric const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
10396c20abcdSDimitry Andric if (IsExpectedRecordDecl(E))
10406c20abcdSDimitry Andric return E;
10416c20abcdSDimitry Andric return Visit(E->getBase());
10426c20abcdSDimitry Andric }
VisitCastExpr(const CastExpr * E)10436c20abcdSDimitry Andric const Expr *VisitCastExpr(const CastExpr *E) {
10446c20abcdSDimitry Andric return Visit(E->getSubExpr());
10456c20abcdSDimitry Andric }
VisitParenExpr(const ParenExpr * E)10466c20abcdSDimitry Andric const Expr *VisitParenExpr(const ParenExpr *E) {
10476c20abcdSDimitry Andric return Visit(E->getSubExpr());
10486c20abcdSDimitry Andric }
VisitUnaryAddrOf(const UnaryOperator * E)10496c20abcdSDimitry Andric const Expr *VisitUnaryAddrOf(const UnaryOperator *E) {
10506c20abcdSDimitry Andric return Visit(E->getSubExpr());
10516c20abcdSDimitry Andric }
VisitUnaryDeref(const UnaryOperator * E)10526c20abcdSDimitry Andric const Expr *VisitUnaryDeref(const UnaryOperator *E) {
10536c20abcdSDimitry Andric return Visit(E->getSubExpr());
10546c20abcdSDimitry Andric }
10556c20abcdSDimitry Andric };
10566c20abcdSDimitry Andric
10576c20abcdSDimitry Andric } // end anonymous namespace
10586c20abcdSDimitry Andric
10596c20abcdSDimitry Andric using RecIndicesTy =
10606c20abcdSDimitry Andric SmallVector<std::pair<const RecordDecl *, llvm::Value *>, 8>;
10616c20abcdSDimitry Andric
getGEPIndicesToField(CodeGenFunction & CGF,const RecordDecl * RD,const FieldDecl * FD,RecIndicesTy & Indices)10626c20abcdSDimitry Andric static bool getGEPIndicesToField(CodeGenFunction &CGF, const RecordDecl *RD,
10636c20abcdSDimitry Andric const FieldDecl *FD, RecIndicesTy &Indices) {
10646c20abcdSDimitry Andric const CGRecordLayout &Layout = CGF.CGM.getTypes().getCGRecordLayout(RD);
10656c20abcdSDimitry Andric int64_t FieldNo = -1;
10666c20abcdSDimitry Andric for (const Decl *D : RD->decls()) {
10676c20abcdSDimitry Andric if (const auto *Field = dyn_cast<FieldDecl>(D)) {
10686c20abcdSDimitry Andric FieldNo = Layout.getLLVMFieldNo(Field);
10696c20abcdSDimitry Andric if (FD == Field) {
10706c20abcdSDimitry Andric Indices.emplace_back(std::make_pair(RD, CGF.Builder.getInt32(FieldNo)));
10716c20abcdSDimitry Andric return true;
10726c20abcdSDimitry Andric }
10736c20abcdSDimitry Andric }
10746c20abcdSDimitry Andric
10756c20abcdSDimitry Andric if (const auto *Record = dyn_cast<RecordDecl>(D)) {
10766c20abcdSDimitry Andric ++FieldNo;
10776c20abcdSDimitry Andric if (getGEPIndicesToField(CGF, Record, FD, Indices)) {
10786c20abcdSDimitry Andric if (RD->isUnion())
10796c20abcdSDimitry Andric FieldNo = 0;
10806c20abcdSDimitry Andric Indices.emplace_back(std::make_pair(RD, CGF.Builder.getInt32(FieldNo)));
10816c20abcdSDimitry Andric return true;
10826c20abcdSDimitry Andric }
10836c20abcdSDimitry Andric }
10846c20abcdSDimitry Andric }
10856c20abcdSDimitry Andric
10866c20abcdSDimitry Andric return false;
10876c20abcdSDimitry Andric }
10886c20abcdSDimitry Andric
10896c20abcdSDimitry Andric /// This method is typically called in contexts where we can't generate
10906c20abcdSDimitry Andric /// side-effects, like in __builtin_dynamic_object_size. When finding
10916c20abcdSDimitry Andric /// expressions, only choose those that have either already been emitted or can
10926c20abcdSDimitry Andric /// be loaded without side-effects.
10936c20abcdSDimitry Andric ///
10946c20abcdSDimitry Andric /// - \p FAMDecl: the \p Decl for the flexible array member. It may not be
10956c20abcdSDimitry Andric /// within the top-level struct.
10966c20abcdSDimitry Andric /// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
EmitCountedByFieldExpr(const Expr * Base,const FieldDecl * FAMDecl,const FieldDecl * CountDecl)10976c20abcdSDimitry Andric llvm::Value *CodeGenFunction::EmitCountedByFieldExpr(
10986c20abcdSDimitry Andric const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
10996c20abcdSDimitry Andric const RecordDecl *RD = CountDecl->getParent()->getOuterLexicalRecordContext();
11006c20abcdSDimitry Andric
11016c20abcdSDimitry Andric // Find the base struct expr (i.e. p in p->a.b.c.d).
11026c20abcdSDimitry Andric const Expr *StructBase = StructAccessBase(RD).Visit(Base);
11036c20abcdSDimitry Andric if (!StructBase || StructBase->HasSideEffects(getContext()))
11046c20abcdSDimitry Andric return nullptr;
11056c20abcdSDimitry Andric
11066c20abcdSDimitry Andric llvm::Value *Res = nullptr;
11076c20abcdSDimitry Andric if (const auto *DRE = dyn_cast<DeclRefExpr>(StructBase)) {
11086c20abcdSDimitry Andric Res = EmitDeclRefLValue(DRE).getPointer(*this);
11096c20abcdSDimitry Andric Res = Builder.CreateAlignedLoad(ConvertType(DRE->getType()), Res,
11106c20abcdSDimitry Andric getPointerAlign(), "dre.load");
11116c20abcdSDimitry Andric } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(StructBase)) {
11126c20abcdSDimitry Andric LValue LV = EmitMemberExpr(ME);
11136c20abcdSDimitry Andric Address Addr = LV.getAddress(*this);
11146c20abcdSDimitry Andric Res = Addr.getPointer();
11156c20abcdSDimitry Andric } else if (StructBase->getType()->isPointerType()) {
11166c20abcdSDimitry Andric LValueBaseInfo BaseInfo;
11176c20abcdSDimitry Andric TBAAAccessInfo TBAAInfo;
11186c20abcdSDimitry Andric Address Addr = EmitPointerWithAlignment(StructBase, &BaseInfo, &TBAAInfo);
11196c20abcdSDimitry Andric Res = Addr.getPointer();
11206c20abcdSDimitry Andric } else {
11216c20abcdSDimitry Andric return nullptr;
11226c20abcdSDimitry Andric }
11236c20abcdSDimitry Andric
11246c20abcdSDimitry Andric llvm::Value *Zero = Builder.getInt32(0);
11256c20abcdSDimitry Andric RecIndicesTy Indices;
11266c20abcdSDimitry Andric
11276c20abcdSDimitry Andric getGEPIndicesToField(*this, RD, CountDecl, Indices);
11286c20abcdSDimitry Andric
11296c20abcdSDimitry Andric for (auto I = Indices.rbegin(), E = Indices.rend(); I != E; ++I)
11306c20abcdSDimitry Andric Res = Builder.CreateInBoundsGEP(
11316c20abcdSDimitry Andric ConvertType(QualType(I->first->getTypeForDecl(), 0)), Res,
11326c20abcdSDimitry Andric {Zero, I->second}, "..counted_by.gep");
11336c20abcdSDimitry Andric
11346c20abcdSDimitry Andric return Builder.CreateAlignedLoad(ConvertType(CountDecl->getType()), Res,
11356c20abcdSDimitry Andric getIntAlign(), "..counted_by.load");
11366c20abcdSDimitry Andric }
11376c20abcdSDimitry Andric
FindCountedByField(const FieldDecl * FD)11386c20abcdSDimitry Andric const FieldDecl *CodeGenFunction::FindCountedByField(const FieldDecl *FD) {
11396c20abcdSDimitry Andric if (!FD || !FD->hasAttr<CountedByAttr>())
11406c20abcdSDimitry Andric return nullptr;
11416c20abcdSDimitry Andric
11426c20abcdSDimitry Andric const auto *CBA = FD->getAttr<CountedByAttr>();
11436c20abcdSDimitry Andric if (!CBA)
11446c20abcdSDimitry Andric return nullptr;
11456c20abcdSDimitry Andric
11466c20abcdSDimitry Andric auto GetNonAnonStructOrUnion =
11476c20abcdSDimitry Andric [](const RecordDecl *RD) -> const RecordDecl * {
11486c20abcdSDimitry Andric while (RD && RD->isAnonymousStructOrUnion()) {
11496c20abcdSDimitry Andric const auto *R = dyn_cast<RecordDecl>(RD->getDeclContext());
11506c20abcdSDimitry Andric if (!R)
11516c20abcdSDimitry Andric return nullptr;
11526c20abcdSDimitry Andric RD = R;
11536c20abcdSDimitry Andric }
11546c20abcdSDimitry Andric return RD;
11556c20abcdSDimitry Andric };
11566c20abcdSDimitry Andric const RecordDecl *EnclosingRD = GetNonAnonStructOrUnion(FD->getParent());
11576c20abcdSDimitry Andric if (!EnclosingRD)
11586c20abcdSDimitry Andric return nullptr;
11596c20abcdSDimitry Andric
11606c20abcdSDimitry Andric DeclarationName DName(CBA->getCountedByField());
11616c20abcdSDimitry Andric DeclContext::lookup_result Lookup = EnclosingRD->lookup(DName);
11626c20abcdSDimitry Andric
11636c20abcdSDimitry Andric if (Lookup.empty())
11646c20abcdSDimitry Andric return nullptr;
11656c20abcdSDimitry Andric
11666c20abcdSDimitry Andric const NamedDecl *ND = Lookup.front();
11676c20abcdSDimitry Andric if (const auto *IFD = dyn_cast<IndirectFieldDecl>(ND))
11686c20abcdSDimitry Andric ND = IFD->getAnonField();
11696c20abcdSDimitry Andric
11706c20abcdSDimitry Andric return dyn_cast<FieldDecl>(ND);
11716c20abcdSDimitry Andric }
11726c20abcdSDimitry Andric
EmitBoundsCheck(const Expr * E,const Expr * Base,llvm::Value * Index,QualType IndexType,bool Accessed)11730b57cec5SDimitry Andric void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
11740b57cec5SDimitry Andric llvm::Value *Index, QualType IndexType,
11750b57cec5SDimitry Andric bool Accessed) {
11760b57cec5SDimitry Andric assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
11770b57cec5SDimitry Andric "should not be called unless adding bounds checks");
1178bdd1243dSDimitry Andric const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
1179bdd1243dSDimitry Andric getLangOpts().getStrictFlexArraysLevel();
11800b57cec5SDimitry Andric QualType IndexedType;
1181fcaf7f86SDimitry Andric llvm::Value *Bound =
1182fcaf7f86SDimitry Andric getArrayIndexingBound(*this, Base, IndexedType, StrictFlexArraysLevel);
11836c20abcdSDimitry Andric
11846c20abcdSDimitry Andric EmitBoundsCheckImpl(E, Bound, Index, IndexType, IndexedType, Accessed);
11856c20abcdSDimitry Andric }
11866c20abcdSDimitry Andric
EmitBoundsCheckImpl(const Expr * E,llvm::Value * Bound,llvm::Value * Index,QualType IndexType,QualType IndexedType,bool Accessed)11876c20abcdSDimitry Andric void CodeGenFunction::EmitBoundsCheckImpl(const Expr *E, llvm::Value *Bound,
11886c20abcdSDimitry Andric llvm::Value *Index,
11896c20abcdSDimitry Andric QualType IndexType,
11906c20abcdSDimitry Andric QualType IndexedType, bool Accessed) {
11910b57cec5SDimitry Andric if (!Bound)
11920b57cec5SDimitry Andric return;
11930b57cec5SDimitry Andric
11946c20abcdSDimitry Andric SanitizerScope SanScope(this);
11956c20abcdSDimitry Andric
11960b57cec5SDimitry Andric bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
11970b57cec5SDimitry Andric llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
11980b57cec5SDimitry Andric llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
11990b57cec5SDimitry Andric
12000b57cec5SDimitry Andric llvm::Constant *StaticData[] = {
12010b57cec5SDimitry Andric EmitCheckSourceLocation(E->getExprLoc()),
12020b57cec5SDimitry Andric EmitCheckTypeDescriptor(IndexedType),
12030b57cec5SDimitry Andric EmitCheckTypeDescriptor(IndexType)
12040b57cec5SDimitry Andric };
12050b57cec5SDimitry Andric llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
12060b57cec5SDimitry Andric : Builder.CreateICmpULE(IndexVal, BoundVal);
12070b57cec5SDimitry Andric EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
12080b57cec5SDimitry Andric SanitizerHandler::OutOfBounds, StaticData, Index);
12090b57cec5SDimitry Andric }
12100b57cec5SDimitry Andric
12110b57cec5SDimitry Andric CodeGenFunction::ComplexPairTy CodeGenFunction::
EmitComplexPrePostIncDec(const UnaryOperator * E,LValue LV,bool isInc,bool isPre)12120b57cec5SDimitry Andric EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
12130b57cec5SDimitry Andric bool isInc, bool isPre) {
12140b57cec5SDimitry Andric ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
12150b57cec5SDimitry Andric
12160b57cec5SDimitry Andric llvm::Value *NextVal;
12170b57cec5SDimitry Andric if (isa<llvm::IntegerType>(InVal.first->getType())) {
12180b57cec5SDimitry Andric uint64_t AmountVal = isInc ? 1 : -1;
12190b57cec5SDimitry Andric NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
12200b57cec5SDimitry Andric
12210b57cec5SDimitry Andric // Add the inc/dec to the real part.
12220b57cec5SDimitry Andric NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
12230b57cec5SDimitry Andric } else {
1224a7dea167SDimitry Andric QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12250b57cec5SDimitry Andric llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
12260b57cec5SDimitry Andric if (!isInc)
12270b57cec5SDimitry Andric FVal.changeSign();
12280b57cec5SDimitry Andric NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
12290b57cec5SDimitry Andric
12300b57cec5SDimitry Andric // Add the inc/dec to the real part.
12310b57cec5SDimitry Andric NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
12320b57cec5SDimitry Andric }
12330b57cec5SDimitry Andric
12340b57cec5SDimitry Andric ComplexPairTy IncVal(NextVal, InVal.second);
12350b57cec5SDimitry Andric
12360b57cec5SDimitry Andric // Store the updated result through the lvalue.
12370b57cec5SDimitry Andric EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1238480093f4SDimitry Andric if (getLangOpts().OpenMP)
1239480093f4SDimitry Andric CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1240480093f4SDimitry Andric E->getSubExpr());
12410b57cec5SDimitry Andric
12420b57cec5SDimitry Andric // If this is a postinc, return the value read from memory, otherwise use the
12430b57cec5SDimitry Andric // updated value.
12440b57cec5SDimitry Andric return isPre ? IncVal : InVal;
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric
EmitExplicitCastExprType(const ExplicitCastExpr * E,CodeGenFunction * CGF)12470b57cec5SDimitry Andric void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
12480b57cec5SDimitry Andric CodeGenFunction *CGF) {
12490b57cec5SDimitry Andric // Bind VLAs in the cast type.
12500b57cec5SDimitry Andric if (CGF && E->getType()->isVariablyModifiedType())
12510b57cec5SDimitry Andric CGF->EmitVariablyModifiedType(E->getType());
12520b57cec5SDimitry Andric
12530b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo())
12540b57cec5SDimitry Andric DI->EmitExplicitCastType(E->getType());
12550b57cec5SDimitry Andric }
12560b57cec5SDimitry Andric
12570b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12580b57cec5SDimitry Andric // LValue Expression Emission
12590b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12600b57cec5SDimitry Andric
EmitPointerWithAlignment(const Expr * E,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo,KnownNonNull_t IsKnownNonNull,CodeGenFunction & CGF)1261fe013be4SDimitry Andric static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo,
1262fe013be4SDimitry Andric TBAAAccessInfo *TBAAInfo,
1263fe013be4SDimitry Andric KnownNonNull_t IsKnownNonNull,
1264fe013be4SDimitry Andric CodeGenFunction &CGF) {
12650b57cec5SDimitry Andric // We allow this with ObjC object pointers because of fragile ABIs.
12660b57cec5SDimitry Andric assert(E->getType()->isPointerType() ||
12670b57cec5SDimitry Andric E->getType()->isObjCObjectPointerType());
12680b57cec5SDimitry Andric E = E->IgnoreParens();
12690b57cec5SDimitry Andric
12700b57cec5SDimitry Andric // Casts:
12710b57cec5SDimitry Andric if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12720b57cec5SDimitry Andric if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1273fe013be4SDimitry Andric CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
12740b57cec5SDimitry Andric
12750b57cec5SDimitry Andric switch (CE->getCastKind()) {
12760b57cec5SDimitry Andric // Non-converting casts (but not C's implicit conversion from void*).
12770b57cec5SDimitry Andric case CK_BitCast:
12780b57cec5SDimitry Andric case CK_NoOp:
12790b57cec5SDimitry Andric case CK_AddressSpaceConversion:
12800b57cec5SDimitry Andric if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
12810b57cec5SDimitry Andric if (PtrTy->getPointeeType()->isVoidType())
12820b57cec5SDimitry Andric break;
12830b57cec5SDimitry Andric
12840b57cec5SDimitry Andric LValueBaseInfo InnerBaseInfo;
12850b57cec5SDimitry Andric TBAAAccessInfo InnerTBAAInfo;
1286fe013be4SDimitry Andric Address Addr = CGF.EmitPointerWithAlignment(
1287fe013be4SDimitry Andric CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
12880b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = InnerBaseInfo;
12890b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
12900b57cec5SDimitry Andric
12910b57cec5SDimitry Andric if (isa<ExplicitCastExpr>(CE)) {
12920b57cec5SDimitry Andric LValueBaseInfo TargetTypeBaseInfo;
12930b57cec5SDimitry Andric TBAAAccessInfo TargetTypeTBAAInfo;
1294fe013be4SDimitry Andric CharUnits Align = CGF.CGM.getNaturalPointeeTypeAlignment(
12955ffd83dbSDimitry Andric E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
12960b57cec5SDimitry Andric if (TBAAInfo)
1297fe013be4SDimitry Andric *TBAAInfo =
1298fe013be4SDimitry Andric CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo);
12990b57cec5SDimitry Andric // If the source l-value is opaque, honor the alignment of the
13000b57cec5SDimitry Andric // casted-to type.
13010b57cec5SDimitry Andric if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
13020b57cec5SDimitry Andric if (BaseInfo)
13030b57cec5SDimitry Andric BaseInfo->mergeForCast(TargetTypeBaseInfo);
1304fe013be4SDimitry Andric Addr = Address(Addr.getPointer(), Addr.getElementType(), Align,
1305fe013be4SDimitry Andric IsKnownNonNull);
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric }
13080b57cec5SDimitry Andric
1309fe013be4SDimitry Andric if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
13100b57cec5SDimitry Andric CE->getCastKind() == CK_BitCast) {
13110b57cec5SDimitry Andric if (auto PT = E->getType()->getAs<PointerType>())
1312fe013be4SDimitry Andric CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
13130b57cec5SDimitry Andric /*MayBeNull=*/true,
13140b57cec5SDimitry Andric CodeGenFunction::CFITCK_UnrelatedCast,
13150b57cec5SDimitry Andric CE->getBeginLoc());
13160b57cec5SDimitry Andric }
13170eae32dcSDimitry Andric
1318fe013be4SDimitry Andric llvm::Type *ElemTy =
1319fe013be4SDimitry Andric CGF.ConvertTypeForMem(E->getType()->getPointeeType());
1320fe013be4SDimitry Andric Addr = Addr.withElementType(ElemTy);
132181ad6265SDimitry Andric if (CE->getCastKind() == CK_AddressSpaceConversion)
1322fe013be4SDimitry Andric Addr = CGF.Builder.CreateAddrSpaceCast(Addr,
1323fe013be4SDimitry Andric CGF.ConvertType(E->getType()));
132481ad6265SDimitry Andric return Addr;
13250b57cec5SDimitry Andric }
13260b57cec5SDimitry Andric break;
13270b57cec5SDimitry Andric
13280b57cec5SDimitry Andric // Array-to-pointer decay.
13290b57cec5SDimitry Andric case CK_ArrayToPointerDecay:
1330fe013be4SDimitry Andric return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
13310b57cec5SDimitry Andric
13320b57cec5SDimitry Andric // Derived-to-base conversions.
13330b57cec5SDimitry Andric case CK_UncheckedDerivedToBase:
13340b57cec5SDimitry Andric case CK_DerivedToBase: {
13350b57cec5SDimitry Andric // TODO: Support accesses to members of base classes in TBAA. For now, we
13360b57cec5SDimitry Andric // conservatively pretend that the complete object is of the base class
13370b57cec5SDimitry Andric // type.
13380b57cec5SDimitry Andric if (TBAAInfo)
1339fe013be4SDimitry Andric *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType());
1340fe013be4SDimitry Andric Address Addr = CGF.EmitPointerWithAlignment(
1341fe013be4SDimitry Andric CE->getSubExpr(), BaseInfo, nullptr,
1342fe013be4SDimitry Andric (KnownNonNull_t)(IsKnownNonNull ||
1343fe013be4SDimitry Andric CE->getCastKind() == CK_UncheckedDerivedToBase));
13440b57cec5SDimitry Andric auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1345fe013be4SDimitry Andric return CGF.GetAddressOfBaseClass(
1346fe013be4SDimitry Andric Addr, Derived, CE->path_begin(), CE->path_end(),
1347fe013be4SDimitry Andric CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
13480b57cec5SDimitry Andric }
13490b57cec5SDimitry Andric
13500b57cec5SDimitry Andric // TODO: Is there any reason to treat base-to-derived conversions
13510b57cec5SDimitry Andric // specially?
13520b57cec5SDimitry Andric default:
13530b57cec5SDimitry Andric break;
13540b57cec5SDimitry Andric }
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric
13570b57cec5SDimitry Andric // Unary &.
13580b57cec5SDimitry Andric if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13590b57cec5SDimitry Andric if (UO->getOpcode() == UO_AddrOf) {
1360fe013be4SDimitry Andric LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull);
13610b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = LV.getBaseInfo();
13620b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1363fe013be4SDimitry Andric return LV.getAddress(CGF);
13640b57cec5SDimitry Andric }
13650b57cec5SDimitry Andric }
13660b57cec5SDimitry Andric
136781ad6265SDimitry Andric // std::addressof and variants.
136881ad6265SDimitry Andric if (auto *Call = dyn_cast<CallExpr>(E)) {
136981ad6265SDimitry Andric switch (Call->getBuiltinCallee()) {
137081ad6265SDimitry Andric default:
137181ad6265SDimitry Andric break;
137281ad6265SDimitry Andric case Builtin::BIaddressof:
137381ad6265SDimitry Andric case Builtin::BI__addressof:
137481ad6265SDimitry Andric case Builtin::BI__builtin_addressof: {
1375fe013be4SDimitry Andric LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull);
137681ad6265SDimitry Andric if (BaseInfo) *BaseInfo = LV.getBaseInfo();
137781ad6265SDimitry Andric if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1378fe013be4SDimitry Andric return LV.getAddress(CGF);
137981ad6265SDimitry Andric }
138081ad6265SDimitry Andric }
138181ad6265SDimitry Andric }
138281ad6265SDimitry Andric
13830b57cec5SDimitry Andric // TODO: conditional operators, comma.
13840b57cec5SDimitry Andric
13850b57cec5SDimitry Andric // Otherwise, use the alignment of the type.
13865ffd83dbSDimitry Andric CharUnits Align =
1387fe013be4SDimitry Andric CGF.CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
1388fe013be4SDimitry Andric llvm::Type *ElemTy = CGF.ConvertTypeForMem(E->getType()->getPointeeType());
1389fe013be4SDimitry Andric return Address(CGF.EmitScalarExpr(E), ElemTy, Align, IsKnownNonNull);
1390fe013be4SDimitry Andric }
1391fe013be4SDimitry Andric
1392fe013be4SDimitry Andric /// EmitPointerWithAlignment - Given an expression of pointer type, try to
1393fe013be4SDimitry Andric /// derive a more accurate bound on the alignment of the pointer.
EmitPointerWithAlignment(const Expr * E,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo,KnownNonNull_t IsKnownNonNull)1394fe013be4SDimitry Andric Address CodeGenFunction::EmitPointerWithAlignment(
1395fe013be4SDimitry Andric const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1396fe013be4SDimitry Andric KnownNonNull_t IsKnownNonNull) {
1397fe013be4SDimitry Andric Address Addr =
1398fe013be4SDimitry Andric ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this);
1399fe013be4SDimitry Andric if (IsKnownNonNull && !Addr.isKnownNonNull())
1400fe013be4SDimitry Andric Addr.setKnownNonNull();
1401fe013be4SDimitry Andric return Addr;
14020b57cec5SDimitry Andric }
14030b57cec5SDimitry Andric
EmitNonNullRValueCheck(RValue RV,QualType T)1404e8d8bef9SDimitry Andric llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1405e8d8bef9SDimitry Andric llvm::Value *V = RV.getScalarVal();
1406e8d8bef9SDimitry Andric if (auto MPT = T->getAs<MemberPointerType>())
1407e8d8bef9SDimitry Andric return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1408e8d8bef9SDimitry Andric return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1409e8d8bef9SDimitry Andric }
1410e8d8bef9SDimitry Andric
GetUndefRValue(QualType Ty)14110b57cec5SDimitry Andric RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
14120b57cec5SDimitry Andric if (Ty->isVoidType())
14130b57cec5SDimitry Andric return RValue::get(nullptr);
14140b57cec5SDimitry Andric
14150b57cec5SDimitry Andric switch (getEvaluationKind(Ty)) {
14160b57cec5SDimitry Andric case TEK_Complex: {
14170b57cec5SDimitry Andric llvm::Type *EltTy =
14180b57cec5SDimitry Andric ConvertType(Ty->castAs<ComplexType>()->getElementType());
14190b57cec5SDimitry Andric llvm::Value *U = llvm::UndefValue::get(EltTy);
14200b57cec5SDimitry Andric return RValue::getComplex(std::make_pair(U, U));
14210b57cec5SDimitry Andric }
14220b57cec5SDimitry Andric
14230b57cec5SDimitry Andric // If this is a use of an undefined aggregate type, the aggregate must have an
14240b57cec5SDimitry Andric // identifiable address. Just because the contents of the value are undefined
14250b57cec5SDimitry Andric // doesn't mean that the address can't be taken and compared.
14260b57cec5SDimitry Andric case TEK_Aggregate: {
14270b57cec5SDimitry Andric Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
14280b57cec5SDimitry Andric return RValue::getAggregate(DestPtr);
14290b57cec5SDimitry Andric }
14300b57cec5SDimitry Andric
14310b57cec5SDimitry Andric case TEK_Scalar:
14320b57cec5SDimitry Andric return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
14330b57cec5SDimitry Andric }
14340b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
14350b57cec5SDimitry Andric }
14360b57cec5SDimitry Andric
EmitUnsupportedRValue(const Expr * E,const char * Name)14370b57cec5SDimitry Andric RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
14380b57cec5SDimitry Andric const char *Name) {
14390b57cec5SDimitry Andric ErrorUnsupported(E, Name);
14400b57cec5SDimitry Andric return GetUndefRValue(E->getType());
14410b57cec5SDimitry Andric }
14420b57cec5SDimitry Andric
EmitUnsupportedLValue(const Expr * E,const char * Name)14430b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
14440b57cec5SDimitry Andric const char *Name) {
14450b57cec5SDimitry Andric ErrorUnsupported(E, Name);
144681ad6265SDimitry Andric llvm::Type *ElTy = ConvertType(E->getType());
1447c9157d92SDimitry Andric llvm::Type *Ty = UnqualPtrTy;
144881ad6265SDimitry Andric return MakeAddrLValue(
144981ad6265SDimitry Andric Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
14500b57cec5SDimitry Andric }
14510b57cec5SDimitry Andric
IsWrappedCXXThis(const Expr * Obj)14520b57cec5SDimitry Andric bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
14530b57cec5SDimitry Andric const Expr *Base = Obj;
14540b57cec5SDimitry Andric while (!isa<CXXThisExpr>(Base)) {
14550b57cec5SDimitry Andric // The result of a dynamic_cast can be null.
14560b57cec5SDimitry Andric if (isa<CXXDynamicCastExpr>(Base))
14570b57cec5SDimitry Andric return false;
14580b57cec5SDimitry Andric
14590b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(Base)) {
14600b57cec5SDimitry Andric Base = CE->getSubExpr();
14610b57cec5SDimitry Andric } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
14620b57cec5SDimitry Andric Base = PE->getSubExpr();
14630b57cec5SDimitry Andric } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
14640b57cec5SDimitry Andric if (UO->getOpcode() == UO_Extension)
14650b57cec5SDimitry Andric Base = UO->getSubExpr();
14660b57cec5SDimitry Andric else
14670b57cec5SDimitry Andric return false;
14680b57cec5SDimitry Andric } else {
14690b57cec5SDimitry Andric return false;
14700b57cec5SDimitry Andric }
14710b57cec5SDimitry Andric }
14720b57cec5SDimitry Andric return true;
14730b57cec5SDimitry Andric }
14740b57cec5SDimitry Andric
EmitCheckedLValue(const Expr * E,TypeCheckKind TCK)14750b57cec5SDimitry Andric LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
14760b57cec5SDimitry Andric LValue LV;
14770b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
14780b57cec5SDimitry Andric LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
14790b57cec5SDimitry Andric else
14800b57cec5SDimitry Andric LV = EmitLValue(E);
14810b57cec5SDimitry Andric if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
14820b57cec5SDimitry Andric SanitizerSet SkippedChecks;
14830b57cec5SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(E)) {
14840b57cec5SDimitry Andric bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
14850b57cec5SDimitry Andric if (IsBaseCXXThis)
14860b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Alignment, true);
14870b57cec5SDimitry Andric if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
14880b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, true);
14890b57cec5SDimitry Andric }
1490480093f4SDimitry Andric EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1491480093f4SDimitry Andric LV.getAlignment(), SkippedChecks);
14920b57cec5SDimitry Andric }
14930b57cec5SDimitry Andric return LV;
14940b57cec5SDimitry Andric }
14950b57cec5SDimitry Andric
14960b57cec5SDimitry Andric /// EmitLValue - Emit code to compute a designator that specifies the location
14970b57cec5SDimitry Andric /// of the expression.
14980b57cec5SDimitry Andric ///
14990b57cec5SDimitry Andric /// This can return one of two things: a simple address or a bitfield reference.
15000b57cec5SDimitry Andric /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
15010b57cec5SDimitry Andric /// an LLVM pointer type.
15020b57cec5SDimitry Andric ///
15030b57cec5SDimitry Andric /// If this returns a bitfield reference, nothing about the pointee type of the
15040b57cec5SDimitry Andric /// LLVM value is known: For example, it may not be a pointer to an integer.
15050b57cec5SDimitry Andric ///
15060b57cec5SDimitry Andric /// If this returns a normal address, and if the lvalue's C type is fixed size,
15070b57cec5SDimitry Andric /// this method guarantees that the returned pointer type will point to an LLVM
15080b57cec5SDimitry Andric /// type of the same size of the lvalue's type. If the lvalue has a variable
15090b57cec5SDimitry Andric /// length type, this is not possible.
15100b57cec5SDimitry Andric ///
EmitLValue(const Expr * E,KnownNonNull_t IsKnownNonNull)1511fe013be4SDimitry Andric LValue CodeGenFunction::EmitLValue(const Expr *E,
1512fe013be4SDimitry Andric KnownNonNull_t IsKnownNonNull) {
1513fe013be4SDimitry Andric LValue LV = EmitLValueHelper(E, IsKnownNonNull);
1514fe013be4SDimitry Andric if (IsKnownNonNull && !LV.isKnownNonNull())
1515fe013be4SDimitry Andric LV.setKnownNonNull();
1516fe013be4SDimitry Andric return LV;
1517fe013be4SDimitry Andric }
1518fe013be4SDimitry Andric
getConstantExprReferredType(const FullExpr * E,const ASTContext & Ctx)1519a58f00eaSDimitry Andric static QualType getConstantExprReferredType(const FullExpr *E,
1520a58f00eaSDimitry Andric const ASTContext &Ctx) {
1521a58f00eaSDimitry Andric const Expr *SE = E->getSubExpr()->IgnoreImplicit();
1522a58f00eaSDimitry Andric if (isa<OpaqueValueExpr>(SE))
1523a58f00eaSDimitry Andric return SE->getType();
1524a58f00eaSDimitry Andric return cast<CallExpr>(SE)->getCallReturnType(Ctx)->getPointeeType();
1525a58f00eaSDimitry Andric }
1526a58f00eaSDimitry Andric
EmitLValueHelper(const Expr * E,KnownNonNull_t IsKnownNonNull)1527fe013be4SDimitry Andric LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1528fe013be4SDimitry Andric KnownNonNull_t IsKnownNonNull) {
15290b57cec5SDimitry Andric ApplyDebugLocation DL(*this, E);
15300b57cec5SDimitry Andric switch (E->getStmtClass()) {
15310b57cec5SDimitry Andric default: return EmitUnsupportedLValue(E, "l-value expression");
15320b57cec5SDimitry Andric
15330b57cec5SDimitry Andric case Expr::ObjCPropertyRefExprClass:
15340b57cec5SDimitry Andric llvm_unreachable("cannot emit a property reference directly");
15350b57cec5SDimitry Andric
15360b57cec5SDimitry Andric case Expr::ObjCSelectorExprClass:
15370b57cec5SDimitry Andric return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
15380b57cec5SDimitry Andric case Expr::ObjCIsaExprClass:
15390b57cec5SDimitry Andric return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
15400b57cec5SDimitry Andric case Expr::BinaryOperatorClass:
15410b57cec5SDimitry Andric return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
15420b57cec5SDimitry Andric case Expr::CompoundAssignOperatorClass: {
15430b57cec5SDimitry Andric QualType Ty = E->getType();
15440b57cec5SDimitry Andric if (const AtomicType *AT = Ty->getAs<AtomicType>())
15450b57cec5SDimitry Andric Ty = AT->getValueType();
15460b57cec5SDimitry Andric if (!Ty->isAnyComplexType())
15470b57cec5SDimitry Andric return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
15480b57cec5SDimitry Andric return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
15490b57cec5SDimitry Andric }
15500b57cec5SDimitry Andric case Expr::CallExprClass:
15510b57cec5SDimitry Andric case Expr::CXXMemberCallExprClass:
15520b57cec5SDimitry Andric case Expr::CXXOperatorCallExprClass:
15530b57cec5SDimitry Andric case Expr::UserDefinedLiteralClass:
15540b57cec5SDimitry Andric return EmitCallExprLValue(cast<CallExpr>(E));
1555a7dea167SDimitry Andric case Expr::CXXRewrittenBinaryOperatorClass:
1556fe013be4SDimitry Andric return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
1557fe013be4SDimitry Andric IsKnownNonNull);
15580b57cec5SDimitry Andric case Expr::VAArgExprClass:
15590b57cec5SDimitry Andric return EmitVAArgExprLValue(cast<VAArgExpr>(E));
15600b57cec5SDimitry Andric case Expr::DeclRefExprClass:
15610b57cec5SDimitry Andric return EmitDeclRefLValue(cast<DeclRefExpr>(E));
15625ffd83dbSDimitry Andric case Expr::ConstantExprClass: {
15635ffd83dbSDimitry Andric const ConstantExpr *CE = cast<ConstantExpr>(E);
15645ffd83dbSDimitry Andric if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
1565a58f00eaSDimitry Andric QualType RetType = getConstantExprReferredType(CE, getContext());
15665ffd83dbSDimitry Andric return MakeNaturalAlignAddrLValue(Result, RetType);
15675ffd83dbSDimitry Andric }
1568fe013be4SDimitry Andric return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull);
15695ffd83dbSDimitry Andric }
15700b57cec5SDimitry Andric case Expr::ParenExprClass:
1571fe013be4SDimitry Andric return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull);
15720b57cec5SDimitry Andric case Expr::GenericSelectionExprClass:
1573fe013be4SDimitry Andric return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(),
1574fe013be4SDimitry Andric IsKnownNonNull);
15750b57cec5SDimitry Andric case Expr::PredefinedExprClass:
15760b57cec5SDimitry Andric return EmitPredefinedLValue(cast<PredefinedExpr>(E));
15770b57cec5SDimitry Andric case Expr::StringLiteralClass:
15780b57cec5SDimitry Andric return EmitStringLiteralLValue(cast<StringLiteral>(E));
15790b57cec5SDimitry Andric case Expr::ObjCEncodeExprClass:
15800b57cec5SDimitry Andric return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
15810b57cec5SDimitry Andric case Expr::PseudoObjectExprClass:
15820b57cec5SDimitry Andric return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
15830b57cec5SDimitry Andric case Expr::InitListExprClass:
15840b57cec5SDimitry Andric return EmitInitListLValue(cast<InitListExpr>(E));
15850b57cec5SDimitry Andric case Expr::CXXTemporaryObjectExprClass:
15860b57cec5SDimitry Andric case Expr::CXXConstructExprClass:
15870b57cec5SDimitry Andric return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
15880b57cec5SDimitry Andric case Expr::CXXBindTemporaryExprClass:
15890b57cec5SDimitry Andric return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
15900b57cec5SDimitry Andric case Expr::CXXUuidofExprClass:
15910b57cec5SDimitry Andric return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
15920b57cec5SDimitry Andric case Expr::LambdaExprClass:
15930b57cec5SDimitry Andric return EmitAggExprToLValue(E);
15940b57cec5SDimitry Andric
15950b57cec5SDimitry Andric case Expr::ExprWithCleanupsClass: {
15960b57cec5SDimitry Andric const auto *cleanups = cast<ExprWithCleanups>(E);
15970b57cec5SDimitry Andric RunCleanupsScope Scope(*this);
1598fe013be4SDimitry Andric LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
15990b57cec5SDimitry Andric if (LV.isSimple()) {
16000b57cec5SDimitry Andric // Defend against branches out of gnu statement expressions surrounded by
16010b57cec5SDimitry Andric // cleanups.
16020eae32dcSDimitry Andric Address Addr = LV.getAddress(*this);
16030eae32dcSDimitry Andric llvm::Value *V = Addr.getPointer();
16040b57cec5SDimitry Andric Scope.ForceCleanup({&V});
1605fe013be4SDimitry Andric return LValue::MakeAddr(Addr.withPointer(V, Addr.isKnownNonNull()),
1606fe013be4SDimitry Andric LV.getType(), getContext(), LV.getBaseInfo(),
1607fe013be4SDimitry Andric LV.getTBAAInfo());
16080b57cec5SDimitry Andric }
16090b57cec5SDimitry Andric // FIXME: Is it possible to create an ExprWithCleanups that produces a
16100b57cec5SDimitry Andric // bitfield lvalue or some other non-simple lvalue?
16110b57cec5SDimitry Andric return LV;
16120b57cec5SDimitry Andric }
16130b57cec5SDimitry Andric
16140b57cec5SDimitry Andric case Expr::CXXDefaultArgExprClass: {
16150b57cec5SDimitry Andric auto *DAE = cast<CXXDefaultArgExpr>(E);
16160b57cec5SDimitry Andric CXXDefaultArgExprScope Scope(*this, DAE);
1617fe013be4SDimitry Andric return EmitLValue(DAE->getExpr(), IsKnownNonNull);
16180b57cec5SDimitry Andric }
16190b57cec5SDimitry Andric case Expr::CXXDefaultInitExprClass: {
16200b57cec5SDimitry Andric auto *DIE = cast<CXXDefaultInitExpr>(E);
16210b57cec5SDimitry Andric CXXDefaultInitExprScope Scope(*this, DIE);
1622fe013be4SDimitry Andric return EmitLValue(DIE->getExpr(), IsKnownNonNull);
16230b57cec5SDimitry Andric }
16240b57cec5SDimitry Andric case Expr::CXXTypeidExprClass:
16250b57cec5SDimitry Andric return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
16260b57cec5SDimitry Andric
16270b57cec5SDimitry Andric case Expr::ObjCMessageExprClass:
16280b57cec5SDimitry Andric return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
16290b57cec5SDimitry Andric case Expr::ObjCIvarRefExprClass:
16300b57cec5SDimitry Andric return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
16310b57cec5SDimitry Andric case Expr::StmtExprClass:
16320b57cec5SDimitry Andric return EmitStmtExprLValue(cast<StmtExpr>(E));
16330b57cec5SDimitry Andric case Expr::UnaryOperatorClass:
16340b57cec5SDimitry Andric return EmitUnaryOpLValue(cast<UnaryOperator>(E));
16350b57cec5SDimitry Andric case Expr::ArraySubscriptExprClass:
16360b57cec5SDimitry Andric return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
16375ffd83dbSDimitry Andric case Expr::MatrixSubscriptExprClass:
16385ffd83dbSDimitry Andric return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
16390b57cec5SDimitry Andric case Expr::OMPArraySectionExprClass:
16400b57cec5SDimitry Andric return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
16410b57cec5SDimitry Andric case Expr::ExtVectorElementExprClass:
16420b57cec5SDimitry Andric return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1643bdd1243dSDimitry Andric case Expr::CXXThisExprClass:
1644bdd1243dSDimitry Andric return MakeAddrLValue(LoadCXXThisAddress(), E->getType());
16450b57cec5SDimitry Andric case Expr::MemberExprClass:
16460b57cec5SDimitry Andric return EmitMemberExpr(cast<MemberExpr>(E));
16470b57cec5SDimitry Andric case Expr::CompoundLiteralExprClass:
16480b57cec5SDimitry Andric return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
16490b57cec5SDimitry Andric case Expr::ConditionalOperatorClass:
16500b57cec5SDimitry Andric return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
16510b57cec5SDimitry Andric case Expr::BinaryConditionalOperatorClass:
16520b57cec5SDimitry Andric return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
16530b57cec5SDimitry Andric case Expr::ChooseExprClass:
1654fe013be4SDimitry Andric return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull);
16550b57cec5SDimitry Andric case Expr::OpaqueValueExprClass:
16560b57cec5SDimitry Andric return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
16570b57cec5SDimitry Andric case Expr::SubstNonTypeTemplateParmExprClass:
1658fe013be4SDimitry Andric return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
1659fe013be4SDimitry Andric IsKnownNonNull);
16600b57cec5SDimitry Andric case Expr::ImplicitCastExprClass:
16610b57cec5SDimitry Andric case Expr::CStyleCastExprClass:
16620b57cec5SDimitry Andric case Expr::CXXFunctionalCastExprClass:
16630b57cec5SDimitry Andric case Expr::CXXStaticCastExprClass:
16640b57cec5SDimitry Andric case Expr::CXXDynamicCastExprClass:
16650b57cec5SDimitry Andric case Expr::CXXReinterpretCastExprClass:
16660b57cec5SDimitry Andric case Expr::CXXConstCastExprClass:
16675ffd83dbSDimitry Andric case Expr::CXXAddrspaceCastExprClass:
16680b57cec5SDimitry Andric case Expr::ObjCBridgedCastExprClass:
16690b57cec5SDimitry Andric return EmitCastLValue(cast<CastExpr>(E));
16700b57cec5SDimitry Andric
16710b57cec5SDimitry Andric case Expr::MaterializeTemporaryExprClass:
16720b57cec5SDimitry Andric return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
16730b57cec5SDimitry Andric
16740b57cec5SDimitry Andric case Expr::CoawaitExprClass:
16750b57cec5SDimitry Andric return EmitCoawaitLValue(cast<CoawaitExpr>(E));
16760b57cec5SDimitry Andric case Expr::CoyieldExprClass:
16770b57cec5SDimitry Andric return EmitCoyieldLValue(cast<CoyieldExpr>(E));
16780b57cec5SDimitry Andric }
16790b57cec5SDimitry Andric }
16800b57cec5SDimitry Andric
16810b57cec5SDimitry Andric /// Given an object of the given canonical type, can we safely copy a
16820b57cec5SDimitry Andric /// value out of it based on its initializer?
isConstantEmittableObjectType(QualType type)16830b57cec5SDimitry Andric static bool isConstantEmittableObjectType(QualType type) {
16840b57cec5SDimitry Andric assert(type.isCanonical());
16850b57cec5SDimitry Andric assert(!type->isReferenceType());
16860b57cec5SDimitry Andric
16870b57cec5SDimitry Andric // Must be const-qualified but non-volatile.
16880b57cec5SDimitry Andric Qualifiers qs = type.getLocalQualifiers();
16890b57cec5SDimitry Andric if (!qs.hasConst() || qs.hasVolatile()) return false;
16900b57cec5SDimitry Andric
16910b57cec5SDimitry Andric // Otherwise, all object types satisfy this except C++ classes with
16920b57cec5SDimitry Andric // mutable subobjects or non-trivial copy/destroy behavior.
16930b57cec5SDimitry Andric if (const auto *RT = dyn_cast<RecordType>(type))
16940b57cec5SDimitry Andric if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
16950b57cec5SDimitry Andric if (RD->hasMutableFields() || !RD->isTrivial())
16960b57cec5SDimitry Andric return false;
16970b57cec5SDimitry Andric
16980b57cec5SDimitry Andric return true;
16990b57cec5SDimitry Andric }
17000b57cec5SDimitry Andric
17010b57cec5SDimitry Andric /// Can we constant-emit a load of a reference to a variable of the
17020b57cec5SDimitry Andric /// given type? This is different from predicates like
17030b57cec5SDimitry Andric /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
17040b57cec5SDimitry Andric /// in situations that don't necessarily satisfy the language's rules
17050b57cec5SDimitry Andric /// for this (e.g. C++'s ODR-use rules). For example, we want to able
17060b57cec5SDimitry Andric /// to do this with const float variables even if those variables
17070b57cec5SDimitry Andric /// aren't marked 'constexpr'.
17080b57cec5SDimitry Andric enum ConstantEmissionKind {
17090b57cec5SDimitry Andric CEK_None,
17100b57cec5SDimitry Andric CEK_AsReferenceOnly,
17110b57cec5SDimitry Andric CEK_AsValueOrReference,
17120b57cec5SDimitry Andric CEK_AsValueOnly
17130b57cec5SDimitry Andric };
checkVarTypeForConstantEmission(QualType type)17140b57cec5SDimitry Andric static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
17150b57cec5SDimitry Andric type = type.getCanonicalType();
17160b57cec5SDimitry Andric if (const auto *ref = dyn_cast<ReferenceType>(type)) {
17170b57cec5SDimitry Andric if (isConstantEmittableObjectType(ref->getPointeeType()))
17180b57cec5SDimitry Andric return CEK_AsValueOrReference;
17190b57cec5SDimitry Andric return CEK_AsReferenceOnly;
17200b57cec5SDimitry Andric }
17210b57cec5SDimitry Andric if (isConstantEmittableObjectType(type))
17220b57cec5SDimitry Andric return CEK_AsValueOnly;
17230b57cec5SDimitry Andric return CEK_None;
17240b57cec5SDimitry Andric }
17250b57cec5SDimitry Andric
17260b57cec5SDimitry Andric /// Try to emit a reference to the given value without producing it as
17270b57cec5SDimitry Andric /// an l-value. This is just an optimization, but it avoids us needing
17280b57cec5SDimitry Andric /// to emit global copies of variables if they're named without triggering
17290b57cec5SDimitry Andric /// a formal use in a context where we can't emit a direct reference to them,
17300b57cec5SDimitry Andric /// for instance if a block or lambda or a member of a local class uses a
17310b57cec5SDimitry Andric /// const int variable or constexpr variable from an enclosing function.
17320b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
tryEmitAsConstant(DeclRefExpr * refExpr)17330b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
17340b57cec5SDimitry Andric ValueDecl *value = refExpr->getDecl();
17350b57cec5SDimitry Andric
17360b57cec5SDimitry Andric // The value needs to be an enum constant or a constant variable.
17370b57cec5SDimitry Andric ConstantEmissionKind CEK;
17380b57cec5SDimitry Andric if (isa<ParmVarDecl>(value)) {
17390b57cec5SDimitry Andric CEK = CEK_None;
17400b57cec5SDimitry Andric } else if (auto *var = dyn_cast<VarDecl>(value)) {
17410b57cec5SDimitry Andric CEK = checkVarTypeForConstantEmission(var->getType());
17420b57cec5SDimitry Andric } else if (isa<EnumConstantDecl>(value)) {
17430b57cec5SDimitry Andric CEK = CEK_AsValueOnly;
17440b57cec5SDimitry Andric } else {
17450b57cec5SDimitry Andric CEK = CEK_None;
17460b57cec5SDimitry Andric }
17470b57cec5SDimitry Andric if (CEK == CEK_None) return ConstantEmission();
17480b57cec5SDimitry Andric
17490b57cec5SDimitry Andric Expr::EvalResult result;
17500b57cec5SDimitry Andric bool resultIsReference;
17510b57cec5SDimitry Andric QualType resultType;
17520b57cec5SDimitry Andric
17530b57cec5SDimitry Andric // It's best to evaluate all the way as an r-value if that's permitted.
17540b57cec5SDimitry Andric if (CEK != CEK_AsReferenceOnly &&
17550b57cec5SDimitry Andric refExpr->EvaluateAsRValue(result, getContext())) {
17560b57cec5SDimitry Andric resultIsReference = false;
17570b57cec5SDimitry Andric resultType = refExpr->getType();
17580b57cec5SDimitry Andric
17590b57cec5SDimitry Andric // Otherwise, try to evaluate as an l-value.
17600b57cec5SDimitry Andric } else if (CEK != CEK_AsValueOnly &&
17610b57cec5SDimitry Andric refExpr->EvaluateAsLValue(result, getContext())) {
17620b57cec5SDimitry Andric resultIsReference = true;
17630b57cec5SDimitry Andric resultType = value->getType();
17640b57cec5SDimitry Andric
17650b57cec5SDimitry Andric // Failure.
17660b57cec5SDimitry Andric } else {
17670b57cec5SDimitry Andric return ConstantEmission();
17680b57cec5SDimitry Andric }
17690b57cec5SDimitry Andric
17700b57cec5SDimitry Andric // In any case, if the initializer has side-effects, abandon ship.
17710b57cec5SDimitry Andric if (result.HasSideEffects)
17720b57cec5SDimitry Andric return ConstantEmission();
17730b57cec5SDimitry Andric
1774e8d8bef9SDimitry Andric // In CUDA/HIP device compilation, a lambda may capture a reference variable
1775e8d8bef9SDimitry Andric // referencing a global host variable by copy. In this case the lambda should
1776e8d8bef9SDimitry Andric // make a copy of the value of the global host variable. The DRE of the
1777e8d8bef9SDimitry Andric // captured reference variable cannot be emitted as load from the host
1778e8d8bef9SDimitry Andric // global variable as compile time constant, since the host variable is not
1779e8d8bef9SDimitry Andric // accessible on device. The DRE of the captured reference variable has to be
1780e8d8bef9SDimitry Andric // loaded from captures.
1781e8d8bef9SDimitry Andric if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1782e8d8bef9SDimitry Andric refExpr->refersToEnclosingVariableOrCapture()) {
1783e8d8bef9SDimitry Andric auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1784e8d8bef9SDimitry Andric if (MD && MD->getParent()->isLambda() &&
1785e8d8bef9SDimitry Andric MD->getOverloadedOperator() == OO_Call) {
1786e8d8bef9SDimitry Andric const APValue::LValueBase &base = result.Val.getLValueBase();
1787e8d8bef9SDimitry Andric if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1788e8d8bef9SDimitry Andric if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1789e8d8bef9SDimitry Andric if (!VD->hasAttr<CUDADeviceAttr>()) {
1790e8d8bef9SDimitry Andric return ConstantEmission();
1791e8d8bef9SDimitry Andric }
1792e8d8bef9SDimitry Andric }
1793e8d8bef9SDimitry Andric }
1794e8d8bef9SDimitry Andric }
1795e8d8bef9SDimitry Andric }
1796e8d8bef9SDimitry Andric
17970b57cec5SDimitry Andric // Emit as a constant.
17980b57cec5SDimitry Andric auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
17990b57cec5SDimitry Andric result.Val, resultType);
18000b57cec5SDimitry Andric
18010b57cec5SDimitry Andric // Make sure we emit a debug reference to the global variable.
18020b57cec5SDimitry Andric // This should probably fire even for
18030b57cec5SDimitry Andric if (isa<VarDecl>(value)) {
18040b57cec5SDimitry Andric if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
18050b57cec5SDimitry Andric EmitDeclRefExprDbgValue(refExpr, result.Val);
18060b57cec5SDimitry Andric } else {
18070b57cec5SDimitry Andric assert(isa<EnumConstantDecl>(value));
18080b57cec5SDimitry Andric EmitDeclRefExprDbgValue(refExpr, result.Val);
18090b57cec5SDimitry Andric }
18100b57cec5SDimitry Andric
18110b57cec5SDimitry Andric // If we emitted a reference constant, we need to dereference that.
18120b57cec5SDimitry Andric if (resultIsReference)
18130b57cec5SDimitry Andric return ConstantEmission::forReference(C);
18140b57cec5SDimitry Andric
18150b57cec5SDimitry Andric return ConstantEmission::forValue(C);
18160b57cec5SDimitry Andric }
18170b57cec5SDimitry Andric
tryToConvertMemberExprToDeclRefExpr(CodeGenFunction & CGF,const MemberExpr * ME)18180b57cec5SDimitry Andric static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
18190b57cec5SDimitry Andric const MemberExpr *ME) {
18200b57cec5SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
18210b57cec5SDimitry Andric // Try to emit static variable member expressions as DREs.
18220b57cec5SDimitry Andric return DeclRefExpr::Create(
18230b57cec5SDimitry Andric CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
18240b57cec5SDimitry Andric /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
18250b57cec5SDimitry Andric ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
18260b57cec5SDimitry Andric }
18270b57cec5SDimitry Andric return nullptr;
18280b57cec5SDimitry Andric }
18290b57cec5SDimitry Andric
18300b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
tryEmitAsConstant(const MemberExpr * ME)18310b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
18320b57cec5SDimitry Andric if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
18330b57cec5SDimitry Andric return tryEmitAsConstant(DRE);
18340b57cec5SDimitry Andric return ConstantEmission();
18350b57cec5SDimitry Andric }
18360b57cec5SDimitry Andric
emitScalarConstant(const CodeGenFunction::ConstantEmission & Constant,Expr * E)18370b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitScalarConstant(
18380b57cec5SDimitry Andric const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
18390b57cec5SDimitry Andric assert(Constant && "not a constant");
18400b57cec5SDimitry Andric if (Constant.isReference())
18410b57cec5SDimitry Andric return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
18420b57cec5SDimitry Andric E->getExprLoc())
18430b57cec5SDimitry Andric .getScalarVal();
18440b57cec5SDimitry Andric return Constant.getValue();
18450b57cec5SDimitry Andric }
18460b57cec5SDimitry Andric
EmitLoadOfScalar(LValue lvalue,SourceLocation Loc)18470b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
18480b57cec5SDimitry Andric SourceLocation Loc) {
1849480093f4SDimitry Andric return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
18500b57cec5SDimitry Andric lvalue.getType(), Loc, lvalue.getBaseInfo(),
18510b57cec5SDimitry Andric lvalue.getTBAAInfo(), lvalue.isNontemporal());
18520b57cec5SDimitry Andric }
18530b57cec5SDimitry Andric
hasBooleanRepresentation(QualType Ty)18540b57cec5SDimitry Andric static bool hasBooleanRepresentation(QualType Ty) {
18550b57cec5SDimitry Andric if (Ty->isBooleanType())
18560b57cec5SDimitry Andric return true;
18570b57cec5SDimitry Andric
18580b57cec5SDimitry Andric if (const EnumType *ET = Ty->getAs<EnumType>())
18590b57cec5SDimitry Andric return ET->getDecl()->getIntegerType()->isBooleanType();
18600b57cec5SDimitry Andric
18610b57cec5SDimitry Andric if (const AtomicType *AT = Ty->getAs<AtomicType>())
18620b57cec5SDimitry Andric return hasBooleanRepresentation(AT->getValueType());
18630b57cec5SDimitry Andric
18640b57cec5SDimitry Andric return false;
18650b57cec5SDimitry Andric }
18660b57cec5SDimitry Andric
getRangeForType(CodeGenFunction & CGF,QualType Ty,llvm::APInt & Min,llvm::APInt & End,bool StrictEnums,bool IsBool)18670b57cec5SDimitry Andric static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
18680b57cec5SDimitry Andric llvm::APInt &Min, llvm::APInt &End,
18690b57cec5SDimitry Andric bool StrictEnums, bool IsBool) {
18700b57cec5SDimitry Andric const EnumType *ET = Ty->getAs<EnumType>();
18710b57cec5SDimitry Andric bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
18720b57cec5SDimitry Andric ET && !ET->getDecl()->isFixed();
18730b57cec5SDimitry Andric if (!IsBool && !IsRegularCPlusPlusEnum)
18740b57cec5SDimitry Andric return false;
18750b57cec5SDimitry Andric
18760b57cec5SDimitry Andric if (IsBool) {
18770b57cec5SDimitry Andric Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
18780b57cec5SDimitry Andric End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
18790b57cec5SDimitry Andric } else {
18800b57cec5SDimitry Andric const EnumDecl *ED = ET->getDecl();
1881bdd1243dSDimitry Andric ED->getValueRange(End, Min);
18820b57cec5SDimitry Andric }
18830b57cec5SDimitry Andric return true;
18840b57cec5SDimitry Andric }
18850b57cec5SDimitry Andric
getRangeForLoadFromType(QualType Ty)18860b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
18870b57cec5SDimitry Andric llvm::APInt Min, End;
18880b57cec5SDimitry Andric if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
18890b57cec5SDimitry Andric hasBooleanRepresentation(Ty)))
18900b57cec5SDimitry Andric return nullptr;
18910b57cec5SDimitry Andric
18920b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext());
18930b57cec5SDimitry Andric return MDHelper.createRange(Min, End);
18940b57cec5SDimitry Andric }
18950b57cec5SDimitry Andric
EmitScalarRangeCheck(llvm::Value * Value,QualType Ty,SourceLocation Loc)18960b57cec5SDimitry Andric bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
18970b57cec5SDimitry Andric SourceLocation Loc) {
18980b57cec5SDimitry Andric bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
18990b57cec5SDimitry Andric bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
19000b57cec5SDimitry Andric if (!HasBoolCheck && !HasEnumCheck)
19010b57cec5SDimitry Andric return false;
19020b57cec5SDimitry Andric
19030b57cec5SDimitry Andric bool IsBool = hasBooleanRepresentation(Ty) ||
19040b57cec5SDimitry Andric NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
19050b57cec5SDimitry Andric bool NeedsBoolCheck = HasBoolCheck && IsBool;
19060b57cec5SDimitry Andric bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
19070b57cec5SDimitry Andric if (!NeedsBoolCheck && !NeedsEnumCheck)
19080b57cec5SDimitry Andric return false;
19090b57cec5SDimitry Andric
19100b57cec5SDimitry Andric // Single-bit booleans don't need to be checked. Special-case this to avoid
19110b57cec5SDimitry Andric // a bit width mismatch when handling bitfield values. This is handled by
19120b57cec5SDimitry Andric // EmitFromMemory for the non-bitfield case.
19130b57cec5SDimitry Andric if (IsBool &&
19140b57cec5SDimitry Andric cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
19150b57cec5SDimitry Andric return false;
19160b57cec5SDimitry Andric
19170b57cec5SDimitry Andric llvm::APInt Min, End;
19180b57cec5SDimitry Andric if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
19190b57cec5SDimitry Andric return true;
19200b57cec5SDimitry Andric
19210b57cec5SDimitry Andric auto &Ctx = getLLVMContext();
19220b57cec5SDimitry Andric SanitizerScope SanScope(this);
19230b57cec5SDimitry Andric llvm::Value *Check;
19240b57cec5SDimitry Andric --End;
19250b57cec5SDimitry Andric if (!Min) {
19260b57cec5SDimitry Andric Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
19270b57cec5SDimitry Andric } else {
19280b57cec5SDimitry Andric llvm::Value *Upper =
19290b57cec5SDimitry Andric Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
19300b57cec5SDimitry Andric llvm::Value *Lower =
19310b57cec5SDimitry Andric Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
19320b57cec5SDimitry Andric Check = Builder.CreateAnd(Upper, Lower);
19330b57cec5SDimitry Andric }
19340b57cec5SDimitry Andric llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
19350b57cec5SDimitry Andric EmitCheckTypeDescriptor(Ty)};
19360b57cec5SDimitry Andric SanitizerMask Kind =
19370b57cec5SDimitry Andric NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
19380b57cec5SDimitry Andric EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
19390b57cec5SDimitry Andric StaticArgs, EmitCheckValue(Value));
19400b57cec5SDimitry Andric return true;
19410b57cec5SDimitry Andric }
19420b57cec5SDimitry Andric
EmitLoadOfScalar(Address Addr,bool Volatile,QualType Ty,SourceLocation Loc,LValueBaseInfo BaseInfo,TBAAAccessInfo TBAAInfo,bool isNontemporal)19430b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
19440b57cec5SDimitry Andric QualType Ty,
19450b57cec5SDimitry Andric SourceLocation Loc,
19460b57cec5SDimitry Andric LValueBaseInfo BaseInfo,
19470b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo,
19480b57cec5SDimitry Andric bool isNontemporal) {
1949bdd1243dSDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getPointer()))
1950bdd1243dSDimitry Andric if (GV->isThreadLocal())
1951fe013be4SDimitry Andric Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
1952fe013be4SDimitry Andric NotKnownNonNull);
1953bdd1243dSDimitry Andric
195481ad6265SDimitry Andric if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
195581ad6265SDimitry Andric // Boolean vectors use `iN` as storage type.
195681ad6265SDimitry Andric if (ClangVecTy->isExtVectorBoolType()) {
195781ad6265SDimitry Andric llvm::Type *ValTy = ConvertType(Ty);
195881ad6265SDimitry Andric unsigned ValNumElems =
195981ad6265SDimitry Andric cast<llvm::FixedVectorType>(ValTy)->getNumElements();
196081ad6265SDimitry Andric // Load the `iP` storage object (P is the padded vector size).
196181ad6265SDimitry Andric auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
196281ad6265SDimitry Andric const auto *RawIntTy = RawIntV->getType();
196381ad6265SDimitry Andric assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
196481ad6265SDimitry Andric // Bitcast iP --> <P x i1>.
196581ad6265SDimitry Andric auto *PaddedVecTy = llvm::FixedVectorType::get(
196681ad6265SDimitry Andric Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
196781ad6265SDimitry Andric llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
196881ad6265SDimitry Andric // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
196981ad6265SDimitry Andric V = emitBoolVecConversion(V, ValNumElems, "extractvec");
19700b57cec5SDimitry Andric
197181ad6265SDimitry Andric return EmitFromMemory(V, Ty);
197281ad6265SDimitry Andric }
19730b57cec5SDimitry Andric
19740b57cec5SDimitry Andric // Handle vectors of size 3 like size 4 for better performance.
197581ad6265SDimitry Andric const llvm::Type *EltTy = Addr.getElementType();
197681ad6265SDimitry Andric const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
197781ad6265SDimitry Andric
197881ad6265SDimitry Andric if (!CGM.getCodeGenOpts().PreserveVec3Type && VTy->getNumElements() == 3) {
19790b57cec5SDimitry Andric
198081ad6265SDimitry Andric llvm::VectorType *vec4Ty =
198181ad6265SDimitry Andric llvm::FixedVectorType::get(VTy->getElementType(), 4);
1982fe013be4SDimitry Andric Address Cast = Addr.withElementType(vec4Ty);
19830b57cec5SDimitry Andric // Now load value.
19840b57cec5SDimitry Andric llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
19850b57cec5SDimitry Andric
19860b57cec5SDimitry Andric // Shuffle vector to get vec3.
198781ad6265SDimitry Andric V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2}, "extractVec");
19880b57cec5SDimitry Andric return EmitFromMemory(V, Ty);
19890b57cec5SDimitry Andric }
19900b57cec5SDimitry Andric }
19910b57cec5SDimitry Andric
19920b57cec5SDimitry Andric // Atomic operations have to be done on integral types.
19930b57cec5SDimitry Andric LValue AtomicLValue =
19940b57cec5SDimitry Andric LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
19950b57cec5SDimitry Andric if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
19960b57cec5SDimitry Andric return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
19970b57cec5SDimitry Andric }
19980b57cec5SDimitry Andric
19990b57cec5SDimitry Andric llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
20000b57cec5SDimitry Andric if (isNontemporal) {
20010b57cec5SDimitry Andric llvm::MDNode *Node = llvm::MDNode::get(
20020b57cec5SDimitry Andric Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2003fe013be4SDimitry Andric Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
20040b57cec5SDimitry Andric }
20050b57cec5SDimitry Andric
20060b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
20070b57cec5SDimitry Andric
20080b57cec5SDimitry Andric if (EmitScalarRangeCheck(Load, Ty, Loc)) {
20090b57cec5SDimitry Andric // In order to prevent the optimizer from throwing away the check, don't
20100b57cec5SDimitry Andric // attach range metadata to the load.
20110b57cec5SDimitry Andric } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
2012bdd1243dSDimitry Andric if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
20130b57cec5SDimitry Andric Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
2014bdd1243dSDimitry Andric Load->setMetadata(llvm::LLVMContext::MD_noundef,
2015bdd1243dSDimitry Andric llvm::MDNode::get(getLLVMContext(), std::nullopt));
2016bdd1243dSDimitry Andric }
20170b57cec5SDimitry Andric
20180b57cec5SDimitry Andric return EmitFromMemory(Load, Ty);
20190b57cec5SDimitry Andric }
20200b57cec5SDimitry Andric
EmitToMemory(llvm::Value * Value,QualType Ty)20210b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
20220b57cec5SDimitry Andric // Bool has a different representation in memory than in registers.
20230b57cec5SDimitry Andric if (hasBooleanRepresentation(Ty)) {
20240b57cec5SDimitry Andric // This should really always be an i1, but sometimes it's already
20250b57cec5SDimitry Andric // an i8, and it's awkward to track those cases down.
20260b57cec5SDimitry Andric if (Value->getType()->isIntegerTy(1))
20270b57cec5SDimitry Andric return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
20280b57cec5SDimitry Andric assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
20290b57cec5SDimitry Andric "wrong value rep of bool");
20300b57cec5SDimitry Andric }
20310b57cec5SDimitry Andric
20320b57cec5SDimitry Andric return Value;
20330b57cec5SDimitry Andric }
20340b57cec5SDimitry Andric
EmitFromMemory(llvm::Value * Value,QualType Ty)20350b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
20360b57cec5SDimitry Andric // Bool has a different representation in memory than in registers.
20370b57cec5SDimitry Andric if (hasBooleanRepresentation(Ty)) {
20380b57cec5SDimitry Andric assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
20390b57cec5SDimitry Andric "wrong value rep of bool");
20400b57cec5SDimitry Andric return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
20410b57cec5SDimitry Andric }
204281ad6265SDimitry Andric if (Ty->isExtVectorBoolType()) {
204381ad6265SDimitry Andric const auto *RawIntTy = Value->getType();
204481ad6265SDimitry Andric // Bitcast iP --> <P x i1>.
204581ad6265SDimitry Andric auto *PaddedVecTy = llvm::FixedVectorType::get(
204681ad6265SDimitry Andric Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
204781ad6265SDimitry Andric auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
204881ad6265SDimitry Andric // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
204981ad6265SDimitry Andric llvm::Type *ValTy = ConvertType(Ty);
205081ad6265SDimitry Andric unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
205181ad6265SDimitry Andric return emitBoolVecConversion(V, ValNumElems, "extractvec");
205281ad6265SDimitry Andric }
20530b57cec5SDimitry Andric
20540b57cec5SDimitry Andric return Value;
20550b57cec5SDimitry Andric }
20560b57cec5SDimitry Andric
20575ffd83dbSDimitry Andric // Convert the pointer of \p Addr to a pointer to a vector (the value type of
20585ffd83dbSDimitry Andric // MatrixType), if it points to a array (the memory type of MatrixType).
MaybeConvertMatrixAddress(Address Addr,CodeGenFunction & CGF,bool IsVector=true)20595ffd83dbSDimitry Andric static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
20605ffd83dbSDimitry Andric bool IsVector = true) {
20610eae32dcSDimitry Andric auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
20625ffd83dbSDimitry Andric if (ArrayTy && IsVector) {
20635ffd83dbSDimitry Andric auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
20645ffd83dbSDimitry Andric ArrayTy->getNumElements());
20655ffd83dbSDimitry Andric
2066fe013be4SDimitry Andric return Addr.withElementType(VectorTy);
20675ffd83dbSDimitry Andric }
20680eae32dcSDimitry Andric auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
20695ffd83dbSDimitry Andric if (VectorTy && !IsVector) {
2070e8d8bef9SDimitry Andric auto *ArrayTy = llvm::ArrayType::get(
2071e8d8bef9SDimitry Andric VectorTy->getElementType(),
2072e8d8bef9SDimitry Andric cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
20735ffd83dbSDimitry Andric
2074fe013be4SDimitry Andric return Addr.withElementType(ArrayTy);
20755ffd83dbSDimitry Andric }
20765ffd83dbSDimitry Andric
20775ffd83dbSDimitry Andric return Addr;
20785ffd83dbSDimitry Andric }
20795ffd83dbSDimitry Andric
20805ffd83dbSDimitry Andric // Emit a store of a matrix LValue. This may require casting the original
20815ffd83dbSDimitry Andric // pointer to memory address (ArrayType) to a pointer to the value type
20825ffd83dbSDimitry Andric // (VectorType).
EmitStoreOfMatrixScalar(llvm::Value * value,LValue lvalue,bool isInit,CodeGenFunction & CGF)20835ffd83dbSDimitry Andric static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
20845ffd83dbSDimitry Andric bool isInit, CodeGenFunction &CGF) {
20855ffd83dbSDimitry Andric Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
20865ffd83dbSDimitry Andric value->getType()->isVectorTy());
20875ffd83dbSDimitry Andric CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
20885ffd83dbSDimitry Andric lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
20895ffd83dbSDimitry Andric lvalue.isNontemporal());
20905ffd83dbSDimitry Andric }
20915ffd83dbSDimitry Andric
EmitStoreOfScalar(llvm::Value * Value,Address Addr,bool Volatile,QualType Ty,LValueBaseInfo BaseInfo,TBAAAccessInfo TBAAInfo,bool isInit,bool isNontemporal)20920b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
20930b57cec5SDimitry Andric bool Volatile, QualType Ty,
20940b57cec5SDimitry Andric LValueBaseInfo BaseInfo,
20950b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo,
20960b57cec5SDimitry Andric bool isInit, bool isNontemporal) {
2097bdd1243dSDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getPointer()))
2098bdd1243dSDimitry Andric if (GV->isThreadLocal())
2099fe013be4SDimitry Andric Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2100fe013be4SDimitry Andric NotKnownNonNull);
2101bdd1243dSDimitry Andric
21020b57cec5SDimitry Andric llvm::Type *SrcTy = Value->getType();
210381ad6265SDimitry Andric if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
210481ad6265SDimitry Andric auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy);
210581ad6265SDimitry Andric if (VecTy && ClangVecTy->isExtVectorBoolType()) {
210681ad6265SDimitry Andric auto *MemIntTy = cast<llvm::IntegerType>(Addr.getElementType());
210781ad6265SDimitry Andric // Expand to the memory bit width.
210881ad6265SDimitry Andric unsigned MemNumElems = MemIntTy->getPrimitiveSizeInBits();
210981ad6265SDimitry Andric // <N x i1> --> <P x i1>.
211081ad6265SDimitry Andric Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
211181ad6265SDimitry Andric // <P x i1> --> iP.
211281ad6265SDimitry Andric Value = Builder.CreateBitCast(Value, MemIntTy);
211381ad6265SDimitry Andric } else if (!CGM.getCodeGenOpts().PreserveVec3Type) {
21140b57cec5SDimitry Andric // Handle vec3 special.
2115e8d8bef9SDimitry Andric if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
21160b57cec5SDimitry Andric // Our source is a vec3, do a shuffle vector to make it a vec4.
2117e8d8bef9SDimitry Andric Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
21185ffd83dbSDimitry Andric "extractVec");
21195ffd83dbSDimitry Andric SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
21200b57cec5SDimitry Andric }
21210b57cec5SDimitry Andric if (Addr.getElementType() != SrcTy) {
2122fe013be4SDimitry Andric Addr = Addr.withElementType(SrcTy);
21230b57cec5SDimitry Andric }
21240b57cec5SDimitry Andric }
21250b57cec5SDimitry Andric }
21260b57cec5SDimitry Andric
21270b57cec5SDimitry Andric Value = EmitToMemory(Value, Ty);
21280b57cec5SDimitry Andric
21290b57cec5SDimitry Andric LValue AtomicLValue =
21300b57cec5SDimitry Andric LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
21310b57cec5SDimitry Andric if (Ty->isAtomicType() ||
21320b57cec5SDimitry Andric (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
21330b57cec5SDimitry Andric EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
21340b57cec5SDimitry Andric return;
21350b57cec5SDimitry Andric }
21360b57cec5SDimitry Andric
21370b57cec5SDimitry Andric llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
21380b57cec5SDimitry Andric if (isNontemporal) {
21390b57cec5SDimitry Andric llvm::MDNode *Node =
21400b57cec5SDimitry Andric llvm::MDNode::get(Store->getContext(),
21410b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2142fe013be4SDimitry Andric Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
21430b57cec5SDimitry Andric }
21440b57cec5SDimitry Andric
21450b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
21460b57cec5SDimitry Andric }
21470b57cec5SDimitry Andric
EmitStoreOfScalar(llvm::Value * value,LValue lvalue,bool isInit)21480b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
21490b57cec5SDimitry Andric bool isInit) {
21505ffd83dbSDimitry Andric if (lvalue.getType()->isConstantMatrixType()) {
21515ffd83dbSDimitry Andric EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
21525ffd83dbSDimitry Andric return;
21535ffd83dbSDimitry Andric }
21545ffd83dbSDimitry Andric
2155480093f4SDimitry Andric EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
21560b57cec5SDimitry Andric lvalue.getType(), lvalue.getBaseInfo(),
21570b57cec5SDimitry Andric lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
21580b57cec5SDimitry Andric }
21590b57cec5SDimitry Andric
21605ffd83dbSDimitry Andric // Emit a load of a LValue of matrix type. This may require casting the pointer
21615ffd83dbSDimitry Andric // to memory address (ArrayType) to a pointer to the value type (VectorType).
EmitLoadOfMatrixLValue(LValue LV,SourceLocation Loc,CodeGenFunction & CGF)21625ffd83dbSDimitry Andric static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
21635ffd83dbSDimitry Andric CodeGenFunction &CGF) {
21645ffd83dbSDimitry Andric assert(LV.getType()->isConstantMatrixType());
21655ffd83dbSDimitry Andric Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
21665ffd83dbSDimitry Andric LV.setAddress(Addr);
21675ffd83dbSDimitry Andric return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
21685ffd83dbSDimitry Andric }
21695ffd83dbSDimitry Andric
21700b57cec5SDimitry Andric /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
21710b57cec5SDimitry Andric /// method emits the address of the lvalue, then loads the result as an rvalue,
21720b57cec5SDimitry Andric /// returning the rvalue.
EmitLoadOfLValue(LValue LV,SourceLocation Loc)21730b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
21740b57cec5SDimitry Andric if (LV.isObjCWeak()) {
21750b57cec5SDimitry Andric // load of a __weak object.
2176480093f4SDimitry Andric Address AddrWeakObj = LV.getAddress(*this);
21770b57cec5SDimitry Andric return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
21780b57cec5SDimitry Andric AddrWeakObj));
21790b57cec5SDimitry Andric }
21800b57cec5SDimitry Andric if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
21810b57cec5SDimitry Andric // In MRC mode, we do a load+autorelease.
21820b57cec5SDimitry Andric if (!getLangOpts().ObjCAutoRefCount) {
2183480093f4SDimitry Andric return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
21840b57cec5SDimitry Andric }
21850b57cec5SDimitry Andric
21860b57cec5SDimitry Andric // In ARC mode, we load retained and then consume the value.
2187480093f4SDimitry Andric llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
21880b57cec5SDimitry Andric Object = EmitObjCConsumeObject(LV.getType(), Object);
21890b57cec5SDimitry Andric return RValue::get(Object);
21900b57cec5SDimitry Andric }
21910b57cec5SDimitry Andric
21920b57cec5SDimitry Andric if (LV.isSimple()) {
21930b57cec5SDimitry Andric assert(!LV.getType()->isFunctionType());
21940b57cec5SDimitry Andric
21955ffd83dbSDimitry Andric if (LV.getType()->isConstantMatrixType())
21965ffd83dbSDimitry Andric return EmitLoadOfMatrixLValue(LV, Loc, *this);
21975ffd83dbSDimitry Andric
21980b57cec5SDimitry Andric // Everything needs a load.
21990b57cec5SDimitry Andric return RValue::get(EmitLoadOfScalar(LV, Loc));
22000b57cec5SDimitry Andric }
22010b57cec5SDimitry Andric
22020b57cec5SDimitry Andric if (LV.isVectorElt()) {
22030b57cec5SDimitry Andric llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
22040b57cec5SDimitry Andric LV.isVolatileQualified());
22050b57cec5SDimitry Andric return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
22060b57cec5SDimitry Andric "vecext"));
22070b57cec5SDimitry Andric }
22080b57cec5SDimitry Andric
22090b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, either
22100b57cec5SDimitry Andric // shuffle the input or extract/insert them as appropriate.
22115ffd83dbSDimitry Andric if (LV.isExtVectorElt()) {
22120b57cec5SDimitry Andric return EmitLoadOfExtVectorElementLValue(LV);
22135ffd83dbSDimitry Andric }
22140b57cec5SDimitry Andric
22150b57cec5SDimitry Andric // Global Register variables always invoke intrinsics
22160b57cec5SDimitry Andric if (LV.isGlobalReg())
22170b57cec5SDimitry Andric return EmitLoadOfGlobalRegLValue(LV);
22180b57cec5SDimitry Andric
22195ffd83dbSDimitry Andric if (LV.isMatrixElt()) {
2220349cc55cSDimitry Andric llvm::Value *Idx = LV.getMatrixIdx();
2221349cc55cSDimitry Andric if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
222204eeddc0SDimitry Andric const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
222381ad6265SDimitry Andric llvm::MatrixBuilder MB(Builder);
2224349cc55cSDimitry Andric MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2225349cc55cSDimitry Andric }
22265ffd83dbSDimitry Andric llvm::LoadInst *Load =
22275ffd83dbSDimitry Andric Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
2228349cc55cSDimitry Andric return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
22295ffd83dbSDimitry Andric }
22305ffd83dbSDimitry Andric
22310b57cec5SDimitry Andric assert(LV.isBitField() && "Unknown LValue type!");
22320b57cec5SDimitry Andric return EmitLoadOfBitfieldLValue(LV, Loc);
22330b57cec5SDimitry Andric }
22340b57cec5SDimitry Andric
EmitLoadOfBitfieldLValue(LValue LV,SourceLocation Loc)22350b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
22360b57cec5SDimitry Andric SourceLocation Loc) {
22370b57cec5SDimitry Andric const CGBitFieldInfo &Info = LV.getBitFieldInfo();
22380b57cec5SDimitry Andric
22390b57cec5SDimitry Andric // Get the output type.
22400b57cec5SDimitry Andric llvm::Type *ResLTy = ConvertType(LV.getType());
22410b57cec5SDimitry Andric
22420b57cec5SDimitry Andric Address Ptr = LV.getBitFieldAddress();
2243e8d8bef9SDimitry Andric llvm::Value *Val =
2244e8d8bef9SDimitry Andric Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
22450b57cec5SDimitry Andric
2246e8d8bef9SDimitry Andric bool UseVolatile = LV.isVolatileQualified() &&
2247e8d8bef9SDimitry Andric Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2248e8d8bef9SDimitry Andric const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2249e8d8bef9SDimitry Andric const unsigned StorageSize =
2250e8d8bef9SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
22510b57cec5SDimitry Andric if (Info.IsSigned) {
2252e8d8bef9SDimitry Andric assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2253e8d8bef9SDimitry Andric unsigned HighBits = StorageSize - Offset - Info.Size;
22540b57cec5SDimitry Andric if (HighBits)
22550b57cec5SDimitry Andric Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2256e8d8bef9SDimitry Andric if (Offset + HighBits)
2257e8d8bef9SDimitry Andric Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
22580b57cec5SDimitry Andric } else {
2259e8d8bef9SDimitry Andric if (Offset)
2260e8d8bef9SDimitry Andric Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2261e8d8bef9SDimitry Andric if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2262e8d8bef9SDimitry Andric Val = Builder.CreateAnd(
2263e8d8bef9SDimitry Andric Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
22640b57cec5SDimitry Andric }
22650b57cec5SDimitry Andric Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
22660b57cec5SDimitry Andric EmitScalarRangeCheck(Val, LV.getType(), Loc);
22670b57cec5SDimitry Andric return RValue::get(Val);
22680b57cec5SDimitry Andric }
22690b57cec5SDimitry Andric
22700b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, create an
22710b57cec5SDimitry Andric // appropriate shufflevector.
EmitLoadOfExtVectorElementLValue(LValue LV)22720b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
22730b57cec5SDimitry Andric llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
22740b57cec5SDimitry Andric LV.isVolatileQualified());
22750b57cec5SDimitry Andric
2276c9157d92SDimitry Andric // HLSL allows treating scalars as one-element vectors. Converting the scalar
2277c9157d92SDimitry Andric // IR value to a vector here allows the rest of codegen to behave as normal.
2278c9157d92SDimitry Andric if (getLangOpts().HLSL && !Vec->getType()->isVectorTy()) {
2279c9157d92SDimitry Andric llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1);
2280c9157d92SDimitry Andric llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2281c9157d92SDimitry Andric Vec = Builder.CreateInsertElement(DstTy, Vec, Zero, "cast.splat");
2282c9157d92SDimitry Andric }
2283c9157d92SDimitry Andric
22840b57cec5SDimitry Andric const llvm::Constant *Elts = LV.getExtVectorElts();
22850b57cec5SDimitry Andric
22860b57cec5SDimitry Andric // If the result of the expression is a non-vector type, we must be extracting
22870b57cec5SDimitry Andric // a single element. Just codegen as an extractelement.
22880b57cec5SDimitry Andric const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
22890b57cec5SDimitry Andric if (!ExprVT) {
22900b57cec5SDimitry Andric unsigned InIdx = getAccessedFieldNo(0, Elts);
22910b57cec5SDimitry Andric llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
22920b57cec5SDimitry Andric return RValue::get(Builder.CreateExtractElement(Vec, Elt));
22930b57cec5SDimitry Andric }
22940b57cec5SDimitry Andric
22950b57cec5SDimitry Andric // Always use shuffle vector to try to retain the original program structure
22960b57cec5SDimitry Andric unsigned NumResultElts = ExprVT->getNumElements();
22970b57cec5SDimitry Andric
22985ffd83dbSDimitry Andric SmallVector<int, 4> Mask;
22990b57cec5SDimitry Andric for (unsigned i = 0; i != NumResultElts; ++i)
23005ffd83dbSDimitry Andric Mask.push_back(getAccessedFieldNo(i, Elts));
23010b57cec5SDimitry Andric
2302e8d8bef9SDimitry Andric Vec = Builder.CreateShuffleVector(Vec, Mask);
23030b57cec5SDimitry Andric return RValue::get(Vec);
23040b57cec5SDimitry Andric }
23050b57cec5SDimitry Andric
23060b57cec5SDimitry Andric /// Generates lvalue for partial ext_vector access.
EmitExtVectorElementLValue(LValue LV)23070b57cec5SDimitry Andric Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
23080b57cec5SDimitry Andric Address VectorAddress = LV.getExtVectorAddress();
2309480093f4SDimitry Andric QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
23100b57cec5SDimitry Andric llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
23110b57cec5SDimitry Andric
2312fe013be4SDimitry Andric Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy);
23130b57cec5SDimitry Andric
23140b57cec5SDimitry Andric const llvm::Constant *Elts = LV.getExtVectorElts();
23150b57cec5SDimitry Andric unsigned ix = getAccessedFieldNo(0, Elts);
23160b57cec5SDimitry Andric
23170b57cec5SDimitry Andric Address VectorBasePtrPlusIx =
23180b57cec5SDimitry Andric Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
23190b57cec5SDimitry Andric "vector.elt");
23200b57cec5SDimitry Andric
23210b57cec5SDimitry Andric return VectorBasePtrPlusIx;
23220b57cec5SDimitry Andric }
23230b57cec5SDimitry Andric
23240b57cec5SDimitry Andric /// Load of global gamed gegisters are always calls to intrinsics.
EmitLoadOfGlobalRegLValue(LValue LV)23250b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
23260b57cec5SDimitry Andric assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
23270b57cec5SDimitry Andric "Bad type for register variable");
23280b57cec5SDimitry Andric llvm::MDNode *RegName = cast<llvm::MDNode>(
23290b57cec5SDimitry Andric cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
23300b57cec5SDimitry Andric
23310b57cec5SDimitry Andric // We accept integer and pointer types only
23320b57cec5SDimitry Andric llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
23330b57cec5SDimitry Andric llvm::Type *Ty = OrigTy;
23340b57cec5SDimitry Andric if (OrigTy->isPointerTy())
23350b57cec5SDimitry Andric Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
23360b57cec5SDimitry Andric llvm::Type *Types[] = { Ty };
23370b57cec5SDimitry Andric
23380b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
23390b57cec5SDimitry Andric llvm::Value *Call = Builder.CreateCall(
23400b57cec5SDimitry Andric F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
23410b57cec5SDimitry Andric if (OrigTy->isPointerTy())
23420b57cec5SDimitry Andric Call = Builder.CreateIntToPtr(Call, OrigTy);
23430b57cec5SDimitry Andric return RValue::get(Call);
23440b57cec5SDimitry Andric }
23450b57cec5SDimitry Andric
23460b57cec5SDimitry Andric /// EmitStoreThroughLValue - Store the specified rvalue into the specified
23470b57cec5SDimitry Andric /// lvalue, where both are guaranteed to the have the same type, and that type
23480b57cec5SDimitry Andric /// is 'Ty'.
EmitStoreThroughLValue(RValue Src,LValue Dst,bool isInit)23490b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
23500b57cec5SDimitry Andric bool isInit) {
23510b57cec5SDimitry Andric if (!Dst.isSimple()) {
23520b57cec5SDimitry Andric if (Dst.isVectorElt()) {
23530b57cec5SDimitry Andric // Read/modify/write the vector, inserting the new element.
23540b57cec5SDimitry Andric llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
23550b57cec5SDimitry Andric Dst.isVolatileQualified());
235681ad6265SDimitry Andric auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
235781ad6265SDimitry Andric if (IRStoreTy) {
235881ad6265SDimitry Andric auto *IRVecTy = llvm::FixedVectorType::get(
235981ad6265SDimitry Andric Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
236081ad6265SDimitry Andric Vec = Builder.CreateBitCast(Vec, IRVecTy);
236181ad6265SDimitry Andric // iN --> <N x i1>.
236281ad6265SDimitry Andric }
23630b57cec5SDimitry Andric Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
23640b57cec5SDimitry Andric Dst.getVectorIdx(), "vecins");
236581ad6265SDimitry Andric if (IRStoreTy) {
236681ad6265SDimitry Andric // <N x i1> --> <iN>.
236781ad6265SDimitry Andric Vec = Builder.CreateBitCast(Vec, IRStoreTy);
236881ad6265SDimitry Andric }
23690b57cec5SDimitry Andric Builder.CreateStore(Vec, Dst.getVectorAddress(),
23700b57cec5SDimitry Andric Dst.isVolatileQualified());
23710b57cec5SDimitry Andric return;
23720b57cec5SDimitry Andric }
23730b57cec5SDimitry Andric
23740b57cec5SDimitry Andric // If this is an update of extended vector elements, insert them as
23750b57cec5SDimitry Andric // appropriate.
23760b57cec5SDimitry Andric if (Dst.isExtVectorElt())
23770b57cec5SDimitry Andric return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
23780b57cec5SDimitry Andric
23790b57cec5SDimitry Andric if (Dst.isGlobalReg())
23800b57cec5SDimitry Andric return EmitStoreThroughGlobalRegLValue(Src, Dst);
23810b57cec5SDimitry Andric
23825ffd83dbSDimitry Andric if (Dst.isMatrixElt()) {
2383349cc55cSDimitry Andric llvm::Value *Idx = Dst.getMatrixIdx();
2384349cc55cSDimitry Andric if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
238504eeddc0SDimitry Andric const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
238681ad6265SDimitry Andric llvm::MatrixBuilder MB(Builder);
2387349cc55cSDimitry Andric MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2388349cc55cSDimitry Andric }
2389349cc55cSDimitry Andric llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2390349cc55cSDimitry Andric llvm::Value *Vec =
2391349cc55cSDimitry Andric Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
23925ffd83dbSDimitry Andric Builder.CreateStore(Vec, Dst.getMatrixAddress(),
23935ffd83dbSDimitry Andric Dst.isVolatileQualified());
23945ffd83dbSDimitry Andric return;
23955ffd83dbSDimitry Andric }
23965ffd83dbSDimitry Andric
23970b57cec5SDimitry Andric assert(Dst.isBitField() && "Unknown LValue type");
23980b57cec5SDimitry Andric return EmitStoreThroughBitfieldLValue(Src, Dst);
23990b57cec5SDimitry Andric }
24000b57cec5SDimitry Andric
24010b57cec5SDimitry Andric // There's special magic for assigning into an ARC-qualified l-value.
24020b57cec5SDimitry Andric if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
24030b57cec5SDimitry Andric switch (Lifetime) {
24040b57cec5SDimitry Andric case Qualifiers::OCL_None:
24050b57cec5SDimitry Andric llvm_unreachable("present but none");
24060b57cec5SDimitry Andric
24070b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone:
24080b57cec5SDimitry Andric // nothing special
24090b57cec5SDimitry Andric break;
24100b57cec5SDimitry Andric
24110b57cec5SDimitry Andric case Qualifiers::OCL_Strong:
24120b57cec5SDimitry Andric if (isInit) {
24130b57cec5SDimitry Andric Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
24140b57cec5SDimitry Andric break;
24150b57cec5SDimitry Andric }
24160b57cec5SDimitry Andric EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
24170b57cec5SDimitry Andric return;
24180b57cec5SDimitry Andric
24190b57cec5SDimitry Andric case Qualifiers::OCL_Weak:
24200b57cec5SDimitry Andric if (isInit)
24210b57cec5SDimitry Andric // Initialize and then skip the primitive store.
2422480093f4SDimitry Andric EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
24230b57cec5SDimitry Andric else
2424480093f4SDimitry Andric EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2425480093f4SDimitry Andric /*ignore*/ true);
24260b57cec5SDimitry Andric return;
24270b57cec5SDimitry Andric
24280b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing:
24290b57cec5SDimitry Andric Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
24300b57cec5SDimitry Andric Src.getScalarVal()));
24310b57cec5SDimitry Andric // fall into the normal path
24320b57cec5SDimitry Andric break;
24330b57cec5SDimitry Andric }
24340b57cec5SDimitry Andric }
24350b57cec5SDimitry Andric
24360b57cec5SDimitry Andric if (Dst.isObjCWeak() && !Dst.isNonGC()) {
24370b57cec5SDimitry Andric // load of a __weak object.
2438480093f4SDimitry Andric Address LvalueDst = Dst.getAddress(*this);
24390b57cec5SDimitry Andric llvm::Value *src = Src.getScalarVal();
24400b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
24410b57cec5SDimitry Andric return;
24420b57cec5SDimitry Andric }
24430b57cec5SDimitry Andric
24440b57cec5SDimitry Andric if (Dst.isObjCStrong() && !Dst.isNonGC()) {
24450b57cec5SDimitry Andric // load of a __strong object.
2446480093f4SDimitry Andric Address LvalueDst = Dst.getAddress(*this);
24470b57cec5SDimitry Andric llvm::Value *src = Src.getScalarVal();
24480b57cec5SDimitry Andric if (Dst.isObjCIvar()) {
24490b57cec5SDimitry Andric assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
24500b57cec5SDimitry Andric llvm::Type *ResultType = IntPtrTy;
24510b57cec5SDimitry Andric Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
24520b57cec5SDimitry Andric llvm::Value *RHS = dst.getPointer();
24530b57cec5SDimitry Andric RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
24540b57cec5SDimitry Andric llvm::Value *LHS =
24550b57cec5SDimitry Andric Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
24560b57cec5SDimitry Andric "sub.ptr.lhs.cast");
24570b57cec5SDimitry Andric llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
24580b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
24590b57cec5SDimitry Andric BytesBetween);
24600b57cec5SDimitry Andric } else if (Dst.isGlobalObjCRef()) {
24610b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
24620b57cec5SDimitry Andric Dst.isThreadLocalRef());
24630b57cec5SDimitry Andric }
24640b57cec5SDimitry Andric else
24650b57cec5SDimitry Andric CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
24660b57cec5SDimitry Andric return;
24670b57cec5SDimitry Andric }
24680b57cec5SDimitry Andric
24690b57cec5SDimitry Andric assert(Src.isScalar() && "Can't emit an agg store with this method");
24700b57cec5SDimitry Andric EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
24710b57cec5SDimitry Andric }
24720b57cec5SDimitry Andric
EmitStoreThroughBitfieldLValue(RValue Src,LValue Dst,llvm::Value ** Result)24730b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
24740b57cec5SDimitry Andric llvm::Value **Result) {
24750b57cec5SDimitry Andric const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
24760b57cec5SDimitry Andric llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
24770b57cec5SDimitry Andric Address Ptr = Dst.getBitFieldAddress();
24780b57cec5SDimitry Andric
24790b57cec5SDimitry Andric // Get the source value, truncated to the width of the bit-field.
24800b57cec5SDimitry Andric llvm::Value *SrcVal = Src.getScalarVal();
24810b57cec5SDimitry Andric
24820b57cec5SDimitry Andric // Cast the source to the storage type and shift it into place.
24830b57cec5SDimitry Andric SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
24840b57cec5SDimitry Andric /*isSigned=*/false);
24850b57cec5SDimitry Andric llvm::Value *MaskedVal = SrcVal;
24860b57cec5SDimitry Andric
2487e8d8bef9SDimitry Andric const bool UseVolatile =
2488e8d8bef9SDimitry Andric CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2489e8d8bef9SDimitry Andric Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2490e8d8bef9SDimitry Andric const unsigned StorageSize =
2491e8d8bef9SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2492e8d8bef9SDimitry Andric const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
24930b57cec5SDimitry Andric // See if there are other bits in the bitfield's storage we'll need to load
24940b57cec5SDimitry Andric // and mask together with source before storing.
2495e8d8bef9SDimitry Andric if (StorageSize != Info.Size) {
2496e8d8bef9SDimitry Andric assert(StorageSize > Info.Size && "Invalid bitfield size.");
24970b57cec5SDimitry Andric llvm::Value *Val =
24980b57cec5SDimitry Andric Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
24990b57cec5SDimitry Andric
25000b57cec5SDimitry Andric // Mask the source value as needed.
25010b57cec5SDimitry Andric if (!hasBooleanRepresentation(Dst.getType()))
2502e8d8bef9SDimitry Andric SrcVal = Builder.CreateAnd(
2503e8d8bef9SDimitry Andric SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
25040b57cec5SDimitry Andric "bf.value");
25050b57cec5SDimitry Andric MaskedVal = SrcVal;
2506e8d8bef9SDimitry Andric if (Offset)
2507e8d8bef9SDimitry Andric SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
25080b57cec5SDimitry Andric
25090b57cec5SDimitry Andric // Mask out the original value.
2510e8d8bef9SDimitry Andric Val = Builder.CreateAnd(
2511e8d8bef9SDimitry Andric Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
25120b57cec5SDimitry Andric "bf.clear");
25130b57cec5SDimitry Andric
25140b57cec5SDimitry Andric // Or together the unchanged values and the source value.
25150b57cec5SDimitry Andric SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
25160b57cec5SDimitry Andric } else {
2517e8d8bef9SDimitry Andric assert(Offset == 0);
25185ffd83dbSDimitry Andric // According to the AACPS:
25195ffd83dbSDimitry Andric // When a volatile bit-field is written, and its container does not overlap
2520e8d8bef9SDimitry Andric // with any non-bit-field member, its container must be read exactly once
2521e8d8bef9SDimitry Andric // and written exactly once using the access width appropriate to the type
2522e8d8bef9SDimitry Andric // of the container. The two accesses are not atomic.
25235ffd83dbSDimitry Andric if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
25245ffd83dbSDimitry Andric CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
25255ffd83dbSDimitry Andric Builder.CreateLoad(Ptr, true, "bf.load");
25260b57cec5SDimitry Andric }
25270b57cec5SDimitry Andric
25280b57cec5SDimitry Andric // Write the new value back out.
25290b57cec5SDimitry Andric Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
25300b57cec5SDimitry Andric
25310b57cec5SDimitry Andric // Return the new value of the bit-field, if requested.
25320b57cec5SDimitry Andric if (Result) {
25330b57cec5SDimitry Andric llvm::Value *ResultVal = MaskedVal;
25340b57cec5SDimitry Andric
25350b57cec5SDimitry Andric // Sign extend the value if needed.
25360b57cec5SDimitry Andric if (Info.IsSigned) {
2537e8d8bef9SDimitry Andric assert(Info.Size <= StorageSize);
2538e8d8bef9SDimitry Andric unsigned HighBits = StorageSize - Info.Size;
25390b57cec5SDimitry Andric if (HighBits) {
25400b57cec5SDimitry Andric ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
25410b57cec5SDimitry Andric ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
25420b57cec5SDimitry Andric }
25430b57cec5SDimitry Andric }
25440b57cec5SDimitry Andric
25450b57cec5SDimitry Andric ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
25460b57cec5SDimitry Andric "bf.result.cast");
25470b57cec5SDimitry Andric *Result = EmitFromMemory(ResultVal, Dst.getType());
25480b57cec5SDimitry Andric }
25490b57cec5SDimitry Andric }
25500b57cec5SDimitry Andric
EmitStoreThroughExtVectorComponentLValue(RValue Src,LValue Dst)25510b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
25520b57cec5SDimitry Andric LValue Dst) {
2553c9157d92SDimitry Andric // HLSL allows storing to scalar values through ExtVector component LValues.
2554c9157d92SDimitry Andric // To support this we need to handle the case where the destination address is
2555c9157d92SDimitry Andric // a scalar.
2556c9157d92SDimitry Andric Address DstAddr = Dst.getExtVectorAddress();
2557c9157d92SDimitry Andric if (!DstAddr.getElementType()->isVectorTy()) {
2558c9157d92SDimitry Andric assert(!Dst.getType()->isVectorType() &&
2559c9157d92SDimitry Andric "this should only occur for non-vector l-values");
2560c9157d92SDimitry Andric Builder.CreateStore(Src.getScalarVal(), DstAddr, Dst.isVolatileQualified());
2561c9157d92SDimitry Andric return;
2562c9157d92SDimitry Andric }
2563c9157d92SDimitry Andric
25640b57cec5SDimitry Andric // This access turns into a read/modify/write of the vector. Load the input
25650b57cec5SDimitry Andric // value now.
2566c9157d92SDimitry Andric llvm::Value *Vec = Builder.CreateLoad(DstAddr, Dst.isVolatileQualified());
25670b57cec5SDimitry Andric const llvm::Constant *Elts = Dst.getExtVectorElts();
25680b57cec5SDimitry Andric
25690b57cec5SDimitry Andric llvm::Value *SrcVal = Src.getScalarVal();
25700b57cec5SDimitry Andric
25710b57cec5SDimitry Andric if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
25720b57cec5SDimitry Andric unsigned NumSrcElts = VTy->getNumElements();
25735ffd83dbSDimitry Andric unsigned NumDstElts =
2574e8d8bef9SDimitry Andric cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
25750b57cec5SDimitry Andric if (NumDstElts == NumSrcElts) {
25760b57cec5SDimitry Andric // Use shuffle vector is the src and destination are the same number of
25770b57cec5SDimitry Andric // elements and restore the vector mask since it is on the side it will be
25780b57cec5SDimitry Andric // stored.
25795ffd83dbSDimitry Andric SmallVector<int, 4> Mask(NumDstElts);
25800b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i)
25815ffd83dbSDimitry Andric Mask[getAccessedFieldNo(i, Elts)] = i;
25820b57cec5SDimitry Andric
2583e8d8bef9SDimitry Andric Vec = Builder.CreateShuffleVector(SrcVal, Mask);
25840b57cec5SDimitry Andric } else if (NumDstElts > NumSrcElts) {
25850b57cec5SDimitry Andric // Extended the source vector to the same length and then shuffle it
25860b57cec5SDimitry Andric // into the destination.
25870b57cec5SDimitry Andric // FIXME: since we're shuffling with undef, can we just use the indices
25880b57cec5SDimitry Andric // into that? This could be simpler.
25895ffd83dbSDimitry Andric SmallVector<int, 4> ExtMask;
25900b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i)
25915ffd83dbSDimitry Andric ExtMask.push_back(i);
25925ffd83dbSDimitry Andric ExtMask.resize(NumDstElts, -1);
2593e8d8bef9SDimitry Andric llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
25940b57cec5SDimitry Andric // build identity
25955ffd83dbSDimitry Andric SmallVector<int, 4> Mask;
25960b57cec5SDimitry Andric for (unsigned i = 0; i != NumDstElts; ++i)
25975ffd83dbSDimitry Andric Mask.push_back(i);
25980b57cec5SDimitry Andric
25990b57cec5SDimitry Andric // When the vector size is odd and .odd or .hi is used, the last element
26000b57cec5SDimitry Andric // of the Elts constant array will be one past the size of the vector.
26010b57cec5SDimitry Andric // Ignore the last element here, if it is greater than the mask size.
26020b57cec5SDimitry Andric if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
26030b57cec5SDimitry Andric NumSrcElts--;
26040b57cec5SDimitry Andric
26050b57cec5SDimitry Andric // modify when what gets shuffled in
26060b57cec5SDimitry Andric for (unsigned i = 0; i != NumSrcElts; ++i)
26075ffd83dbSDimitry Andric Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
26085ffd83dbSDimitry Andric Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
26090b57cec5SDimitry Andric } else {
26100b57cec5SDimitry Andric // We should never shorten the vector
26110b57cec5SDimitry Andric llvm_unreachable("unexpected shorten vector length");
26120b57cec5SDimitry Andric }
26130b57cec5SDimitry Andric } else {
2614c9157d92SDimitry Andric // If the Src is a scalar (not a vector), and the target is a vector it must
2615c9157d92SDimitry Andric // be updating one element.
26160b57cec5SDimitry Andric unsigned InIdx = getAccessedFieldNo(0, Elts);
26170b57cec5SDimitry Andric llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
26180b57cec5SDimitry Andric Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
26190b57cec5SDimitry Andric }
26200b57cec5SDimitry Andric
26210b57cec5SDimitry Andric Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
26220b57cec5SDimitry Andric Dst.isVolatileQualified());
26230b57cec5SDimitry Andric }
26240b57cec5SDimitry Andric
26250b57cec5SDimitry Andric /// Store of global named registers are always calls to intrinsics.
EmitStoreThroughGlobalRegLValue(RValue Src,LValue Dst)26260b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
26270b57cec5SDimitry Andric assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
26280b57cec5SDimitry Andric "Bad type for register variable");
26290b57cec5SDimitry Andric llvm::MDNode *RegName = cast<llvm::MDNode>(
26300b57cec5SDimitry Andric cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
26310b57cec5SDimitry Andric assert(RegName && "Register LValue is not metadata");
26320b57cec5SDimitry Andric
26330b57cec5SDimitry Andric // We accept integer and pointer types only
26340b57cec5SDimitry Andric llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
26350b57cec5SDimitry Andric llvm::Type *Ty = OrigTy;
26360b57cec5SDimitry Andric if (OrigTy->isPointerTy())
26370b57cec5SDimitry Andric Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
26380b57cec5SDimitry Andric llvm::Type *Types[] = { Ty };
26390b57cec5SDimitry Andric
26400b57cec5SDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
26410b57cec5SDimitry Andric llvm::Value *Value = Src.getScalarVal();
26420b57cec5SDimitry Andric if (OrigTy->isPointerTy())
26430b57cec5SDimitry Andric Value = Builder.CreatePtrToInt(Value, Ty);
26440b57cec5SDimitry Andric Builder.CreateCall(
26450b57cec5SDimitry Andric F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
26460b57cec5SDimitry Andric }
26470b57cec5SDimitry Andric
26480b57cec5SDimitry Andric // setObjCGCLValueClass - sets class of the lvalue for the purpose of
26490b57cec5SDimitry Andric // generating write-barries API. It is currently a global, ivar,
26500b57cec5SDimitry Andric // or neither.
setObjCGCLValueClass(const ASTContext & Ctx,const Expr * E,LValue & LV,bool IsMemberAccess=false)26510b57cec5SDimitry Andric static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
26520b57cec5SDimitry Andric LValue &LV,
26530b57cec5SDimitry Andric bool IsMemberAccess=false) {
26540b57cec5SDimitry Andric if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
26550b57cec5SDimitry Andric return;
26560b57cec5SDimitry Andric
26570b57cec5SDimitry Andric if (isa<ObjCIvarRefExpr>(E)) {
26580b57cec5SDimitry Andric QualType ExpTy = E->getType();
26590b57cec5SDimitry Andric if (IsMemberAccess && ExpTy->isPointerType()) {
26600b57cec5SDimitry Andric // If ivar is a structure pointer, assigning to field of
26610b57cec5SDimitry Andric // this struct follows gcc's behavior and makes it a non-ivar
26620b57cec5SDimitry Andric // writer-barrier conservatively.
2663a7dea167SDimitry Andric ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
26640b57cec5SDimitry Andric if (ExpTy->isRecordType()) {
26650b57cec5SDimitry Andric LV.setObjCIvar(false);
26660b57cec5SDimitry Andric return;
26670b57cec5SDimitry Andric }
26680b57cec5SDimitry Andric }
26690b57cec5SDimitry Andric LV.setObjCIvar(true);
26700b57cec5SDimitry Andric auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
26710b57cec5SDimitry Andric LV.setBaseIvarExp(Exp->getBase());
26720b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType());
26730b57cec5SDimitry Andric return;
26740b57cec5SDimitry Andric }
26750b57cec5SDimitry Andric
26760b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
26770b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
26780b57cec5SDimitry Andric if (VD->hasGlobalStorage()) {
26790b57cec5SDimitry Andric LV.setGlobalObjCRef(true);
26800b57cec5SDimitry Andric LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
26810b57cec5SDimitry Andric }
26820b57cec5SDimitry Andric }
26830b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType());
26840b57cec5SDimitry Andric return;
26850b57cec5SDimitry Andric }
26860b57cec5SDimitry Andric
26870b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
26880b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
26890b57cec5SDimitry Andric return;
26900b57cec5SDimitry Andric }
26910b57cec5SDimitry Andric
26920b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
26930b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
26940b57cec5SDimitry Andric if (LV.isObjCIvar()) {
26950b57cec5SDimitry Andric // If cast is to a structure pointer, follow gcc's behavior and make it
26960b57cec5SDimitry Andric // a non-ivar write-barrier.
26970b57cec5SDimitry Andric QualType ExpTy = E->getType();
26980b57cec5SDimitry Andric if (ExpTy->isPointerType())
2699a7dea167SDimitry Andric ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
27000b57cec5SDimitry Andric if (ExpTy->isRecordType())
27010b57cec5SDimitry Andric LV.setObjCIvar(false);
27020b57cec5SDimitry Andric }
27030b57cec5SDimitry Andric return;
27040b57cec5SDimitry Andric }
27050b57cec5SDimitry Andric
27060b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
27070b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
27080b57cec5SDimitry Andric return;
27090b57cec5SDimitry Andric }
27100b57cec5SDimitry Andric
27110b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
27120b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
27130b57cec5SDimitry Andric return;
27140b57cec5SDimitry Andric }
27150b57cec5SDimitry Andric
27160b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
27170b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
27180b57cec5SDimitry Andric return;
27190b57cec5SDimitry Andric }
27200b57cec5SDimitry Andric
27210b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
27220b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
27230b57cec5SDimitry Andric return;
27240b57cec5SDimitry Andric }
27250b57cec5SDimitry Andric
27260b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
27270b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
27280b57cec5SDimitry Andric if (LV.isObjCIvar() && !LV.isObjCArray())
27290b57cec5SDimitry Andric // Using array syntax to assigning to what an ivar points to is not
27300b57cec5SDimitry Andric // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
27310b57cec5SDimitry Andric LV.setObjCIvar(false);
27320b57cec5SDimitry Andric else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
27330b57cec5SDimitry Andric // Using array syntax to assigning to what global points to is not
27340b57cec5SDimitry Andric // same as assigning to the global itself. {id *G;} G[i] = 0;
27350b57cec5SDimitry Andric LV.setGlobalObjCRef(false);
27360b57cec5SDimitry Andric return;
27370b57cec5SDimitry Andric }
27380b57cec5SDimitry Andric
27390b57cec5SDimitry Andric if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
27400b57cec5SDimitry Andric setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
27410b57cec5SDimitry Andric // We don't know if member is an 'ivar', but this flag is looked at
27420b57cec5SDimitry Andric // only in the context of LV.isObjCIvar().
27430b57cec5SDimitry Andric LV.setObjCArray(E->getType()->isArrayType());
27440b57cec5SDimitry Andric return;
27450b57cec5SDimitry Andric }
27460b57cec5SDimitry Andric }
27470b57cec5SDimitry Andric
EmitThreadPrivateVarDeclLValue(CodeGenFunction & CGF,const VarDecl * VD,QualType T,Address Addr,llvm::Type * RealVarTy,SourceLocation Loc)27480b57cec5SDimitry Andric static LValue EmitThreadPrivateVarDeclLValue(
27490b57cec5SDimitry Andric CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
27500b57cec5SDimitry Andric llvm::Type *RealVarTy, SourceLocation Loc) {
27515ffd83dbSDimitry Andric if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
27525ffd83dbSDimitry Andric Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
27535ffd83dbSDimitry Andric CGF, VD, Addr, Loc);
27545ffd83dbSDimitry Andric else
27555ffd83dbSDimitry Andric Addr =
27565ffd83dbSDimitry Andric CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
27575ffd83dbSDimitry Andric
2758fe013be4SDimitry Andric Addr = Addr.withElementType(RealVarTy);
27590b57cec5SDimitry Andric return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
27600b57cec5SDimitry Andric }
27610b57cec5SDimitry Andric
emitDeclTargetVarDeclLValue(CodeGenFunction & CGF,const VarDecl * VD,QualType T)27620b57cec5SDimitry Andric static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
27630b57cec5SDimitry Andric const VarDecl *VD, QualType T) {
2764bdd1243dSDimitry Andric std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
27650b57cec5SDimitry Andric OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2766bdd1243dSDimitry Andric // Return an invalid address if variable is MT_To (or MT_Enter starting with
2767bdd1243dSDimitry Andric // OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link
2768bdd1243dSDimitry Andric // and MT_To (or MT_Enter) with unified memory, return a valid address.
2769bdd1243dSDimitry Andric if (!Res || ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2770bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
27710b57cec5SDimitry Andric !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
27720b57cec5SDimitry Andric return Address::invalid();
27730b57cec5SDimitry Andric assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2774bdd1243dSDimitry Andric ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2775bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
27760b57cec5SDimitry Andric CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
27770b57cec5SDimitry Andric "Expected link clause OR to clause with unified memory enabled.");
27780b57cec5SDimitry Andric QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
27790b57cec5SDimitry Andric Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
27800b57cec5SDimitry Andric return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
27810b57cec5SDimitry Andric }
27820b57cec5SDimitry Andric
27830b57cec5SDimitry Andric Address
EmitLoadOfReference(LValue RefLVal,LValueBaseInfo * PointeeBaseInfo,TBAAAccessInfo * PointeeTBAAInfo)27840b57cec5SDimitry Andric CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
27850b57cec5SDimitry Andric LValueBaseInfo *PointeeBaseInfo,
27860b57cec5SDimitry Andric TBAAAccessInfo *PointeeTBAAInfo) {
2787480093f4SDimitry Andric llvm::LoadInst *Load =
2788480093f4SDimitry Andric Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
27890b57cec5SDimitry Andric CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
27900b57cec5SDimitry Andric
27910eae32dcSDimitry Andric QualType PointeeType = RefLVal.getType()->getPointeeType();
27925ffd83dbSDimitry Andric CharUnits Align = CGM.getNaturalTypeAlignment(
27930eae32dcSDimitry Andric PointeeType, PointeeBaseInfo, PointeeTBAAInfo,
27940b57cec5SDimitry Andric /* forPointeeType= */ true);
27950eae32dcSDimitry Andric return Address(Load, ConvertTypeForMem(PointeeType), Align);
27960b57cec5SDimitry Andric }
27970b57cec5SDimitry Andric
EmitLoadOfReferenceLValue(LValue RefLVal)27980b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
27990b57cec5SDimitry Andric LValueBaseInfo PointeeBaseInfo;
28000b57cec5SDimitry Andric TBAAAccessInfo PointeeTBAAInfo;
28010b57cec5SDimitry Andric Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
28020b57cec5SDimitry Andric &PointeeTBAAInfo);
28030b57cec5SDimitry Andric return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
28040b57cec5SDimitry Andric PointeeBaseInfo, PointeeTBAAInfo);
28050b57cec5SDimitry Andric }
28060b57cec5SDimitry Andric
EmitLoadOfPointer(Address Ptr,const PointerType * PtrTy,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)28070b57cec5SDimitry Andric Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
28080b57cec5SDimitry Andric const PointerType *PtrTy,
28090b57cec5SDimitry Andric LValueBaseInfo *BaseInfo,
28100b57cec5SDimitry Andric TBAAAccessInfo *TBAAInfo) {
28110b57cec5SDimitry Andric llvm::Value *Addr = Builder.CreateLoad(Ptr);
281281ad6265SDimitry Andric return Address(Addr, ConvertTypeForMem(PtrTy->getPointeeType()),
281381ad6265SDimitry Andric CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(), BaseInfo,
281481ad6265SDimitry Andric TBAAInfo,
28150b57cec5SDimitry Andric /*forPointeeType=*/true));
28160b57cec5SDimitry Andric }
28170b57cec5SDimitry Andric
EmitLoadOfPointerLValue(Address PtrAddr,const PointerType * PtrTy)28180b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
28190b57cec5SDimitry Andric const PointerType *PtrTy) {
28200b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
28210b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
28220b57cec5SDimitry Andric Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
28230b57cec5SDimitry Andric return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
28240b57cec5SDimitry Andric }
28250b57cec5SDimitry Andric
EmitGlobalVarDeclLValue(CodeGenFunction & CGF,const Expr * E,const VarDecl * VD)28260b57cec5SDimitry Andric static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
28270b57cec5SDimitry Andric const Expr *E, const VarDecl *VD) {
28280b57cec5SDimitry Andric QualType T = E->getType();
28290b57cec5SDimitry Andric
28300b57cec5SDimitry Andric // If it's thread_local, emit a call to its wrapper function instead.
28310b57cec5SDimitry Andric if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2832a7dea167SDimitry Andric CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
28330b57cec5SDimitry Andric return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
28340b57cec5SDimitry Andric // Check if the variable is marked as declare target with link clause in
28350b57cec5SDimitry Andric // device codegen.
2836fe013be4SDimitry Andric if (CGF.getLangOpts().OpenMPIsTargetDevice) {
28370b57cec5SDimitry Andric Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
28380b57cec5SDimitry Andric if (Addr.isValid())
28390b57cec5SDimitry Andric return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
28400b57cec5SDimitry Andric }
28410b57cec5SDimitry Andric
28420b57cec5SDimitry Andric llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2843bdd1243dSDimitry Andric
2844bdd1243dSDimitry Andric if (VD->getTLSKind() != VarDecl::TLS_None)
2845bdd1243dSDimitry Andric V = CGF.Builder.CreateThreadLocalAddress(V);
2846bdd1243dSDimitry Andric
28470b57cec5SDimitry Andric llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
28480b57cec5SDimitry Andric CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
28490eae32dcSDimitry Andric Address Addr(V, RealVarTy, Alignment);
28500b57cec5SDimitry Andric // Emit reference to the private copy of the variable if it is an OpenMP
28510b57cec5SDimitry Andric // threadprivate variable.
28520b57cec5SDimitry Andric if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
28530b57cec5SDimitry Andric VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
28540b57cec5SDimitry Andric return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
28550b57cec5SDimitry Andric E->getExprLoc());
28560b57cec5SDimitry Andric }
28570b57cec5SDimitry Andric LValue LV = VD->getType()->isReferenceType() ?
28580b57cec5SDimitry Andric CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
28590b57cec5SDimitry Andric AlignmentSource::Decl) :
28600b57cec5SDimitry Andric CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
28610b57cec5SDimitry Andric setObjCGCLValueClass(CGF.getContext(), E, LV);
28620b57cec5SDimitry Andric return LV;
28630b57cec5SDimitry Andric }
28640b57cec5SDimitry Andric
EmitFunctionDeclPointer(CodeGenModule & CGM,GlobalDecl GD)28650b57cec5SDimitry Andric static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
28665ffd83dbSDimitry Andric GlobalDecl GD) {
28675ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
28680b57cec5SDimitry Andric if (FD->hasAttr<WeakRefAttr>()) {
28690b57cec5SDimitry Andric ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
28700b57cec5SDimitry Andric return aliasee.getPointer();
28710b57cec5SDimitry Andric }
28720b57cec5SDimitry Andric
28735ffd83dbSDimitry Andric llvm::Constant *V = CGM.GetAddrOfFunction(GD);
28740b57cec5SDimitry Andric return V;
28750b57cec5SDimitry Andric }
28760b57cec5SDimitry Andric
EmitFunctionDeclLValue(CodeGenFunction & CGF,const Expr * E,GlobalDecl GD)28775ffd83dbSDimitry Andric static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
28785ffd83dbSDimitry Andric GlobalDecl GD) {
28795ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
28805ffd83dbSDimitry Andric llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
28810b57cec5SDimitry Andric CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
28820b57cec5SDimitry Andric return CGF.MakeAddrLValue(V, E->getType(), Alignment,
28830b57cec5SDimitry Andric AlignmentSource::Decl);
28840b57cec5SDimitry Andric }
28850b57cec5SDimitry Andric
EmitCapturedFieldLValue(CodeGenFunction & CGF,const FieldDecl * FD,llvm::Value * ThisValue)28860b57cec5SDimitry Andric static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
28870b57cec5SDimitry Andric llvm::Value *ThisValue) {
2888c9157d92SDimitry Andric
2889c9157d92SDimitry Andric return CGF.EmitLValueForLambdaField(FD, ThisValue);
28900b57cec5SDimitry Andric }
28910b57cec5SDimitry Andric
28920b57cec5SDimitry Andric /// Named Registers are named metadata pointing to the register name
28930b57cec5SDimitry Andric /// which will be read from/written to as an argument to the intrinsic
28940b57cec5SDimitry Andric /// @llvm.read/write_register.
28950b57cec5SDimitry Andric /// So far, only the name is being passed down, but other options such as
28960b57cec5SDimitry Andric /// register type, allocation type or even optimization options could be
28970b57cec5SDimitry Andric /// passed down via the metadata node.
EmitGlobalNamedRegister(const VarDecl * VD,CodeGenModule & CGM)28980b57cec5SDimitry Andric static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
28990b57cec5SDimitry Andric SmallString<64> Name("llvm.named.register.");
29000b57cec5SDimitry Andric AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
29010b57cec5SDimitry Andric assert(Asm->getLabel().size() < 64-Name.size() &&
29020b57cec5SDimitry Andric "Register name too big");
29030b57cec5SDimitry Andric Name.append(Asm->getLabel());
29040b57cec5SDimitry Andric llvm::NamedMDNode *M =
29050b57cec5SDimitry Andric CGM.getModule().getOrInsertNamedMetadata(Name);
29060b57cec5SDimitry Andric if (M->getNumOperands() == 0) {
29070b57cec5SDimitry Andric llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
29080b57cec5SDimitry Andric Asm->getLabel());
29090b57cec5SDimitry Andric llvm::Metadata *Ops[] = {Str};
29100b57cec5SDimitry Andric M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
29110b57cec5SDimitry Andric }
29120b57cec5SDimitry Andric
29130b57cec5SDimitry Andric CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
29140b57cec5SDimitry Andric
29150b57cec5SDimitry Andric llvm::Value *Ptr =
29160b57cec5SDimitry Andric llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
29170eae32dcSDimitry Andric return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
29180b57cec5SDimitry Andric }
29190b57cec5SDimitry Andric
29200b57cec5SDimitry Andric /// Determine whether we can emit a reference to \p VD from the current
29210b57cec5SDimitry Andric /// context, despite not necessarily having seen an odr-use of the variable in
29220b57cec5SDimitry Andric /// this context.
canEmitSpuriousReferenceToVariable(CodeGenFunction & CGF,const DeclRefExpr * E,const VarDecl * VD)29230b57cec5SDimitry Andric static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
29240b57cec5SDimitry Andric const DeclRefExpr *E,
2925271697daSDimitry Andric const VarDecl *VD) {
29260b57cec5SDimitry Andric // For a variable declared in an enclosing scope, do not emit a spurious
29270b57cec5SDimitry Andric // reference even if we have a capture, as that will emit an unwarranted
29280b57cec5SDimitry Andric // reference to our capture state, and will likely generate worse code than
29290b57cec5SDimitry Andric // emitting a local copy.
29300b57cec5SDimitry Andric if (E->refersToEnclosingVariableOrCapture())
29310b57cec5SDimitry Andric return false;
29320b57cec5SDimitry Andric
29330b57cec5SDimitry Andric // For a local declaration declared in this function, we can always reference
29340b57cec5SDimitry Andric // it even if we don't have an odr-use.
29350b57cec5SDimitry Andric if (VD->hasLocalStorage()) {
29360b57cec5SDimitry Andric return VD->getDeclContext() ==
29370b57cec5SDimitry Andric dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
29380b57cec5SDimitry Andric }
29390b57cec5SDimitry Andric
29400b57cec5SDimitry Andric // For a global declaration, we can emit a reference to it if we know
29410b57cec5SDimitry Andric // for sure that we are able to emit a definition of it.
29420b57cec5SDimitry Andric VD = VD->getDefinition(CGF.getContext());
29430b57cec5SDimitry Andric if (!VD)
29440b57cec5SDimitry Andric return false;
29450b57cec5SDimitry Andric
29460b57cec5SDimitry Andric // Don't emit a spurious reference if it might be to a variable that only
29470b57cec5SDimitry Andric // exists on a different device / target.
29480b57cec5SDimitry Andric // FIXME: This is unnecessarily broad. Check whether this would actually be a
29490b57cec5SDimitry Andric // cross-target reference.
29500b57cec5SDimitry Andric if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
29510b57cec5SDimitry Andric CGF.getLangOpts().OpenCL) {
29520b57cec5SDimitry Andric return false;
29530b57cec5SDimitry Andric }
29540b57cec5SDimitry Andric
29550b57cec5SDimitry Andric // We can emit a spurious reference only if the linkage implies that we'll
29560b57cec5SDimitry Andric // be emitting a non-interposable symbol that will be retained until link
29570b57cec5SDimitry Andric // time.
2958271697daSDimitry Andric switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) {
29590b57cec5SDimitry Andric case llvm::GlobalValue::ExternalLinkage:
29600b57cec5SDimitry Andric case llvm::GlobalValue::LinkOnceODRLinkage:
29610b57cec5SDimitry Andric case llvm::GlobalValue::WeakODRLinkage:
29620b57cec5SDimitry Andric case llvm::GlobalValue::InternalLinkage:
29630b57cec5SDimitry Andric case llvm::GlobalValue::PrivateLinkage:
29640b57cec5SDimitry Andric return true;
29650b57cec5SDimitry Andric default:
29660b57cec5SDimitry Andric return false;
29670b57cec5SDimitry Andric }
29680b57cec5SDimitry Andric }
29690b57cec5SDimitry Andric
EmitDeclRefLValue(const DeclRefExpr * E)29700b57cec5SDimitry Andric LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
29710b57cec5SDimitry Andric const NamedDecl *ND = E->getDecl();
29720b57cec5SDimitry Andric QualType T = E->getType();
29730b57cec5SDimitry Andric
29740b57cec5SDimitry Andric assert(E->isNonOdrUse() != NOUR_Unevaluated &&
29750b57cec5SDimitry Andric "should not emit an unevaluated operand");
29760b57cec5SDimitry Andric
29770b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(ND)) {
29780b57cec5SDimitry Andric // Global Named registers access via intrinsics only
29790b57cec5SDimitry Andric if (VD->getStorageClass() == SC_Register &&
29800b57cec5SDimitry Andric VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
29810b57cec5SDimitry Andric return EmitGlobalNamedRegister(VD, CGM);
29820b57cec5SDimitry Andric
29830b57cec5SDimitry Andric // If this DeclRefExpr does not constitute an odr-use of the variable,
29840b57cec5SDimitry Andric // we're not permitted to emit a reference to it in general, and it might
29850b57cec5SDimitry Andric // not be captured if capture would be necessary for a use. Emit the
29860b57cec5SDimitry Andric // constant value directly instead.
29870b57cec5SDimitry Andric if (E->isNonOdrUse() == NOUR_Constant &&
29880b57cec5SDimitry Andric (VD->getType()->isReferenceType() ||
2989271697daSDimitry Andric !canEmitSpuriousReferenceToVariable(*this, E, VD))) {
29900b57cec5SDimitry Andric VD->getAnyInitializer(VD);
29910b57cec5SDimitry Andric llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
29920b57cec5SDimitry Andric E->getLocation(), *VD->evaluateValue(), VD->getType());
29930b57cec5SDimitry Andric assert(Val && "failed to emit constant expression");
29940b57cec5SDimitry Andric
29950b57cec5SDimitry Andric Address Addr = Address::invalid();
29960b57cec5SDimitry Andric if (!VD->getType()->isReferenceType()) {
29970b57cec5SDimitry Andric // Spill the constant value to a global.
29980b57cec5SDimitry Andric Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
29990b57cec5SDimitry Andric getContext().getDeclAlign(VD));
3000c14a5a88SDimitry Andric llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
3001c14a5a88SDimitry Andric auto *PTy = llvm::PointerType::get(
3002bdd1243dSDimitry Andric VarTy, getTypes().getTargetAddressSpace(VD->getType()));
300381ad6265SDimitry Andric Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
30040b57cec5SDimitry Andric } else {
30050b57cec5SDimitry Andric // Should we be using the alignment of the constant pointer we emitted?
30060b57cec5SDimitry Andric CharUnits Alignment =
30075ffd83dbSDimitry Andric CGM.getNaturalTypeAlignment(E->getType(),
30080b57cec5SDimitry Andric /* BaseInfo= */ nullptr,
30090b57cec5SDimitry Andric /* TBAAInfo= */ nullptr,
30100b57cec5SDimitry Andric /* forPointeeType= */ true);
30110eae32dcSDimitry Andric Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
30120b57cec5SDimitry Andric }
30130b57cec5SDimitry Andric return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
30140b57cec5SDimitry Andric }
30150b57cec5SDimitry Andric
30160b57cec5SDimitry Andric // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
30170b57cec5SDimitry Andric
30180b57cec5SDimitry Andric // Check for captured variables.
30190b57cec5SDimitry Andric if (E->refersToEnclosingVariableOrCapture()) {
30200b57cec5SDimitry Andric VD = VD->getCanonicalDecl();
30210b57cec5SDimitry Andric if (auto *FD = LambdaCaptureFields.lookup(VD))
30220b57cec5SDimitry Andric return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3023480093f4SDimitry Andric if (CapturedStmtInfo) {
30240b57cec5SDimitry Andric auto I = LocalDeclMap.find(VD);
30250b57cec5SDimitry Andric if (I != LocalDeclMap.end()) {
3026480093f4SDimitry Andric LValue CapLVal;
30270b57cec5SDimitry Andric if (VD->getType()->isReferenceType())
3028480093f4SDimitry Andric CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
30290b57cec5SDimitry Andric AlignmentSource::Decl);
3030480093f4SDimitry Andric else
3031480093f4SDimitry Andric CapLVal = MakeAddrLValue(I->second, T);
3032480093f4SDimitry Andric // Mark lvalue as nontemporal if the variable is marked as nontemporal
3033480093f4SDimitry Andric // in simd context.
3034480093f4SDimitry Andric if (getLangOpts().OpenMP &&
3035480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3036480093f4SDimitry Andric CapLVal.setNontemporal(/*Value=*/true);
3037480093f4SDimitry Andric return CapLVal;
30380b57cec5SDimitry Andric }
30390b57cec5SDimitry Andric LValue CapLVal =
30400b57cec5SDimitry Andric EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
30410b57cec5SDimitry Andric CapturedStmtInfo->getContextValue());
304281ad6265SDimitry Andric Address LValueAddress = CapLVal.getAddress(*this);
3043480093f4SDimitry Andric CapLVal = MakeAddrLValue(
304481ad6265SDimitry Andric Address(LValueAddress.getPointer(), LValueAddress.getElementType(),
304581ad6265SDimitry Andric getContext().getDeclAlign(VD)),
30460b57cec5SDimitry Andric CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
30470b57cec5SDimitry Andric CapLVal.getTBAAInfo());
3048480093f4SDimitry Andric // Mark lvalue as nontemporal if the variable is marked as nontemporal
3049480093f4SDimitry Andric // in simd context.
3050480093f4SDimitry Andric if (getLangOpts().OpenMP &&
3051480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3052480093f4SDimitry Andric CapLVal.setNontemporal(/*Value=*/true);
3053480093f4SDimitry Andric return CapLVal;
30540b57cec5SDimitry Andric }
30550b57cec5SDimitry Andric
30560b57cec5SDimitry Andric assert(isa<BlockDecl>(CurCodeDecl));
30570b57cec5SDimitry Andric Address addr = GetAddrOfBlockDecl(VD);
30580b57cec5SDimitry Andric return MakeAddrLValue(addr, T, AlignmentSource::Decl);
30590b57cec5SDimitry Andric }
30600b57cec5SDimitry Andric }
30610b57cec5SDimitry Andric
30620b57cec5SDimitry Andric // FIXME: We should be able to assert this for FunctionDecls as well!
30630b57cec5SDimitry Andric // FIXME: We should be able to assert this for all DeclRefExprs, not just
30640b57cec5SDimitry Andric // those with a valid source location.
30650b57cec5SDimitry Andric assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
30660b57cec5SDimitry Andric !E->getLocation().isValid()) &&
30670b57cec5SDimitry Andric "Should not use decl without marking it used!");
30680b57cec5SDimitry Andric
30690b57cec5SDimitry Andric if (ND->hasAttr<WeakRefAttr>()) {
30700b57cec5SDimitry Andric const auto *VD = cast<ValueDecl>(ND);
30710b57cec5SDimitry Andric ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
30720b57cec5SDimitry Andric return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
30730b57cec5SDimitry Andric }
30740b57cec5SDimitry Andric
30750b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(ND)) {
30760b57cec5SDimitry Andric // Check if this is a global variable.
30770b57cec5SDimitry Andric if (VD->hasLinkage() || VD->isStaticDataMember())
30780b57cec5SDimitry Andric return EmitGlobalVarDeclLValue(*this, E, VD);
30790b57cec5SDimitry Andric
30800b57cec5SDimitry Andric Address addr = Address::invalid();
30810b57cec5SDimitry Andric
30820b57cec5SDimitry Andric // The variable should generally be present in the local decl map.
30830b57cec5SDimitry Andric auto iter = LocalDeclMap.find(VD);
30840b57cec5SDimitry Andric if (iter != LocalDeclMap.end()) {
30850b57cec5SDimitry Andric addr = iter->second;
30860b57cec5SDimitry Andric
30870b57cec5SDimitry Andric // Otherwise, it might be static local we haven't emitted yet for
30880b57cec5SDimitry Andric // some reason; most likely, because it's in an outer function.
30890b57cec5SDimitry Andric } else if (VD->isStaticLocal()) {
30900eae32dcSDimitry Andric llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
3091271697daSDimitry Andric *VD, CGM.getLLVMLinkageVarDefinition(VD));
30920eae32dcSDimitry Andric addr = Address(
30930eae32dcSDimitry Andric var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
30940b57cec5SDimitry Andric
30950b57cec5SDimitry Andric // No other cases for now.
30960b57cec5SDimitry Andric } else {
30970b57cec5SDimitry Andric llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
30980b57cec5SDimitry Andric }
30990b57cec5SDimitry Andric
3100bdd1243dSDimitry Andric // Handle threadlocal function locals.
3101bdd1243dSDimitry Andric if (VD->getTLSKind() != VarDecl::TLS_None)
3102fe013be4SDimitry Andric addr = addr.withPointer(
3103fe013be4SDimitry Andric Builder.CreateThreadLocalAddress(addr.getPointer()), NotKnownNonNull);
31040b57cec5SDimitry Andric
31050b57cec5SDimitry Andric // Check for OpenMP threadprivate variables.
31060b57cec5SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
31070b57cec5SDimitry Andric VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
31080b57cec5SDimitry Andric return EmitThreadPrivateVarDeclLValue(
31090b57cec5SDimitry Andric *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
31100b57cec5SDimitry Andric E->getExprLoc());
31110b57cec5SDimitry Andric }
31120b57cec5SDimitry Andric
31130b57cec5SDimitry Andric // Drill into block byref variables.
31140b57cec5SDimitry Andric bool isBlockByref = VD->isEscapingByref();
31150b57cec5SDimitry Andric if (isBlockByref) {
31160b57cec5SDimitry Andric addr = emitBlockByrefAddress(addr, VD);
31170b57cec5SDimitry Andric }
31180b57cec5SDimitry Andric
31190b57cec5SDimitry Andric // Drill into reference types.
31200b57cec5SDimitry Andric LValue LV = VD->getType()->isReferenceType() ?
31210b57cec5SDimitry Andric EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
31220b57cec5SDimitry Andric MakeAddrLValue(addr, T, AlignmentSource::Decl);
31230b57cec5SDimitry Andric
31240b57cec5SDimitry Andric bool isLocalStorage = VD->hasLocalStorage();
31250b57cec5SDimitry Andric
31260b57cec5SDimitry Andric bool NonGCable = isLocalStorage &&
31270b57cec5SDimitry Andric !VD->getType()->isReferenceType() &&
31280b57cec5SDimitry Andric !isBlockByref;
31290b57cec5SDimitry Andric if (NonGCable) {
31300b57cec5SDimitry Andric LV.getQuals().removeObjCGCAttr();
31310b57cec5SDimitry Andric LV.setNonGC(true);
31320b57cec5SDimitry Andric }
31330b57cec5SDimitry Andric
31340b57cec5SDimitry Andric bool isImpreciseLifetime =
31350b57cec5SDimitry Andric (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
31360b57cec5SDimitry Andric if (isImpreciseLifetime)
31370b57cec5SDimitry Andric LV.setARCPreciseLifetime(ARCImpreciseLifetime);
31380b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV);
31390b57cec5SDimitry Andric return LV;
31400b57cec5SDimitry Andric }
31410b57cec5SDimitry Andric
3142fe6060f1SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
3143fe6060f1SDimitry Andric LValue LV = EmitFunctionDeclLValue(*this, E, FD);
3144fe6060f1SDimitry Andric
3145fe6060f1SDimitry Andric // Emit debuginfo for the function declaration if the target wants to.
3146fe6060f1SDimitry Andric if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
3147fe6060f1SDimitry Andric if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
3148fe6060f1SDimitry Andric auto *Fn =
3149fe6060f1SDimitry Andric cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
3150fe6060f1SDimitry Andric if (!Fn->getSubprogram())
3151fe6060f1SDimitry Andric DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
3152fe6060f1SDimitry Andric }
3153fe6060f1SDimitry Andric }
3154fe6060f1SDimitry Andric
3155fe6060f1SDimitry Andric return LV;
3156fe6060f1SDimitry Andric }
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
3175c9157d92SDimitry Andric if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
3176c9157d92SDimitry Andric auto ATPO = CGM.GetAddrOfTemplateParamObject(TPO);
3177c9157d92SDimitry Andric auto AS = getLangASFromTargetAS(ATPO.getAddressSpace());
3178c9157d92SDimitry Andric
3179c9157d92SDimitry Andric if (AS != T.getAddressSpace()) {
3180c9157d92SDimitry Andric auto TargetAS = getContext().getTargetAddressSpace(T.getAddressSpace());
3181c9157d92SDimitry Andric auto PtrTy = ATPO.getElementType()->getPointerTo(TargetAS);
3182c9157d92SDimitry Andric auto ASC = getTargetHooks().performAddrSpaceCast(
3183c9157d92SDimitry Andric CGM, ATPO.getPointer(), AS, T.getAddressSpace(), PtrTy);
3184c9157d92SDimitry Andric ATPO = ConstantAddress(ASC, ATPO.getElementType(), ATPO.getAlignment());
3185c9157d92SDimitry Andric }
3186c9157d92SDimitry Andric
3187c9157d92SDimitry Andric return MakeAddrLValue(ATPO, T, AlignmentSource::Decl);
3188c9157d92SDimitry Andric }
3189e8d8bef9SDimitry Andric
31900b57cec5SDimitry Andric llvm_unreachable("Unhandled DeclRefExpr");
31910b57cec5SDimitry Andric }
31920b57cec5SDimitry Andric
EmitUnaryOpLValue(const UnaryOperator * E)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 &&
3230480093f4SDimitry Andric !LV.getAddress(*this).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
3239480093f4SDimitry Andric ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
3240480093f4SDimitry Andric : emitAddrOfImagComponent(LV.getAddress(*this), 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
EmitStringLiteralLValue(const StringLiteral * E)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
EmitObjCEncodeExprLValue(const ObjCEncodeExpr * E)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
EmitPredefinedLValue(const PredefinedExpr * E)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();
3274c9157d92SDimitry 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.
EmitCheckTypeDescriptor(QualType T)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
EmitCheckValue(llvm::Value * V)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()) {
33710b57cec5SDimitry Andric Address 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.
EmitCheckSourceLocation(SourceLocation Loc)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
getRecoverableKind(SanitizerMask Kind)34510b57cec5SDimitry Andric static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
34520b57cec5SDimitry Andric assert(Kind.countPopulation() == 1);
3453fe013be4SDimitry 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
emitCheckHandlerCall(CodeGenFunction & CGF,llvm::FunctionType * FnType,ArrayRef<llvm::Value * > FnArgs,SanitizerHandler CheckHandler,CheckRecoverableKind RecoverKind,bool IsFatal,llvm::BasicBlock * ContBB)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
EmitCheck(ArrayRef<std::pair<llvm::Value *,SanitizerMask>> Checked,SanitizerHandler CheckHandler,ArrayRef<llvm::Constant * > StaticArgs,ArrayRef<llvm::Value * > DynamicArgs)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
35470b57cec5SDimitry Andric if (TrapCond)
3548e8d8bef9SDimitry Andric EmitTrapCheck(TrapCond, CheckHandler);
35490b57cec5SDimitry Andric if (!FatalCond && !RecoverableCond)
35500b57cec5SDimitry Andric return;
35510b57cec5SDimitry Andric
35520b57cec5SDimitry Andric llvm::Value *JointCond;
35530b57cec5SDimitry Andric if (FatalCond && RecoverableCond)
35540b57cec5SDimitry Andric JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
35550b57cec5SDimitry Andric else
35560b57cec5SDimitry Andric JointCond = FatalCond ? FatalCond : RecoverableCond;
35570b57cec5SDimitry Andric assert(JointCond);
35580b57cec5SDimitry Andric
35590b57cec5SDimitry Andric CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
35600b57cec5SDimitry Andric assert(SanOpts.has(Checked[0].second));
35610b57cec5SDimitry Andric #ifndef NDEBUG
35620b57cec5SDimitry Andric for (int i = 1, n = Checked.size(); i < n; ++i) {
35630b57cec5SDimitry Andric assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
35640b57cec5SDimitry Andric "All recoverable kinds in a single check must be same!");
35650b57cec5SDimitry Andric assert(SanOpts.has(Checked[i].second));
35660b57cec5SDimitry Andric }
35670b57cec5SDimitry Andric #endif
35680b57cec5SDimitry Andric
35690b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont");
35700b57cec5SDimitry Andric llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
35710b57cec5SDimitry Andric llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
35720b57cec5SDimitry Andric // Give hint that we very much don't expect to execute the handler
35730b57cec5SDimitry Andric // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
35740b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext());
35750b57cec5SDimitry Andric llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
35760b57cec5SDimitry Andric Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
35770b57cec5SDimitry Andric EmitBlock(Handlers);
35780b57cec5SDimitry Andric
35790b57cec5SDimitry Andric // Handler functions take an i8* pointing to the (handler-specific) static
35800b57cec5SDimitry Andric // information block, followed by a sequence of intptr_t arguments
35810b57cec5SDimitry Andric // representing operand values.
35820b57cec5SDimitry Andric SmallVector<llvm::Value *, 4> Args;
35830b57cec5SDimitry Andric SmallVector<llvm::Type *, 4> ArgTypes;
35840b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
35850b57cec5SDimitry Andric Args.reserve(DynamicArgs.size() + 1);
35860b57cec5SDimitry Andric ArgTypes.reserve(DynamicArgs.size() + 1);
35870b57cec5SDimitry Andric
35880b57cec5SDimitry Andric // Emit handler arguments and create handler function type.
35890b57cec5SDimitry Andric if (!StaticArgs.empty()) {
35900b57cec5SDimitry Andric llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3591bdd1243dSDimitry Andric auto *InfoPtr = new llvm::GlobalVariable(
3592bdd1243dSDimitry Andric CGM.getModule(), Info->getType(), false,
3593bdd1243dSDimitry Andric llvm::GlobalVariable::PrivateLinkage, Info, "", nullptr,
3594bdd1243dSDimitry Andric llvm::GlobalVariable::NotThreadLocal,
3595bdd1243dSDimitry Andric CGM.getDataLayout().getDefaultGlobalsAddressSpace());
35960b57cec5SDimitry Andric InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
35970b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3598fe013be4SDimitry Andric Args.push_back(InfoPtr);
3599bdd1243dSDimitry Andric ArgTypes.push_back(Args.back()->getType());
36000b57cec5SDimitry Andric }
36010b57cec5SDimitry Andric
36020b57cec5SDimitry Andric for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
36030b57cec5SDimitry Andric Args.push_back(EmitCheckValue(DynamicArgs[i]));
36040b57cec5SDimitry Andric ArgTypes.push_back(IntPtrTy);
36050b57cec5SDimitry Andric }
36060b57cec5SDimitry Andric }
36070b57cec5SDimitry Andric
36080b57cec5SDimitry Andric llvm::FunctionType *FnType =
36090b57cec5SDimitry Andric llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
36100b57cec5SDimitry Andric
36110b57cec5SDimitry Andric if (!FatalCond || !RecoverableCond) {
36120b57cec5SDimitry Andric // Simple case: we need to generate a single handler call, either
36130b57cec5SDimitry Andric // fatal, or non-fatal.
36140b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
36150b57cec5SDimitry Andric (FatalCond != nullptr), Cont);
36160b57cec5SDimitry Andric } else {
36170b57cec5SDimitry Andric // Emit two handler calls: first one for set of unrecoverable checks,
36180b57cec5SDimitry Andric // another one for recoverable.
36190b57cec5SDimitry Andric llvm::BasicBlock *NonFatalHandlerBB =
36200b57cec5SDimitry Andric createBasicBlock("non_fatal." + CheckName);
36210b57cec5SDimitry Andric llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
36220b57cec5SDimitry Andric Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
36230b57cec5SDimitry Andric EmitBlock(FatalHandlerBB);
36240b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
36250b57cec5SDimitry Andric NonFatalHandlerBB);
36260b57cec5SDimitry Andric EmitBlock(NonFatalHandlerBB);
36270b57cec5SDimitry Andric emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
36280b57cec5SDimitry Andric Cont);
36290b57cec5SDimitry Andric }
36300b57cec5SDimitry Andric
36310b57cec5SDimitry Andric EmitBlock(Cont);
36320b57cec5SDimitry Andric }
36330b57cec5SDimitry Andric
EmitCfiSlowPathCheck(SanitizerMask Kind,llvm::Value * Cond,llvm::ConstantInt * TypeId,llvm::Value * Ptr,ArrayRef<llvm::Constant * > StaticArgs)36340b57cec5SDimitry Andric void CodeGenFunction::EmitCfiSlowPathCheck(
36350b57cec5SDimitry Andric SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
36360b57cec5SDimitry Andric llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
36370b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
36380b57cec5SDimitry Andric
36390b57cec5SDimitry Andric llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
36400b57cec5SDimitry Andric llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
36410b57cec5SDimitry Andric
36420b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext());
36430b57cec5SDimitry Andric llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
36440b57cec5SDimitry Andric BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
36450b57cec5SDimitry Andric
36460b57cec5SDimitry Andric EmitBlock(CheckBB);
36470b57cec5SDimitry Andric
36480b57cec5SDimitry Andric bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
36490b57cec5SDimitry Andric
36500b57cec5SDimitry Andric llvm::CallInst *CheckCall;
36510b57cec5SDimitry Andric llvm::FunctionCallee SlowPathFn;
36520b57cec5SDimitry Andric if (WithDiag) {
36530b57cec5SDimitry Andric llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
36540b57cec5SDimitry Andric auto *InfoPtr =
36550b57cec5SDimitry Andric new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
36560b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage, Info);
36570b57cec5SDimitry Andric InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
36580b57cec5SDimitry Andric CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
36590b57cec5SDimitry Andric
36600b57cec5SDimitry Andric SlowPathFn = CGM.getModule().getOrInsertFunction(
36610b57cec5SDimitry Andric "__cfi_slowpath_diag",
36620b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
36630b57cec5SDimitry Andric false));
3664c9157d92SDimitry Andric CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr});
36650b57cec5SDimitry Andric } else {
36660b57cec5SDimitry Andric SlowPathFn = CGM.getModule().getOrInsertFunction(
36670b57cec5SDimitry Andric "__cfi_slowpath",
36680b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
36690b57cec5SDimitry Andric CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
36700b57cec5SDimitry Andric }
36710b57cec5SDimitry Andric
36720b57cec5SDimitry Andric CGM.setDSOLocal(
36730b57cec5SDimitry Andric cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
36740b57cec5SDimitry Andric CheckCall->setDoesNotThrow();
36750b57cec5SDimitry Andric
36760b57cec5SDimitry Andric EmitBlock(Cont);
36770b57cec5SDimitry Andric }
36780b57cec5SDimitry Andric
36790b57cec5SDimitry Andric // Emit a stub for __cfi_check function so that the linker knows about this
36800b57cec5SDimitry Andric // symbol in LTO mode.
EmitCfiCheckStub()36810b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckStub() {
36820b57cec5SDimitry Andric llvm::Module *M = &CGM.getModule();
36830b57cec5SDimitry Andric auto &Ctx = M->getContext();
36840b57cec5SDimitry Andric llvm::Function *F = llvm::Function::Create(
36850b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
36860b57cec5SDimitry Andric llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
3687c9157d92SDimitry Andric F->setAlignment(llvm::Align(4096));
36880b57cec5SDimitry Andric CGM.setDSOLocal(F);
36890b57cec5SDimitry Andric llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3690c9157d92SDimitry Andric // CrossDSOCFI pass is not executed if there is no executable code.
3691c9157d92SDimitry Andric SmallVector<llvm::Value*> Args{F->getArg(2), F->getArg(1)};
3692c9157d92SDimitry Andric llvm::CallInst::Create(M->getFunction("__cfi_check_fail"), Args, "", BB);
36930b57cec5SDimitry Andric llvm::ReturnInst::Create(Ctx, nullptr, BB);
36940b57cec5SDimitry Andric }
36950b57cec5SDimitry Andric
36960b57cec5SDimitry Andric // This function is basically a switch over the CFI failure kind, which is
36970b57cec5SDimitry Andric // extracted from CFICheckFailData (1st function argument). Each case is either
36980b57cec5SDimitry Andric // llvm.trap or a call to one of the two runtime handlers, based on
36990b57cec5SDimitry Andric // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
37000b57cec5SDimitry Andric // failure kind) traps, but this should really never happen. CFICheckFailData
37010b57cec5SDimitry Andric // can be nullptr if the calling module has -fsanitize-trap behavior for this
37020b57cec5SDimitry Andric // check kind; in this case __cfi_check_fail traps as well.
EmitCfiCheckFail()37030b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckFail() {
37040b57cec5SDimitry Andric SanitizerScope SanScope(this);
37050b57cec5SDimitry Andric FunctionArgList Args;
37060b57cec5SDimitry Andric ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3707c9157d92SDimitry Andric ImplicitParamKind::Other);
37080b57cec5SDimitry Andric ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3709c9157d92SDimitry Andric ImplicitParamKind::Other);
37100b57cec5SDimitry Andric Args.push_back(&ArgData);
37110b57cec5SDimitry Andric Args.push_back(&ArgAddr);
37120b57cec5SDimitry Andric
37130b57cec5SDimitry Andric const CGFunctionInfo &FI =
37140b57cec5SDimitry Andric CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
37150b57cec5SDimitry Andric
37160b57cec5SDimitry Andric llvm::Function *F = llvm::Function::Create(
37170b57cec5SDimitry Andric llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
37180b57cec5SDimitry Andric llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3719480093f4SDimitry Andric
3720fe6060f1SDimitry Andric CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3721480093f4SDimitry Andric CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
37220b57cec5SDimitry Andric F->setVisibility(llvm::GlobalValue::HiddenVisibility);
37230b57cec5SDimitry Andric
37240b57cec5SDimitry Andric StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
37250b57cec5SDimitry Andric SourceLocation());
37260b57cec5SDimitry Andric
3727fe6060f1SDimitry Andric // This function is not affected by NoSanitizeList. This function does
37280b57cec5SDimitry Andric // not have a source location, but "src:*" would still apply. Revert any
37290b57cec5SDimitry Andric // changes to SanOpts made in StartFunction.
37300b57cec5SDimitry Andric SanOpts = CGM.getLangOpts().Sanitize;
37310b57cec5SDimitry Andric
37320b57cec5SDimitry Andric llvm::Value *Data =
37330b57cec5SDimitry Andric EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
37340b57cec5SDimitry Andric CGM.getContext().VoidPtrTy, ArgData.getLocation());
37350b57cec5SDimitry Andric llvm::Value *Addr =
37360b57cec5SDimitry Andric EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
37370b57cec5SDimitry Andric CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
37380b57cec5SDimitry Andric
37390b57cec5SDimitry Andric // Data == nullptr means the calling module has trap behaviour for this check.
37400b57cec5SDimitry Andric llvm::Value *DataIsNotNullPtr =
37410b57cec5SDimitry Andric Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3742e8d8bef9SDimitry Andric EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
37430b57cec5SDimitry Andric
37440b57cec5SDimitry Andric llvm::StructType *SourceLocationTy =
37450b57cec5SDimitry Andric llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
37460b57cec5SDimitry Andric llvm::StructType *CfiCheckFailDataTy =
37470b57cec5SDimitry Andric llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
37480b57cec5SDimitry Andric
37490b57cec5SDimitry Andric llvm::Value *V = Builder.CreateConstGEP2_32(
37500b57cec5SDimitry Andric CfiCheckFailDataTy,
37510b57cec5SDimitry Andric Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
37520b57cec5SDimitry Andric 0);
375381ad6265SDimitry Andric
375481ad6265SDimitry Andric Address CheckKindAddr(V, Int8Ty, getIntAlign());
37550b57cec5SDimitry Andric llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
37560b57cec5SDimitry Andric
37570b57cec5SDimitry Andric llvm::Value *AllVtables = llvm::MetadataAsValue::get(
37580b57cec5SDimitry Andric CGM.getLLVMContext(),
37590b57cec5SDimitry Andric llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
37600b57cec5SDimitry Andric llvm::Value *ValidVtable = Builder.CreateZExt(
37610b57cec5SDimitry Andric Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
37620b57cec5SDimitry Andric {Addr, AllVtables}),
37630b57cec5SDimitry Andric IntPtrTy);
37640b57cec5SDimitry Andric
37650b57cec5SDimitry Andric const std::pair<int, SanitizerMask> CheckKinds[] = {
37660b57cec5SDimitry Andric {CFITCK_VCall, SanitizerKind::CFIVCall},
37670b57cec5SDimitry Andric {CFITCK_NVCall, SanitizerKind::CFINVCall},
37680b57cec5SDimitry Andric {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
37690b57cec5SDimitry Andric {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
37700b57cec5SDimitry Andric {CFITCK_ICall, SanitizerKind::CFIICall}};
37710b57cec5SDimitry Andric
37720b57cec5SDimitry Andric SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
37730b57cec5SDimitry Andric for (auto CheckKindMaskPair : CheckKinds) {
37740b57cec5SDimitry Andric int Kind = CheckKindMaskPair.first;
37750b57cec5SDimitry Andric SanitizerMask Mask = CheckKindMaskPair.second;
37760b57cec5SDimitry Andric llvm::Value *Cond =
37770b57cec5SDimitry Andric Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
37780b57cec5SDimitry Andric if (CGM.getLangOpts().Sanitize.has(Mask))
37790b57cec5SDimitry Andric EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
37800b57cec5SDimitry Andric {Data, Addr, ValidVtable});
37810b57cec5SDimitry Andric else
3782e8d8bef9SDimitry Andric EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
37830b57cec5SDimitry Andric }
37840b57cec5SDimitry Andric
37850b57cec5SDimitry Andric FinishFunction();
37860b57cec5SDimitry Andric // The only reference to this function will be created during LTO link.
37870b57cec5SDimitry Andric // Make sure it survives until then.
37880b57cec5SDimitry Andric CGM.addUsedGlobal(F);
37890b57cec5SDimitry Andric }
37900b57cec5SDimitry Andric
EmitUnreachable(SourceLocation Loc)37910b57cec5SDimitry Andric void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
37920b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Unreachable)) {
37930b57cec5SDimitry Andric SanitizerScope SanScope(this);
37940b57cec5SDimitry Andric EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
37950b57cec5SDimitry Andric SanitizerKind::Unreachable),
37960b57cec5SDimitry Andric SanitizerHandler::BuiltinUnreachable,
3797bdd1243dSDimitry Andric EmitCheckSourceLocation(Loc), std::nullopt);
37980b57cec5SDimitry Andric }
37990b57cec5SDimitry Andric Builder.CreateUnreachable();
38000b57cec5SDimitry Andric }
38010b57cec5SDimitry Andric
EmitTrapCheck(llvm::Value * Checked,SanitizerHandler CheckHandlerID)3802e8d8bef9SDimitry Andric void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3803e8d8bef9SDimitry Andric SanitizerHandler CheckHandlerID) {
38040b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont");
38050b57cec5SDimitry Andric
38060b57cec5SDimitry Andric // If we're optimizing, collapse all calls to trap down to just one per
3807e8d8bef9SDimitry Andric // check-type per function to save on code size.
3808e8d8bef9SDimitry Andric if (TrapBBs.size() <= CheckHandlerID)
3809e8d8bef9SDimitry Andric TrapBBs.resize(CheckHandlerID + 1);
3810c9157d92SDimitry Andric
3811e8d8bef9SDimitry Andric llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3812e8d8bef9SDimitry Andric
3813c9157d92SDimitry Andric if (!ClSanitizeDebugDeoptimization &&
3814c9157d92SDimitry Andric CGM.getCodeGenOpts().OptimizationLevel && TrapBB &&
3815c9157d92SDimitry Andric (!CurCodeDecl || !CurCodeDecl->hasAttr<OptimizeNoneAttr>())) {
3816c9157d92SDimitry Andric auto Call = TrapBB->begin();
3817c9157d92SDimitry Andric assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3818c9157d92SDimitry Andric
3819c9157d92SDimitry Andric Call->applyMergedLocation(Call->getDebugLoc(),
3820c9157d92SDimitry Andric Builder.getCurrentDebugLocation());
3821c9157d92SDimitry Andric Builder.CreateCondBr(Checked, Cont, TrapBB);
3822c9157d92SDimitry Andric } else {
38230b57cec5SDimitry Andric TrapBB = createBasicBlock("trap");
38240b57cec5SDimitry Andric Builder.CreateCondBr(Checked, Cont, TrapBB);
38250b57cec5SDimitry Andric EmitBlock(TrapBB);
3826e8d8bef9SDimitry Andric
3827c9157d92SDimitry Andric llvm::CallInst *TrapCall = Builder.CreateCall(
3828c9157d92SDimitry Andric CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3829c9157d92SDimitry Andric llvm::ConstantInt::get(CGM.Int8Ty, ClSanitizeDebugDeoptimization
3830c9157d92SDimitry Andric ? TrapBB->getParent()->size()
3831c9157d92SDimitry Andric : CheckHandlerID));
3832e8d8bef9SDimitry Andric
3833e8d8bef9SDimitry Andric if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3834e8d8bef9SDimitry Andric auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3835e8d8bef9SDimitry Andric CGM.getCodeGenOpts().TrapFuncName);
3836349cc55cSDimitry Andric TrapCall->addFnAttr(A);
3837e8d8bef9SDimitry Andric }
38380b57cec5SDimitry Andric TrapCall->setDoesNotReturn();
38390b57cec5SDimitry Andric TrapCall->setDoesNotThrow();
38400b57cec5SDimitry Andric Builder.CreateUnreachable();
38410b57cec5SDimitry Andric }
38420b57cec5SDimitry Andric
38430b57cec5SDimitry Andric EmitBlock(Cont);
38440b57cec5SDimitry Andric }
38450b57cec5SDimitry Andric
EmitTrapCall(llvm::Intrinsic::ID IntrID)38460b57cec5SDimitry Andric llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3847e8d8bef9SDimitry Andric llvm::CallInst *TrapCall =
3848e8d8bef9SDimitry Andric Builder.CreateCall(CGM.getIntrinsic(IntrID));
38490b57cec5SDimitry Andric
38500b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
38510b57cec5SDimitry Andric auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
38520b57cec5SDimitry Andric CGM.getCodeGenOpts().TrapFuncName);
3853349cc55cSDimitry Andric TrapCall->addFnAttr(A);
38540b57cec5SDimitry Andric }
38550b57cec5SDimitry Andric
38560b57cec5SDimitry Andric return TrapCall;
38570b57cec5SDimitry Andric }
38580b57cec5SDimitry Andric
EmitArrayToPointerDecay(const Expr * E,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)38590b57cec5SDimitry Andric Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
38600b57cec5SDimitry Andric LValueBaseInfo *BaseInfo,
38610b57cec5SDimitry Andric TBAAAccessInfo *TBAAInfo) {
38620b57cec5SDimitry Andric assert(E->getType()->isArrayType() &&
38630b57cec5SDimitry Andric "Array to pointer decay must have array source type!");
38640b57cec5SDimitry Andric
38650b57cec5SDimitry Andric // Expressions of array type can't be bitfields or vector elements.
38660b57cec5SDimitry Andric LValue LV = EmitLValue(E);
3867480093f4SDimitry Andric Address Addr = LV.getAddress(*this);
38680b57cec5SDimitry Andric
38690b57cec5SDimitry Andric // If the array type was an incomplete type, we need to make sure
38700b57cec5SDimitry Andric // the decay ends up being the right type.
38710b57cec5SDimitry Andric llvm::Type *NewTy = ConvertType(E->getType());
3872fe013be4SDimitry Andric Addr = Addr.withElementType(NewTy);
38730b57cec5SDimitry Andric
38740b57cec5SDimitry Andric // Note that VLA pointers are always decayed, so we don't need to do
38750b57cec5SDimitry Andric // anything here.
38760b57cec5SDimitry Andric if (!E->getType()->isVariableArrayType()) {
38770b57cec5SDimitry Andric assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
38780b57cec5SDimitry Andric "Expected pointer to array");
38790b57cec5SDimitry Andric Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
38800b57cec5SDimitry Andric }
38810b57cec5SDimitry Andric
38820b57cec5SDimitry Andric // The result of this decay conversion points to an array element within the
38830b57cec5SDimitry Andric // base lvalue. However, since TBAA currently does not support representing
38840b57cec5SDimitry Andric // accesses to elements of member arrays, we conservatively represent accesses
38850b57cec5SDimitry Andric // to the pointee object as if it had no any base lvalue specified.
38860b57cec5SDimitry Andric // TODO: Support TBAA for member arrays.
38870b57cec5SDimitry Andric QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
38880b57cec5SDimitry Andric if (BaseInfo) *BaseInfo = LV.getBaseInfo();
38890b57cec5SDimitry Andric if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
38900b57cec5SDimitry Andric
3891fe013be4SDimitry Andric return Addr.withElementType(ConvertTypeForMem(EltType));
38920b57cec5SDimitry Andric }
38930b57cec5SDimitry Andric
38940b57cec5SDimitry Andric /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
38950b57cec5SDimitry Andric /// array to pointer, return the array subexpression.
isSimpleArrayDecayOperand(const Expr * E)38960b57cec5SDimitry Andric static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
38970b57cec5SDimitry Andric // If this isn't just an array->pointer decay, bail out.
38980b57cec5SDimitry Andric const auto *CE = dyn_cast<CastExpr>(E);
38990b57cec5SDimitry Andric if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
39000b57cec5SDimitry Andric return nullptr;
39010b57cec5SDimitry Andric
39020b57cec5SDimitry Andric // If this is a decay from variable width array, bail out.
39030b57cec5SDimitry Andric const Expr *SubExpr = CE->getSubExpr();
39040b57cec5SDimitry Andric if (SubExpr->getType()->isVariableArrayType())
39050b57cec5SDimitry Andric return nullptr;
39060b57cec5SDimitry Andric
39070b57cec5SDimitry Andric return SubExpr;
39080b57cec5SDimitry Andric }
39090b57cec5SDimitry Andric
emitArraySubscriptGEP(CodeGenFunction & CGF,llvm::Type * elemType,llvm::Value * ptr,ArrayRef<llvm::Value * > indices,bool inbounds,bool signedIndices,SourceLocation loc,const llvm::Twine & name="arrayidx")39100b57cec5SDimitry Andric static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3911fe6060f1SDimitry Andric llvm::Type *elemType,
39120b57cec5SDimitry Andric llvm::Value *ptr,
39130b57cec5SDimitry Andric ArrayRef<llvm::Value*> indices,
39140b57cec5SDimitry Andric bool inbounds,
39150b57cec5SDimitry Andric bool signedIndices,
39160b57cec5SDimitry Andric SourceLocation loc,
39170b57cec5SDimitry Andric const llvm::Twine &name = "arrayidx") {
39180b57cec5SDimitry Andric if (inbounds) {
39190eae32dcSDimitry Andric return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
39200b57cec5SDimitry Andric CodeGenFunction::NotSubtraction, loc,
39210b57cec5SDimitry Andric name);
39220b57cec5SDimitry Andric } else {
3923fe6060f1SDimitry Andric return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
39240b57cec5SDimitry Andric }
39250b57cec5SDimitry Andric }
39260b57cec5SDimitry Andric
getArrayElementAlign(CharUnits arrayAlign,llvm::Value * idx,CharUnits eltSize)39270b57cec5SDimitry Andric static CharUnits getArrayElementAlign(CharUnits arrayAlign,
39280b57cec5SDimitry Andric llvm::Value *idx,
39290b57cec5SDimitry Andric CharUnits eltSize) {
39300b57cec5SDimitry Andric // If we have a constant index, we can use the exact offset of the
39310b57cec5SDimitry Andric // element we're accessing.
39320b57cec5SDimitry Andric if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
39330b57cec5SDimitry Andric CharUnits offset = constantIdx->getZExtValue() * eltSize;
39340b57cec5SDimitry Andric return arrayAlign.alignmentAtOffset(offset);
39350b57cec5SDimitry Andric
39360b57cec5SDimitry Andric // Otherwise, use the worst-case alignment for any element.
39370b57cec5SDimitry Andric } else {
39380b57cec5SDimitry Andric return arrayAlign.alignmentOfArrayElement(eltSize);
39390b57cec5SDimitry Andric }
39400b57cec5SDimitry Andric }
39410b57cec5SDimitry Andric
getFixedSizeElementType(const ASTContext & ctx,const VariableArrayType * vla)39420b57cec5SDimitry Andric static QualType getFixedSizeElementType(const ASTContext &ctx,
39430b57cec5SDimitry Andric const VariableArrayType *vla) {
39440b57cec5SDimitry Andric QualType eltType;
39450b57cec5SDimitry Andric do {
39460b57cec5SDimitry Andric eltType = vla->getElementType();
39470b57cec5SDimitry Andric } while ((vla = ctx.getAsVariableArrayType(eltType)));
39480b57cec5SDimitry Andric return eltType;
39490b57cec5SDimitry Andric }
39500b57cec5SDimitry Andric
hasBPFPreserveStaticOffset(const RecordDecl * D)3951c9157d92SDimitry Andric static bool hasBPFPreserveStaticOffset(const RecordDecl *D) {
3952c9157d92SDimitry Andric return D && D->hasAttr<BPFPreserveStaticOffsetAttr>();
3953c9157d92SDimitry Andric }
3954c9157d92SDimitry Andric
hasBPFPreserveStaticOffset(const Expr * E)3955c9157d92SDimitry Andric static bool hasBPFPreserveStaticOffset(const Expr *E) {
3956c9157d92SDimitry Andric if (!E)
3957c9157d92SDimitry Andric return false;
3958c9157d92SDimitry Andric QualType PointeeType = E->getType()->getPointeeType();
3959c9157d92SDimitry Andric if (PointeeType.isNull())
3960c9157d92SDimitry Andric return false;
3961c9157d92SDimitry Andric if (const auto *BaseDecl = PointeeType->getAsRecordDecl())
3962c9157d92SDimitry Andric return hasBPFPreserveStaticOffset(BaseDecl);
3963c9157d92SDimitry Andric return false;
3964c9157d92SDimitry Andric }
3965c9157d92SDimitry Andric
3966c9157d92SDimitry Andric // Wraps Addr with a call to llvm.preserve.static.offset intrinsic.
wrapWithBPFPreserveStaticOffset(CodeGenFunction & CGF,Address & Addr)3967c9157d92SDimitry Andric static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF,
3968c9157d92SDimitry Andric Address &Addr) {
3969c9157d92SDimitry Andric if (!CGF.getTarget().getTriple().isBPF())
3970c9157d92SDimitry Andric return Addr;
3971c9157d92SDimitry Andric
3972c9157d92SDimitry Andric llvm::Function *Fn =
3973c9157d92SDimitry Andric CGF.CGM.getIntrinsic(llvm::Intrinsic::preserve_static_offset);
3974c9157d92SDimitry Andric llvm::CallInst *Call = CGF.Builder.CreateCall(Fn, {Addr.getPointer()});
3975c9157d92SDimitry Andric return Address(Call, Addr.getElementType(), Addr.getAlignment());
3976c9157d92SDimitry Andric }
3977c9157d92SDimitry Andric
3978480093f4SDimitry Andric /// Given an array base, check whether its member access belongs to a record
3979480093f4SDimitry Andric /// with preserve_access_index attribute or not.
IsPreserveAIArrayBase(CodeGenFunction & CGF,const Expr * ArrayBase)3980480093f4SDimitry Andric static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3981480093f4SDimitry Andric if (!ArrayBase || !CGF.getDebugInfo())
3982480093f4SDimitry Andric return false;
3983480093f4SDimitry Andric
3984480093f4SDimitry Andric // Only support base as either a MemberExpr or DeclRefExpr.
3985480093f4SDimitry Andric // DeclRefExpr to cover cases like:
3986480093f4SDimitry Andric // struct s { int a; int b[10]; };
3987480093f4SDimitry Andric // struct s *p;
3988480093f4SDimitry Andric // p[1].a
3989480093f4SDimitry Andric // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3990480093f4SDimitry Andric // p->b[5] is a MemberExpr example.
3991480093f4SDimitry Andric const Expr *E = ArrayBase->IgnoreImpCasts();
3992480093f4SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(E))
3993480093f4SDimitry Andric return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3994480093f4SDimitry Andric
3995480093f4SDimitry Andric if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3996480093f4SDimitry Andric const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3997480093f4SDimitry Andric if (!VarDef)
3998480093f4SDimitry Andric return false;
3999480093f4SDimitry Andric
4000480093f4SDimitry Andric const auto *PtrT = VarDef->getType()->getAs<PointerType>();
4001480093f4SDimitry Andric if (!PtrT)
4002480093f4SDimitry Andric return false;
4003480093f4SDimitry Andric
4004480093f4SDimitry Andric const auto *PointeeT = PtrT->getPointeeType()
4005480093f4SDimitry Andric ->getUnqualifiedDesugaredType();
4006480093f4SDimitry Andric if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
4007480093f4SDimitry Andric return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4008480093f4SDimitry Andric return false;
4009480093f4SDimitry Andric }
4010480093f4SDimitry Andric
4011480093f4SDimitry Andric return false;
4012480093f4SDimitry Andric }
4013480093f4SDimitry Andric
emitArraySubscriptGEP(CodeGenFunction & CGF,Address addr,ArrayRef<llvm::Value * > indices,QualType eltType,bool inbounds,bool signedIndices,SourceLocation loc,QualType * arrayType=nullptr,const Expr * Base=nullptr,const llvm::Twine & name="arrayidx")40140b57cec5SDimitry Andric static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
40150b57cec5SDimitry Andric ArrayRef<llvm::Value *> indices,
40160b57cec5SDimitry Andric QualType eltType, bool inbounds,
40170b57cec5SDimitry Andric bool signedIndices, SourceLocation loc,
4018a7dea167SDimitry Andric QualType *arrayType = nullptr,
4019480093f4SDimitry Andric const Expr *Base = nullptr,
40200b57cec5SDimitry Andric const llvm::Twine &name = "arrayidx") {
40210b57cec5SDimitry Andric // All the indices except that last must be zero.
40220b57cec5SDimitry Andric #ifndef NDEBUG
4023bdd1243dSDimitry Andric for (auto *idx : indices.drop_back())
40240b57cec5SDimitry Andric assert(isa<llvm::ConstantInt>(idx) &&
40250b57cec5SDimitry Andric cast<llvm::ConstantInt>(idx)->isZero());
40260b57cec5SDimitry Andric #endif
40270b57cec5SDimitry Andric
40280b57cec5SDimitry Andric // Determine the element size of the statically-sized base. This is
40290b57cec5SDimitry Andric // the thing that the indices are expressed in terms of.
40300b57cec5SDimitry Andric if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
40310b57cec5SDimitry Andric eltType = getFixedSizeElementType(CGF.getContext(), vla);
40320b57cec5SDimitry Andric }
40330b57cec5SDimitry Andric
40340b57cec5SDimitry Andric // We can use that to compute the best alignment of the element.
40350b57cec5SDimitry Andric CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
40360b57cec5SDimitry Andric CharUnits eltAlign =
40370b57cec5SDimitry Andric getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
40380b57cec5SDimitry Andric
4039c9157d92SDimitry Andric if (hasBPFPreserveStaticOffset(Base))
4040c9157d92SDimitry Andric addr = wrapWithBPFPreserveStaticOffset(CGF, addr);
4041c9157d92SDimitry Andric
40420b57cec5SDimitry Andric llvm::Value *eltPtr;
40430b57cec5SDimitry Andric auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
4044480093f4SDimitry Andric if (!LastIndex ||
4045480093f4SDimitry Andric (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
40460b57cec5SDimitry Andric eltPtr = emitArraySubscriptGEP(
4047fe6060f1SDimitry Andric CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
4048fe6060f1SDimitry Andric signedIndices, loc, name);
40490b57cec5SDimitry Andric } else {
40500b57cec5SDimitry Andric // Remember the original array subscript for bpf target
40510b57cec5SDimitry Andric unsigned idx = LastIndex->getZExtValue();
4052a7dea167SDimitry Andric llvm::DIType *DbgInfo = nullptr;
4053a7dea167SDimitry Andric if (arrayType)
4054a7dea167SDimitry Andric DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
4055480093f4SDimitry Andric eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
4056480093f4SDimitry Andric addr.getPointer(),
40570b57cec5SDimitry Andric indices.size() - 1,
4058a7dea167SDimitry Andric idx, DbgInfo);
40590b57cec5SDimitry Andric }
40600b57cec5SDimitry Andric
40610eae32dcSDimitry Andric return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
40620b57cec5SDimitry Andric }
40630b57cec5SDimitry Andric
40646c20abcdSDimitry Andric /// The offset of a field from the beginning of the record.
getFieldOffsetInBits(CodeGenFunction & CGF,const RecordDecl * RD,const FieldDecl * FD,int64_t & Offset)40656c20abcdSDimitry Andric static bool getFieldOffsetInBits(CodeGenFunction &CGF, const RecordDecl *RD,
40666c20abcdSDimitry Andric const FieldDecl *FD, int64_t &Offset) {
40676c20abcdSDimitry Andric ASTContext &Ctx = CGF.getContext();
40686c20abcdSDimitry Andric const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
40696c20abcdSDimitry Andric unsigned FieldNo = 0;
40706c20abcdSDimitry Andric
40716c20abcdSDimitry Andric for (const Decl *D : RD->decls()) {
40726c20abcdSDimitry Andric if (const auto *Record = dyn_cast<RecordDecl>(D))
40736c20abcdSDimitry Andric if (getFieldOffsetInBits(CGF, Record, FD, Offset)) {
40746c20abcdSDimitry Andric Offset += Layout.getFieldOffset(FieldNo);
40756c20abcdSDimitry Andric return true;
40766c20abcdSDimitry Andric }
40776c20abcdSDimitry Andric
40786c20abcdSDimitry Andric if (const auto *Field = dyn_cast<FieldDecl>(D))
40796c20abcdSDimitry Andric if (FD == Field) {
40806c20abcdSDimitry Andric Offset += Layout.getFieldOffset(FieldNo);
40816c20abcdSDimitry Andric return true;
40826c20abcdSDimitry Andric }
40836c20abcdSDimitry Andric
40846c20abcdSDimitry Andric if (isa<FieldDecl>(D))
40856c20abcdSDimitry Andric ++FieldNo;
40866c20abcdSDimitry Andric }
40876c20abcdSDimitry Andric
40886c20abcdSDimitry Andric return false;
40896c20abcdSDimitry Andric }
40906c20abcdSDimitry Andric
40916c20abcdSDimitry Andric /// Returns the relative offset difference between \p FD1 and \p FD2.
40926c20abcdSDimitry Andric /// \code
40936c20abcdSDimitry Andric /// offsetof(struct foo, FD1) - offsetof(struct foo, FD2)
40946c20abcdSDimitry Andric /// \endcode
40956c20abcdSDimitry Andric /// Both fields must be within the same struct.
getOffsetDifferenceInBits(CodeGenFunction & CGF,const FieldDecl * FD1,const FieldDecl * FD2)40966c20abcdSDimitry Andric static std::optional<int64_t> getOffsetDifferenceInBits(CodeGenFunction &CGF,
40976c20abcdSDimitry Andric const FieldDecl *FD1,
40986c20abcdSDimitry Andric const FieldDecl *FD2) {
40996c20abcdSDimitry Andric const RecordDecl *FD1OuterRec =
41006c20abcdSDimitry Andric FD1->getParent()->getOuterLexicalRecordContext();
41016c20abcdSDimitry Andric const RecordDecl *FD2OuterRec =
41026c20abcdSDimitry Andric FD2->getParent()->getOuterLexicalRecordContext();
41036c20abcdSDimitry Andric
41046c20abcdSDimitry Andric if (FD1OuterRec != FD2OuterRec)
41056c20abcdSDimitry Andric // Fields must be within the same RecordDecl.
41066c20abcdSDimitry Andric return std::optional<int64_t>();
41076c20abcdSDimitry Andric
41086c20abcdSDimitry Andric int64_t FD1Offset = 0;
41096c20abcdSDimitry Andric if (!getFieldOffsetInBits(CGF, FD1OuterRec, FD1, FD1Offset))
41106c20abcdSDimitry Andric return std::optional<int64_t>();
41116c20abcdSDimitry Andric
41126c20abcdSDimitry Andric int64_t FD2Offset = 0;
41136c20abcdSDimitry Andric if (!getFieldOffsetInBits(CGF, FD2OuterRec, FD2, FD2Offset))
41146c20abcdSDimitry Andric return std::optional<int64_t>();
41156c20abcdSDimitry Andric
41166c20abcdSDimitry Andric return std::make_optional<int64_t>(FD1Offset - FD2Offset);
41176c20abcdSDimitry Andric }
41186c20abcdSDimitry Andric
EmitArraySubscriptExpr(const ArraySubscriptExpr * E,bool Accessed)41190b57cec5SDimitry Andric LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
41200b57cec5SDimitry Andric bool Accessed) {
41210b57cec5SDimitry Andric // The index must always be an integer, which is not an aggregate. Emit it
41220b57cec5SDimitry Andric // in lexical order (this complexity is, sadly, required by C++17).
41230b57cec5SDimitry Andric llvm::Value *IdxPre =
41240b57cec5SDimitry Andric (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
41250b57cec5SDimitry Andric bool SignedIndices = false;
41260b57cec5SDimitry Andric auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
41270b57cec5SDimitry Andric auto *Idx = IdxPre;
41280b57cec5SDimitry Andric if (E->getLHS() != E->getIdx()) {
41290b57cec5SDimitry Andric assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
41300b57cec5SDimitry Andric Idx = EmitScalarExpr(E->getIdx());
41310b57cec5SDimitry Andric }
41320b57cec5SDimitry Andric
41330b57cec5SDimitry Andric QualType IdxTy = E->getIdx()->getType();
41340b57cec5SDimitry Andric bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
41350b57cec5SDimitry Andric SignedIndices |= IdxSigned;
41360b57cec5SDimitry Andric
41370b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ArrayBounds))
41380b57cec5SDimitry Andric EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
41390b57cec5SDimitry Andric
41400b57cec5SDimitry Andric // Extend or truncate the index type to 32 or 64-bits.
41410b57cec5SDimitry Andric if (Promote && Idx->getType() != IntPtrTy)
41420b57cec5SDimitry Andric Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
41430b57cec5SDimitry Andric
41440b57cec5SDimitry Andric return Idx;
41450b57cec5SDimitry Andric };
41460b57cec5SDimitry Andric IdxPre = nullptr;
41470b57cec5SDimitry Andric
41480b57cec5SDimitry Andric // If the base is a vector type, then we are forming a vector element lvalue
41490b57cec5SDimitry Andric // with this subscript.
41500b57cec5SDimitry Andric if (E->getBase()->getType()->isVectorType() &&
41510b57cec5SDimitry Andric !isa<ExtVectorElementExpr>(E->getBase())) {
41520b57cec5SDimitry Andric // Emit the vector as an lvalue to get its address.
41530b57cec5SDimitry Andric LValue LHS = EmitLValue(E->getBase());
41540b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/false);
41550b57cec5SDimitry Andric assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
4156480093f4SDimitry Andric return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
4157480093f4SDimitry Andric E->getBase()->getType(), LHS.getBaseInfo(),
4158480093f4SDimitry Andric TBAAAccessInfo());
41590b57cec5SDimitry Andric }
41600b57cec5SDimitry Andric
41610b57cec5SDimitry Andric // All the other cases basically behave like simple offsetting.
41620b57cec5SDimitry Andric
41630b57cec5SDimitry Andric // Handle the extvector case we ignored above.
41640b57cec5SDimitry Andric if (isa<ExtVectorElementExpr>(E->getBase())) {
41650b57cec5SDimitry Andric LValue LV = EmitLValue(E->getBase());
41660b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
41670b57cec5SDimitry Andric Address Addr = EmitExtVectorElementLValue(LV);
41680b57cec5SDimitry Andric
41690b57cec5SDimitry Andric QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
41700b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
41710b57cec5SDimitry Andric SignedIndices, E->getExprLoc());
41720b57cec5SDimitry Andric return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
41730b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, EltType));
41740b57cec5SDimitry Andric }
41750b57cec5SDimitry Andric
41760b57cec5SDimitry Andric LValueBaseInfo EltBaseInfo;
41770b57cec5SDimitry Andric TBAAAccessInfo EltTBAAInfo;
41780b57cec5SDimitry Andric Address Addr = Address::invalid();
41790b57cec5SDimitry Andric if (const VariableArrayType *vla =
41800b57cec5SDimitry Andric getContext().getAsVariableArrayType(E->getType())) {
41810b57cec5SDimitry Andric // The base must be a pointer, which is not an aggregate. Emit
41820b57cec5SDimitry Andric // it. It needs to be emitted first in case it's what captures
41830b57cec5SDimitry Andric // the VLA bounds.
41840b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
41850b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
41860b57cec5SDimitry Andric
41870b57cec5SDimitry Andric // The element count here is the total number of non-VLA elements.
41880b57cec5SDimitry Andric llvm::Value *numElements = getVLASize(vla).NumElts;
41890b57cec5SDimitry Andric
41900b57cec5SDimitry Andric // Effectively, the multiply by the VLA size is part of the GEP.
41910b57cec5SDimitry Andric // GEP indexes are signed, and scaling an index isn't permitted to
41920b57cec5SDimitry Andric // signed-overflow, so we use the same semantics for our explicit
41930b57cec5SDimitry Andric // multiply. We suppress this if overflow is not undefined behavior.
41940b57cec5SDimitry Andric if (getLangOpts().isSignedOverflowDefined()) {
41950b57cec5SDimitry Andric Idx = Builder.CreateMul(Idx, numElements);
41960b57cec5SDimitry Andric } else {
41970b57cec5SDimitry Andric Idx = Builder.CreateNSWMul(Idx, numElements);
41980b57cec5SDimitry Andric }
41990b57cec5SDimitry Andric
42000b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
42010b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(),
42020b57cec5SDimitry Andric SignedIndices, E->getExprLoc());
42030b57cec5SDimitry Andric
42040b57cec5SDimitry Andric } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
42050b57cec5SDimitry Andric // Indexing over an interface, as in "NSString *P; P[4];"
42060b57cec5SDimitry Andric
42070b57cec5SDimitry Andric // Emit the base pointer.
42080b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
42090b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
42100b57cec5SDimitry Andric
42110b57cec5SDimitry Andric CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
42120b57cec5SDimitry Andric llvm::Value *InterfaceSizeVal =
42130b57cec5SDimitry Andric llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
42140b57cec5SDimitry Andric
42150b57cec5SDimitry Andric llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
42160b57cec5SDimitry Andric
42170b57cec5SDimitry Andric // We don't necessarily build correct LLVM struct types for ObjC
42180b57cec5SDimitry Andric // interfaces, so we can't rely on GEP to do this scaling
42190b57cec5SDimitry Andric // correctly, so we need to cast to i8*. FIXME: is this actually
42200b57cec5SDimitry Andric // true? A lot of other things in the fragile ABI would break...
422181ad6265SDimitry Andric llvm::Type *OrigBaseElemTy = Addr.getElementType();
42220b57cec5SDimitry Andric
42230b57cec5SDimitry Andric // Do the GEP.
42240b57cec5SDimitry Andric CharUnits EltAlign =
42250b57cec5SDimitry Andric getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
42260b57cec5SDimitry Andric llvm::Value *EltPtr =
4227fe013be4SDimitry Andric emitArraySubscriptGEP(*this, Int8Ty, Addr.getPointer(), ScaledIdx,
4228fe013be4SDimitry Andric false, SignedIndices, E->getExprLoc());
4229fe013be4SDimitry Andric Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
42300b57cec5SDimitry Andric } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
42310b57cec5SDimitry Andric // If this is A[i] where A is an array, the frontend will have decayed the
42320b57cec5SDimitry Andric // base to be a ArrayToPointerDecay implicit cast. While correct, it is
42330b57cec5SDimitry Andric // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
42340b57cec5SDimitry Andric // "gep x, i" here. Emit one "gep A, 0, i".
42350b57cec5SDimitry Andric assert(Array->getType()->isArrayType() &&
42360b57cec5SDimitry Andric "Array to pointer decay must have array source type!");
42370b57cec5SDimitry Andric LValue ArrayLV;
42380b57cec5SDimitry Andric // For simple multidimensional array indexing, set the 'accessed' flag for
42390b57cec5SDimitry Andric // better bounds-checking of the base expression.
42400b57cec5SDimitry Andric if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
42410b57cec5SDimitry Andric ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
42420b57cec5SDimitry Andric else
42430b57cec5SDimitry Andric ArrayLV = EmitLValue(Array);
42440b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
42450b57cec5SDimitry Andric
42466c20abcdSDimitry Andric if (SanOpts.has(SanitizerKind::ArrayBounds)) {
42476c20abcdSDimitry Andric // If the array being accessed has a "counted_by" attribute, generate
42486c20abcdSDimitry Andric // bounds checking code. The "count" field is at the top level of the
42496c20abcdSDimitry Andric // struct or in an anonymous struct, that's also at the top level. Future
42506c20abcdSDimitry Andric // expansions may allow the "count" to reside at any place in the struct,
42516c20abcdSDimitry Andric // but the value of "counted_by" will be a "simple" path to the count,
42526c20abcdSDimitry Andric // i.e. "a.b.count", so we shouldn't need the full force of EmitLValue or
42536c20abcdSDimitry Andric // similar to emit the correct GEP.
42546c20abcdSDimitry Andric const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
42556c20abcdSDimitry Andric getLangOpts().getStrictFlexArraysLevel();
42566c20abcdSDimitry Andric
42576c20abcdSDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(Array);
42586c20abcdSDimitry Andric ME &&
42596c20abcdSDimitry Andric ME->isFlexibleArrayMemberLike(getContext(), StrictFlexArraysLevel) &&
42606c20abcdSDimitry Andric ME->getMemberDecl()->hasAttr<CountedByAttr>()) {
42616c20abcdSDimitry Andric const FieldDecl *FAMDecl = dyn_cast<FieldDecl>(ME->getMemberDecl());
42626c20abcdSDimitry Andric if (const FieldDecl *CountFD = FindCountedByField(FAMDecl)) {
42636c20abcdSDimitry Andric if (std::optional<int64_t> Diff =
42646c20abcdSDimitry Andric getOffsetDifferenceInBits(*this, CountFD, FAMDecl)) {
42656c20abcdSDimitry Andric CharUnits OffsetDiff = CGM.getContext().toCharUnitsFromBits(*Diff);
42666c20abcdSDimitry Andric
42676c20abcdSDimitry Andric // Create a GEP with a byte offset between the FAM and count and
42686c20abcdSDimitry Andric // use that to load the count value.
42696c20abcdSDimitry Andric Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(
42706c20abcdSDimitry Andric ArrayLV.getAddress(*this), Int8PtrTy, Int8Ty);
42716c20abcdSDimitry Andric
42726c20abcdSDimitry Andric llvm::Type *CountTy = ConvertType(CountFD->getType());
42736c20abcdSDimitry Andric llvm::Value *Res = Builder.CreateInBoundsGEP(
42746c20abcdSDimitry Andric Int8Ty, Addr.getPointer(),
42756c20abcdSDimitry Andric Builder.getInt32(OffsetDiff.getQuantity()), ".counted_by.gep");
42766c20abcdSDimitry Andric Res = Builder.CreateAlignedLoad(CountTy, Res, getIntAlign(),
42776c20abcdSDimitry Andric ".counted_by.load");
42786c20abcdSDimitry Andric
42796c20abcdSDimitry Andric // Now emit the bounds checking.
42806c20abcdSDimitry Andric EmitBoundsCheckImpl(E, Res, Idx, E->getIdx()->getType(),
42816c20abcdSDimitry Andric Array->getType(), Accessed);
42826c20abcdSDimitry Andric }
42836c20abcdSDimitry Andric }
42846c20abcdSDimitry Andric }
42856c20abcdSDimitry Andric }
42866c20abcdSDimitry Andric
42870b57cec5SDimitry Andric // Propagate the alignment from the array itself to the result.
4288a7dea167SDimitry Andric QualType arrayType = Array->getType();
42890b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(
4290480093f4SDimitry Andric *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
42910b57cec5SDimitry Andric E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
4292480093f4SDimitry Andric E->getExprLoc(), &arrayType, E->getBase());
42930b57cec5SDimitry Andric EltBaseInfo = ArrayLV.getBaseInfo();
42940b57cec5SDimitry Andric EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
42950b57cec5SDimitry Andric } else {
42960b57cec5SDimitry Andric // The base must be a pointer; emit it with an estimate of its alignment.
42970b57cec5SDimitry Andric Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
42980b57cec5SDimitry Andric auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4299a7dea167SDimitry Andric QualType ptrType = E->getBase()->getType();
43000b57cec5SDimitry Andric Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
43010b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(),
4302480093f4SDimitry Andric SignedIndices, E->getExprLoc(), &ptrType,
4303480093f4SDimitry Andric E->getBase());
43040b57cec5SDimitry Andric }
43050b57cec5SDimitry Andric
43060b57cec5SDimitry Andric LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
43070b57cec5SDimitry Andric
43080b57cec5SDimitry Andric if (getLangOpts().ObjC &&
43090b57cec5SDimitry Andric getLangOpts().getGC() != LangOptions::NonGC) {
43100b57cec5SDimitry Andric LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
43110b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV);
43120b57cec5SDimitry Andric }
43130b57cec5SDimitry Andric return LV;
43140b57cec5SDimitry Andric }
43150b57cec5SDimitry Andric
EmitMatrixSubscriptExpr(const MatrixSubscriptExpr * E)43165ffd83dbSDimitry Andric LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
43175ffd83dbSDimitry Andric assert(
43185ffd83dbSDimitry Andric !E->isIncomplete() &&
43195ffd83dbSDimitry Andric "incomplete matrix subscript expressions should be rejected during Sema");
43205ffd83dbSDimitry Andric LValue Base = EmitLValue(E->getBase());
43215ffd83dbSDimitry Andric llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
43225ffd83dbSDimitry Andric llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
43235ffd83dbSDimitry Andric llvm::Value *NumRows = Builder.getIntN(
43245ffd83dbSDimitry Andric RowIdx->getType()->getScalarSizeInBits(),
4325e8d8bef9SDimitry Andric E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
43265ffd83dbSDimitry Andric llvm::Value *FinalIdx =
43275ffd83dbSDimitry Andric Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
43285ffd83dbSDimitry Andric return LValue::MakeMatrixElt(
43295ffd83dbSDimitry Andric MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
43305ffd83dbSDimitry Andric E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
43315ffd83dbSDimitry Andric }
43325ffd83dbSDimitry Andric
emitOMPArraySectionBase(CodeGenFunction & CGF,const Expr * Base,LValueBaseInfo & BaseInfo,TBAAAccessInfo & TBAAInfo,QualType BaseTy,QualType ElTy,bool IsLowerBound)43330b57cec5SDimitry Andric static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
43340b57cec5SDimitry Andric LValueBaseInfo &BaseInfo,
43350b57cec5SDimitry Andric TBAAAccessInfo &TBAAInfo,
43360b57cec5SDimitry Andric QualType BaseTy, QualType ElTy,
43370b57cec5SDimitry Andric bool IsLowerBound) {
43380b57cec5SDimitry Andric LValue BaseLVal;
43390b57cec5SDimitry Andric if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
43400b57cec5SDimitry Andric BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
43410b57cec5SDimitry Andric if (BaseTy->isArrayType()) {
4342480093f4SDimitry Andric Address Addr = BaseLVal.getAddress(CGF);
43430b57cec5SDimitry Andric BaseInfo = BaseLVal.getBaseInfo();
43440b57cec5SDimitry Andric
43450b57cec5SDimitry Andric // If the array type was an incomplete type, we need to make sure
43460b57cec5SDimitry Andric // the decay ends up being the right type.
43470b57cec5SDimitry Andric llvm::Type *NewTy = CGF.ConvertType(BaseTy);
4348fe013be4SDimitry Andric Addr = Addr.withElementType(NewTy);
43490b57cec5SDimitry Andric
43500b57cec5SDimitry Andric // Note that VLA pointers are always decayed, so we don't need to do
43510b57cec5SDimitry Andric // anything here.
43520b57cec5SDimitry Andric if (!BaseTy->isVariableArrayType()) {
43530b57cec5SDimitry Andric assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
43540b57cec5SDimitry Andric "Expected pointer to array");
43550b57cec5SDimitry Andric Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
43560b57cec5SDimitry Andric }
43570b57cec5SDimitry Andric
4358fe013be4SDimitry Andric return Addr.withElementType(CGF.ConvertTypeForMem(ElTy));
43590b57cec5SDimitry Andric }
43600b57cec5SDimitry Andric LValueBaseInfo TypeBaseInfo;
43610b57cec5SDimitry Andric TBAAAccessInfo TypeTBAAInfo;
43625ffd83dbSDimitry Andric CharUnits Align =
43635ffd83dbSDimitry Andric CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
43640b57cec5SDimitry Andric BaseInfo.mergeForCast(TypeBaseInfo);
43650b57cec5SDimitry Andric TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
436681ad6265SDimitry Andric return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)),
436781ad6265SDimitry Andric CGF.ConvertTypeForMem(ElTy), Align);
43680b57cec5SDimitry Andric }
43690b57cec5SDimitry Andric return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
43700b57cec5SDimitry Andric }
43710b57cec5SDimitry Andric
EmitOMPArraySectionExpr(const OMPArraySectionExpr * E,bool IsLowerBound)43720b57cec5SDimitry Andric LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
43730b57cec5SDimitry Andric bool IsLowerBound) {
43740b57cec5SDimitry Andric QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
43750b57cec5SDimitry Andric QualType ResultExprTy;
43760b57cec5SDimitry Andric if (auto *AT = getContext().getAsArrayType(BaseTy))
43770b57cec5SDimitry Andric ResultExprTy = AT->getElementType();
43780b57cec5SDimitry Andric else
43790b57cec5SDimitry Andric ResultExprTy = BaseTy->getPointeeType();
43800b57cec5SDimitry Andric llvm::Value *Idx = nullptr;
43815ffd83dbSDimitry Andric if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
43820b57cec5SDimitry Andric // Requesting lower bound or upper bound, but without provided length and
43830b57cec5SDimitry Andric // without ':' symbol for the default length -> length = 1.
43840b57cec5SDimitry Andric // Idx = LowerBound ?: 0;
43850b57cec5SDimitry Andric if (auto *LowerBound = E->getLowerBound()) {
43860b57cec5SDimitry Andric Idx = Builder.CreateIntCast(
43870b57cec5SDimitry Andric EmitScalarExpr(LowerBound), IntPtrTy,
43880b57cec5SDimitry Andric LowerBound->getType()->hasSignedIntegerRepresentation());
43890b57cec5SDimitry Andric } else
43900b57cec5SDimitry Andric Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
43910b57cec5SDimitry Andric } else {
43920b57cec5SDimitry Andric // Try to emit length or lower bound as constant. If this is possible, 1
43930b57cec5SDimitry Andric // is subtracted from constant length or lower bound. Otherwise, emit LLVM
43940b57cec5SDimitry Andric // IR (LB + Len) - 1.
43950b57cec5SDimitry Andric auto &C = CGM.getContext();
43960b57cec5SDimitry Andric auto *Length = E->getLength();
43970b57cec5SDimitry Andric llvm::APSInt ConstLength;
43980b57cec5SDimitry Andric if (Length) {
43990b57cec5SDimitry Andric // Idx = LowerBound + Length - 1;
4400bdd1243dSDimitry Andric if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
4401e8d8bef9SDimitry Andric ConstLength = CL->zextOrTrunc(PointerWidthInBits);
44020b57cec5SDimitry Andric Length = nullptr;
44030b57cec5SDimitry Andric }
44040b57cec5SDimitry Andric auto *LowerBound = E->getLowerBound();
44050b57cec5SDimitry Andric llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
4406e8d8bef9SDimitry Andric if (LowerBound) {
4407bdd1243dSDimitry Andric if (std::optional<llvm::APSInt> LB =
4408bdd1243dSDimitry Andric LowerBound->getIntegerConstantExpr(C)) {
4409e8d8bef9SDimitry Andric ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
44100b57cec5SDimitry Andric LowerBound = nullptr;
44110b57cec5SDimitry Andric }
4412e8d8bef9SDimitry Andric }
44130b57cec5SDimitry Andric if (!Length)
44140b57cec5SDimitry Andric --ConstLength;
44150b57cec5SDimitry Andric else if (!LowerBound)
44160b57cec5SDimitry Andric --ConstLowerBound;
44170b57cec5SDimitry Andric
44180b57cec5SDimitry Andric if (Length || LowerBound) {
44190b57cec5SDimitry Andric auto *LowerBoundVal =
44200b57cec5SDimitry Andric LowerBound
44210b57cec5SDimitry Andric ? Builder.CreateIntCast(
44220b57cec5SDimitry Andric EmitScalarExpr(LowerBound), IntPtrTy,
44230b57cec5SDimitry Andric LowerBound->getType()->hasSignedIntegerRepresentation())
44240b57cec5SDimitry Andric : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
44250b57cec5SDimitry Andric auto *LengthVal =
44260b57cec5SDimitry Andric Length
44270b57cec5SDimitry Andric ? Builder.CreateIntCast(
44280b57cec5SDimitry Andric EmitScalarExpr(Length), IntPtrTy,
44290b57cec5SDimitry Andric Length->getType()->hasSignedIntegerRepresentation())
44300b57cec5SDimitry Andric : llvm::ConstantInt::get(IntPtrTy, ConstLength);
44310b57cec5SDimitry Andric Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
44320b57cec5SDimitry Andric /*HasNUW=*/false,
44330b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined());
44340b57cec5SDimitry Andric if (Length && LowerBound) {
44350b57cec5SDimitry Andric Idx = Builder.CreateSub(
44360b57cec5SDimitry Andric Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
44370b57cec5SDimitry Andric /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
44380b57cec5SDimitry Andric }
44390b57cec5SDimitry Andric } else
44400b57cec5SDimitry Andric Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
44410b57cec5SDimitry Andric } else {
44420b57cec5SDimitry Andric // Idx = ArraySize - 1;
44430b57cec5SDimitry Andric QualType ArrayTy = BaseTy->isPointerType()
44440b57cec5SDimitry Andric ? E->getBase()->IgnoreParenImpCasts()->getType()
44450b57cec5SDimitry Andric : BaseTy;
44460b57cec5SDimitry Andric if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
44470b57cec5SDimitry Andric Length = VAT->getSizeExpr();
4448bdd1243dSDimitry Andric if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
4449e8d8bef9SDimitry Andric ConstLength = *L;
44500b57cec5SDimitry Andric Length = nullptr;
4451e8d8bef9SDimitry Andric }
44520b57cec5SDimitry Andric } else {
44530b57cec5SDimitry Andric auto *CAT = C.getAsConstantArrayType(ArrayTy);
4454fe013be4SDimitry Andric assert(CAT && "unexpected type for array initializer");
44550b57cec5SDimitry Andric ConstLength = CAT->getSize();
44560b57cec5SDimitry Andric }
44570b57cec5SDimitry Andric if (Length) {
44580b57cec5SDimitry Andric auto *LengthVal = Builder.CreateIntCast(
44590b57cec5SDimitry Andric EmitScalarExpr(Length), IntPtrTy,
44600b57cec5SDimitry Andric Length->getType()->hasSignedIntegerRepresentation());
44610b57cec5SDimitry Andric Idx = Builder.CreateSub(
44620b57cec5SDimitry Andric LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
44630b57cec5SDimitry Andric /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
44640b57cec5SDimitry Andric } else {
44650b57cec5SDimitry Andric ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
44660b57cec5SDimitry Andric --ConstLength;
44670b57cec5SDimitry Andric Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
44680b57cec5SDimitry Andric }
44690b57cec5SDimitry Andric }
44700b57cec5SDimitry Andric }
44710b57cec5SDimitry Andric assert(Idx);
44720b57cec5SDimitry Andric
44730b57cec5SDimitry Andric Address EltPtr = Address::invalid();
44740b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
44750b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
44760b57cec5SDimitry Andric if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
44770b57cec5SDimitry Andric // The base must be a pointer, which is not an aggregate. Emit
44780b57cec5SDimitry Andric // it. It needs to be emitted first in case it's what captures
44790b57cec5SDimitry Andric // the VLA bounds.
44800b57cec5SDimitry Andric Address Base =
44810b57cec5SDimitry Andric emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
44820b57cec5SDimitry Andric BaseTy, VLA->getElementType(), IsLowerBound);
44830b57cec5SDimitry Andric // The element count here is the total number of non-VLA elements.
44840b57cec5SDimitry Andric llvm::Value *NumElements = getVLASize(VLA).NumElts;
44850b57cec5SDimitry Andric
44860b57cec5SDimitry Andric // Effectively, the multiply by the VLA size is part of the GEP.
44870b57cec5SDimitry Andric // GEP indexes are signed, and scaling an index isn't permitted to
44880b57cec5SDimitry Andric // signed-overflow, so we use the same semantics for our explicit
44890b57cec5SDimitry Andric // multiply. We suppress this if overflow is not undefined behavior.
44900b57cec5SDimitry Andric if (getLangOpts().isSignedOverflowDefined())
44910b57cec5SDimitry Andric Idx = Builder.CreateMul(Idx, NumElements);
44920b57cec5SDimitry Andric else
44930b57cec5SDimitry Andric Idx = Builder.CreateNSWMul(Idx, NumElements);
44940b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
44950b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(),
44960b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc());
44970b57cec5SDimitry Andric } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
44980b57cec5SDimitry Andric // If this is A[i] where A is an array, the frontend will have decayed the
44990b57cec5SDimitry Andric // base to be a ArrayToPointerDecay implicit cast. While correct, it is
45000b57cec5SDimitry Andric // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
45010b57cec5SDimitry Andric // "gep x, i" here. Emit one "gep A, 0, i".
45020b57cec5SDimitry Andric assert(Array->getType()->isArrayType() &&
45030b57cec5SDimitry Andric "Array to pointer decay must have array source type!");
45040b57cec5SDimitry Andric LValue ArrayLV;
45050b57cec5SDimitry Andric // For simple multidimensional array indexing, set the 'accessed' flag for
45060b57cec5SDimitry Andric // better bounds-checking of the base expression.
45070b57cec5SDimitry Andric if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
45080b57cec5SDimitry Andric ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
45090b57cec5SDimitry Andric else
45100b57cec5SDimitry Andric ArrayLV = EmitLValue(Array);
45110b57cec5SDimitry Andric
45120b57cec5SDimitry Andric // Propagate the alignment from the array itself to the result.
45130b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP(
4514480093f4SDimitry Andric *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
45150b57cec5SDimitry Andric ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
45160b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc());
45170b57cec5SDimitry Andric BaseInfo = ArrayLV.getBaseInfo();
45180b57cec5SDimitry Andric TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
45190b57cec5SDimitry Andric } else {
45200b57cec5SDimitry Andric Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
45210b57cec5SDimitry Andric TBAAInfo, BaseTy, ResultExprTy,
45220b57cec5SDimitry Andric IsLowerBound);
45230b57cec5SDimitry Andric EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
45240b57cec5SDimitry Andric !getLangOpts().isSignedOverflowDefined(),
45250b57cec5SDimitry Andric /*signedIndices=*/false, E->getExprLoc());
45260b57cec5SDimitry Andric }
45270b57cec5SDimitry Andric
45280b57cec5SDimitry Andric return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
45290b57cec5SDimitry Andric }
45300b57cec5SDimitry Andric
45310b57cec5SDimitry Andric LValue CodeGenFunction::
EmitExtVectorElementExpr(const ExtVectorElementExpr * E)45320b57cec5SDimitry Andric EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
45330b57cec5SDimitry Andric // Emit the base vector as an l-value.
45340b57cec5SDimitry Andric LValue Base;
45350b57cec5SDimitry Andric
45360b57cec5SDimitry Andric // ExtVectorElementExpr's base can either be a vector or pointer to vector.
45370b57cec5SDimitry Andric if (E->isArrow()) {
45380b57cec5SDimitry Andric // If it is a pointer to a vector, emit the address and form an lvalue with
45390b57cec5SDimitry Andric // it.
45400b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
45410b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
45420b57cec5SDimitry Andric Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4543480093f4SDimitry Andric const auto *PT = E->getBase()->getType()->castAs<PointerType>();
45440b57cec5SDimitry Andric Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
45450b57cec5SDimitry Andric Base.getQuals().removeObjCGCAttr();
45460b57cec5SDimitry Andric } else if (E->getBase()->isGLValue()) {
45470b57cec5SDimitry Andric // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
45480b57cec5SDimitry Andric // emit the base as an lvalue.
45490b57cec5SDimitry Andric assert(E->getBase()->getType()->isVectorType());
45500b57cec5SDimitry Andric Base = EmitLValue(E->getBase());
45510b57cec5SDimitry Andric } else {
45520b57cec5SDimitry Andric // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
45530b57cec5SDimitry Andric assert(E->getBase()->getType()->isVectorType() &&
45540b57cec5SDimitry Andric "Result must be a vector");
45550b57cec5SDimitry Andric llvm::Value *Vec = EmitScalarExpr(E->getBase());
45560b57cec5SDimitry Andric
45570b57cec5SDimitry Andric // Store the vector to memory (because LValue wants an address).
45580b57cec5SDimitry Andric Address VecMem = CreateMemTemp(E->getBase()->getType());
45590b57cec5SDimitry Andric Builder.CreateStore(Vec, VecMem);
45600b57cec5SDimitry Andric Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
45610b57cec5SDimitry Andric AlignmentSource::Decl);
45620b57cec5SDimitry Andric }
45630b57cec5SDimitry Andric
45640b57cec5SDimitry Andric QualType type =
45650b57cec5SDimitry Andric E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
45660b57cec5SDimitry Andric
45670b57cec5SDimitry Andric // Encode the element access list into a vector of unsigned indices.
45680b57cec5SDimitry Andric SmallVector<uint32_t, 4> Indices;
45690b57cec5SDimitry Andric E->getEncodedElementAccess(Indices);
45700b57cec5SDimitry Andric
45710b57cec5SDimitry Andric if (Base.isSimple()) {
45720b57cec5SDimitry Andric llvm::Constant *CV =
45730b57cec5SDimitry Andric llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4574480093f4SDimitry Andric return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
45750b57cec5SDimitry Andric Base.getBaseInfo(), TBAAAccessInfo());
45760b57cec5SDimitry Andric }
45770b57cec5SDimitry Andric assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
45780b57cec5SDimitry Andric
45790b57cec5SDimitry Andric llvm::Constant *BaseElts = Base.getExtVectorElts();
45800b57cec5SDimitry Andric SmallVector<llvm::Constant *, 4> CElts;
45810b57cec5SDimitry Andric
45820b57cec5SDimitry Andric for (unsigned i = 0, e = Indices.size(); i != e; ++i)
45830b57cec5SDimitry Andric CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
45840b57cec5SDimitry Andric llvm::Constant *CV = llvm::ConstantVector::get(CElts);
45850b57cec5SDimitry Andric return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
45860b57cec5SDimitry Andric Base.getBaseInfo(), TBAAAccessInfo());
45870b57cec5SDimitry Andric }
45880b57cec5SDimitry Andric
EmitMemberExpr(const MemberExpr * E)45890b57cec5SDimitry Andric LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
45900b57cec5SDimitry Andric if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
45910b57cec5SDimitry Andric EmitIgnoredExpr(E->getBase());
45920b57cec5SDimitry Andric return EmitDeclRefLValue(DRE);
45930b57cec5SDimitry Andric }
45940b57cec5SDimitry Andric
45950b57cec5SDimitry Andric Expr *BaseExpr = E->getBase();
45960b57cec5SDimitry Andric // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
45970b57cec5SDimitry Andric LValue BaseLV;
45980b57cec5SDimitry Andric if (E->isArrow()) {
45990b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
46000b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
46010b57cec5SDimitry Andric Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
46020b57cec5SDimitry Andric QualType PtrTy = BaseExpr->getType()->getPointeeType();
46030b57cec5SDimitry Andric SanitizerSet SkippedChecks;
46040b57cec5SDimitry Andric bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
46050b57cec5SDimitry Andric if (IsBaseCXXThis)
46060b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Alignment, true);
46070b57cec5SDimitry Andric if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
46080b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, true);
46090b57cec5SDimitry Andric EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
46100b57cec5SDimitry Andric /*Alignment=*/CharUnits::Zero(), SkippedChecks);
46110b57cec5SDimitry Andric BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
46120b57cec5SDimitry Andric } else
46130b57cec5SDimitry Andric BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
46140b57cec5SDimitry Andric
46150b57cec5SDimitry Andric NamedDecl *ND = E->getMemberDecl();
46160b57cec5SDimitry Andric if (auto *Field = dyn_cast<FieldDecl>(ND)) {
46170b57cec5SDimitry Andric LValue LV = EmitLValueForField(BaseLV, Field);
46180b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV);
4619480093f4SDimitry Andric if (getLangOpts().OpenMP) {
4620480093f4SDimitry Andric // If the member was explicitly marked as nontemporal, mark it as
4621480093f4SDimitry Andric // nontemporal. If the base lvalue is marked as nontemporal, mark access
4622480093f4SDimitry Andric // to children as nontemporal too.
4623480093f4SDimitry Andric if ((IsWrappedCXXThis(BaseExpr) &&
4624480093f4SDimitry Andric CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4625480093f4SDimitry Andric BaseLV.isNontemporal())
4626480093f4SDimitry Andric LV.setNontemporal(/*Value=*/true);
4627480093f4SDimitry Andric }
46280b57cec5SDimitry Andric return LV;
46290b57cec5SDimitry Andric }
46300b57cec5SDimitry Andric
46310b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND))
46320b57cec5SDimitry Andric return EmitFunctionDeclLValue(*this, E, FD);
46330b57cec5SDimitry Andric
46340b57cec5SDimitry Andric llvm_unreachable("Unhandled member declaration!");
46350b57cec5SDimitry Andric }
46360b57cec5SDimitry Andric
46370b57cec5SDimitry Andric /// Given that we are currently emitting a lambda, emit an l-value for
46380b57cec5SDimitry Andric /// one of its members.
4639c9157d92SDimitry Andric ///
EmitLValueForLambdaField(const FieldDecl * Field,llvm::Value * ThisValue)4640c9157d92SDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field,
4641c9157d92SDimitry Andric llvm::Value *ThisValue) {
4642c9157d92SDimitry Andric bool HasExplicitObjectParameter = false;
4643c9157d92SDimitry Andric if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(CurCodeDecl)) {
4644c9157d92SDimitry Andric HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
4645c9157d92SDimitry Andric assert(MD->getParent()->isLambda());
4646c9157d92SDimitry Andric assert(MD->getParent() == Field->getParent());
4647fe6060f1SDimitry Andric }
4648c9157d92SDimitry Andric LValue LambdaLV;
4649c9157d92SDimitry Andric if (HasExplicitObjectParameter) {
4650c9157d92SDimitry Andric const VarDecl *D = cast<CXXMethodDecl>(CurCodeDecl)->getParamDecl(0);
4651c9157d92SDimitry Andric auto It = LocalDeclMap.find(D);
4652c9157d92SDimitry Andric assert(It != LocalDeclMap.end() && "explicit parameter not loaded?");
4653c9157d92SDimitry Andric Address AddrOfExplicitObject = It->getSecond();
4654c9157d92SDimitry Andric if (D->getType()->isReferenceType())
4655c9157d92SDimitry Andric LambdaLV = EmitLoadOfReferenceLValue(AddrOfExplicitObject, D->getType(),
4656c9157d92SDimitry Andric AlignmentSource::Decl);
4657c9157d92SDimitry Andric else
4658c9157d92SDimitry Andric LambdaLV = MakeNaturalAlignAddrLValue(AddrOfExplicitObject.getPointer(),
4659c9157d92SDimitry Andric D->getType().getNonReferenceType());
4660c9157d92SDimitry Andric } else {
4661c9157d92SDimitry Andric QualType LambdaTagType = getContext().getTagDeclType(Field->getParent());
4662c9157d92SDimitry Andric LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType);
4663c9157d92SDimitry Andric }
46640b57cec5SDimitry Andric return EmitLValueForField(LambdaLV, Field);
46650b57cec5SDimitry Andric }
46660b57cec5SDimitry Andric
EmitLValueForLambdaField(const FieldDecl * Field)4667c9157d92SDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4668c9157d92SDimitry Andric return EmitLValueForLambdaField(Field, CXXABIThisValue);
4669c9157d92SDimitry Andric }
4670c9157d92SDimitry Andric
46710b57cec5SDimitry Andric /// Get the field index in the debug info. The debug info structure/union
46720b57cec5SDimitry Andric /// will ignore the unnamed bitfields.
getDebugInfoFIndex(const RecordDecl * Rec,unsigned FieldIndex)46730b57cec5SDimitry Andric unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
46740b57cec5SDimitry Andric unsigned FieldIndex) {
46750b57cec5SDimitry Andric unsigned I = 0, Skipped = 0;
46760b57cec5SDimitry Andric
4677bdd1243dSDimitry Andric for (auto *F : Rec->getDefinition()->fields()) {
46780b57cec5SDimitry Andric if (I == FieldIndex)
46790b57cec5SDimitry Andric break;
46800b57cec5SDimitry Andric if (F->isUnnamedBitfield())
46810b57cec5SDimitry Andric Skipped++;
46820b57cec5SDimitry Andric I++;
46830b57cec5SDimitry Andric }
46840b57cec5SDimitry Andric
46850b57cec5SDimitry Andric return FieldIndex - Skipped;
46860b57cec5SDimitry Andric }
46870b57cec5SDimitry Andric
46880b57cec5SDimitry Andric /// Get the address of a zero-sized field within a record. The resulting
46890b57cec5SDimitry Andric /// address doesn't necessarily have the right type.
emitAddrOfZeroSizeField(CodeGenFunction & CGF,Address Base,const FieldDecl * Field)46900b57cec5SDimitry Andric static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
46910b57cec5SDimitry Andric const FieldDecl *Field) {
46920b57cec5SDimitry Andric CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
46930b57cec5SDimitry Andric CGF.getContext().getFieldOffset(Field));
46940b57cec5SDimitry Andric if (Offset.isZero())
46950b57cec5SDimitry Andric return Base;
4696fe013be4SDimitry Andric Base = Base.withElementType(CGF.Int8Ty);
46970b57cec5SDimitry Andric return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
46980b57cec5SDimitry Andric }
46990b57cec5SDimitry Andric
47000b57cec5SDimitry Andric /// Drill down to the storage of a field without walking into
47010b57cec5SDimitry Andric /// reference types.
47020b57cec5SDimitry Andric ///
47030b57cec5SDimitry Andric /// The resulting address doesn't necessarily have the right type.
emitAddrOfFieldStorage(CodeGenFunction & CGF,Address base,const FieldDecl * field)47040b57cec5SDimitry Andric static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
47050b57cec5SDimitry Andric const FieldDecl *field) {
47060b57cec5SDimitry Andric if (field->isZeroSize(CGF.getContext()))
47070b57cec5SDimitry Andric return emitAddrOfZeroSizeField(CGF, base, field);
47080b57cec5SDimitry Andric
47090b57cec5SDimitry Andric const RecordDecl *rec = field->getParent();
47100b57cec5SDimitry Andric
47110b57cec5SDimitry Andric unsigned idx =
47120b57cec5SDimitry Andric CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
47130b57cec5SDimitry Andric
47140b57cec5SDimitry Andric return CGF.Builder.CreateStructGEP(base, idx, field->getName());
47150b57cec5SDimitry Andric }
47160b57cec5SDimitry Andric
emitPreserveStructAccess(CodeGenFunction & CGF,LValue base,Address addr,const FieldDecl * field)47175ffd83dbSDimitry Andric static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
47185ffd83dbSDimitry Andric Address addr, const FieldDecl *field) {
47190b57cec5SDimitry Andric const RecordDecl *rec = field->getParent();
47205ffd83dbSDimitry Andric llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
47215ffd83dbSDimitry Andric base.getType(), rec->getLocation());
47220b57cec5SDimitry Andric
47230b57cec5SDimitry Andric unsigned idx =
47240b57cec5SDimitry Andric CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
47250b57cec5SDimitry Andric
47260b57cec5SDimitry Andric return CGF.Builder.CreatePreserveStructAccessIndex(
47275ffd83dbSDimitry Andric addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
47280b57cec5SDimitry Andric }
47290b57cec5SDimitry Andric
hasAnyVptr(const QualType Type,const ASTContext & Context)47300b57cec5SDimitry Andric static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
47310b57cec5SDimitry Andric const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
47320b57cec5SDimitry Andric if (!RD)
47330b57cec5SDimitry Andric return false;
47340b57cec5SDimitry Andric
47350b57cec5SDimitry Andric if (RD->isDynamicClass())
47360b57cec5SDimitry Andric return true;
47370b57cec5SDimitry Andric
47380b57cec5SDimitry Andric for (const auto &Base : RD->bases())
47390b57cec5SDimitry Andric if (hasAnyVptr(Base.getType(), Context))
47400b57cec5SDimitry Andric return true;
47410b57cec5SDimitry Andric
47420b57cec5SDimitry Andric for (const FieldDecl *Field : RD->fields())
47430b57cec5SDimitry Andric if (hasAnyVptr(Field->getType(), Context))
47440b57cec5SDimitry Andric return true;
47450b57cec5SDimitry Andric
47460b57cec5SDimitry Andric return false;
47470b57cec5SDimitry Andric }
47480b57cec5SDimitry Andric
EmitLValueForField(LValue base,const FieldDecl * field)47490b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForField(LValue base,
47500b57cec5SDimitry Andric const FieldDecl *field) {
47510b57cec5SDimitry Andric LValueBaseInfo BaseInfo = base.getBaseInfo();
47520b57cec5SDimitry Andric
47530b57cec5SDimitry Andric if (field->isBitField()) {
47540b57cec5SDimitry Andric const CGRecordLayout &RL =
47550b57cec5SDimitry Andric CGM.getTypes().getCGRecordLayout(field->getParent());
47560b57cec5SDimitry Andric const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4757e8d8bef9SDimitry Andric const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4758e8d8bef9SDimitry Andric CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4759e8d8bef9SDimitry Andric Info.VolatileStorageSize != 0 &&
4760e8d8bef9SDimitry Andric field->getType()
4761e8d8bef9SDimitry Andric .withCVRQualifiers(base.getVRQualifiers())
4762e8d8bef9SDimitry Andric .isVolatileQualified();
4763480093f4SDimitry Andric Address Addr = base.getAddress(*this);
47640b57cec5SDimitry Andric unsigned Idx = RL.getLLVMFieldNo(field);
4765480093f4SDimitry Andric const RecordDecl *rec = field->getParent();
4766c9157d92SDimitry Andric if (hasBPFPreserveStaticOffset(rec))
4767c9157d92SDimitry Andric Addr = wrapWithBPFPreserveStaticOffset(*this, Addr);
4768e8d8bef9SDimitry Andric if (!UseVolatile) {
4769480093f4SDimitry Andric if (!IsInPreservedAIRegion &&
4770480093f4SDimitry Andric (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
47710b57cec5SDimitry Andric if (Idx != 0)
47720b57cec5SDimitry Andric // For structs, we GEP to the field that the record layout suggests.
47730b57cec5SDimitry Andric Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4774a7dea167SDimitry Andric } else {
4775a7dea167SDimitry Andric llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4776a7dea167SDimitry Andric getContext().getRecordType(rec), rec->getLocation());
4777e8d8bef9SDimitry Andric Addr = Builder.CreatePreserveStructAccessIndex(
4778e8d8bef9SDimitry Andric Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4779a7dea167SDimitry Andric DbgInfo);
4780a7dea167SDimitry Andric }
4781e8d8bef9SDimitry Andric }
4782e8d8bef9SDimitry Andric const unsigned SS =
4783e8d8bef9SDimitry Andric UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
47840b57cec5SDimitry Andric // Get the access type.
4785e8d8bef9SDimitry Andric llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
4786fe013be4SDimitry Andric Addr = Addr.withElementType(FieldIntTy);
4787e8d8bef9SDimitry Andric if (UseVolatile) {
4788e8d8bef9SDimitry Andric const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4789e8d8bef9SDimitry Andric if (VolatileOffset)
4790e8d8bef9SDimitry Andric Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4791e8d8bef9SDimitry Andric }
47920b57cec5SDimitry Andric
47930b57cec5SDimitry Andric QualType fieldType =
47940b57cec5SDimitry Andric field->getType().withCVRQualifiers(base.getVRQualifiers());
47950b57cec5SDimitry Andric // TODO: Support TBAA for bit fields.
47960b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
47970b57cec5SDimitry Andric return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
47980b57cec5SDimitry Andric TBAAAccessInfo());
47990b57cec5SDimitry Andric }
48000b57cec5SDimitry Andric
48010b57cec5SDimitry Andric // Fields of may-alias structures are may-alias themselves.
48020b57cec5SDimitry Andric // FIXME: this should get propagated down through anonymous structs
48030b57cec5SDimitry Andric // and unions.
48040b57cec5SDimitry Andric QualType FieldType = field->getType();
48050b57cec5SDimitry Andric const RecordDecl *rec = field->getParent();
48060b57cec5SDimitry Andric AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
48070b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
48080b57cec5SDimitry Andric TBAAAccessInfo FieldTBAAInfo;
48090b57cec5SDimitry Andric if (base.getTBAAInfo().isMayAlias() ||
48100b57cec5SDimitry Andric rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
48110b57cec5SDimitry Andric FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
48120b57cec5SDimitry Andric } else if (rec->isUnion()) {
48130b57cec5SDimitry Andric // TODO: Support TBAA for unions.
48140b57cec5SDimitry Andric FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
48150b57cec5SDimitry Andric } else {
48160b57cec5SDimitry Andric // If no base type been assigned for the base access, then try to generate
48170b57cec5SDimitry Andric // one for this base lvalue.
48180b57cec5SDimitry Andric FieldTBAAInfo = base.getTBAAInfo();
48190b57cec5SDimitry Andric if (!FieldTBAAInfo.BaseType) {
48200b57cec5SDimitry Andric FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
48210b57cec5SDimitry Andric assert(!FieldTBAAInfo.Offset &&
48220b57cec5SDimitry Andric "Nonzero offset for an access with no base type!");
48230b57cec5SDimitry Andric }
48240b57cec5SDimitry Andric
48250b57cec5SDimitry Andric // Adjust offset to be relative to the base type.
48260b57cec5SDimitry Andric const ASTRecordLayout &Layout =
48270b57cec5SDimitry Andric getContext().getASTRecordLayout(field->getParent());
48280b57cec5SDimitry Andric unsigned CharWidth = getContext().getCharWidth();
48290b57cec5SDimitry Andric if (FieldTBAAInfo.BaseType)
48300b57cec5SDimitry Andric FieldTBAAInfo.Offset +=
48310b57cec5SDimitry Andric Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
48320b57cec5SDimitry Andric
48330b57cec5SDimitry Andric // Update the final access type and size.
48340b57cec5SDimitry Andric FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
48350b57cec5SDimitry Andric FieldTBAAInfo.Size =
48360b57cec5SDimitry Andric getContext().getTypeSizeInChars(FieldType).getQuantity();
48370b57cec5SDimitry Andric }
48380b57cec5SDimitry Andric
4839480093f4SDimitry Andric Address addr = base.getAddress(*this);
4840c9157d92SDimitry Andric if (hasBPFPreserveStaticOffset(rec))
4841c9157d92SDimitry Andric addr = wrapWithBPFPreserveStaticOffset(*this, addr);
48420b57cec5SDimitry Andric if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
48430b57cec5SDimitry Andric if (CGM.getCodeGenOpts().StrictVTablePointers &&
48440b57cec5SDimitry Andric ClassDef->isDynamicClass()) {
48450b57cec5SDimitry Andric // Getting to any field of dynamic object requires stripping dynamic
48460b57cec5SDimitry Andric // information provided by invariant.group. This is because accessing
48470b57cec5SDimitry Andric // fields may leak the real address of dynamic object, which could result
48480b57cec5SDimitry Andric // in miscompilation when leaked pointer would be compared.
48490b57cec5SDimitry Andric auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
485081ad6265SDimitry Andric addr = Address(stripped, addr.getElementType(), addr.getAlignment());
48510b57cec5SDimitry Andric }
48520b57cec5SDimitry Andric }
48530b57cec5SDimitry Andric
48540b57cec5SDimitry Andric unsigned RecordCVR = base.getVRQualifiers();
48550b57cec5SDimitry Andric if (rec->isUnion()) {
48560b57cec5SDimitry Andric // For unions, there is no pointer adjustment.
48570b57cec5SDimitry Andric if (CGM.getCodeGenOpts().StrictVTablePointers &&
48580b57cec5SDimitry Andric hasAnyVptr(FieldType, getContext()))
48590b57cec5SDimitry Andric // Because unions can easily skip invariant.barriers, we need to add
48600b57cec5SDimitry Andric // a barrier every time CXXRecord field with vptr is referenced.
48610eae32dcSDimitry Andric addr = Builder.CreateLaunderInvariantGroup(addr);
48620b57cec5SDimitry Andric
4863480093f4SDimitry Andric if (IsInPreservedAIRegion ||
4864480093f4SDimitry Andric (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
48650b57cec5SDimitry Andric // Remember the original union field index
48665ffd83dbSDimitry Andric llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
48675ffd83dbSDimitry Andric rec->getLocation());
48680b57cec5SDimitry Andric addr = Address(
48690b57cec5SDimitry Andric Builder.CreatePreserveUnionAccessIndex(
48700b57cec5SDimitry Andric addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
487181ad6265SDimitry Andric addr.getElementType(), addr.getAlignment());
48720b57cec5SDimitry Andric }
48730b57cec5SDimitry Andric
4874a7dea167SDimitry Andric if (FieldType->isReferenceType())
4875fe013be4SDimitry Andric addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
4876a7dea167SDimitry Andric } else {
4877480093f4SDimitry Andric if (!IsInPreservedAIRegion &&
4878480093f4SDimitry Andric (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
48790b57cec5SDimitry Andric // For structs, we GEP to the field that the record layout suggests.
48800b57cec5SDimitry Andric addr = emitAddrOfFieldStorage(*this, addr, field);
48810b57cec5SDimitry Andric else
48820b57cec5SDimitry Andric // Remember the original struct field index
48835ffd83dbSDimitry Andric addr = emitPreserveStructAccess(*this, base, addr, field);
4884a7dea167SDimitry Andric }
48850b57cec5SDimitry Andric
48860b57cec5SDimitry Andric // If this is a reference field, load the reference right now.
48870b57cec5SDimitry Andric if (FieldType->isReferenceType()) {
4888a7dea167SDimitry Andric LValue RefLVal =
4889a7dea167SDimitry Andric MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
48900b57cec5SDimitry Andric if (RecordCVR & Qualifiers::Volatile)
48910b57cec5SDimitry Andric RefLVal.getQuals().addVolatile();
48920b57cec5SDimitry Andric addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
48930b57cec5SDimitry Andric
48940b57cec5SDimitry Andric // Qualifiers on the struct don't apply to the referencee.
48950b57cec5SDimitry Andric RecordCVR = 0;
48960b57cec5SDimitry Andric FieldType = FieldType->getPointeeType();
48970b57cec5SDimitry Andric }
48980b57cec5SDimitry Andric
48990b57cec5SDimitry Andric // Make sure that the address is pointing to the right type. This is critical
4900fe013be4SDimitry Andric // for both unions and structs.
4901fe013be4SDimitry Andric addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
49020b57cec5SDimitry Andric
49030b57cec5SDimitry Andric if (field->hasAttr<AnnotateAttr>())
49040b57cec5SDimitry Andric addr = EmitFieldAnnotations(field, addr);
49050b57cec5SDimitry Andric
49060b57cec5SDimitry Andric LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
49070b57cec5SDimitry Andric LV.getQuals().addCVRQualifiers(RecordCVR);
49080b57cec5SDimitry Andric
49090b57cec5SDimitry Andric // __weak attribute on a field is ignored.
49100b57cec5SDimitry Andric if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
49110b57cec5SDimitry Andric LV.getQuals().removeObjCGCAttr();
49120b57cec5SDimitry Andric
49130b57cec5SDimitry Andric return LV;
49140b57cec5SDimitry Andric }
49150b57cec5SDimitry Andric
49160b57cec5SDimitry Andric LValue
EmitLValueForFieldInitialization(LValue Base,const FieldDecl * Field)49170b57cec5SDimitry Andric CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
49180b57cec5SDimitry Andric const FieldDecl *Field) {
49190b57cec5SDimitry Andric QualType FieldType = Field->getType();
49200b57cec5SDimitry Andric
49210b57cec5SDimitry Andric if (!FieldType->isReferenceType())
49220b57cec5SDimitry Andric return EmitLValueForField(Base, Field);
49230b57cec5SDimitry Andric
4924480093f4SDimitry Andric Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
49250b57cec5SDimitry Andric
49260b57cec5SDimitry Andric // Make sure that the address is pointing to the right type.
49270b57cec5SDimitry Andric llvm::Type *llvmType = ConvertTypeForMem(FieldType);
4928fe013be4SDimitry Andric V = V.withElementType(llvmType);
49290b57cec5SDimitry Andric
49300b57cec5SDimitry Andric // TODO: Generate TBAA information that describes this access as a structure
49310b57cec5SDimitry Andric // member access and not just an access to an object of the field's type. This
49320b57cec5SDimitry Andric // should be similar to what we do in EmitLValueForField().
49330b57cec5SDimitry Andric LValueBaseInfo BaseInfo = Base.getBaseInfo();
49340b57cec5SDimitry Andric AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
49350b57cec5SDimitry Andric LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
49360b57cec5SDimitry Andric return MakeAddrLValue(V, FieldType, FieldBaseInfo,
49370b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(Base, FieldType));
49380b57cec5SDimitry Andric }
49390b57cec5SDimitry Andric
EmitCompoundLiteralLValue(const CompoundLiteralExpr * E)49400b57cec5SDimitry Andric LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
49410b57cec5SDimitry Andric if (E->isFileScope()) {
49420b57cec5SDimitry Andric ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
49430b57cec5SDimitry Andric return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
49440b57cec5SDimitry Andric }
49450b57cec5SDimitry Andric if (E->getType()->isVariablyModifiedType())
49460b57cec5SDimitry Andric // make sure to emit the VLA size.
49470b57cec5SDimitry Andric EmitVariablyModifiedType(E->getType());
49480b57cec5SDimitry Andric
49490b57cec5SDimitry Andric Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
49500b57cec5SDimitry Andric const Expr *InitExpr = E->getInitializer();
49510b57cec5SDimitry Andric LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
49520b57cec5SDimitry Andric
49530b57cec5SDimitry Andric EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
49540b57cec5SDimitry Andric /*Init*/ true);
49550b57cec5SDimitry Andric
49565ffd83dbSDimitry Andric // Block-scope compound literals are destroyed at the end of the enclosing
49575ffd83dbSDimitry Andric // scope in C.
49585ffd83dbSDimitry Andric if (!getLangOpts().CPlusPlus)
49595ffd83dbSDimitry Andric if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
49605ffd83dbSDimitry Andric pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
49615ffd83dbSDimitry Andric E->getType(), getDestroyer(DtorKind),
49625ffd83dbSDimitry Andric DtorKind & EHCleanup);
49635ffd83dbSDimitry Andric
49640b57cec5SDimitry Andric return Result;
49650b57cec5SDimitry Andric }
49660b57cec5SDimitry Andric
EmitInitListLValue(const InitListExpr * E)49670b57cec5SDimitry Andric LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
49680b57cec5SDimitry Andric if (!E->isGLValue())
49690b57cec5SDimitry Andric // Initializing an aggregate temporary in C++11: T{...}.
49700b57cec5SDimitry Andric return EmitAggExprToLValue(E);
49710b57cec5SDimitry Andric
49720b57cec5SDimitry Andric // An lvalue initializer list must be initializing a reference.
49730b57cec5SDimitry Andric assert(E->isTransparent() && "non-transparent glvalue init list");
49740b57cec5SDimitry Andric return EmitLValue(E->getInit(0));
49750b57cec5SDimitry Andric }
49760b57cec5SDimitry Andric
49770b57cec5SDimitry Andric /// Emit the operand of a glvalue conditional operator. This is either a glvalue
49780b57cec5SDimitry Andric /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
49790b57cec5SDimitry Andric /// LValue is returned and the current block has been terminated.
EmitLValueOrThrowExpression(CodeGenFunction & CGF,const Expr * Operand)4980bdd1243dSDimitry Andric static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
49810b57cec5SDimitry Andric const Expr *Operand) {
49820b57cec5SDimitry Andric if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
49830b57cec5SDimitry Andric CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4984bdd1243dSDimitry Andric return std::nullopt;
49850b57cec5SDimitry Andric }
49860b57cec5SDimitry Andric
49870b57cec5SDimitry Andric return CGF.EmitLValue(Operand);
49880b57cec5SDimitry Andric }
49890b57cec5SDimitry Andric
499081ad6265SDimitry Andric namespace {
499181ad6265SDimitry Andric // Handle the case where the condition is a constant evaluatable simple integer,
499281ad6265SDimitry Andric // which means we don't have to separately handle the true/false blocks.
HandleConditionalOperatorLValueSimpleCase(CodeGenFunction & CGF,const AbstractConditionalOperator * E)4993bdd1243dSDimitry Andric std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
499481ad6265SDimitry Andric CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
499581ad6265SDimitry Andric const Expr *condExpr = E->getCond();
499681ad6265SDimitry Andric bool CondExprBool;
499781ad6265SDimitry Andric if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
499881ad6265SDimitry Andric const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
499981ad6265SDimitry Andric if (!CondExprBool)
500081ad6265SDimitry Andric std::swap(Live, Dead);
500181ad6265SDimitry Andric
500281ad6265SDimitry Andric if (!CGF.ContainsLabel(Dead)) {
500381ad6265SDimitry Andric // If the true case is live, we need to track its region.
500481ad6265SDimitry Andric if (CondExprBool)
500581ad6265SDimitry Andric CGF.incrementProfileCounter(E);
500681ad6265SDimitry Andric // If a throw expression we emit it and return an undefined lvalue
500781ad6265SDimitry Andric // because it can't be used.
500881ad6265SDimitry Andric if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
500981ad6265SDimitry Andric CGF.EmitCXXThrowExpr(ThrowExpr);
501081ad6265SDimitry Andric llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
5011c9157d92SDimitry Andric llvm::Type *Ty = CGF.UnqualPtrTy;
501281ad6265SDimitry Andric return CGF.MakeAddrLValue(
501381ad6265SDimitry Andric Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
501481ad6265SDimitry Andric Dead->getType());
501581ad6265SDimitry Andric }
501681ad6265SDimitry Andric return CGF.EmitLValue(Live);
501781ad6265SDimitry Andric }
501881ad6265SDimitry Andric }
5019bdd1243dSDimitry Andric return std::nullopt;
502081ad6265SDimitry Andric }
502181ad6265SDimitry Andric struct ConditionalInfo {
502281ad6265SDimitry Andric llvm::BasicBlock *lhsBlock, *rhsBlock;
5023bdd1243dSDimitry Andric std::optional<LValue> LHS, RHS;
502481ad6265SDimitry Andric };
502581ad6265SDimitry Andric
502681ad6265SDimitry Andric // Create and generate the 3 blocks for a conditional operator.
502781ad6265SDimitry Andric // Leaves the 'current block' in the continuation basic block.
502881ad6265SDimitry Andric template<typename FuncTy>
EmitConditionalBlocks(CodeGenFunction & CGF,const AbstractConditionalOperator * E,const FuncTy & BranchGenFunc)502981ad6265SDimitry Andric ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
503081ad6265SDimitry Andric const AbstractConditionalOperator *E,
503181ad6265SDimitry Andric const FuncTy &BranchGenFunc) {
503281ad6265SDimitry Andric ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
5033bdd1243dSDimitry Andric CGF.createBasicBlock("cond.false"), std::nullopt,
5034bdd1243dSDimitry Andric std::nullopt};
503581ad6265SDimitry Andric llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
503681ad6265SDimitry Andric
503781ad6265SDimitry Andric CodeGenFunction::ConditionalEvaluation eval(CGF);
503881ad6265SDimitry Andric CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
503981ad6265SDimitry Andric CGF.getProfileCount(E));
504081ad6265SDimitry Andric
504181ad6265SDimitry Andric // Any temporaries created here are conditional.
504281ad6265SDimitry Andric CGF.EmitBlock(Info.lhsBlock);
504381ad6265SDimitry Andric CGF.incrementProfileCounter(E);
504481ad6265SDimitry Andric eval.begin(CGF);
504581ad6265SDimitry Andric Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
504681ad6265SDimitry Andric eval.end(CGF);
504781ad6265SDimitry Andric Info.lhsBlock = CGF.Builder.GetInsertBlock();
504881ad6265SDimitry Andric
504981ad6265SDimitry Andric if (Info.LHS)
505081ad6265SDimitry Andric CGF.Builder.CreateBr(endBlock);
505181ad6265SDimitry Andric
505281ad6265SDimitry Andric // Any temporaries created here are conditional.
505381ad6265SDimitry Andric CGF.EmitBlock(Info.rhsBlock);
505481ad6265SDimitry Andric eval.begin(CGF);
505581ad6265SDimitry Andric Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
505681ad6265SDimitry Andric eval.end(CGF);
505781ad6265SDimitry Andric Info.rhsBlock = CGF.Builder.GetInsertBlock();
505881ad6265SDimitry Andric CGF.EmitBlock(endBlock);
505981ad6265SDimitry Andric
506081ad6265SDimitry Andric return Info;
506181ad6265SDimitry Andric }
506281ad6265SDimitry Andric } // namespace
506381ad6265SDimitry Andric
EmitIgnoredConditionalOperator(const AbstractConditionalOperator * E)506481ad6265SDimitry Andric void CodeGenFunction::EmitIgnoredConditionalOperator(
506581ad6265SDimitry Andric const AbstractConditionalOperator *E) {
506681ad6265SDimitry Andric if (!E->isGLValue()) {
506781ad6265SDimitry Andric // ?: here should be an aggregate.
506881ad6265SDimitry Andric assert(hasAggregateEvaluationKind(E->getType()) &&
506981ad6265SDimitry Andric "Unexpected conditional operator!");
507081ad6265SDimitry Andric return (void)EmitAggExprToLValue(E);
507181ad6265SDimitry Andric }
507281ad6265SDimitry Andric
507381ad6265SDimitry Andric OpaqueValueMapping binding(*this, E);
507481ad6265SDimitry Andric if (HandleConditionalOperatorLValueSimpleCase(*this, E))
507581ad6265SDimitry Andric return;
507681ad6265SDimitry Andric
507781ad6265SDimitry Andric EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
507881ad6265SDimitry Andric CGF.EmitIgnoredExpr(E);
507981ad6265SDimitry Andric return LValue{};
508081ad6265SDimitry Andric });
508181ad6265SDimitry Andric }
EmitConditionalOperatorLValue(const AbstractConditionalOperator * expr)508281ad6265SDimitry Andric LValue CodeGenFunction::EmitConditionalOperatorLValue(
508381ad6265SDimitry Andric const AbstractConditionalOperator *expr) {
50840b57cec5SDimitry Andric if (!expr->isGLValue()) {
50850b57cec5SDimitry Andric // ?: here should be an aggregate.
50860b57cec5SDimitry Andric assert(hasAggregateEvaluationKind(expr->getType()) &&
50870b57cec5SDimitry Andric "Unexpected conditional operator!");
50880b57cec5SDimitry Andric return EmitAggExprToLValue(expr);
50890b57cec5SDimitry Andric }
50900b57cec5SDimitry Andric
50910b57cec5SDimitry Andric OpaqueValueMapping binding(*this, expr);
5092bdd1243dSDimitry Andric if (std::optional<LValue> Res =
509381ad6265SDimitry Andric HandleConditionalOperatorLValueSimpleCase(*this, expr))
509481ad6265SDimitry Andric return *Res;
50950b57cec5SDimitry Andric
509681ad6265SDimitry Andric ConditionalInfo Info = EmitConditionalBlocks(
509781ad6265SDimitry Andric *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
509881ad6265SDimitry Andric return EmitLValueOrThrowExpression(CGF, E);
509981ad6265SDimitry Andric });
51000b57cec5SDimitry Andric
510181ad6265SDimitry Andric if ((Info.LHS && !Info.LHS->isSimple()) ||
510281ad6265SDimitry Andric (Info.RHS && !Info.RHS->isSimple()))
51030b57cec5SDimitry Andric return EmitUnsupportedLValue(expr, "conditional operator");
51040b57cec5SDimitry Andric
510581ad6265SDimitry Andric if (Info.LHS && Info.RHS) {
510681ad6265SDimitry Andric Address lhsAddr = Info.LHS->getAddress(*this);
510781ad6265SDimitry Andric Address rhsAddr = Info.RHS->getAddress(*this);
51080eae32dcSDimitry Andric llvm::PHINode *phi = Builder.CreatePHI(lhsAddr.getType(), 2, "cond-lvalue");
510981ad6265SDimitry Andric phi->addIncoming(lhsAddr.getPointer(), Info.lhsBlock);
511081ad6265SDimitry Andric phi->addIncoming(rhsAddr.getPointer(), Info.rhsBlock);
51110eae32dcSDimitry Andric Address result(phi, lhsAddr.getElementType(),
51120eae32dcSDimitry Andric std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
51130b57cec5SDimitry Andric AlignmentSource alignSource =
511481ad6265SDimitry Andric std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
511581ad6265SDimitry Andric Info.RHS->getBaseInfo().getAlignmentSource());
51160b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
511781ad6265SDimitry Andric Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
51180b57cec5SDimitry Andric return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
51190b57cec5SDimitry Andric TBAAInfo);
51200b57cec5SDimitry Andric } else {
512181ad6265SDimitry Andric assert((Info.LHS || Info.RHS) &&
51220b57cec5SDimitry Andric "both operands of glvalue conditional are throw-expressions?");
512381ad6265SDimitry Andric return Info.LHS ? *Info.LHS : *Info.RHS;
51240b57cec5SDimitry Andric }
51250b57cec5SDimitry Andric }
51260b57cec5SDimitry Andric
51270b57cec5SDimitry Andric /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
51280b57cec5SDimitry Andric /// type. If the cast is to a reference, we can have the usual lvalue result,
51290b57cec5SDimitry Andric /// otherwise if a cast is needed by the code generator in an lvalue context,
51300b57cec5SDimitry Andric /// then it must mean that we need the address of an aggregate in order to
51310b57cec5SDimitry Andric /// access one of its members. This can happen for all the reasons that casts
51320b57cec5SDimitry Andric /// are permitted with aggregate result, including noop aggregate casts, and
51330b57cec5SDimitry Andric /// cast from scalar to union.
EmitCastLValue(const CastExpr * E)51340b57cec5SDimitry Andric LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
51350b57cec5SDimitry Andric switch (E->getCastKind()) {
51360b57cec5SDimitry Andric case CK_ToVoid:
51370b57cec5SDimitry Andric case CK_BitCast:
51380b57cec5SDimitry Andric case CK_LValueToRValueBitCast:
51390b57cec5SDimitry Andric case CK_ArrayToPointerDecay:
51400b57cec5SDimitry Andric case CK_FunctionToPointerDecay:
51410b57cec5SDimitry Andric case CK_NullToMemberPointer:
51420b57cec5SDimitry Andric case CK_NullToPointer:
51430b57cec5SDimitry Andric case CK_IntegralToPointer:
51440b57cec5SDimitry Andric case CK_PointerToIntegral:
51450b57cec5SDimitry Andric case CK_PointerToBoolean:
51460b57cec5SDimitry Andric case CK_IntegralCast:
51470b57cec5SDimitry Andric case CK_BooleanToSignedIntegral:
51480b57cec5SDimitry Andric case CK_IntegralToBoolean:
51490b57cec5SDimitry Andric case CK_IntegralToFloating:
51500b57cec5SDimitry Andric case CK_FloatingToIntegral:
51510b57cec5SDimitry Andric case CK_FloatingToBoolean:
51520b57cec5SDimitry Andric case CK_FloatingCast:
51530b57cec5SDimitry Andric case CK_FloatingRealToComplex:
51540b57cec5SDimitry Andric case CK_FloatingComplexToReal:
51550b57cec5SDimitry Andric case CK_FloatingComplexToBoolean:
51560b57cec5SDimitry Andric case CK_FloatingComplexCast:
51570b57cec5SDimitry Andric case CK_FloatingComplexToIntegralComplex:
51580b57cec5SDimitry Andric case CK_IntegralRealToComplex:
51590b57cec5SDimitry Andric case CK_IntegralComplexToReal:
51600b57cec5SDimitry Andric case CK_IntegralComplexToBoolean:
51610b57cec5SDimitry Andric case CK_IntegralComplexCast:
51620b57cec5SDimitry Andric case CK_IntegralComplexToFloatingComplex:
51630b57cec5SDimitry Andric case CK_DerivedToBaseMemberPointer:
51640b57cec5SDimitry Andric case CK_BaseToDerivedMemberPointer:
51650b57cec5SDimitry Andric case CK_MemberPointerToBoolean:
51660b57cec5SDimitry Andric case CK_ReinterpretMemberPointer:
51670b57cec5SDimitry Andric case CK_AnyPointerToBlockPointerCast:
51680b57cec5SDimitry Andric case CK_ARCProduceObject:
51690b57cec5SDimitry Andric case CK_ARCConsumeObject:
51700b57cec5SDimitry Andric case CK_ARCReclaimReturnedObject:
51710b57cec5SDimitry Andric case CK_ARCExtendBlockObject:
51720b57cec5SDimitry Andric case CK_CopyAndAutoreleaseBlockObject:
51730b57cec5SDimitry Andric case CK_IntToOCLSampler:
5174e8d8bef9SDimitry Andric case CK_FloatingToFixedPoint:
5175e8d8bef9SDimitry Andric case CK_FixedPointToFloating:
51760b57cec5SDimitry Andric case CK_FixedPointCast:
51770b57cec5SDimitry Andric case CK_FixedPointToBoolean:
51780b57cec5SDimitry Andric case CK_FixedPointToIntegral:
51790b57cec5SDimitry Andric case CK_IntegralToFixedPoint:
5180fe6060f1SDimitry Andric case CK_MatrixCast:
51810b57cec5SDimitry Andric return EmitUnsupportedLValue(E, "unexpected cast lvalue");
51820b57cec5SDimitry Andric
51830b57cec5SDimitry Andric case CK_Dependent:
51840b57cec5SDimitry Andric llvm_unreachable("dependent cast kind in IR gen!");
51850b57cec5SDimitry Andric
51860b57cec5SDimitry Andric case CK_BuiltinFnToFnPtr:
51870b57cec5SDimitry Andric llvm_unreachable("builtin functions are handled elsewhere");
51880b57cec5SDimitry Andric
51890b57cec5SDimitry Andric // These are never l-values; just use the aggregate emission code.
51900b57cec5SDimitry Andric case CK_NonAtomicToAtomic:
51910b57cec5SDimitry Andric case CK_AtomicToNonAtomic:
51920b57cec5SDimitry Andric return EmitAggExprToLValue(E);
51930b57cec5SDimitry Andric
51940b57cec5SDimitry Andric case CK_Dynamic: {
51950b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
5196480093f4SDimitry Andric Address V = LV.getAddress(*this);
51970b57cec5SDimitry Andric const auto *DCE = cast<CXXDynamicCastExpr>(E);
51980b57cec5SDimitry Andric return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
51990b57cec5SDimitry Andric }
52000b57cec5SDimitry Andric
52010b57cec5SDimitry Andric case CK_ConstructorConversion:
52020b57cec5SDimitry Andric case CK_UserDefinedConversion:
52030b57cec5SDimitry Andric case CK_CPointerToObjCPointerCast:
52040b57cec5SDimitry Andric case CK_BlockPointerToObjCPointerCast:
52050b57cec5SDimitry Andric case CK_LValueToRValue:
52060b57cec5SDimitry Andric return EmitLValue(E->getSubExpr());
52070b57cec5SDimitry Andric
5208349cc55cSDimitry Andric case CK_NoOp: {
5209349cc55cSDimitry Andric // CK_NoOp can model a qualification conversion, which can remove an array
5210349cc55cSDimitry Andric // bound and change the IR type.
5211349cc55cSDimitry Andric // FIXME: Once pointee types are removed from IR, remove this.
5212349cc55cSDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
5213c9157d92SDimitry Andric // Propagate the volatile qualifer to LValue, if exist in E.
5214c9157d92SDimitry Andric if (E->changesVolatileQualification())
5215c9157d92SDimitry Andric LV.getQuals() = E->getType().getQualifiers();
5216349cc55cSDimitry Andric if (LV.isSimple()) {
5217349cc55cSDimitry Andric Address V = LV.getAddress(*this);
5218349cc55cSDimitry Andric if (V.isValid()) {
521904eeddc0SDimitry Andric llvm::Type *T = ConvertTypeForMem(E->getType());
522004eeddc0SDimitry Andric if (V.getElementType() != T)
5221fe013be4SDimitry Andric LV.setAddress(V.withElementType(T));
5222349cc55cSDimitry Andric }
5223349cc55cSDimitry Andric }
5224349cc55cSDimitry Andric return LV;
5225349cc55cSDimitry Andric }
5226349cc55cSDimitry Andric
52270b57cec5SDimitry Andric case CK_UncheckedDerivedToBase:
52280b57cec5SDimitry Andric case CK_DerivedToBase: {
5229480093f4SDimitry Andric const auto *DerivedClassTy =
5230480093f4SDimitry Andric E->getSubExpr()->getType()->castAs<RecordType>();
52310b57cec5SDimitry Andric auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
52320b57cec5SDimitry Andric
52330b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
5234480093f4SDimitry Andric Address This = LV.getAddress(*this);
52350b57cec5SDimitry Andric
52360b57cec5SDimitry Andric // Perform the derived-to-base conversion
52370b57cec5SDimitry Andric Address Base = GetAddressOfBaseClass(
52380b57cec5SDimitry Andric This, DerivedClassDecl, E->path_begin(), E->path_end(),
52390b57cec5SDimitry Andric /*NullCheckValue=*/false, E->getExprLoc());
52400b57cec5SDimitry Andric
52410b57cec5SDimitry Andric // TODO: Support accesses to members of base classes in TBAA. For now, we
52420b57cec5SDimitry Andric // conservatively pretend that the complete object is of the base class
52430b57cec5SDimitry Andric // type.
52440b57cec5SDimitry Andric return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
52450b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType()));
52460b57cec5SDimitry Andric }
52470b57cec5SDimitry Andric case CK_ToUnion:
52480b57cec5SDimitry Andric return EmitAggExprToLValue(E);
52490b57cec5SDimitry Andric case CK_BaseToDerived: {
5250480093f4SDimitry Andric const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
52510b57cec5SDimitry Andric auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
52520b57cec5SDimitry Andric
52530b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
52540b57cec5SDimitry Andric
52550b57cec5SDimitry Andric // Perform the base-to-derived conversion
5256480093f4SDimitry Andric Address Derived = GetAddressOfDerivedClass(
5257480093f4SDimitry Andric LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
52580b57cec5SDimitry Andric /*NullCheckValue=*/false);
52590b57cec5SDimitry Andric
52600b57cec5SDimitry Andric // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
52610b57cec5SDimitry Andric // performed and the object is not of the derived type.
52620b57cec5SDimitry Andric if (sanitizePerformTypeCheck())
52630b57cec5SDimitry Andric EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
52640b57cec5SDimitry Andric Derived.getPointer(), E->getType());
52650b57cec5SDimitry Andric
52660b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIDerivedCast))
526781ad6265SDimitry Andric EmitVTablePtrCheckForCast(E->getType(), Derived,
52680b57cec5SDimitry Andric /*MayBeNull=*/false, CFITCK_DerivedCast,
52690b57cec5SDimitry Andric E->getBeginLoc());
52700b57cec5SDimitry Andric
52710b57cec5SDimitry Andric return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
52720b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType()));
52730b57cec5SDimitry Andric }
52740b57cec5SDimitry Andric case CK_LValueBitCast: {
52750b57cec5SDimitry Andric // This must be a reinterpret_cast (or c-style equivalent).
52760b57cec5SDimitry Andric const auto *CE = cast<ExplicitCastExpr>(E);
52770b57cec5SDimitry Andric
52780b57cec5SDimitry Andric CGM.EmitExplicitCastExprType(CE, this);
52790b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
5280fe013be4SDimitry Andric Address V = LV.getAddress(*this).withElementType(
528104eeddc0SDimitry Andric ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
52820b57cec5SDimitry Andric
52830b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
528481ad6265SDimitry Andric EmitVTablePtrCheckForCast(E->getType(), V,
52850b57cec5SDimitry Andric /*MayBeNull=*/false, CFITCK_UnrelatedCast,
52860b57cec5SDimitry Andric E->getBeginLoc());
52870b57cec5SDimitry Andric
52880b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
52890b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType()));
52900b57cec5SDimitry Andric }
52910b57cec5SDimitry Andric case CK_AddressSpaceConversion: {
52920b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
52930b57cec5SDimitry Andric QualType DestTy = getContext().getPointerType(E->getType());
52940b57cec5SDimitry Andric llvm::Value *V = getTargetHooks().performAddrSpaceCast(
5295480093f4SDimitry Andric *this, LV.getPointer(*this),
5296480093f4SDimitry Andric E->getSubExpr()->getType().getAddressSpace(),
52970b57cec5SDimitry Andric E->getType().getAddressSpace(), ConvertType(DestTy));
529881ad6265SDimitry Andric return MakeAddrLValue(Address(V, ConvertTypeForMem(E->getType()),
529981ad6265SDimitry Andric LV.getAddress(*this).getAlignment()),
53000b57cec5SDimitry Andric E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
53010b57cec5SDimitry Andric }
53020b57cec5SDimitry Andric case CK_ObjCObjectLValueCast: {
53030b57cec5SDimitry Andric LValue LV = EmitLValue(E->getSubExpr());
5304fe013be4SDimitry Andric Address V = LV.getAddress(*this).withElementType(ConvertType(E->getType()));
53050b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
53060b57cec5SDimitry Andric CGM.getTBAAInfoForSubobject(LV, E->getType()));
53070b57cec5SDimitry Andric }
53080b57cec5SDimitry Andric case CK_ZeroToOCLOpaqueType:
53090b57cec5SDimitry Andric llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
5310c9157d92SDimitry Andric
5311c9157d92SDimitry Andric case CK_VectorSplat: {
5312c9157d92SDimitry Andric // LValue results of vector splats are only supported in HLSL.
5313c9157d92SDimitry Andric if (!getLangOpts().HLSL)
5314c9157d92SDimitry Andric return EmitUnsupportedLValue(E, "unexpected cast lvalue");
5315c9157d92SDimitry Andric return EmitLValue(E->getSubExpr());
5316c9157d92SDimitry Andric }
53170b57cec5SDimitry Andric }
53180b57cec5SDimitry Andric
53190b57cec5SDimitry Andric llvm_unreachable("Unhandled lvalue cast kind?");
53200b57cec5SDimitry Andric }
53210b57cec5SDimitry Andric
EmitOpaqueValueLValue(const OpaqueValueExpr * e)53220b57cec5SDimitry Andric LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
53230b57cec5SDimitry Andric assert(OpaqueValueMappingData::shouldBindAsLValue(e));
53240b57cec5SDimitry Andric return getOrCreateOpaqueLValueMapping(e);
53250b57cec5SDimitry Andric }
53260b57cec5SDimitry Andric
53270b57cec5SDimitry Andric LValue
getOrCreateOpaqueLValueMapping(const OpaqueValueExpr * e)53280b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
53290b57cec5SDimitry Andric assert(OpaqueValueMapping::shouldBindAsLValue(e));
53300b57cec5SDimitry Andric
53310b57cec5SDimitry Andric llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
53320b57cec5SDimitry Andric it = OpaqueLValues.find(e);
53330b57cec5SDimitry Andric
53340b57cec5SDimitry Andric if (it != OpaqueLValues.end())
53350b57cec5SDimitry Andric return it->second;
53360b57cec5SDimitry Andric
53370b57cec5SDimitry Andric assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
53380b57cec5SDimitry Andric return EmitLValue(e->getSourceExpr());
53390b57cec5SDimitry Andric }
53400b57cec5SDimitry Andric
53410b57cec5SDimitry Andric RValue
getOrCreateOpaqueRValueMapping(const OpaqueValueExpr * e)53420b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
53430b57cec5SDimitry Andric assert(!OpaqueValueMapping::shouldBindAsLValue(e));
53440b57cec5SDimitry Andric
53450b57cec5SDimitry Andric llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
53460b57cec5SDimitry Andric it = OpaqueRValues.find(e);
53470b57cec5SDimitry Andric
53480b57cec5SDimitry Andric if (it != OpaqueRValues.end())
53490b57cec5SDimitry Andric return it->second;
53500b57cec5SDimitry Andric
53510b57cec5SDimitry Andric assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
53520b57cec5SDimitry Andric return EmitAnyExpr(e->getSourceExpr());
53530b57cec5SDimitry Andric }
53540b57cec5SDimitry Andric
EmitRValueForField(LValue LV,const FieldDecl * FD,SourceLocation Loc)53550b57cec5SDimitry Andric RValue CodeGenFunction::EmitRValueForField(LValue LV,
53560b57cec5SDimitry Andric const FieldDecl *FD,
53570b57cec5SDimitry Andric SourceLocation Loc) {
53580b57cec5SDimitry Andric QualType FT = FD->getType();
53590b57cec5SDimitry Andric LValue FieldLV = EmitLValueForField(LV, FD);
53600b57cec5SDimitry Andric switch (getEvaluationKind(FT)) {
53610b57cec5SDimitry Andric case TEK_Complex:
53620b57cec5SDimitry Andric return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
53630b57cec5SDimitry Andric case TEK_Aggregate:
5364480093f4SDimitry Andric return FieldLV.asAggregateRValue(*this);
53650b57cec5SDimitry Andric case TEK_Scalar:
53660b57cec5SDimitry Andric // This routine is used to load fields one-by-one to perform a copy, so
53670b57cec5SDimitry Andric // don't load reference fields.
53680b57cec5SDimitry Andric if (FD->getType()->isReferenceType())
5369480093f4SDimitry Andric return RValue::get(FieldLV.getPointer(*this));
5370480093f4SDimitry Andric // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
5371480093f4SDimitry Andric // primitive load.
5372480093f4SDimitry Andric if (FieldLV.isBitField())
53730b57cec5SDimitry Andric return EmitLoadOfLValue(FieldLV, Loc);
5374480093f4SDimitry Andric return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
53750b57cec5SDimitry Andric }
53760b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
53770b57cec5SDimitry Andric }
53780b57cec5SDimitry Andric
53790b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
53800b57cec5SDimitry Andric // Expression Emission
53810b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
53820b57cec5SDimitry Andric
EmitCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)53830b57cec5SDimitry Andric RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
53840b57cec5SDimitry Andric ReturnValueSlot ReturnValue) {
53850b57cec5SDimitry Andric // Builtins never have block type.
53860b57cec5SDimitry Andric if (E->getCallee()->getType()->isBlockPointerType())
53870b57cec5SDimitry Andric return EmitBlockCallExpr(E, ReturnValue);
53880b57cec5SDimitry Andric
53890b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
53900b57cec5SDimitry Andric return EmitCXXMemberCallExpr(CE, ReturnValue);
53910b57cec5SDimitry Andric
53920b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
53930b57cec5SDimitry Andric return EmitCUDAKernelCallExpr(CE, ReturnValue);
53940b57cec5SDimitry Andric
5395c9157d92SDimitry Andric // A CXXOperatorCallExpr is created even for explicit object methods, but
5396c9157d92SDimitry Andric // these should be treated like static function call.
53970b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
5398c9157d92SDimitry Andric if (const auto *MD =
5399c9157d92SDimitry Andric dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
5400c9157d92SDimitry Andric MD && MD->isImplicitObjectMemberFunction())
54010b57cec5SDimitry Andric return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
54020b57cec5SDimitry Andric
54030b57cec5SDimitry Andric CGCallee callee = EmitCallee(E->getCallee());
54040b57cec5SDimitry Andric
54050b57cec5SDimitry Andric if (callee.isBuiltin()) {
54060b57cec5SDimitry Andric return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
54070b57cec5SDimitry Andric E, ReturnValue);
54080b57cec5SDimitry Andric }
54090b57cec5SDimitry Andric
54100b57cec5SDimitry Andric if (callee.isPseudoDestructor()) {
54110b57cec5SDimitry Andric return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
54120b57cec5SDimitry Andric }
54130b57cec5SDimitry Andric
54140b57cec5SDimitry Andric return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
54150b57cec5SDimitry Andric }
54160b57cec5SDimitry Andric
54170b57cec5SDimitry Andric /// Emit a CallExpr without considering whether it might be a subclass.
EmitSimpleCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)54180b57cec5SDimitry Andric RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
54190b57cec5SDimitry Andric ReturnValueSlot ReturnValue) {
54200b57cec5SDimitry Andric CGCallee Callee = EmitCallee(E->getCallee());
54210b57cec5SDimitry Andric return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
54220b57cec5SDimitry Andric }
54230b57cec5SDimitry Andric
54243a9a9c0cSDimitry Andric // Detect the unusual situation where an inline version is shadowed by a
54253a9a9c0cSDimitry Andric // non-inline version. In that case we should pick the external one
54263a9a9c0cSDimitry Andric // everywhere. That's GCC behavior too.
OnlyHasInlineBuiltinDeclaration(const FunctionDecl * FD)54273a9a9c0cSDimitry Andric static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD) {
54283a9a9c0cSDimitry Andric for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
54293a9a9c0cSDimitry Andric if (!PD->isInlineBuiltinDeclaration())
54303a9a9c0cSDimitry Andric return false;
54313a9a9c0cSDimitry Andric return true;
54323a9a9c0cSDimitry Andric }
54333a9a9c0cSDimitry Andric
EmitDirectCallee(CodeGenFunction & CGF,GlobalDecl GD)54345ffd83dbSDimitry Andric static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
54355ffd83dbSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
5436480093f4SDimitry Andric
54370b57cec5SDimitry Andric if (auto builtinID = FD->getBuiltinID()) {
543881ad6265SDimitry Andric std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
543981ad6265SDimitry Andric std::string NoBuiltins = "no-builtins";
5440bdd1243dSDimitry Andric
5441bdd1243dSDimitry Andric StringRef Ident = CGF.CGM.getMangledName(GD);
5442bdd1243dSDimitry Andric std::string FDInlineName = (Ident + ".inline").str();
544381ad6265SDimitry Andric
544481ad6265SDimitry Andric bool IsPredefinedLibFunction =
544581ad6265SDimitry Andric CGF.getContext().BuiltinInfo.isPredefinedLibFunction(builtinID);
544681ad6265SDimitry Andric bool HasAttributeNoBuiltin =
544781ad6265SDimitry Andric CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
544881ad6265SDimitry Andric CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
544981ad6265SDimitry Andric
5450349cc55cSDimitry Andric // When directing calling an inline builtin, call it through it's mangled
5451349cc55cSDimitry Andric // name to make it clear it's not the actual builtin.
54523a9a9c0cSDimitry Andric if (CGF.CurFn->getName() != FDInlineName &&
54533a9a9c0cSDimitry Andric OnlyHasInlineBuiltinDeclaration(FD)) {
5454349cc55cSDimitry Andric llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
5455349cc55cSDimitry Andric llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
5456349cc55cSDimitry Andric llvm::Module *M = Fn->getParent();
5457349cc55cSDimitry Andric llvm::Function *Clone = M->getFunction(FDInlineName);
5458349cc55cSDimitry Andric if (!Clone) {
5459349cc55cSDimitry Andric Clone = llvm::Function::Create(Fn->getFunctionType(),
5460349cc55cSDimitry Andric llvm::GlobalValue::InternalLinkage,
5461349cc55cSDimitry Andric Fn->getAddressSpace(), FDInlineName, M);
5462349cc55cSDimitry Andric Clone->addFnAttr(llvm::Attribute::AlwaysInline);
5463349cc55cSDimitry Andric }
5464349cc55cSDimitry Andric return CGCallee::forDirect(Clone, GD);
5465349cc55cSDimitry Andric }
5466349cc55cSDimitry Andric
5467349cc55cSDimitry Andric // Replaceable builtins provide their own implementation of a builtin. If we
5468349cc55cSDimitry Andric // are in an inline builtin implementation, avoid trivial infinite
546981ad6265SDimitry Andric // recursion. Honor __attribute__((no_builtin("foo"))) or
547081ad6265SDimitry Andric // __attribute__((no_builtin)) on the current function unless foo is
547181ad6265SDimitry Andric // not a predefined library function which means we must generate the
547281ad6265SDimitry Andric // builtin no matter what.
547381ad6265SDimitry Andric else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
54740b57cec5SDimitry Andric return CGCallee::forBuiltin(builtinID, FD);
54750b57cec5SDimitry Andric }
54760b57cec5SDimitry Andric
5477fe6060f1SDimitry Andric llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
5478fe6060f1SDimitry Andric if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
5479fe6060f1SDimitry Andric FD->hasAttr<CUDAGlobalAttr>())
5480fe6060f1SDimitry Andric CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
5481fe6060f1SDimitry Andric cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
5482349cc55cSDimitry Andric
5483fe6060f1SDimitry Andric return CGCallee::forDirect(CalleePtr, GD);
54840b57cec5SDimitry Andric }
54850b57cec5SDimitry Andric
EmitCallee(const Expr * E)54860b57cec5SDimitry Andric CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
54870b57cec5SDimitry Andric E = E->IgnoreParens();
54880b57cec5SDimitry Andric
54890b57cec5SDimitry Andric // Look through function-to-pointer decay.
54900b57cec5SDimitry Andric if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
54910b57cec5SDimitry Andric if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
54920b57cec5SDimitry Andric ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
54930b57cec5SDimitry Andric return EmitCallee(ICE->getSubExpr());
54940b57cec5SDimitry Andric }
54950b57cec5SDimitry Andric
54960b57cec5SDimitry Andric // Resolve direct calls.
54970b57cec5SDimitry Andric } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
54980b57cec5SDimitry Andric if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
54990b57cec5SDimitry Andric return EmitDirectCallee(*this, FD);
55000b57cec5SDimitry Andric }
55010b57cec5SDimitry Andric } else if (auto ME = dyn_cast<MemberExpr>(E)) {
55020b57cec5SDimitry Andric if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
55030b57cec5SDimitry Andric EmitIgnoredExpr(ME->getBase());
55040b57cec5SDimitry Andric return EmitDirectCallee(*this, FD);
55050b57cec5SDimitry Andric }
55060b57cec5SDimitry Andric
55070b57cec5SDimitry Andric // Look through template substitutions.
55080b57cec5SDimitry Andric } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
55090b57cec5SDimitry Andric return EmitCallee(NTTP->getReplacement());
55100b57cec5SDimitry Andric
55110b57cec5SDimitry Andric // Treat pseudo-destructor calls differently.
55120b57cec5SDimitry Andric } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
55130b57cec5SDimitry Andric return CGCallee::forPseudoDestructor(PDE);
55140b57cec5SDimitry Andric }
55150b57cec5SDimitry Andric
55160b57cec5SDimitry Andric // Otherwise, we have an indirect reference.
55170b57cec5SDimitry Andric llvm::Value *calleePtr;
55180b57cec5SDimitry Andric QualType functionType;
55190b57cec5SDimitry Andric if (auto ptrType = E->getType()->getAs<PointerType>()) {
55200b57cec5SDimitry Andric calleePtr = EmitScalarExpr(E);
55210b57cec5SDimitry Andric functionType = ptrType->getPointeeType();
55220b57cec5SDimitry Andric } else {
55230b57cec5SDimitry Andric functionType = E->getType();
5524fe013be4SDimitry Andric calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
55250b57cec5SDimitry Andric }
55260b57cec5SDimitry Andric assert(functionType->isFunctionType());
55270b57cec5SDimitry Andric
55280b57cec5SDimitry Andric GlobalDecl GD;
55290b57cec5SDimitry Andric if (const auto *VD =
55300b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
55310b57cec5SDimitry Andric GD = GlobalDecl(VD);
55320b57cec5SDimitry Andric
55330b57cec5SDimitry Andric CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
55340b57cec5SDimitry Andric CGCallee callee(calleeInfo, calleePtr);
55350b57cec5SDimitry Andric return callee;
55360b57cec5SDimitry Andric }
55370b57cec5SDimitry Andric
EmitBinaryOperatorLValue(const BinaryOperator * E)55380b57cec5SDimitry Andric LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
55390b57cec5SDimitry Andric // Comma expressions just emit their LHS then their RHS as an l-value.
55400b57cec5SDimitry Andric if (E->getOpcode() == BO_Comma) {
55410b57cec5SDimitry Andric EmitIgnoredExpr(E->getLHS());
55420b57cec5SDimitry Andric EnsureInsertPoint();
55430b57cec5SDimitry Andric return EmitLValue(E->getRHS());
55440b57cec5SDimitry Andric }
55450b57cec5SDimitry Andric
55460b57cec5SDimitry Andric if (E->getOpcode() == BO_PtrMemD ||
55470b57cec5SDimitry Andric E->getOpcode() == BO_PtrMemI)
55480b57cec5SDimitry Andric return EmitPointerToDataMemberBinaryExpr(E);
55490b57cec5SDimitry Andric
55500b57cec5SDimitry Andric assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
55510b57cec5SDimitry Andric
55520b57cec5SDimitry Andric // Note that in all of these cases, __block variables need the RHS
55530b57cec5SDimitry Andric // evaluated first just in case the variable gets moved by the RHS.
55540b57cec5SDimitry Andric
55550b57cec5SDimitry Andric switch (getEvaluationKind(E->getType())) {
55560b57cec5SDimitry Andric case TEK_Scalar: {
55570b57cec5SDimitry Andric switch (E->getLHS()->getType().getObjCLifetime()) {
55580b57cec5SDimitry Andric case Qualifiers::OCL_Strong:
55590b57cec5SDimitry Andric return EmitARCStoreStrong(E, /*ignored*/ false).first;
55600b57cec5SDimitry Andric
55610b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing:
55620b57cec5SDimitry Andric return EmitARCStoreAutoreleasing(E).first;
55630b57cec5SDimitry Andric
55640b57cec5SDimitry Andric // No reason to do any of these differently.
55650b57cec5SDimitry Andric case Qualifiers::OCL_None:
55660b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone:
55670b57cec5SDimitry Andric case Qualifiers::OCL_Weak:
55680b57cec5SDimitry Andric break;
55690b57cec5SDimitry Andric }
55700b57cec5SDimitry Andric
55710b57cec5SDimitry Andric RValue RV = EmitAnyExpr(E->getRHS());
55720b57cec5SDimitry Andric LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
55730b57cec5SDimitry Andric if (RV.isScalar())
55740b57cec5SDimitry Andric EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
55750b57cec5SDimitry Andric EmitStoreThroughLValue(RV, LV);
5576480093f4SDimitry Andric if (getLangOpts().OpenMP)
5577480093f4SDimitry Andric CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
5578480093f4SDimitry Andric E->getLHS());
55790b57cec5SDimitry Andric return LV;
55800b57cec5SDimitry Andric }
55810b57cec5SDimitry Andric
55820b57cec5SDimitry Andric case TEK_Complex:
55830b57cec5SDimitry Andric return EmitComplexAssignmentLValue(E);
55840b57cec5SDimitry Andric
55850b57cec5SDimitry Andric case TEK_Aggregate:
55860b57cec5SDimitry Andric return EmitAggExprToLValue(E);
55870b57cec5SDimitry Andric }
55880b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
55890b57cec5SDimitry Andric }
55900b57cec5SDimitry Andric
EmitCallExprLValue(const CallExpr * E)55910b57cec5SDimitry Andric LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
55920b57cec5SDimitry Andric RValue RV = EmitCallExpr(E);
55930b57cec5SDimitry Andric
55940b57cec5SDimitry Andric if (!RV.isScalar())
55950b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
55960b57cec5SDimitry Andric AlignmentSource::Decl);
55970b57cec5SDimitry Andric
55980b57cec5SDimitry Andric assert(E->getCallReturnType(getContext())->isReferenceType() &&
55990b57cec5SDimitry Andric "Can't have a scalar return unless the return type is a "
56000b57cec5SDimitry Andric "reference type!");
56010b57cec5SDimitry Andric
56020b57cec5SDimitry Andric return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
56030b57cec5SDimitry Andric }
56040b57cec5SDimitry Andric
EmitVAArgExprLValue(const VAArgExpr * E)56050b57cec5SDimitry Andric LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
56060b57cec5SDimitry Andric // FIXME: This shouldn't require another copy.
56070b57cec5SDimitry Andric return EmitAggExprToLValue(E);
56080b57cec5SDimitry Andric }
56090b57cec5SDimitry Andric
EmitCXXConstructLValue(const CXXConstructExpr * E)56100b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
56110b57cec5SDimitry Andric assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
56120b57cec5SDimitry Andric && "binding l-value to type which needs a temporary");
56130b57cec5SDimitry Andric AggValueSlot Slot = CreateAggTemp(E->getType());
56140b57cec5SDimitry Andric EmitCXXConstructExpr(E, Slot);
56150b57cec5SDimitry Andric return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
56160b57cec5SDimitry Andric }
56170b57cec5SDimitry Andric
56180b57cec5SDimitry Andric LValue
EmitCXXTypeidLValue(const CXXTypeidExpr * E)56190b57cec5SDimitry Andric CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
56200b57cec5SDimitry Andric return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
56210b57cec5SDimitry Andric }
56220b57cec5SDimitry Andric
EmitCXXUuidofExpr(const CXXUuidofExpr * E)56230b57cec5SDimitry Andric Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
5624fe013be4SDimitry Andric return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl())
5625fe013be4SDimitry Andric .withElementType(ConvertType(E->getType()));
56260b57cec5SDimitry Andric }
56270b57cec5SDimitry Andric
EmitCXXUuidofLValue(const CXXUuidofExpr * E)56280b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
56290b57cec5SDimitry Andric return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
56300b57cec5SDimitry Andric AlignmentSource::Decl);
56310b57cec5SDimitry Andric }
56320b57cec5SDimitry Andric
56330b57cec5SDimitry Andric LValue
EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr * E)56340b57cec5SDimitry Andric CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
56350b57cec5SDimitry Andric AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
56360b57cec5SDimitry Andric Slot.setExternallyDestructed();
56370b57cec5SDimitry Andric EmitAggExpr(E->getSubExpr(), Slot);
56380b57cec5SDimitry Andric EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
56390b57cec5SDimitry Andric return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
56400b57cec5SDimitry Andric }
56410b57cec5SDimitry Andric
EmitObjCMessageExprLValue(const ObjCMessageExpr * E)56420b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
56430b57cec5SDimitry Andric RValue RV = EmitObjCMessageExpr(E);
56440b57cec5SDimitry Andric
56450b57cec5SDimitry Andric if (!RV.isScalar())
56460b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
56470b57cec5SDimitry Andric AlignmentSource::Decl);
56480b57cec5SDimitry Andric
56490b57cec5SDimitry Andric assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
56500b57cec5SDimitry Andric "Can't have a scalar return unless the return type is a "
56510b57cec5SDimitry Andric "reference type!");
56520b57cec5SDimitry Andric
56530b57cec5SDimitry Andric return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
56540b57cec5SDimitry Andric }
56550b57cec5SDimitry Andric
EmitObjCSelectorLValue(const ObjCSelectorExpr * E)56560b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
56570b57cec5SDimitry Andric Address V =
56580b57cec5SDimitry Andric CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
56590b57cec5SDimitry Andric return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
56600b57cec5SDimitry Andric }
56610b57cec5SDimitry Andric
EmitIvarOffset(const ObjCInterfaceDecl * Interface,const ObjCIvarDecl * Ivar)56620b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
56630b57cec5SDimitry Andric const ObjCIvarDecl *Ivar) {
56640b57cec5SDimitry Andric return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
56650b57cec5SDimitry Andric }
56660b57cec5SDimitry Andric
5667bdd1243dSDimitry Andric llvm::Value *
EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl * Interface,const ObjCIvarDecl * Ivar)5668bdd1243dSDimitry Andric CodeGenFunction::EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface,
5669bdd1243dSDimitry Andric const ObjCIvarDecl *Ivar) {
5670bdd1243dSDimitry Andric llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
5671bdd1243dSDimitry Andric QualType PointerDiffType = getContext().getPointerDiffType();
5672bdd1243dSDimitry Andric return Builder.CreateZExtOrTrunc(OffsetValue,
5673bdd1243dSDimitry Andric getTypes().ConvertType(PointerDiffType));
5674bdd1243dSDimitry Andric }
5675bdd1243dSDimitry Andric
EmitLValueForIvar(QualType ObjectTy,llvm::Value * BaseValue,const ObjCIvarDecl * Ivar,unsigned CVRQualifiers)56760b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
56770b57cec5SDimitry Andric llvm::Value *BaseValue,
56780b57cec5SDimitry Andric const ObjCIvarDecl *Ivar,
56790b57cec5SDimitry Andric unsigned CVRQualifiers) {
56800b57cec5SDimitry Andric return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
56810b57cec5SDimitry Andric Ivar, CVRQualifiers);
56820b57cec5SDimitry Andric }
56830b57cec5SDimitry Andric
EmitObjCIvarRefLValue(const ObjCIvarRefExpr * E)56840b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
56850b57cec5SDimitry Andric // FIXME: A lot of the code below could be shared with EmitMemberExpr.
56860b57cec5SDimitry Andric llvm::Value *BaseValue = nullptr;
56870b57cec5SDimitry Andric const Expr *BaseExpr = E->getBase();
56880b57cec5SDimitry Andric Qualifiers BaseQuals;
56890b57cec5SDimitry Andric QualType ObjectTy;
56900b57cec5SDimitry Andric if (E->isArrow()) {
56910b57cec5SDimitry Andric BaseValue = EmitScalarExpr(BaseExpr);
56920b57cec5SDimitry Andric ObjectTy = BaseExpr->getType()->getPointeeType();
56930b57cec5SDimitry Andric BaseQuals = ObjectTy.getQualifiers();
56940b57cec5SDimitry Andric } else {
56950b57cec5SDimitry Andric LValue BaseLV = EmitLValue(BaseExpr);
5696480093f4SDimitry Andric BaseValue = BaseLV.getPointer(*this);
56970b57cec5SDimitry Andric ObjectTy = BaseExpr->getType();
56980b57cec5SDimitry Andric BaseQuals = ObjectTy.getQualifiers();
56990b57cec5SDimitry Andric }
57000b57cec5SDimitry Andric
57010b57cec5SDimitry Andric LValue LV =
57020b57cec5SDimitry Andric EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
57030b57cec5SDimitry Andric BaseQuals.getCVRQualifiers());
57040b57cec5SDimitry Andric setObjCGCLValueClass(getContext(), E, LV);
57050b57cec5SDimitry Andric return LV;
57060b57cec5SDimitry Andric }
57070b57cec5SDimitry Andric
EmitStmtExprLValue(const StmtExpr * E)57080b57cec5SDimitry Andric LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
57090b57cec5SDimitry Andric // Can only get l-value for message expression returning aggregate type
57100b57cec5SDimitry Andric RValue RV = EmitAnyExprToTemp(E);
57110b57cec5SDimitry Andric return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
57120b57cec5SDimitry Andric AlignmentSource::Decl);
57130b57cec5SDimitry Andric }
57140b57cec5SDimitry Andric
EmitCall(QualType CalleeType,const CGCallee & OrigCallee,const CallExpr * E,ReturnValueSlot ReturnValue,llvm::Value * Chain)57150b57cec5SDimitry Andric RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
57160b57cec5SDimitry Andric const CallExpr *E, ReturnValueSlot ReturnValue,
57170b57cec5SDimitry Andric llvm::Value *Chain) {
57180b57cec5SDimitry Andric // Get the actual function type. The callee type will always be a pointer to
57190b57cec5SDimitry Andric // function type or a block pointer type.
57200b57cec5SDimitry Andric assert(CalleeType->isFunctionPointerType() &&
57210b57cec5SDimitry Andric "Call must have function pointer type!");
57220b57cec5SDimitry Andric
57230b57cec5SDimitry Andric const Decl *TargetDecl =
57240b57cec5SDimitry Andric OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
57250b57cec5SDimitry Andric
5726fe013be4SDimitry Andric assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
5727fe013be4SDimitry Andric !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
5728fe013be4SDimitry Andric "trying to emit a call to an immediate function");
5729fe013be4SDimitry Andric
57300b57cec5SDimitry Andric CalleeType = getContext().getCanonicalType(CalleeType);
57310b57cec5SDimitry Andric
57320b57cec5SDimitry Andric auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
57330b57cec5SDimitry Andric
57340b57cec5SDimitry Andric CGCallee Callee = OrigCallee;
57350b57cec5SDimitry Andric
5736fe013be4SDimitry Andric if (SanOpts.has(SanitizerKind::Function) &&
5737fe013be4SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
5738fe013be4SDimitry Andric !isa<FunctionNoProtoType>(PointeeType)) {
57390b57cec5SDimitry Andric if (llvm::Constant *PrefixSig =
57400b57cec5SDimitry Andric CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
57410b57cec5SDimitry Andric SanitizerScope SanScope(this);
5742fe013be4SDimitry Andric auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
5743fe013be4SDimitry Andric
5744fe6060f1SDimitry Andric llvm::Type *PrefixSigType = PrefixSig->getType();
57450b57cec5SDimitry Andric llvm::StructType *PrefixStructTy = llvm::StructType::get(
5746fe6060f1SDimitry Andric CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
57470b57cec5SDimitry Andric
57480b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer();
57490b57cec5SDimitry Andric
5750fe013be4SDimitry Andric // On 32-bit Arm, the low bit of a function pointer indicates whether
5751fe013be4SDimitry Andric // it's using the Arm or Thumb instruction set. The actual first
5752fe013be4SDimitry Andric // instruction lives at the same address either way, so we must clear
5753fe013be4SDimitry Andric // that low bit before using the function address to find the prefix
5754fe013be4SDimitry Andric // structure.
5755fe013be4SDimitry Andric //
5756fe013be4SDimitry Andric // This applies to both Arm and Thumb target triples, because
5757fe013be4SDimitry Andric // either one could be used in an interworking context where it
5758fe013be4SDimitry Andric // might be passed function pointers of both types.
5759fe013be4SDimitry Andric llvm::Value *AlignedCalleePtr;
5760fe013be4SDimitry Andric if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
5761fe013be4SDimitry Andric llvm::Value *CalleeAddress =
5762fe013be4SDimitry Andric Builder.CreatePtrToInt(CalleePtr, IntPtrTy);
5763fe013be4SDimitry Andric llvm::Value *Mask = llvm::ConstantInt::get(IntPtrTy, ~1);
5764fe013be4SDimitry Andric llvm::Value *AlignedCalleeAddress =
5765fe013be4SDimitry Andric Builder.CreateAnd(CalleeAddress, Mask);
5766fe013be4SDimitry Andric AlignedCalleePtr =
5767fe013be4SDimitry Andric Builder.CreateIntToPtr(AlignedCalleeAddress, CalleePtr->getType());
5768fe013be4SDimitry Andric } else {
5769fe013be4SDimitry Andric AlignedCalleePtr = CalleePtr;
5770fe013be4SDimitry Andric }
5771fe013be4SDimitry Andric
5772c9157d92SDimitry Andric llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
57730b57cec5SDimitry Andric llvm::Value *CalleeSigPtr =
5774fe013be4SDimitry Andric Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
57750b57cec5SDimitry Andric llvm::Value *CalleeSig =
5776fe6060f1SDimitry Andric Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
57770b57cec5SDimitry Andric llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
57780b57cec5SDimitry Andric
57790b57cec5SDimitry Andric llvm::BasicBlock *Cont = createBasicBlock("cont");
57800b57cec5SDimitry Andric llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
57810b57cec5SDimitry Andric Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
57820b57cec5SDimitry Andric
57830b57cec5SDimitry Andric EmitBlock(TypeCheck);
5784fe013be4SDimitry Andric llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
5785fe013be4SDimitry Andric Int32Ty,
5786fe013be4SDimitry Andric Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
5787fe013be4SDimitry Andric getPointerAlign());
5788fe013be4SDimitry Andric llvm::Value *CalleeTypeHashMatch =
5789fe013be4SDimitry Andric Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
57900b57cec5SDimitry Andric llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
57910b57cec5SDimitry Andric EmitCheckTypeDescriptor(CalleeType)};
5792fe013be4SDimitry Andric EmitCheck(std::make_pair(CalleeTypeHashMatch, SanitizerKind::Function),
57930b57cec5SDimitry Andric SanitizerHandler::FunctionTypeMismatch, StaticData,
5794fe013be4SDimitry Andric {CalleePtr});
57950b57cec5SDimitry Andric
57960b57cec5SDimitry Andric Builder.CreateBr(Cont);
57970b57cec5SDimitry Andric EmitBlock(Cont);
57980b57cec5SDimitry Andric }
57990b57cec5SDimitry Andric }
58000b57cec5SDimitry Andric
58010b57cec5SDimitry Andric const auto *FnType = cast<FunctionType>(PointeeType);
58020b57cec5SDimitry Andric
58030b57cec5SDimitry Andric // If we are checking indirect calls and this call is indirect, check that the
58040b57cec5SDimitry Andric // function pointer is a member of the bit set for the function type.
58050b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFIICall) &&
58060b57cec5SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
58070b57cec5SDimitry Andric SanitizerScope SanScope(this);
58080b57cec5SDimitry Andric EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
58090b57cec5SDimitry Andric
58100b57cec5SDimitry Andric llvm::Metadata *MD;
58110b57cec5SDimitry Andric if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
58120b57cec5SDimitry Andric MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
58130b57cec5SDimitry Andric else
58140b57cec5SDimitry Andric MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
58150b57cec5SDimitry Andric
58160b57cec5SDimitry Andric llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
58170b57cec5SDimitry Andric
58180b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer();
58190b57cec5SDimitry Andric llvm::Value *TypeTest = Builder.CreateCall(
5820c9157d92SDimitry Andric CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
58210b57cec5SDimitry Andric
58220b57cec5SDimitry Andric auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
58230b57cec5SDimitry Andric llvm::Constant *StaticData[] = {
58240b57cec5SDimitry Andric llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
58250b57cec5SDimitry Andric EmitCheckSourceLocation(E->getBeginLoc()),
58260b57cec5SDimitry Andric EmitCheckTypeDescriptor(QualType(FnType, 0)),
58270b57cec5SDimitry Andric };
58280b57cec5SDimitry Andric if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
58290b57cec5SDimitry Andric EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
5830c9157d92SDimitry Andric CalleePtr, StaticData);
58310b57cec5SDimitry Andric } else {
58320b57cec5SDimitry Andric EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
58330b57cec5SDimitry Andric SanitizerHandler::CFICheckFail, StaticData,
5834c9157d92SDimitry Andric {CalleePtr, llvm::UndefValue::get(IntPtrTy)});
58350b57cec5SDimitry Andric }
58360b57cec5SDimitry Andric }
58370b57cec5SDimitry Andric
58380b57cec5SDimitry Andric CallArgList Args;
58390b57cec5SDimitry Andric if (Chain)
5840c9157d92SDimitry Andric Args.add(RValue::get(Chain), CGM.getContext().VoidPtrTy);
58410b57cec5SDimitry Andric
58420b57cec5SDimitry Andric // C++17 requires that we evaluate arguments to a call using assignment syntax
58430b57cec5SDimitry Andric // right-to-left, and that we evaluate arguments to certain other operators
58440b57cec5SDimitry Andric // left-to-right. Note that we allow this to override the order dictated by
58450b57cec5SDimitry Andric // the calling convention on the MS ABI, which means that parameter
58460b57cec5SDimitry Andric // destruction order is not necessarily reverse construction order.
58470b57cec5SDimitry Andric // FIXME: Revisit this based on C++ committee response to unimplementability.
58480b57cec5SDimitry Andric EvaluationOrder Order = EvaluationOrder::Default;
5849*b9d9368bSDimitry Andric bool StaticOperator = false;
58500b57cec5SDimitry Andric if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
58510b57cec5SDimitry Andric if (OCE->isAssignmentOp())
58520b57cec5SDimitry Andric Order = EvaluationOrder::ForceRightToLeft;
58530b57cec5SDimitry Andric else {
58540b57cec5SDimitry Andric switch (OCE->getOperator()) {
58550b57cec5SDimitry Andric case OO_LessLess:
58560b57cec5SDimitry Andric case OO_GreaterGreater:
58570b57cec5SDimitry Andric case OO_AmpAmp:
58580b57cec5SDimitry Andric case OO_PipePipe:
58590b57cec5SDimitry Andric case OO_Comma:
58600b57cec5SDimitry Andric case OO_ArrowStar:
58610b57cec5SDimitry Andric Order = EvaluationOrder::ForceLeftToRight;
58620b57cec5SDimitry Andric break;
58630b57cec5SDimitry Andric default:
58640b57cec5SDimitry Andric break;
58650b57cec5SDimitry Andric }
58660b57cec5SDimitry Andric }
5867*b9d9368bSDimitry Andric
5868*b9d9368bSDimitry Andric if (const auto *MD =
5869*b9d9368bSDimitry Andric dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl());
5870*b9d9368bSDimitry Andric MD && MD->isStatic())
5871*b9d9368bSDimitry Andric StaticOperator = true;
58720b57cec5SDimitry Andric }
58730b57cec5SDimitry Andric
5874*b9d9368bSDimitry Andric auto Arguments = E->arguments();
5875*b9d9368bSDimitry Andric if (StaticOperator) {
5876*b9d9368bSDimitry Andric // If we're calling a static operator, we need to emit the object argument
5877*b9d9368bSDimitry Andric // and ignore it.
5878*b9d9368bSDimitry Andric EmitIgnoredExpr(E->getArg(0));
5879*b9d9368bSDimitry Andric Arguments = drop_begin(Arguments, 1);
5880*b9d9368bSDimitry Andric }
5881*b9d9368bSDimitry Andric EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments,
5882*b9d9368bSDimitry Andric E->getDirectCallee(), /*ParamsToSkip=*/0, Order);
58830b57cec5SDimitry Andric
58840b57cec5SDimitry Andric const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
58850b57cec5SDimitry Andric Args, FnType, /*ChainCall=*/Chain);
58860b57cec5SDimitry Andric
58870b57cec5SDimitry Andric // C99 6.5.2.2p6:
58880b57cec5SDimitry Andric // If the expression that denotes the called function has a type
58890b57cec5SDimitry Andric // that does not include a prototype, [the default argument
58900b57cec5SDimitry Andric // promotions are performed]. If the number of arguments does not
58910b57cec5SDimitry Andric // equal the number of parameters, the behavior is undefined. If
58920b57cec5SDimitry Andric // the function is defined with a type that includes a prototype,
58930b57cec5SDimitry Andric // and either the prototype ends with an ellipsis (, ...) or the
58940b57cec5SDimitry Andric // types of the arguments after promotion are not compatible with
58950b57cec5SDimitry Andric // the types of the parameters, the behavior is undefined. If the
58960b57cec5SDimitry Andric // function is defined with a type that does not include a
58970b57cec5SDimitry Andric // prototype, and the types of the arguments after promotion are
58980b57cec5SDimitry Andric // not compatible with those of the parameters after promotion,
58990b57cec5SDimitry Andric // the behavior is undefined [except in some trivial cases].
59000b57cec5SDimitry Andric // That is, in the general case, we should assume that a call
59010b57cec5SDimitry Andric // through an unprototyped function type works like a *non-variadic*
59020b57cec5SDimitry Andric // call. The way we make this work is to cast to the exact type
59030b57cec5SDimitry Andric // of the promoted arguments.
59040b57cec5SDimitry Andric //
59050b57cec5SDimitry Andric // Chain calls use this same code path to add the invisible chain parameter
59060b57cec5SDimitry Andric // to the function type.
59070b57cec5SDimitry Andric if (isa<FunctionNoProtoType>(FnType) || Chain) {
59080b57cec5SDimitry Andric llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
59095ffd83dbSDimitry Andric int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
59105ffd83dbSDimitry Andric CalleeTy = CalleeTy->getPointerTo(AS);
59110b57cec5SDimitry Andric
59120b57cec5SDimitry Andric llvm::Value *CalleePtr = Callee.getFunctionPointer();
59130b57cec5SDimitry Andric CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
59140b57cec5SDimitry Andric Callee.setFunctionPointer(CalleePtr);
59150b57cec5SDimitry Andric }
59160b57cec5SDimitry Andric
5917fe6060f1SDimitry Andric // HIP function pointer contains kernel handle when it is used in triple
5918fe6060f1SDimitry Andric // chevron. The kernel stub needs to be loaded from kernel handle and used
5919fe6060f1SDimitry Andric // as callee.
5920fe6060f1SDimitry Andric if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
5921fe6060f1SDimitry Andric isa<CUDAKernelCallExpr>(E) &&
5922fe6060f1SDimitry Andric (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5923fe6060f1SDimitry Andric llvm::Value *Handle = Callee.getFunctionPointer();
592481ad6265SDimitry Andric auto *Stub = Builder.CreateLoad(
5925c9157d92SDimitry Andric Address(Handle, Handle->getType(), CGM.getPointerAlign()));
5926fe6060f1SDimitry Andric Callee.setFunctionPointer(Stub);
5927fe6060f1SDimitry Andric }
59280b57cec5SDimitry Andric llvm::CallBase *CallOrInvoke = nullptr;
59290b57cec5SDimitry Andric RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5930fe6060f1SDimitry Andric E == MustTailCall, E->getExprLoc());
59310b57cec5SDimitry Andric
59320b57cec5SDimitry Andric // Generate function declaration DISuprogram in order to be used
59330b57cec5SDimitry Andric // in debug info about call sites.
59340b57cec5SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) {
5935349cc55cSDimitry Andric if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5936349cc55cSDimitry Andric FunctionArgList Args;
5937349cc55cSDimitry Andric QualType ResTy = BuildFunctionArgList(CalleeDecl, Args);
5938349cc55cSDimitry Andric DI->EmitFuncDeclForCallSite(CallOrInvoke,
5939349cc55cSDimitry Andric DI->getFunctionType(CalleeDecl, ResTy, Args),
59400b57cec5SDimitry Andric CalleeDecl);
59410b57cec5SDimitry Andric }
5942349cc55cSDimitry Andric }
59430b57cec5SDimitry Andric
59440b57cec5SDimitry Andric return Call;
59450b57cec5SDimitry Andric }
59460b57cec5SDimitry Andric
59470b57cec5SDimitry Andric LValue CodeGenFunction::
EmitPointerToDataMemberBinaryExpr(const BinaryOperator * E)59480b57cec5SDimitry Andric EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
59490b57cec5SDimitry Andric Address BaseAddr = Address::invalid();
59500b57cec5SDimitry Andric if (E->getOpcode() == BO_PtrMemI) {
59510b57cec5SDimitry Andric BaseAddr = EmitPointerWithAlignment(E->getLHS());
59520b57cec5SDimitry Andric } else {
5953480093f4SDimitry Andric BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
59540b57cec5SDimitry Andric }
59550b57cec5SDimitry Andric
59560b57cec5SDimitry Andric llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5957480093f4SDimitry Andric const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
59580b57cec5SDimitry Andric
59590b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
59600b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
59610b57cec5SDimitry Andric Address MemberAddr =
59620b57cec5SDimitry Andric EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
59630b57cec5SDimitry Andric &TBAAInfo);
59640b57cec5SDimitry Andric
59650b57cec5SDimitry Andric return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
59660b57cec5SDimitry Andric }
59670b57cec5SDimitry Andric
59680b57cec5SDimitry Andric /// Given the address of a temporary variable, produce an r-value of
59690b57cec5SDimitry Andric /// its type.
convertTempToRValue(Address addr,QualType type,SourceLocation loc)59700b57cec5SDimitry Andric RValue CodeGenFunction::convertTempToRValue(Address addr,
59710b57cec5SDimitry Andric QualType type,
59720b57cec5SDimitry Andric SourceLocation loc) {
59730b57cec5SDimitry Andric LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
59740b57cec5SDimitry Andric switch (getEvaluationKind(type)) {
59750b57cec5SDimitry Andric case TEK_Complex:
59760b57cec5SDimitry Andric return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
59770b57cec5SDimitry Andric case TEK_Aggregate:
5978480093f4SDimitry Andric return lvalue.asAggregateRValue(*this);
59790b57cec5SDimitry Andric case TEK_Scalar:
59800b57cec5SDimitry Andric return RValue::get(EmitLoadOfScalar(lvalue, loc));
59810b57cec5SDimitry Andric }
59820b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
59830b57cec5SDimitry Andric }
59840b57cec5SDimitry Andric
SetFPAccuracy(llvm::Value * Val,float Accuracy)59850b57cec5SDimitry Andric void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
59860b57cec5SDimitry Andric assert(Val->getType()->isFPOrFPVectorTy());
59870b57cec5SDimitry Andric if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
59880b57cec5SDimitry Andric return;
59890b57cec5SDimitry Andric
59900b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext());
59910b57cec5SDimitry Andric llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
59920b57cec5SDimitry Andric
59930b57cec5SDimitry Andric cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
59940b57cec5SDimitry Andric }
59950b57cec5SDimitry Andric
SetSqrtFPAccuracy(llvm::Value * Val)5996fe013be4SDimitry Andric void CodeGenFunction::SetSqrtFPAccuracy(llvm::Value *Val) {
5997fe013be4SDimitry Andric llvm::Type *EltTy = Val->getType()->getScalarType();
5998fe013be4SDimitry Andric if (!EltTy->isFloatTy())
5999fe013be4SDimitry Andric return;
6000fe013be4SDimitry Andric
6001fe013be4SDimitry Andric if ((getLangOpts().OpenCL &&
6002fe013be4SDimitry Andric !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
6003fe013be4SDimitry Andric (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
6004fe013be4SDimitry Andric !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
6005fe013be4SDimitry Andric // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 3ulp
6006fe013be4SDimitry Andric //
6007fe013be4SDimitry Andric // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
6008fe013be4SDimitry Andric // build option allows an application to specify that single precision
6009fe013be4SDimitry Andric // floating-point divide (x/y and 1/x) and sqrt used in the program
6010fe013be4SDimitry Andric // source are correctly rounded.
6011fe013be4SDimitry Andric //
6012fe013be4SDimitry Andric // TODO: CUDA has a prec-sqrt flag
6013fe013be4SDimitry Andric SetFPAccuracy(Val, 3.0f);
6014fe013be4SDimitry Andric }
6015fe013be4SDimitry Andric }
6016fe013be4SDimitry Andric
SetDivFPAccuracy(llvm::Value * Val)6017fe013be4SDimitry Andric void CodeGenFunction::SetDivFPAccuracy(llvm::Value *Val) {
6018fe013be4SDimitry Andric llvm::Type *EltTy = Val->getType()->getScalarType();
6019fe013be4SDimitry Andric if (!EltTy->isFloatTy())
6020fe013be4SDimitry Andric return;
6021fe013be4SDimitry Andric
6022fe013be4SDimitry Andric if ((getLangOpts().OpenCL &&
6023fe013be4SDimitry Andric !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
6024fe013be4SDimitry Andric (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
6025fe013be4SDimitry Andric !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
6026fe013be4SDimitry Andric // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
6027fe013be4SDimitry Andric //
6028fe013be4SDimitry Andric // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
6029fe013be4SDimitry Andric // build option allows an application to specify that single precision
6030fe013be4SDimitry Andric // floating-point divide (x/y and 1/x) and sqrt used in the program
6031fe013be4SDimitry Andric // source are correctly rounded.
6032fe013be4SDimitry Andric //
6033fe013be4SDimitry Andric // TODO: CUDA has a prec-div flag
6034fe013be4SDimitry Andric SetFPAccuracy(Val, 2.5f);
6035fe013be4SDimitry Andric }
6036fe013be4SDimitry Andric }
6037fe013be4SDimitry Andric
60380b57cec5SDimitry Andric namespace {
60390b57cec5SDimitry Andric struct LValueOrRValue {
60400b57cec5SDimitry Andric LValue LV;
60410b57cec5SDimitry Andric RValue RV;
60420b57cec5SDimitry Andric };
60430b57cec5SDimitry Andric }
60440b57cec5SDimitry Andric
emitPseudoObjectExpr(CodeGenFunction & CGF,const PseudoObjectExpr * E,bool forLValue,AggValueSlot slot)60450b57cec5SDimitry Andric static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
60460b57cec5SDimitry Andric const PseudoObjectExpr *E,
60470b57cec5SDimitry Andric bool forLValue,
60480b57cec5SDimitry Andric AggValueSlot slot) {
60490b57cec5SDimitry Andric SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
60500b57cec5SDimitry Andric
60510b57cec5SDimitry Andric // Find the result expression, if any.
60520b57cec5SDimitry Andric const Expr *resultExpr = E->getResultExpr();
60530b57cec5SDimitry Andric LValueOrRValue result;
60540b57cec5SDimitry Andric
60550b57cec5SDimitry Andric for (PseudoObjectExpr::const_semantics_iterator
60560b57cec5SDimitry Andric i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
60570b57cec5SDimitry Andric const Expr *semantic = *i;
60580b57cec5SDimitry Andric
60590b57cec5SDimitry Andric // If this semantic expression is an opaque value, bind it
60600b57cec5SDimitry Andric // to the result of its source expression.
60610b57cec5SDimitry Andric if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
60620b57cec5SDimitry Andric // Skip unique OVEs.
60630b57cec5SDimitry Andric if (ov->isUnique()) {
60640b57cec5SDimitry Andric assert(ov != resultExpr &&
60650b57cec5SDimitry Andric "A unique OVE cannot be used as the result expression");
60660b57cec5SDimitry Andric continue;
60670b57cec5SDimitry Andric }
60680b57cec5SDimitry Andric
60690b57cec5SDimitry Andric // If this is the result expression, we may need to evaluate
60700b57cec5SDimitry Andric // directly into the slot.
60710b57cec5SDimitry Andric typedef CodeGenFunction::OpaqueValueMappingData OVMA;
60720b57cec5SDimitry Andric OVMA opaqueData;
6073fe6060f1SDimitry Andric if (ov == resultExpr && ov->isPRValue() && !forLValue &&
60740b57cec5SDimitry Andric CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
60750b57cec5SDimitry Andric CGF.EmitAggExpr(ov->getSourceExpr(), slot);
60760b57cec5SDimitry Andric LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
60770b57cec5SDimitry Andric AlignmentSource::Decl);
60780b57cec5SDimitry Andric opaqueData = OVMA::bind(CGF, ov, LV);
60790b57cec5SDimitry Andric result.RV = slot.asRValue();
60800b57cec5SDimitry Andric
60810b57cec5SDimitry Andric // Otherwise, emit as normal.
60820b57cec5SDimitry Andric } else {
60830b57cec5SDimitry Andric opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
60840b57cec5SDimitry Andric
60850b57cec5SDimitry Andric // If this is the result, also evaluate the result now.
60860b57cec5SDimitry Andric if (ov == resultExpr) {
60870b57cec5SDimitry Andric if (forLValue)
60880b57cec5SDimitry Andric result.LV = CGF.EmitLValue(ov);
60890b57cec5SDimitry Andric else
60900b57cec5SDimitry Andric result.RV = CGF.EmitAnyExpr(ov, slot);
60910b57cec5SDimitry Andric }
60920b57cec5SDimitry Andric }
60930b57cec5SDimitry Andric
60940b57cec5SDimitry Andric opaques.push_back(opaqueData);
60950b57cec5SDimitry Andric
60960b57cec5SDimitry Andric // Otherwise, if the expression is the result, evaluate it
60970b57cec5SDimitry Andric // and remember the result.
60980b57cec5SDimitry Andric } else if (semantic == resultExpr) {
60990b57cec5SDimitry Andric if (forLValue)
61000b57cec5SDimitry Andric result.LV = CGF.EmitLValue(semantic);
61010b57cec5SDimitry Andric else
61020b57cec5SDimitry Andric result.RV = CGF.EmitAnyExpr(semantic, slot);
61030b57cec5SDimitry Andric
61040b57cec5SDimitry Andric // Otherwise, evaluate the expression in an ignored context.
61050b57cec5SDimitry Andric } else {
61060b57cec5SDimitry Andric CGF.EmitIgnoredExpr(semantic);
61070b57cec5SDimitry Andric }
61080b57cec5SDimitry Andric }
61090b57cec5SDimitry Andric
61100b57cec5SDimitry Andric // Unbind all the opaques now.
61110b57cec5SDimitry Andric for (unsigned i = 0, e = opaques.size(); i != e; ++i)
61120b57cec5SDimitry Andric opaques[i].unbind(CGF);
61130b57cec5SDimitry Andric
61140b57cec5SDimitry Andric return result;
61150b57cec5SDimitry Andric }
61160b57cec5SDimitry Andric
EmitPseudoObjectRValue(const PseudoObjectExpr * E,AggValueSlot slot)61170b57cec5SDimitry Andric RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
61180b57cec5SDimitry Andric AggValueSlot slot) {
61190b57cec5SDimitry Andric return emitPseudoObjectExpr(*this, E, false, slot).RV;
61200b57cec5SDimitry Andric }
61210b57cec5SDimitry Andric
EmitPseudoObjectLValue(const PseudoObjectExpr * E)61220b57cec5SDimitry Andric LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
61230b57cec5SDimitry Andric return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
61240b57cec5SDimitry Andric }
6125