#include "CodeGenFunction.h"
#include "CGBlocks.h"
#include "CGCUDARuntime.h"
#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGDebugInfo.h"
#include "CGOpenMPRuntime.h"
#include "CodeGenModule.h"
#include "CodeGenPGO.h"
#include "TargetInfo.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/FPEnv.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/CRC.h"
#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
using namespace clang;
using namespace CodeGen;
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
const LangOptions &LangOpts) {
if (CGOpts.DisableLifetimeMarkers)
return false;
if (CGOpts.SanitizeAddressUseAfterScope ||
LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
LangOpts.Sanitize.has(SanitizerKind::Memory))
return true;
return CGOpts.OptimizationLevel != 0;
}
CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
: CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
CGBuilderInserterTy(this)),
SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
ShouldEmitLifetimeMarkers(
shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
if (!suppressNewContext)
CGM.getCXXABI().getMangleContext().startNewFunction();
EHStack.setCGF(this);
SetFastMathFlags(CurFPFeatures);
}
CodeGenFunction::~CodeGenFunction() {
assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
if (getLangOpts().OpenMP && CurFn)
CGM.getOpenMPRuntime().functionFinished(*this);
if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
}
llvm::fp::ExceptionBehavior
clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
switch (Kind) {
case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore;
case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
case LangOptions::FPE_Strict: return llvm::fp::ebStrict;
default:
llvm_unreachable("Unsupported FP Exception Behavior");
}
}
void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
llvm::FastMathFlags FMF;
FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
FMF.setNoInfs(FPFeatures.getNoHonorInfs());
FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
Builder.setFastMathFlags(FMF);
}
CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
const Expr *E)
: CGF(CGF) {
ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
}
CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
FPOptions FPFeatures)
: CGF(CGF) {
ConstructorHelper(FPFeatures);
}
void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
OldFPFeatures = CGF.CurFPFeatures;
CGF.CurFPFeatures = FPFeatures;
OldExcept = CGF.Builder.getDefaultConstrainedExcept();
OldRounding = CGF.Builder.getDefaultConstrainedRounding();
if (OldFPFeatures == FPFeatures)
return;
FMFGuard.emplace(CGF.Builder);
llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
auto NewExceptionBehavior =
ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
FPFeatures.getExceptionMode()));
CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
CGF.SetFastMathFlags(FPFeatures);
assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
(NewExceptionBehavior == llvm::fp::ebIgnore &&
NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
"FPConstrained should be enabled on entire function");
auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
auto OldValue =
CGF.CurFn->getFnAttribute(Name).getValueAsBool();
auto NewValue = OldValue & Value;
if (OldValue != NewValue)
CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
};
mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
mergeFnAttrValue("unsafe-fp-math", FPFeatures.getAllowFPReassociate() &&
FPFeatures.getAllowReciprocal() &&
FPFeatures.getAllowApproxFunc() &&
FPFeatures.getNoSignedZero());
}
CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
CGF.CurFPFeatures = OldFPFeatures;
CGF.Builder.setDefaultConstrainedExcept(OldExcept);
CGF.Builder.setDefaultConstrainedRounding(OldRounding);
}
LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
LValueBaseInfo BaseInfo;
TBAAAccessInfo TBAAInfo;
CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
Address Addr(V, ConvertTypeForMem(T), Alignment);
return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
}
LValue
CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
LValueBaseInfo BaseInfo;
TBAAAccessInfo TBAAInfo;
CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
true);
Address Addr(V, ConvertTypeForMem(T), Align);
return MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
}
llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
return CGM.getTypes().ConvertTypeForMem(T);
}
llvm::Type *CodeGenFunction::ConvertType(QualType T) {
return CGM.getTypes().ConvertType(T);
}
TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
type = type.getCanonicalType();
while (true) {
switch (type->getTypeClass()) {
#define TYPE(name, parent)
#define ABSTRACT_TYPE(name, parent)
#define NON_CANONICAL_TYPE(name, parent) case Type::name:
#define DEPENDENT_TYPE(name, parent) case Type::name:
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
#include "clang/AST/TypeNodes.inc"
llvm_unreachable("non-canonical or dependent type in IR-generation");
case Type::Auto:
case Type::DeducedTemplateSpecialization:
llvm_unreachable("undeduced type in IR-generation");
case Type::Builtin:
case Type::Pointer:
case Type::BlockPointer:
case Type::LValueReference:
case Type::RValueReference:
case Type::MemberPointer:
case Type::Vector:
case Type::ExtVector:
case Type::ConstantMatrix:
case Type::FunctionProto:
case Type::FunctionNoProto:
case Type::Enum:
case Type::ObjCObjectPointer:
case Type::Pipe:
case Type::BitInt:
return TEK_Scalar;
case Type::Complex:
return TEK_Complex;
case Type::ConstantArray:
case Type::IncompleteArray:
case Type::VariableArray:
case Type::Record:
case Type::ObjCObject:
case Type::ObjCInterface:
return TEK_Aggregate;
case Type::Atomic:
type = cast<AtomicType>(type)->getValueType();
continue;
}
llvm_unreachable("unknown type kind!");
}
}
llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
if (CurBB) {
assert(!CurBB->getTerminator() && "Unexpected terminated block.");
if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
delete ReturnBlock.getBlock();
ReturnBlock = JumpDest();
} else
EmitBlock(ReturnBlock.getBlock());
return llvm::DebugLoc();
}
if (ReturnBlock.getBlock()->hasOneUse()) {
llvm::BranchInst *BI =
dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
if (BI && BI->isUnconditional() &&
BI->getSuccessor(0) == ReturnBlock.getBlock()) {
llvm::DebugLoc Loc = BI->getDebugLoc();
Builder.SetInsertPoint(BI->getParent());
BI->eraseFromParent();
delete ReturnBlock.getBlock();
ReturnBlock = JumpDest();
return Loc;
}
}
EmitBlock(ReturnBlock.getBlock());
return llvm::DebugLoc();
}
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
if (!BB) return;
if (!BB->use_empty())
return CGF.CurFn->getBasicBlockList().push_back(BB);
delete BB;
}
void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
assert(BreakContinueStack.empty() &&
"mismatched push/pop in break/continue stack!");
bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
&& NumSimpleReturnExprs == NumReturnExprs
&& ReturnBlock.getBlock()->use_empty();
if (CGDebugInfo *DI = getDebugInfo()) {
if (OnlySimpleReturnStmts)
DI->EmitLocation(Builder, LastStopPoint);
else
DI->EmitLocation(Builder, EndLoc);
}
bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
bool HasOnlyLifetimeMarkers =
HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
if (HasCleanups) {
Optional<ApplyDebugLocation> AL;
if (CGDebugInfo *DI = getDebugInfo()) {
if (OnlySimpleReturnStmts)
DI->EmitLocation(Builder, EndLoc);
else
AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
}
PopCleanupBlocks(PrologueCleanupDepth);
}
llvm::DebugLoc Loc = EmitReturnBlock();
if (ShouldInstrumentFunction()) {
if (CGM.getCodeGenOpts().InstrumentFunctions)
CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
CurFn->addFnAttr("instrument-function-exit-inlined",
"__cyg_profile_func_exit");
}
if (CGDebugInfo *DI = getDebugInfo())
DI->EmitFunctionEnd(Builder, CurFn);
ApplyDebugLocation AL(*this, Loc);
EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
EmitEndEHSpec(CurCodeDecl);
assert(EHStack.empty() &&
"did not remove all scopes from cleanup stack!");
if (IndirectBranch) {
EmitBlock(IndirectBranch->getParent());
Builder.ClearInsertionPoint();
}
if (!EscapedLocals.empty()) {
SmallVector<llvm::Value *, 4> EscapeArgs;
EscapeArgs.resize(EscapedLocals.size());
for (auto &Pair : EscapedLocals)
EscapeArgs[Pair.second] = Pair.first;
llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
&CGM.getModule(), llvm::Intrinsic::localescape);
CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
}
llvm::Instruction *Ptr = AllocaInsertPt;
AllocaInsertPt = nullptr;
Ptr->eraseFromParent();
if (PostAllocaInsertPt) {
llvm::Instruction *PostPtr = PostAllocaInsertPt;
PostAllocaInsertPt = nullptr;
PostPtr->eraseFromParent();
}
if (IndirectBranch) {
llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
if (PN->getNumIncomingValues() == 0) {
PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
PN->eraseFromParent();
}
}
EmitIfUsed(*this, EHResumeBlock);
EmitIfUsed(*this, TerminateLandingPad);
EmitIfUsed(*this, TerminateHandler);
EmitIfUsed(*this, UnreachableBlock);
for (const auto &FuncletAndParent : TerminateFunclets)
EmitIfUsed(*this, FuncletAndParent.second);
if (CGM.getCodeGenOpts().EmitDeclMetadata)
EmitDeclMetadata();
for (const auto &R : DeferredReplacements) {
if (llvm::Value *Old = R.first) {
Old->replaceAllUsesWith(R.second);
cast<llvm::Instruction>(Old)->eraseFromParent();
}
}
DeferredReplacements.clear();
if (NormalCleanupDest.isValid() && isCoroutine()) {
llvm::DominatorTree DT(*CurFn);
llvm::PromoteMemToReg(
cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
NormalCleanupDest = Address::invalid();
}
for (llvm::Argument &A : CurFn->args())
if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
LargestVectorWidth =
std::max((uint64_t)LargestVectorWidth,
VT->getPrimitiveSizeInBits().getKnownMinSize());
if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
LargestVectorWidth =
std::max((uint64_t)LargestVectorWidth,
VT->getPrimitiveSizeInBits().getKnownMinSize());
if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth)
LargestVectorWidth = CurFnInfo->getMaxVectorWidth();
CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
Optional<std::pair<unsigned, unsigned>> VScaleRange =
getContext().getTargetInfo().getVScaleRange(getLangOpts());
if (VScaleRange) {
CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
getLLVMContext(), VScaleRange->first, VScaleRange->second));
}
if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
Builder.ClearInsertionPoint();
ReturnBlock.getBlock()->eraseFromParent();
}
if (ReturnValue.isValid()) {
auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
if (RetAlloca && RetAlloca->use_empty()) {
RetAlloca->eraseFromParent();
ReturnValue = Address::invalid();
}
}
}
bool CodeGenFunction::ShouldInstrumentFunction() {
if (!CGM.getCodeGenOpts().InstrumentFunctions &&
!CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
!CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
return false;
if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
return false;
return true;
}
bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
if (!CurFuncDecl)
return false;
return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
}
bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
return CGM.getCodeGenOpts().XRayInstrumentFunctions;
}
bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
(CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
XRayInstrKind::Custom);
}
bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
(CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
XRayInstrKind::Typed);
}
llvm::Value *
CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
llvm::Value *EncodedAddr) {
auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
return Builder.CreateLoad(Address(GOTAddr, Int8PtrTy, getPointerAlign()),
"decoded_addr");
}
void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD,
llvm::Function *Fn) {
if (!FD->hasAttr<OpenCLKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>())
return;
llvm::LLVMContext &Context = getLLVMContext();
CGM.GenKernelArgMetadata(Fn, FD, this);
if (!getLangOpts().OpenCL)
return;
if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
QualType HintQTy = A->getTypeHint();
const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
bool IsSignedInteger =
HintQTy->isSignedIntegerType() ||
(HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
llvm::Metadata *AttrMDArgs[] = {
llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
CGM.getTypes().ConvertType(A->getTypeHint()))),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::IntegerType::get(Context, 32),
llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
}
if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
llvm::Metadata *AttrMDArgs[] = {
llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
}
if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
llvm::Metadata *AttrMDArgs[] = {
llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
}
if (const OpenCLIntelReqdSubGroupSizeAttr *A =
FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
llvm::Metadata *AttrMDArgs[] = {
llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
Fn->setMetadata("intel_reqd_sub_group_size",
llvm::MDNode::get(Context, AttrMDArgs));
}
}
static bool endsWithReturn(const Decl* F) {
const Stmt *Body = nullptr;
if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
Body = FD->getBody();
else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
Body = OMD->getBody();
if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
auto LastStmt = CS->body_rbegin();
if (LastStmt != CS->body_rend())
return isa<ReturnStmt>(*LastStmt);
}
return false;
}
void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
if (SanOpts.has(SanitizerKind::Thread)) {
Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
}
}
bool CodeGenFunction::requiresReturnValueCheck() const {
return requiresReturnValueNullabilityCheck() ||
(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
CurCodeDecl->getAttr<ReturnsNonNullAttr>());
}
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
!MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
(MD->getNumParams() != 1 && MD->getNumParams() != 2))
return false;
if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
return false;
if (MD->getNumParams() == 2) {
auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
if (!PT || !PT->isVoidPointerType() ||
!PT->getPointeeType().isConstQualified())
return false;
}
return true;
}
static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
const FunctionDecl *FD) {
if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
if (!MD->isStatic())
return nullptr;
return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
}
void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
llvm::Function *Fn,
const CGFunctionInfo &FnInfo,
const FunctionArgList &Args,
SourceLocation Loc,
SourceLocation StartLoc) {
assert(!CurFn &&
"Do not use a CodeGenFunction object for more than one function");
const Decl *D = GD.getDecl();
DidCallStackSave = false;
CurCodeDecl = D;
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
if (FD && FD->usesSEHTry())
CurSEHParent = FD;
CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
FnRetTy = RetTy;
CurFn = Fn;
CurFnInfo = &FnInfo;
assert(CurFn->isDeclaration() && "Function already has body?");
do {
#define SANITIZER(NAME, ID) \
if (SanOpts.empty()) \
break; \
if (SanOpts.has(SanitizerKind::ID)) \
if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
SanOpts.set(SanitizerKind::ID, false);
#include "clang/Basic/Sanitizers.def"
#undef SANITIZER
} while (false);
if (D) {
const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds);
bool NoSanitizeCoverage = false;
for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
SanitizerMask mask = Attr->getMask();
SanOpts.Mask &= ~mask;
if (mask & SanitizerKind::Address)
SanOpts.set(SanitizerKind::KernelAddress, false);
if (mask & SanitizerKind::KernelAddress)
SanOpts.set(SanitizerKind::Address, false);
if (mask & SanitizerKind::HWAddress)
SanOpts.set(SanitizerKind::KernelHWAddress, false);
if (mask & SanitizerKind::KernelHWAddress)
SanOpts.set(SanitizerKind::HWAddress, false);
if (Attr->hasCoverage())
NoSanitizeCoverage = true;
}
if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds))
Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
}
if (ShouldSkipSanitizerInstrumentation()) {
CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
} else {
if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
if (SanOpts.hasOneOf(SanitizerKind::HWAddress |
SanitizerKind::KernelHWAddress))
Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
if (SanOpts.has(SanitizerKind::MemtagStack))
Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
if (SanOpts.has(SanitizerKind::Thread))
Fn->addFnAttr(llvm::Attribute::SanitizeThread);
if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
}
if (SanOpts.has(SanitizerKind::SafeStack))
Fn->addFnAttr(llvm::Attribute::SafeStack);
if (SanOpts.has(SanitizerKind::ShadowCallStack))
Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
if (SanOpts.has(SanitizerKind::Thread)) {
if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
if (OMD->getMethodFamily() == OMF_dealloc ||
OMD->getMethodFamily() == OMF_initialize ||
(OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
markAsIgnoreThreadCheckingAtRuntime(Fn);
}
}
}
if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
if (matchesStlAllocatorFn(D, getContext()))
SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
}
if (D && SanOpts.has(SanitizerKind::Null))
if (FD && FD->getBody() &&
FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
SanOpts.Mask &= ~SanitizerKind::Null;
bool AlwaysXRayAttr = false;
if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
XRayInstrKind::FunctionEntry) ||
CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
XRayInstrKind::FunctionExit)) {
if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
Fn->addFnAttr("function-instrument", "xray-always");
AlwaysXRayAttr = true;
}
if (XRayAttr->neverXRayInstrument())
Fn->addFnAttr("function-instrument", "xray-never");
if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
if (ShouldXRayInstrumentFunction())
Fn->addFnAttr("xray-log-args",
llvm::utostr(LogArgs->getArgumentCount()));
}
} else {
if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
Fn->addFnAttr(
"xray-instruction-threshold",
llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
}
if (ShouldXRayInstrumentFunction()) {
if (CGM.getCodeGenOpts().XRayIgnoreLoops)
Fn->addFnAttr("xray-ignore-loops");
if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
XRayInstrKind::FunctionExit))
Fn->addFnAttr("xray-skip-exit");
if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
XRayInstrKind::FunctionEntry))
Fn->addFnAttr("xray-skip-entry");
auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
if (FuncGroups > 1) {
auto FuncName = llvm::makeArrayRef<uint8_t>(
CurFn->getName().bytes_begin(), CurFn->getName().bytes_end());
auto Group = crc32(FuncName) % FuncGroups;
if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
!AlwaysXRayAttr)
Fn->addFnAttr("function-instrument", "xray-never");
}
}
if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone)
if (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc))
Fn->addFnAttr(llvm::Attribute::NoProfile);
unsigned Count, Offset;
if (const auto *Attr =
D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
Count = Attr->getCount();
Offset = Attr->getOffset();
} else {
Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
}
if (Count && Offset <= Count) {
Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
if (Offset)
Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
}
if (CGM.getCodeGenOpts().HotPatch &&
getContext().getTargetInfo().getTriple().isX86())
Fn->addFnAttr("patchable-function", "prologue-short-redirect");
if (CGM.getCodeGenOpts().NoUseJumpTables)
Fn->addFnAttr("no-jump-tables", "true");
if (CGM.getCodeGenOpts().NoInlineLineTables)
Fn->addFnAttr("no-inline-line-tables");
if (CGM.getCodeGenOpts().ProfileSampleAccurate)
Fn->addFnAttr("profile-sample-accurate");
if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
Fn->addFnAttr("use-sample-profile");
if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
Fn->addFnAttr("cfi-canonical-jump-table");
if (D && D->hasAttr<NoProfileFunctionAttr>())
Fn->addFnAttr(llvm::Attribute::NoProfile);
if (D) {
if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
switch (A->getThunkType()) {
case FunctionReturnThunksAttr::Kind::Keep:
break;
case FunctionReturnThunksAttr::Kind::Extern:
Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
break;
}
} else if (CGM.getCodeGenOpts().FunctionReturnThunks)
Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
}
if (FD && (getLangOpts().OpenCL ||
(getLangOpts().HIP && getLangOpts().CUDAIsDevice))) {
EmitKernelMetadata(FD, Fn);
}
if (FD && getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
auto ProtoTy = getContext().getFunctionTypeWithExceptionSpec(
FD->getType(), EST_None);
llvm::Constant *FTRTTIConst =
CGM.GetAddrOfRTTIDescriptor(ProtoTy, true);
llvm::GlobalVariable *FTRTTIProxy =
CGM.GetOrCreateRTTIProxyGlobalVariable(FTRTTIConst);
llvm::LLVMContext &Ctx = Fn->getContext();
llvm::MDBuilder MDB(Ctx);
Fn->setMetadata(llvm::LLVMContext::MD_func_sanitize,
MDB.createRTTIPointerPrologue(PrologueSig, FTRTTIProxy));
CGM.addCompilerUsedGlobal(FTRTTIProxy);
}
}
if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
auto Nullability = FnRetTy->getNullability(getContext());
if (Nullability && *Nullability == NullabilityKind::NonNull) {
if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
RetValNullabilityPrecondition =
llvm::ConstantInt::getTrue(getLLVMContext());
}
}
if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) ||
getLangOpts().OpenCL || getLangOpts().SYCLIsDevice ||
(getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
Fn->addFnAttr(llvm::Attribute::NoRecurse);
llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
llvm::fp::ExceptionBehavior FPExceptionBehavior =
ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
Builder.setDefaultConstrainedRounding(RM);
Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
(!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
RM != llvm::RoundingMode::NearestTiesToEven))) {
Builder.setIsFPConstrained(true);
Fn->addFnAttr(llvm::Attribute::StrictFP);
}
if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
CGM.getCodeGenOpts().StackAlignment))
Fn->addFnAttr("stackrealign");
if (FD && FD->isMain())
Fn->removeFnAttr("zero-call-used-regs");
llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
ReturnBlock = getJumpDestInCurrentScope("return");
Builder.SetInsertPoint(EntryBB);
if (requiresReturnValueCheck()) {
ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
ReturnLocation);
}
if (CGDebugInfo *DI = getDebugInfo()) {
DI->emitFunctionStart(GD, Loc, StartLoc,
DI->getFunctionType(FD, RetTy, Args), CurFn,
CurFuncIsThunk);
}
if (ShouldInstrumentFunction()) {
if (CGM.getCodeGenOpts().InstrumentFunctions)
CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
CurFn->addFnAttr("instrument-function-entry-inlined",
"__cyg_profile_func_enter");
if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
CurFn->addFnAttr("instrument-function-entry-inlined",
"__cyg_profile_func_enter_bare");
}
if (CGM.getCodeGenOpts().InstrumentForProfiling) {
if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
if (CGM.getCodeGenOpts().CallFEntry)
Fn->addFnAttr("fentry-call", "true");
else {
Fn->addFnAttr("instrument-function-entry-inlined",
getTarget().getMCountName());
}
if (CGM.getCodeGenOpts().MNopMCount) {
if (!CGM.getCodeGenOpts().CallFEntry)
CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
<< "-mnop-mcount" << "-mfentry";
Fn->addFnAttr("mnop-mcount");
}
if (CGM.getCodeGenOpts().RecordMCount) {
if (!CGM.getCodeGenOpts().CallFEntry)
CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
<< "-mrecord-mcount" << "-mfentry";
Fn->addFnAttr("mrecord-mcount");
}
}
}
if (CGM.getCodeGenOpts().PackedStack) {
if (getContext().getTargetInfo().getTriple().getArch() !=
llvm::Triple::systemz)
CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
<< "-mpacked-stack";
Fn->addFnAttr("packed-stack");
}
if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
!CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
Fn->addFnAttr("warn-stack-size",
std::to_string(CGM.getCodeGenOpts().WarnStackSize));
if (RetTy->isVoidType()) {
ReturnValue = Address::invalid();
if (!endsWithReturn(D))
++NumReturnExprs;
} else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
auto AI = CurFn->arg_begin();
if (CurFnInfo->getReturnInfo().isSRetAfterThis())
++AI;
ReturnValue = Address(&*AI, ConvertType(RetTy),
CurFnInfo->getReturnInfo().getIndirectAlign());
if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
ReturnValuePointer =
CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
ReturnValue.getPointer(), Int8PtrTy),
ReturnValuePointer);
}
} else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
!hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
llvm::Function::arg_iterator EI = CurFn->arg_end();
--EI;
llvm::Value *Addr = Builder.CreateStructGEP(
CurFnInfo->getArgStruct(), &*EI, Idx);
llvm::Type *Ty =
cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
ReturnValue =
Address(Addr, ConvertType(RetTy), CGM.getNaturalTypeAlignment(RetTy));
} else {
ReturnValue = CreateIRTemp(RetTy, "retval");
if (getLangOpts().ObjCAutoRefCount &&
!CurFnInfo->isReturnsRetained() &&
RetTy->isObjCRetainableType())
AutoreleaseResult = true;
}
EmitStartEHSpec(CurCodeDecl);
PrologueCleanupDepth = EHStack.stable_begin();
if (getLangOpts().OpenMP && CurCodeDecl)
CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
EmitFunctionProlog(*CurFnInfo, CurFn, Args);
if (isa_and_nonnull<CXXMethodDecl>(D) &&
cast<CXXMethodDecl>(D)->isInstance()) {
CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
if (MD->getParent()->isLambda() &&
MD->getOverloadedOperator() == OO_Call) {
MD->getParent()->getCaptureFields(LambdaCaptureFields,
LambdaThisCaptureField);
if (LambdaThisCaptureField) {
LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
if (!LambdaThisCaptureField->getType()->isPointerType()) {
CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
} else {
CXXThisValue =
EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
}
}
for (auto *FD : MD->getParent()->fields()) {
if (FD->hasCapturedVLAType()) {
auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
SourceLocation()).getScalarVal();
auto VAT = FD->getCapturedVLAType();
VLASizeMap[VAT->getSizeExpr()] = ExprArg;
}
}
} else {
CXXThisValue = CXXABIThisValue;
}
if (CXXABIThisValue) {
SanitizerSet SkippedChecks;
SkippedChecks.set(SanitizerKind::ObjectSize, true);
QualType ThisTy = MD->getThisType();
if (isLambdaCallOperator(MD) &&
MD->getParent()->getLambdaCaptureDefault() == LCD_None)
SkippedChecks.set(SanitizerKind::Null, true);
EmitTypeCheck(
isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
}
}
if (!FD || !FD->hasAttr<NakedAttr>()) {
for (const VarDecl *VD : Args) {
QualType Ty;
if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
Ty = PVD->getOriginalType();
else
Ty = VD->getType();
if (Ty->isVariablyModifiedType())
EmitVariablyModifiedType(Ty);
}
}
if (CGDebugInfo *DI = getDebugInfo())
DI->EmitLocation(Builder, StartLoc);
if (CurFuncDecl)
if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
LargestVectorWidth = VecWidth->getVectorWidth();
}
void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
incrementProfileCounter(Body);
if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
EmitCompoundStmtWithoutScope(*S);
else
EmitStmt(Body);
if (checkIfFunctionMustProgress())
CurFn->addFnAttr(llvm::Attribute::MustProgress);
}
void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
const Stmt *S) {
llvm::BasicBlock *SkipCountBB = nullptr;
if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
SkipCountBB = createBasicBlock("skipcount");
EmitBranch(SkipCountBB);
}
EmitBlock(BB);
uint64_t CurrentCount = getCurrentProfileCount();
incrementProfileCounter(S);
setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
if (SkipCountBB)
EmitBlock(SkipCountBB);
}
static void TryMarkNoThrow(llvm::Function *F) {
if (F->isInterposable()) return;
for (llvm::BasicBlock &BB : *F)
for (llvm::Instruction &I : BB)
if (I.mayThrow())
return;
F->setDoesNotThrow();
}
QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
FunctionArgList &Args) {
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
QualType ResTy = FD->getReturnType();
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
if (MD && MD->isInstance()) {
if (CGM.getCXXABI().HasThisReturn(GD))
ResTy = MD->getThisType();
else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
ResTy = CGM.getContext().VoidPtrTy;
CGM.getCXXABI().buildThisParam(*this, Args);
}
bool PassedParams = true;
if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
if (auto Inherited = CD->getInheritedConstructor())
PassedParams =
getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
if (PassedParams) {
for (auto *Param : FD->parameters()) {
Args.push_back(Param);
if (!Param->hasAttr<PassObjectSizeAttr>())
continue;
auto *Implicit = ImplicitParamDecl::Create(
getContext(), Param->getDeclContext(), Param->getLocation(),
nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
SizeArguments[Param] = Implicit;
Args.push_back(Implicit);
}
}
if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
return ResTy;
}
void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
const CGFunctionInfo &FnInfo) {
assert(Fn && "generating code for null Function");
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
CurGD = GD;
FunctionArgList Args;
QualType ResTy = BuildFunctionArgList(GD, Args);
if (FD->isInlineBuiltinDeclaration()) {
std::string FDInlineName = (Fn->getName() + ".inline").str();
llvm::Module *M = Fn->getParent();
llvm::Function *Clone = M->getFunction(FDInlineName);
if (!Clone) {
Clone = llvm::Function::Create(Fn->getFunctionType(),
llvm::GlobalValue::InternalLinkage,
Fn->getAddressSpace(), FDInlineName, M);
Clone->addFnAttr(llvm::Attribute::AlwaysInline);
}
Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
Fn = Clone;
} else {
for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
PD = PD->getPreviousDecl()) {
if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
std::string FDInlineName = (Fn->getName() + ".inline").str();
llvm::Module *M = Fn->getParent();
if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
Clone->replaceAllUsesWith(Fn);
Clone->eraseFromParent();
}
break;
}
}
}
if (FD->hasAttr<NoDebugAttr>()) {
Fn->setSubprogram(nullptr);
DebugInfo = nullptr;
}
SourceRange BodyRange;
if (Stmt *Body = FD->getBody())
BodyRange = Body->getSourceRange();
else
BodyRange = FD->getLocation();
CurEHLocation = BodyRange.getEnd();
SourceLocation Loc = FD->getLocation();
if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
if (SpecDecl->hasBody(SpecDecl))
Loc = SpecDecl->getLocation();
Stmt *Body = FD->getBody();
if (Body) {
if (isa<CoroutineBodyStmt>(Body))
ShouldEmitLifetimeMarkers = true;
if (ShouldEmitLifetimeMarkers)
Bypasses.Init(Body);
}
StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
llvm::append_range(FnArgs, FD->parameters());
PGO.assignRegionCounters(GD, CurFn);
if (isa<CXXDestructorDecl>(FD))
EmitDestructorBody(Args);
else if (isa<CXXConstructorDecl>(FD))
EmitConstructorBody(Args);
else if (getLangOpts().CUDA &&
!getLangOpts().CUDAIsDevice &&
FD->hasAttr<CUDAGlobalAttr>())
CGM.getCUDARuntime().emitDeviceStub(*this, Args);
else if (isa<CXXMethodDecl>(FD) &&
cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
} else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
(cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
emitImplicitAssignmentOperatorBody(Args);
} else if (Body) {
EmitFunctionBody(Body);
} else
llvm_unreachable("no definition for emitted function");
if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
!FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
bool ShouldEmitUnreachable =
CGM.getCodeGenOpts().StrictReturn ||
!CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
if (SanOpts.has(SanitizerKind::Return)) {
SanitizerScope SanScope(this);
llvm::Value *IsFalse = Builder.getFalse();
EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
SanitizerHandler::MissingReturn,
EmitCheckSourceLocation(FD->getLocation()), None);
} else if (ShouldEmitUnreachable) {
if (CGM.getCodeGenOpts().OptimizationLevel == 0)
EmitTrapCall(llvm::Intrinsic::trap);
}
if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
Builder.CreateUnreachable();
Builder.ClearInsertionPoint();
}
}
FinishFunction(BodyRange.getEnd());
if (!CurFn->doesNotThrow())
TryMarkNoThrow(CurFn);
}
bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
if (!S) return false;
if (isa<LabelStmt>(S))
return true;
if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
return true;
if (isa<SwitchStmt>(S))
IgnoreCaseStmts = true;
for (const Stmt *SubStmt : S->children())
if (ContainsLabel(SubStmt, IgnoreCaseStmts))
return true;
return false;
}
bool CodeGenFunction::containsBreak(const Stmt *S) {
if (!S) return false;
if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
isa<ForStmt>(S))
return false;
if (isa<BreakStmt>(S))
return true;
for (const Stmt *SubStmt : S->children())
if (containsBreak(SubStmt))
return true;
return false;
}
bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
if (!S) return false;
if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
return false;
if (isa<DeclStmt>(S))
return true;
for (const Stmt *SubStmt : S->children())
if (mightAddDeclToScope(SubStmt))
return true;
return false;
}
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
bool &ResultBool,
bool AllowLabels) {
llvm::APSInt ResultInt;
if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
return false;
ResultBool = ResultInt.getBoolValue();
return true;
}
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
llvm::APSInt &ResultInt,
bool AllowLabels) {
Expr::EvalResult Result;
if (!Cond->EvaluateAsInt(Result, getContext()))
return false;
llvm::APSInt Int = Result.Val.getInt();
if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
return false;
ResultInt = Int;
return true;
}
bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens()))
if (UnOp->getOpcode() == UO_LNot)
C = UnOp->getSubExpr();
const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens());
return (!BOp || !BOp->isLogicalOp());
}
void CodeGenFunction::EmitBranchToCounterBlock(
const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
llvm::BasicBlock *FalseBlock, uint64_t TrueCount ,
Stmt::Likelihood LH , const Expr *CntrIdx ) {
bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
if (!InstrumentRegions || !isInstrumentedCondition(Cond))
return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
llvm::BasicBlock *ThenBlock = nullptr;
llvm::BasicBlock *ElseBlock = nullptr;
llvm::BasicBlock *NextBlock = nullptr;
llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
if (LOp == BO_LAnd) {
ThenBlock = CounterIncrBlock;
ElseBlock = FalseBlock;
NextBlock = TrueBlock;
}
else if (LOp == BO_LOr) {
ThenBlock = TrueBlock;
ElseBlock = CounterIncrBlock;
NextBlock = FalseBlock;
} else {
llvm_unreachable("Expected Opcode must be that of a Logical Operator");
}
EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
EmitBlock(CounterIncrBlock);
incrementProfileCounter(CntrIdx ? CntrIdx : Cond);
EmitBranch(NextBlock);
}
void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
llvm::BasicBlock *TrueBlock,
llvm::BasicBlock *FalseBlock,
uint64_t TrueCount,
Stmt::Likelihood LH) {
Cond = Cond->IgnoreParens();
if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
if (CondBOp->getOpcode() == BO_LAnd) {
bool ConstantBool = false;
if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
ConstantBool) {
incrementProfileCounter(CondBOp);
return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
FalseBlock, TrueCount, LH);
}
if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
ConstantBool) {
return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
FalseBlock, TrueCount, LH, CondBOp);
}
llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
ConditionalEvaluation eval(*this);
{
ApplyDebugLocation DL(*this, Cond);
EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
EmitBlock(LHSTrue);
}
incrementProfileCounter(CondBOp);
setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
eval.begin(*this);
EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
FalseBlock, TrueCount, LH);
eval.end(*this);
return;
}
if (CondBOp->getOpcode() == BO_LOr) {
bool ConstantBool = false;
if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
!ConstantBool) {
incrementProfileCounter(CondBOp);
return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
FalseBlock, TrueCount, LH);
}
if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
!ConstantBool) {
return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
FalseBlock, TrueCount, LH, CondBOp);
}
llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
uint64_t LHSCount =
getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
uint64_t RHSCount = TrueCount - LHSCount;
ConditionalEvaluation eval(*this);
{
ApplyDebugLocation DL(*this, Cond);
EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
EmitBlock(LHSFalse);
}
incrementProfileCounter(CondBOp);
setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
eval.begin(*this);
EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
RHSCount, LH);
eval.end(*this);
return;
}
}
if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
if (CondUOp->getOpcode() == UO_LNot) {
uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
LH = static_cast<Stmt::Likelihood>(-LH);
return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
FalseCount, LH);
}
}
if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
ConditionalEvaluation cond(*this);
EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
getProfileCount(CondOp), Stmt::LH_None);
uint64_t LHSScaledTrueCount = 0;
if (TrueCount) {
double LHSRatio =
getProfileCount(CondOp) / (double)getCurrentProfileCount();
LHSScaledTrueCount = TrueCount * LHSRatio;
}
cond.begin(*this);
EmitBlock(LHSBlock);
incrementProfileCounter(CondOp);
{
ApplyDebugLocation DL(*this, Cond);
EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
LHSScaledTrueCount, LH);
}
cond.end(*this);
cond.begin(*this);
EmitBlock(RHSBlock);
EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
TrueCount - LHSScaledTrueCount, LH);
cond.end(*this);
return;
}
if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
EmitCXXThrowExpr(Throw, false);
return;
}
llvm::Value *CondV;
{
ApplyDebugLocation DL(*this, Cond);
CondV = EvaluateExprAsBool(Cond);
}
llvm::MDNode *Weights = nullptr;
llvm::MDNode *Unpredictable = nullptr;
auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
llvm::MDBuilder MDHelper(getLLVMContext());
Unpredictable = MDHelper.createUnpredictable();
}
}
llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
if (CondV != NewCondV)
CondV = NewCondV;
else {
uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
}
Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
}
void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
CGM.ErrorUnsupported(S, Type);
}
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
Address dest, Address src,
llvm::Value *sizeInChars) {
CGBuilderTy &Builder = CGF.Builder;
CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
llvm::Value *baseSizeInChars
= llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
Address begin =
Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
llvm::Value *end = Builder.CreateInBoundsGEP(
begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end");
llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
CGF.EmitBlock(loopBB);
llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
cur->addIncoming(begin.getPointer(), originBB);
CharUnits curAlign =
dest.getAlignment().alignmentOfArrayElement(baseSize);
Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
false);
llvm::Value *next =
Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
Builder.CreateCondBr(done, contBB, loopBB);
cur->addIncoming(next, loopBB);
CGF.EmitBlock(contBB);
}
void
CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
if (getLangOpts().CPlusPlus) {
if (const RecordType *RT = Ty->getAs<RecordType>()) {
if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
return;
}
}
if (DestPtr.getElementType() != Int8Ty)
DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
CharUnits size = getContext().getTypeSizeInChars(Ty);
llvm::Value *SizeVal;
const VariableArrayType *vla;
if (size.isZero()) {
if (const VariableArrayType *vlaType =
dyn_cast_or_null<VariableArrayType>(
getContext().getAsArrayType(Ty))) {
auto VlaSize = getVLASize(vlaType);
SizeVal = VlaSize.NumElts;
CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
if (!eltSize.isOne())
SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
vla = vlaType;
} else {
return;
}
} else {
SizeVal = CGM.getSize(size);
vla = nullptr;
}
if (!CGM.getTypes().isZeroInitializable(Ty)) {
if (vla) Ty = getContext().getBaseElementType(vla);
llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
llvm::GlobalVariable *NullVariable =
new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
true,
llvm::GlobalVariable::PrivateLinkage,
NullConstant, Twine());
CharUnits NullAlign = DestPtr.getAlignment();
NullVariable->setAlignment(NullAlign.getAsAlign());
Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
Builder.getInt8Ty(), NullAlign);
if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
return;
}
Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
}
llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
if (!IndirectBranch)
GetIndirectGotoBlock();
llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
IndirectBranch->addDestination(BB);
return llvm::BlockAddress::get(CurFn, BB);
}
llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
if (IndirectBranch) return IndirectBranch->getParent();
CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
"indirect.goto.dest");
IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
return IndirectBranch->getParent();
}
llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
QualType &baseType,
Address &addr) {
const ArrayType *arrayType = origArrayType;
llvm::Value *numVLAElements = nullptr;
if (isa<VariableArrayType>(arrayType)) {
numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
do {
QualType elementType = arrayType->getElementType();
arrayType = getContext().getAsArrayType(elementType);
if (!arrayType) {
baseType = elementType;
return numVLAElements;
}
} while (isa<VariableArrayType>(arrayType));
}
SmallVector<llvm::Value*, 8> gepIndices;
llvm::ConstantInt *zero = Builder.getInt32(0);
gepIndices.push_back(zero);
uint64_t countFromCLAs = 1;
QualType eltType;
llvm::ArrayType *llvmArrayType =
dyn_cast<llvm::ArrayType>(addr.getElementType());
while (llvmArrayType) {
assert(isa<ConstantArrayType>(arrayType));
assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
== llvmArrayType->getNumElements());
gepIndices.push_back(zero);
countFromCLAs *= llvmArrayType->getNumElements();
eltType = arrayType->getElementType();
llvmArrayType =
dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
arrayType = getContext().getAsArrayType(arrayType->getElementType());
assert((!llvmArrayType || arrayType) &&
"LLVM and Clang types are out-of-synch");
}
if (arrayType) {
while (arrayType) {
countFromCLAs *=
cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
eltType = arrayType->getElementType();
arrayType = getContext().getAsArrayType(eltType);
}
llvm::Type *baseType = ConvertType(eltType);
addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
} else {
addr = Address(Builder.CreateInBoundsGEP(
addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"),
ConvertTypeForMem(eltType),
addr.getAlignment());
}
baseType = eltType;
llvm::Value *numElements
= llvm::ConstantInt::get(SizeTy, countFromCLAs);
if (numVLAElements)
numElements = Builder.CreateNUWMul(numVLAElements, numElements);
return numElements;
}
CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
assert(vla && "type was not a variable array type!");
return getVLASize(vla);
}
CodeGenFunction::VlaSizePair
CodeGenFunction::getVLASize(const VariableArrayType *type) {
llvm::Value *numElements = nullptr;
QualType elementType;
do {
elementType = type->getElementType();
llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
assert(vlaSize && "no size for VLA!");
assert(vlaSize->getType() == SizeTy);
if (!numElements) {
numElements = vlaSize;
} else {
numElements = Builder.CreateNUWMul(numElements, vlaSize);
}
} while ((type = getContext().getAsVariableArrayType(elementType)));
return { numElements, elementType };
}
CodeGenFunction::VlaSizePair
CodeGenFunction::getVLAElements1D(QualType type) {
const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
assert(vla && "type was not a variable array type!");
return getVLAElements1D(vla);
}
CodeGenFunction::VlaSizePair
CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
assert(VlaSize && "no size for VLA!");
assert(VlaSize->getType() == SizeTy);
return { VlaSize, Vla->getElementType() };
}
void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
assert(type->isVariablyModifiedType() &&
"Must pass variably modified type to EmitVLASizes!");
EnsureInsertPoint();
do {
assert(type->isVariablyModifiedType());
const Type *ty = type.getTypePtr();
switch (ty->getTypeClass()) {
#define TYPE(Class, Base)
#define ABSTRACT_TYPE(Class, Base)
#define NON_CANONICAL_TYPE(Class, Base)
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
#include "clang/AST/TypeNodes.inc"
llvm_unreachable("unexpected dependent type!");
case Type::Builtin:
case Type::Complex:
case Type::Vector:
case Type::ExtVector:
case Type::ConstantMatrix:
case Type::Record:
case Type::Enum:
case Type::Elaborated:
case Type::Using:
case Type::TemplateSpecialization:
case Type::ObjCTypeParam:
case Type::ObjCObject:
case Type::ObjCInterface:
case Type::ObjCObjectPointer:
case Type::BitInt:
llvm_unreachable("type class is never variably-modified!");
case Type::Adjusted:
type = cast<AdjustedType>(ty)->getAdjustedType();
break;
case Type::Decayed:
type = cast<DecayedType>(ty)->getPointeeType();
break;
case Type::Pointer:
type = cast<PointerType>(ty)->getPointeeType();
break;
case Type::BlockPointer:
type = cast<BlockPointerType>(ty)->getPointeeType();
break;
case Type::LValueReference:
case Type::RValueReference:
type = cast<ReferenceType>(ty)->getPointeeType();
break;
case Type::MemberPointer:
type = cast<MemberPointerType>(ty)->getPointeeType();
break;
case Type::ConstantArray:
case Type::IncompleteArray:
type = cast<ArrayType>(ty)->getElementType();
break;
case Type::VariableArray: {
const VariableArrayType *vat = cast<VariableArrayType>(ty);
if (const Expr *sizeExpr = vat->getSizeExpr()) {
llvm::Value *&entry = VLASizeMap[sizeExpr];
if (!entry) {
llvm::Value *size = EmitScalarExpr(sizeExpr);
if (SanOpts.has(SanitizerKind::VLABound)) {
SanitizerScope SanScope(this);
llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
clang::QualType SEType = sizeExpr->getType();
llvm::Value *CheckCondition =
SEType->isSignedIntegerType()
? Builder.CreateICmpSGT(size, Zero)
: Builder.CreateICmpUGT(size, Zero);
llvm::Constant *StaticArgs[] = {
EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
EmitCheckTypeDescriptor(SEType)};
EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
}
entry = Builder.CreateIntCast(size, SizeTy, false);
}
}
type = vat->getElementType();
break;
}
case Type::FunctionProto:
case Type::FunctionNoProto:
type = cast<FunctionType>(ty)->getReturnType();
break;
case Type::Paren:
case Type::TypeOf:
case Type::UnaryTransform:
case Type::Attributed:
case Type::BTFTagAttributed:
case Type::SubstTemplateTypeParm:
case Type::MacroQualified:
type = type.getSingleStepDesugaredType(getContext());
break;
case Type::Typedef:
case Type::Decltype:
case Type::Auto:
case Type::DeducedTemplateSpecialization:
return;
case Type::TypeOfExpr:
EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
return;
case Type::Atomic:
type = cast<AtomicType>(ty)->getValueType();
break;
case Type::Pipe:
type = cast<PipeType>(ty)->getElementType();
break;
}
} while (type->isVariablyModifiedType());
}
Address CodeGenFunction::EmitVAListRef(const Expr* E) {
if (getContext().getBuiltinVaListType()->isArrayType())
return EmitPointerWithAlignment(E);
return EmitLValue(E).getAddress(*this);
}
Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
return EmitLValue(E).getAddress(*this);
}
void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
const APValue &Init) {
assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
if (CGDebugInfo *Dbg = getDebugInfo())
if (CGM.getCodeGenOpts().hasReducedDebugInfo())
Dbg->EmitGlobalVariable(E->getDecl(), Init);
}
CodeGenFunction::PeepholeProtection
CodeGenFunction::protectFromPeepholes(RValue rvalue) {
if (!rvalue.isScalar()) return PeepholeProtection();
llvm::Value *value = rvalue.getScalarVal();
if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
assert(HaveInsertPoint());
llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
Builder.GetInsertBlock());
PeepholeProtection protection;
protection.Inst = inst;
return protection;
}
void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
if (!protection.Inst) return;
protection.Inst->eraseFromParent();
}
void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
QualType Ty, SourceLocation Loc,
SourceLocation AssumptionLoc,
llvm::Value *Alignment,
llvm::Value *OffsetValue) {
if (Alignment->getType() != IntPtrTy)
Alignment =
Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
if (OffsetValue && OffsetValue->getType() != IntPtrTy)
OffsetValue =
Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
llvm::Value *TheCheck = nullptr;
if (SanOpts.has(SanitizerKind::Alignment)) {
llvm::Value *PtrIntValue =
Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
if (OffsetValue) {
bool IsOffsetZero = false;
if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
IsOffsetZero = CI->isZero();
if (!IsOffsetZero)
PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
}
llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
llvm::Value *Mask =
Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
}
llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
if (!SanOpts.has(SanitizerKind::Alignment))
return;
emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
OffsetValue, TheCheck, Assumption);
}
void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
const Expr *E,
SourceLocation AssumptionLoc,
llvm::Value *Alignment,
llvm::Value *OffsetValue) {
if (auto *CE = dyn_cast<CastExpr>(E))
E = CE->getSubExprAsWritten();
QualType Ty = E->getType();
SourceLocation Loc = E->getExprLoc();
emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
OffsetValue);
}
llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
llvm::Value *AnnotatedVal,
StringRef AnnotationStr,
SourceLocation Location,
const AnnotateAttr *Attr) {
SmallVector<llvm::Value *, 5> Args = {
AnnotatedVal,
Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
CGM.EmitAnnotationLineNo(Location),
};
if (Attr)
Args.push_back(CGM.EmitAnnotationArgs(Attr));
return Builder.CreateCall(AnnotationFn, Args);
}
void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
for (const auto *I : D->specific_attrs<AnnotateAttr>())
EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
I->getAnnotation(), D->getLocation(), I);
}
Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
Address Addr) {
assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
llvm::Value *V = Addr.getPointer();
llvm::Type *VTy = V->getType();
auto *PTy = dyn_cast<llvm::PointerType>(VTy);
unsigned AS = PTy ? PTy->getAddressSpace() : 0;
llvm::PointerType *IntrinTy =
llvm::PointerType::getWithSamePointeeType(CGM.Int8PtrTy, AS);
llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, IntrinTy);
for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
if (VTy != IntrinTy)
V = Builder.CreateBitCast(V, IntrinTy);
V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
V = Builder.CreateBitCast(V, VTy);
}
return Address(V, Addr.getElementType(), Addr.getAlignment());
}
CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
: CGF(CGF) {
assert(!CGF->IsSanitizerScope);
CGF->IsSanitizerScope = true;
}
CodeGenFunction::SanitizerScope::~SanitizerScope() {
CGF->IsSanitizerScope = false;
}
void CodeGenFunction::InsertHelper(llvm::Instruction *I,
const llvm::Twine &Name,
llvm::BasicBlock *BB,
llvm::BasicBlock::iterator InsertPt) const {
LoopStack.InsertHelper(I);
if (IsSanitizerScope)
CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
}
void CGBuilderInserter::InsertHelper(
llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
llvm::BasicBlock::iterator InsertPt) const {
llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
if (CGF)
CGF->InsertHelper(I, Name, BB, InsertPt);
}
void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
const FunctionDecl *TargetDecl) {
return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
}
void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
const FunctionDecl *TargetDecl) {
if (!TargetDecl)
return;
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
if (!FD)
return;
unsigned BuiltinID = TargetDecl->getBuiltinID();
std::string MissingFeature;
llvm::StringMap<bool> CallerFeatureMap;
CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
if (BuiltinID) {
StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
if (!Builtin::evaluateRequiredTargetFeatures(
FeatureList, CallerFeatureMap)) {
CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
<< TargetDecl->getDeclName()
<< FeatureList;
}
} else if (!TargetDecl->isMultiVersion() &&
TargetDecl->hasAttr<TargetAttr>()) {
const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
ParsedTargetAttr ParsedAttr =
CGM.getContext().filterFunctionTargetAttrs(TD);
SmallVector<StringRef, 1> ReqFeatures;
llvm::StringMap<bool> CalleeFeatureMap;
CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
for (const auto &F : ParsedAttr.Features) {
if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
ReqFeatures.push_back(StringRef(F).substr(1));
}
for (const auto &F : CalleeFeatureMap) {
if (F.getValue())
ReqFeatures.push_back(F.getKey());
}
if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
if (!CallerFeatureMap.lookup(Feature)) {
MissingFeature = Feature.str();
return false;
}
return true;
}))
CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
<< FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
}
}
void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
if (!CGM.getCodeGenOpts().SanitizeStats)
return;
llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
CGM.getSanStats().create(IRB, SSK);
}
llvm::Value *
CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
llvm::Value *Condition = nullptr;
if (!RO.Conditions.Architecture.empty())
Condition = EmitX86CpuIs(RO.Conditions.Architecture);
if (!RO.Conditions.Features.empty()) {
llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
Condition =
Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
}
return Condition;
}
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
llvm::Function *Resolver,
CGBuilderTy &Builder,
llvm::Function *FuncToReturn,
bool SupportsIFunc) {
if (SupportsIFunc) {
Builder.CreateRet(FuncToReturn);
return;
}
llvm::SmallVector<llvm::Value *, 10> Args(
llvm::make_pointer_range(Resolver->args()));
llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
if (Resolver->getReturnType()->isVoidTy())
Builder.CreateRetVoid();
else
Builder.CreateRet(Result);
}
void CodeGenFunction::EmitMultiVersionResolver(
llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
assert(getContext().getTargetInfo().getTriple().isX86() &&
"Only implemented for x86 targets");
bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
Builder.SetInsertPoint(CurBlock);
EmitX86CpuInit();
for (const MultiVersionResolverOption &RO : Options) {
Builder.SetInsertPoint(CurBlock);
llvm::Value *Condition = FormResolverCondition(RO);
if (!Condition) {
assert(&RO == Options.end() - 1 &&
"Default or Generic case must be last");
CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
SupportsIFunc);
return;
}
llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
CGBuilderTy RetBuilder(*this, RetBlock);
CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
SupportsIFunc);
CurBlock = createBasicBlock("resolver_else", Resolver);
Builder.CreateCondBr(Condition, RetBlock, CurBlock);
}
Builder.SetInsertPoint(CurBlock);
llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
TrapCall->setDoesNotReturn();
TrapCall->setDoesNotThrow();
Builder.CreateUnreachable();
Builder.ClearInsertionPoint();
}
void CodeGenFunction::emitAlignmentAssumptionCheck(
llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
SourceLocation SecondaryLoc, llvm::Value *Alignment,
llvm::Value *OffsetValue, llvm::Value *TheCheck,
llvm::Instruction *Assumption) {
assert(Assumption && isa<llvm::CallInst>(Assumption) &&
cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
llvm::Intrinsic::getDeclaration(
Builder.GetInsertBlock()->getParent()->getParent(),
llvm::Intrinsic::assume) &&
"Assumption should be a call to llvm.assume().");
assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
"Assumption should be the last instruction of the basic block, "
"since the basic block is still being generated.");
if (!SanOpts.has(SanitizerKind::Alignment))
return;
if (Ty->getPointeeType().isVolatileQualified())
return;
Assumption->removeFromParent();
{
SanitizerScope SanScope(this);
if (!OffsetValue)
OffsetValue = Builder.getInt1(false);
llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
EmitCheckSourceLocation(SecondaryLoc),
EmitCheckTypeDescriptor(Ty)};
llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
EmitCheckValue(Alignment),
EmitCheckValue(OffsetValue)};
EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
}
Builder.Insert(Assumption);
}
llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
if (CGDebugInfo *DI = getDebugInfo())
return DI->SourceLocToDebugLoc(Location);
return llvm::DebugLoc();
}
llvm::Value *
CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
Stmt::Likelihood LH) {
switch (LH) {
case Stmt::LH_None:
return Cond;
case Stmt::LH_Likely:
case Stmt::LH_Unlikely:
if (CGM.getCodeGenOpts().OptimizationLevel == 0)
return Cond;
llvm::Type *CondTy = Cond->getType();
assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
llvm::Function *FnExpect =
CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
llvm::Value *ExpectedValueOfCond =
llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
Cond->getName() + ".expval");
}
llvm_unreachable("Unknown Likelihood");
}
llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
unsigned NumElementsDst,
const llvm::Twine &Name) {
auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
unsigned NumElementsSrc = SrcTy->getNumElements();
if (NumElementsSrc == NumElementsDst)
return SrcVec;
std::vector<int> ShuffleMask(NumElementsDst, -1);
for (unsigned MaskIdx = 0;
MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
ShuffleMask[MaskIdx] = MaskIdx;
return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
}