LLVM 17.0.0git
Go to the documentation of this file.
1//===-- KCFI.cpp - Generic KCFI operand bundle lowering ---------*- C++ -*-===//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
9// This pass emits generic KCFI indirect call checks for targets that don't
10// support lowering KCFI operand bundles in the back-end.
15#include "llvm/ADT/Statistic.h"
16#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
21#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/MDBuilder.h"
26#include "llvm/IR/Module.h"
28#include "llvm/Pass.h"
33using namespace llvm;
35#define DEBUG_TYPE "kcfi"
37STATISTIC(NumKCFIChecks, "Number of kcfi operands transformed into checks");
39namespace {
40class DiagnosticInfoKCFI : public DiagnosticInfo {
41 const Twine &Msg;
44 DiagnosticInfoKCFI(const Twine &DiagMsg,
46 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
47 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
49} // namespace
52 Module &M = *F.getParent();
53 if (!M.getModuleFlag("kcfi"))
56 // Find call instructions with KCFI operand bundles.
58 for (Instruction &I : instructions(F)) {
59 if (auto *CI = dyn_cast<CallInst>(&I))
60 if (CI->getOperandBundle(LLVMContext::OB_kcfi))
61 KCFICalls.push_back(CI);
62 }
64 if (KCFICalls.empty())
67 LLVMContext &Ctx = M.getContext();
68 // patchable-function-prefix emits nops between the KCFI type identifier
69 // and the function start. As we don't know the size of the emitted nops,
70 // don't allow this attribute with generic lowering.
71 if (F.hasFnAttribute("patchable-function-prefix"))
72 Ctx.diagnose(
73 DiagnosticInfoKCFI("-fpatchable-function-entry=N,M, where M>0 is not "
74 "compatible with -fsanitize=kcfi on this target"));
77 MDNode *VeryUnlikelyWeights =
78 MDBuilder(Ctx).createBranchWeights(1, (1U << 20) - 1);
80 for (CallInst *CI : KCFICalls) {
81 // Get the expected hash value.
82 const uint32_t ExpectedHash =
83 cast<ConstantInt>(CI->getOperandBundle(LLVMContext::OB_kcfi)->Inputs[0])
84 ->getZExtValue();
86 // Drop the KCFI operand bundle.
87 CallBase *Call =
89 assert(Call != CI);
90 Call->copyMetadata(*CI);
91 CI->replaceAllUsesWith(Call);
92 CI->eraseFromParent();
94 if (!Call->isIndirectCall())
95 continue;
97 // Emit a check and trap if the target hash doesn't match.
98 IRBuilder<> Builder(Call);
99 Value *HashPtr = Builder.CreateConstInBoundsGEP1_32(
100 Int32Ty, Call->getCalledOperand(), -1);
101 Value *Test = Builder.CreateICmpNE(Builder.CreateLoad(Int32Ty, HashPtr),
102 ConstantInt::get(Int32Ty, ExpectedHash));
103 Instruction *ThenTerm =
104 SplitBlockAndInsertIfThen(Test, Call, false, VeryUnlikelyWeights);
105 Builder.SetInsertPoint(ThenTerm);
106 Builder.CreateCall(Intrinsic::getDeclaration(&M, Intrinsic::trap));
107 ++NumKCFIChecks;
108 }
assume Assume Builder
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Module.h This file contains the declarations for the Module class.
print must be executed print the must be executed context for all instructions
IntegerType * Int32Ty
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
Definition: Statistic.h:167
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1186
static CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, Instruction *InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
This is the base abstract class for diagnostic reporting in the backend.
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
Interface for custom diagnostic printing.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2558
Class to represent integer types.
Definition: DerivedTypes.h:40
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: KCFI.cpp:51
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:37
Metadata node.
Definition: Metadata.h:943
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:155
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
bool empty() const
Definition: SmallVector.h:94
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static IntegerType * getInt32Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
const CustomOperand< const MCSubtargetInfo & > Msg[]
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1506
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ DK_Linker
Defines the different supported severity of a diagnostic.
@ DS_Error
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights, DominatorTree *DT, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...