85 static const unsigned Read = 1;
86 static const unsigned Write = 2;
87 static const unsigned Callee = 4;
88 static const unsigned Branchee = 8;
124 Value *findValue(
Value *V,
bool OffsetOk)
const;
136 std::string Messages;
144 bool runOnFunction(
Function &
F)
override;
156 for (
const Value *V : Vs) {
159 if (isa<Instruction>(V)) {
160 MessagesStr << *V <<
'\n';
162 V->printAsOperand(MessagesStr,
true, Mod);
172 void CheckFailed(
const Twine &Message) { MessagesStr << Message <<
'\n'; }
178 template <
typename T1,
typename... Ts>
179 void CheckFailed(
const Twine &Message,
const T1 &V1,
const Ts &...Vs) {
180 CheckFailed(Message);
181 WriteValues({V1, Vs...});
197 #define Assert(C, ...) \
198 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
206 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
207 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
208 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
209 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
211 dbgs() << MessagesStr.str();
220 "Unusual: Unnamed function with non-local linkage", &
F);
225 void Lint::visitCallSite(
CallSite CS) {
232 if (
Function *F = dyn_cast<Function>(findValue(Callee,
235 "Undefined behavior: Caller and callee calling convention differ",
239 unsigned NumActualArgs = CS.
arg_size();
241 Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
242 : FT->getNumParams() == NumActualArgs,
243 "Undefined behavior: Call argument count mismatches callee "
248 "Undefined behavior: Call return type mismatches "
249 "callee return type",
256 for (; AI != AE; ++AI) {
261 "Undefined behavior: Call argument type mismatches "
262 "callee parameter type",
270 if (AI != BI && (*BI)->getType()->isPointerTy()) {
273 "Unusual: noalias argument aliases another argument", &I);
279 cast<PointerType>(Formal->
getType())->getElementType();
282 MemRef::Read | MemRef::Write);
291 Value *Obj = findValue(*AI,
true);
292 Assert(!isa<AllocaInst>(Obj),
293 "Undefined behavior: Call with \"tail\" keyword references "
300 switch (II->getIntrinsicID()) {
305 case Intrinsic::memcpy: {
318 dyn_cast<ConstantInt>(findValue(MCI->
getLength(),
320 if (Len->getValue().isIntN(32))
321 Size = Len->getValue().getZExtValue();
324 "Undefined behavior: memcpy source and destination overlap", &I);
327 case Intrinsic::memmove: {
336 case Intrinsic::memset: {
344 case Intrinsic::vastart:
346 "Undefined behavior: va_start called in a non-varargs function",
350 nullptr, MemRef::Read | MemRef::Write);
352 case Intrinsic::vacopy:
354 nullptr, MemRef::Write);
356 nullptr, MemRef::Read);
358 case Intrinsic::vaend:
360 nullptr, MemRef::Read | MemRef::Write);
363 case Intrinsic::stackrestore:
368 nullptr, MemRef::Read | MemRef::Write);
373 void Lint::visitCallInst(
CallInst &I) {
374 return visitCallSite(&I);
378 return visitCallSite(&I);
384 "Unusual: Return statement in function with noreturn attribute", &
I);
387 Value *Obj = findValue(V,
true);
388 Assert(!isa<AllocaInst>(Obj),
"Unusual: Returning alloca value", &I);
403 Assert(!isa<ConstantPointerNull>(UnderlyingObject),
404 "Undefined behavior: Null pointer dereference", &I);
405 Assert(!isa<UndefValue>(UnderlyingObject),
406 "Undefined behavior: Undef pointer dereference", &I);
407 Assert(!isa<ConstantInt>(UnderlyingObject) ||
408 !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
409 "Unusual: All-ones pointer dereference", &I);
410 Assert(!isa<ConstantInt>(UnderlyingObject) ||
411 !cast<ConstantInt>(UnderlyingObject)->isOne(),
412 "Unusual: Address one pointer dereference", &I);
414 if (Flags & MemRef::Write) {
415 if (
const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
416 Assert(!GV->isConstant(),
"Undefined behavior: Write to read-only memory",
418 Assert(!isa<Function>(UnderlyingObject) &&
419 !isa<BlockAddress>(UnderlyingObject),
420 "Undefined behavior: Write to text section", &I);
422 if (Flags & MemRef::Read) {
423 Assert(!isa<Function>(UnderlyingObject),
"Unusual: Load from function body",
425 Assert(!isa<BlockAddress>(UnderlyingObject),
426 "Undefined behavior: Load from block address", &I);
428 if (Flags & MemRef::Callee) {
429 Assert(!isa<BlockAddress>(UnderlyingObject),
430 "Undefined behavior: Call to block address", &I);
432 if (Flags & MemRef::Branchee) {
433 Assert(!isa<Constant>(UnderlyingObject) ||
434 isa<BlockAddress>(UnderlyingObject),
435 "Undefined behavior: Branch to non-blockaddress", &I);
447 unsigned BaseAlign = 0;
450 Type *ATy = AI->getAllocatedType();
451 if (!AI->isArrayAllocation() && ATy->
isSized())
453 BaseAlign = AI->getAlignment();
454 if (BaseAlign == 0 && ATy->
isSized())
459 if (GV->hasDefinitiveInitializer()) {
460 Type *GTy = GV->getValueType();
463 BaseAlign = GV->getAlignment();
464 if (BaseAlign == 0 && GTy->
isSized())
473 (Offset >= 0 && Offset + Size <= BaseSize),
474 "Undefined behavior: Buffer overflow", &I);
478 if (Align == 0 && Ty && Ty->
isSized())
481 "Undefined behavior: Memory reference address is misaligned", &I);
485 void Lint::visitLoadInst(
LoadInst &I) {
491 void Lint::visitStoreInst(
StoreInst &I) {
500 "Undefined result: xor(undef, undef)", &I);
505 "Undefined result: sub(undef, undef)", &I);
512 "Undefined result: Shift count out of range", &I);
517 dyn_cast<ConstantInt>(findValue(I.
getOperand(1),
false)))
519 "Undefined result: Shift count out of range", &I);
524 dyn_cast<ConstantInt>(findValue(I.
getOperand(1),
false)))
526 "Undefined result: Shift count out of range", &I);
532 if (isa<UndefValue>(V))
553 if (isa<UndefValue>(Elem))
566 "Undefined behavior: Division by zero", &I);
571 "Undefined behavior: Division by zero", &I);
576 "Undefined behavior: Division by zero", &I);
581 "Undefined behavior: Division by zero", &I);
588 "Pessimization: Static alloca outside of entry block", &
I);
593 void Lint::visitVAArgInst(
VAArgInst &I) {
595 nullptr, MemRef::Read | MemRef::Write);
600 nullptr, MemRef::Branchee);
603 "Undefined behavior: indirectbr with no destinations", &
I);
610 "Undefined result: extractelement index out of range", &I);
617 "Undefined result: insertelement index out of range", &I);
624 "Unusual: unreachable immediately preceded by instruction without "
636 Value *Lint::findValue(
Value *V,
bool OffsetOk)
const {
638 return findValueImpl(V, OffsetOk, Visited);
642 Value *Lint::findValueImpl(
Value *V,
bool OffsetOk,
645 if (!Visited.
insert(V).second)
654 if (
LoadInst *
L = dyn_cast<LoadInst>(V)) {
659 if (!VisitedBlocks.
insert(BB).second)
663 return findValueImpl(U, OffsetOk, Visited);
664 if (BBI != BB->
begin())
break;
669 }
else if (
PHINode *PN = dyn_cast<PHINode>(V)) {
670 if (
Value *W = PN->hasConstantValue())
672 return findValueImpl(W, OffsetOk, Visited);
673 }
else if (
CastInst *CI = dyn_cast<CastInst>(V)) {
674 if (CI->isNoopCast(*
DL))
675 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
680 return findValueImpl(W, OffsetOk, Visited);
681 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
685 CE->getOperand(0)->getType(),
CE->getType(),
687 return findValueImpl(
CE->getOperand(0), OffsetOk, Visited);
688 }
else if (
CE->getOpcode() == Instruction::ExtractValue) {
692 return findValueImpl(W, OffsetOk, Visited);
697 if (
Instruction *Inst = dyn_cast<Instruction>(V)) {
699 return findValueImpl(W, OffsetOk, Visited);
700 }
else if (
auto *
C = dyn_cast<Constant>(V)) {
703 return findValueImpl(W, OffsetOk, Visited);
724 Lint *V =
new Lint();
733 Lint *V =
new Lint();
735 PM.
run(const_cast<Module&>(M));
unsigned getAlignment() const
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
The two locations precisely alias each other.
Return a value (possibly void), from a function.
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
A parsed version of the target data layout string in and methods for querying it. ...
void lintModule(const Module &M)
Check a module.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Base class for instruction visitors.
A Module instance is used to store all the information related to an LLVM module. ...
The two locations alias, but only due to a partial overlap.
This class represents a function call, abstracting a target machine's calling convention.
cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
void lintFunction(const Function &F)
lintFunction - Check a function for errors, printing messages on stderr.
Statically lint checks LLVM false
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of .assume calls within a function.
This class wraps the llvm.memset intrinsic.
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
An instruction for reading from memory.
INITIALIZE_PASS_BEGIN(Lint,"lint","Statically lint-checks LLVM IR", false, true) INITIALIZE_PASS_END(Lint
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
unsigned arg_size() const
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void add(Pass *P) override
Add a pass to the queue of passes to run.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This is the base class for all instructions that perform data casts.
This class wraps the llvm.memmove intrinsic.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, AliasAnalysis *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
ValTy * getCalledValue() const
Return the pointer to function that is being called.
bool isCall() const
Return true if a CallInst is enclosed.
static bool isNoopCast(Instruction::CastOps Opcode, Type *SrcTy, Type *DstTy, Type *IntPtrTy)
A no-op cast is one that can be effected without changing any bits.
Windows NT (Windows on ARM)
This file implements a class to represent arbitrary precision integral constant values and operations...
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
A constant value that is initialized with an expression using other constant values.
Class to represent function types.
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
VectorType * getType() const
Overload to return most specific vector type.
bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
An instruction for storing to memory.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
PassManager manages ModulePassManagers.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
This instruction inserts a single (scalar) element into a VectorType value.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
FunctionType * getFunctionType() const
Returns the FunctionType for me.
This function has undefined behavior.
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Indirect Branch Instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool isZeroValue() const
Return true if the value is negative zero or null value.
bool doesNotReturn() const
Determine if the function cannot return.
AliasResult
The possible results of an alias query.
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
uint64_t getNumElements() const
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
Value * getPointerOperand()
self_iterator getIterator()
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
FunctionPassManager manages FunctionPasses and BasicBlockPassManagers.
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, Instruction *InsertBefore=nullptr)
Given an aggregrate and an sequence of indices, see if the scalar value indexed is already around as ...
FunctionPass * createLintPass()
Create a lint pass.
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
InstrTy * getInstruction() const
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions that feed it, giving the original input.
ValTy * getArgument(unsigned ArgNo) const
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
Value * getLength() const
void initializeLintPass(PassRegistry &)
This class wraps the llvm.memcpy intrinsic.
const BasicBlock & getEntryBlock() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Class to represent vector types.
void setPreservesAll()
Set by analyses that do not transform their input at all.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static std::vector< std::string > Flags
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
unsigned getAlignment() const
Return the alignment of the access that is being performed.
This file provides utility analysis objects describing memory locations.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isZero() const
Returns true if value is all zero.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
bool hasLocalLinkage() const
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
const Value * getArraySize() const
Get the number of elements allocated.
This class implements an extremely fast bulk output stream that can only output to a stream...
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Value * getPointerOperand()
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
Statically lint checks LLVM IR
const BasicBlock * getParent() const
A wrapper class for inspecting calls to intrinsic functions.
an instruction to allocate memory on the stack