83 cl::desc(
"In the Lint pass, abort on errors."));
87static const unsigned Read = 1;
88static const unsigned Write = 2;
89static const unsigned Callee = 4;
90static const unsigned Branchee = 8;
121 Value *findValue(
Value *V,
bool OffsetOk)
const;
133 std::string Messages;
138 :
Mod(
Mod),
DL(
DL), AA(AA), AC(AC), DT(DT), TLI(TLI),
139 MessagesStr(Messages) {}
142 for (
const Value *V : Vs) {
145 if (isa<Instruction>(V)) {
146 MessagesStr << *
V <<
'\n';
148 V->printAsOperand(MessagesStr,
true,
Mod);
158 void CheckFailed(
const Twine &Message) { MessagesStr << Message <<
'\n'; }
164 template <
typename T1,
typename... Ts>
165 void CheckFailed(
const Twine &Message,
const T1 &V1,
const Ts &... Vs) {
166 CheckFailed(Message);
167 WriteValues({V1, Vs...});
173#define Check(C, ...) \
176 CheckFailed(__VA_ARGS__); \
184 Check(
F.hasName() ||
F.hasLocalLinkage(),
185 "Unusual: Unnamed function with non-local linkage", &
F);
194 nullptr, MemRef::Callee);
196 if (
Function *
F = dyn_cast<Function>(findValue(Callee,
198 Check(
I.getCallingConv() ==
F->getCallingConv(),
199 "Undefined behavior: Caller and callee calling convention differ",
203 unsigned NumActualArgs =
I.arg_size();
205 Check(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
206 : FT->getNumParams() == NumActualArgs,
207 "Undefined behavior: Call argument count mismatches callee "
211 Check(FT->getReturnType() ==
I.getType(),
212 "Undefined behavior: Call return type mismatches "
213 "callee return type",
219 auto AI =
I.arg_begin(), AE =
I.arg_end();
220 for (; AI != AE; ++AI) {
225 "Undefined behavior: Call argument type mismatches "
226 "callee parameter type",
235 for (
auto *BI =
I.arg_begin(); BI != AE; ++BI, ++ArgNo) {
245 if (
I.doesNotAccessMemory(ArgNo))
247 if (AI != BI && (*BI)->getType()->isPointerTy()) {
251 "Unusual: noalias argument aliases another argument", &
I);
261 visitMemoryReference(
I, Loc,
DL->getABITypeAlign(Ty), Ty,
262 MemRef::Read | MemRef::Write);
268 if (
const auto *CI = dyn_cast<CallInst>(&
I)) {
269 if (CI->isTailCall()) {
272 for (
Value *Arg :
I.args()) {
277 Value *Obj = findValue(Arg,
true);
278 Check(!isa<AllocaInst>(Obj),
279 "Undefined behavior: Call with \"tail\" keyword references "
287 switch (II->getIntrinsicID()) {
293 case Intrinsic::memcpy: {
305 dyn_cast<ConstantInt>(findValue(MCI->
getLength(),
307 if (
Len->getValue().isIntN(32))
311 "Undefined behavior: memcpy source and destination overlap", &
I);
314 case Intrinsic::memcpy_inline: {
328 "Undefined behavior: memcpy source and destination overlap", &
I);
331 case Intrinsic::memmove: {
339 case Intrinsic::memset: {
345 case Intrinsic::memset_inline: {
352 case Intrinsic::vastart:
353 Check(
I.getParent()->getParent()->isVarArg(),
354 "Undefined behavior: va_start called in a non-varargs function",
358 std::nullopt,
nullptr, MemRef::Read | MemRef::Write);
360 case Intrinsic::vacopy:
362 std::nullopt,
nullptr, MemRef::Write);
364 std::nullopt,
nullptr, MemRef::Read);
366 case Intrinsic::vaend:
368 std::nullopt,
nullptr, MemRef::Read | MemRef::Write);
371 case Intrinsic::stackrestore:
376 std::nullopt,
nullptr, MemRef::Read | MemRef::Write);
378 case Intrinsic::get_active_lane_mask:
379 if (
auto *TripCount = dyn_cast<ConstantInt>(
I.getArgOperand(1)))
380 Check(!TripCount->isZero(),
381 "get_active_lane_mask: operand #2 "
382 "must be greater than 0",
390 Check(!
F->doesNotReturn(),
391 "Unusual: Return statement in function with noreturn attribute", &
I);
393 if (
Value *V =
I.getReturnValue()) {
394 Value *Obj = findValue(V,
true);
395 Check(!isa<AllocaInst>(Obj),
"Unusual: Returning alloca value", &
I);
411 "Undefined behavior: Null pointer dereference", &
I);
413 "Undefined behavior: Undef pointer dereference", &
I);
416 "Unusual: All-ones pointer dereference", &
I);
419 "Unusual: Address one pointer dereference", &
I);
421 if (Flags & MemRef::Write) {
423 Check(!GV->isConstant(),
"Undefined behavior: Write to read-only memory",
427 "Undefined behavior: Write to text section", &
I);
429 if (Flags & MemRef::Read) {
433 "Undefined behavior: Load from block address", &
I);
435 if (Flags & MemRef::Callee) {
437 "Undefined behavior: Call to block address", &
I);
439 if (Flags & MemRef::Branchee) {
442 "Undefined behavior: Branch to non-blockaddress", &
I);
457 Type *ATy = AI->getAllocatedType();
458 if (!AI->isArrayAllocation() && ATy->
isSized())
459 BaseSize =
DL->getTypeAllocSize(ATy);
460 BaseAlign = AI->getAlign();
464 if (GV->hasDefinitiveInitializer()) {
465 Type *GTy = GV->getValueType();
467 BaseSize =
DL->getTypeAllocSize(GTy);
468 BaseAlign = GV->getAlign();
469 if (!BaseAlign && GTy->
isSized())
470 BaseAlign =
DL->getABITypeAlign(GTy);
478 "Undefined behavior: Buffer overflow", &
I);
483 Align =
DL->getABITypeAlign(Ty);
484 if (BaseAlign &&
Align)
486 "Undefined behavior: Memory reference address is misaligned", &
I);
497 I.getOperand(0)->getType(), MemRef::Write);
501 Check(!isa<UndefValue>(
I.getOperand(0)) || !isa<UndefValue>(
I.getOperand(1)),
502 "Undefined result: xor(undef, undef)", &
I);
506 Check(!isa<UndefValue>(
I.getOperand(0)) || !isa<UndefValue>(
I.getOperand(1)),
507 "Undefined result: sub(undef, undef)", &
I);
511 if (
ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
I.getOperand(1),
513 Check(CI->getValue().ult(cast<IntegerType>(
I.getType())->getBitWidth()),
514 "Undefined result: Shift count out of range", &
I);
519 dyn_cast<ConstantInt>(findValue(
I.getOperand(1),
false)))
520 Check(CI->getValue().ult(cast<IntegerType>(
I.getType())->getBitWidth()),
521 "Undefined result: Shift count out of range", &
I);
526 dyn_cast<ConstantInt>(findValue(
I.getOperand(1),
false)))
527 Check(CI->getValue().ult(cast<IntegerType>(
I.getType())->getBitWidth()),
528 "Undefined result: Shift count out of range", &
I);
534 if (isa<UndefValue>(V))
537 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
549 if (
C->isZeroValue())
554 for (
unsigned I = 0,
N = cast<FixedVectorType>(VecTy)->getNumElements();
557 if (isa<UndefValue>(Elem))
569 Check(!
isZero(
I.getOperand(1),
I.getModule()->getDataLayout(), DT, AC),
570 "Undefined behavior: Division by zero", &
I);
574 Check(!
isZero(
I.getOperand(1),
I.getModule()->getDataLayout(), DT, AC),
575 "Undefined behavior: Division by zero", &
I);
579 Check(!
isZero(
I.getOperand(1),
I.getModule()->getDataLayout(), DT, AC),
580 "Undefined behavior: Division by zero", &
I);
584 Check(!
isZero(
I.getOperand(1),
I.getModule()->getDataLayout(), DT, AC),
585 "Undefined behavior: Division by zero", &
I);
589 if (isa<ConstantInt>(
I.getArraySize()))
591 Check(&
I.getParent()->getParent()->getEntryBlock() ==
I.getParent(),
592 "Pessimization: Static alloca outside of entry block", &
I);
599 MemRef::Read | MemRef::Write);
604 std::nullopt,
nullptr, MemRef::Branchee);
606 Check(
I.getNumDestinations() != 0,
607 "Undefined behavior: indirectbr with no destinations", &
I);
611 if (
ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
I.getIndexOperand(),
615 cast<FixedVectorType>(
I.getVectorOperandType())->getNumElements()),
616 "Undefined result: extractelement index out of range", &
I);
620 if (
ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
I.getOperand(2),
622 Check(CI->getValue().ult(
623 cast<FixedVectorType>(
I.getType())->getNumElements()),
624 "Undefined result: insertelement index out of range", &
I);
629 Check(&
I == &
I.getParent()->front() ||
630 std::prev(
I.getIterator())->mayHaveSideEffects(),
631 "Unusual: unreachable immediately preceded by instruction without "
643Value *Lint::findValue(
Value *V,
bool OffsetOk)
const {
645 return findValueImpl(V, OffsetOk, Visited);
649Value *Lint::findValueImpl(
Value *V,
bool OffsetOk,
652 if (!Visited.
insert(V).second)
661 if (
LoadInst *L = dyn_cast<LoadInst>(V)) {
667 if (!VisitedBlocks.
insert(BB).second)
671 return findValueImpl(U, OffsetOk, Visited);
672 if (BBI != BB->
begin())
679 }
else if (
PHINode *PN = dyn_cast<PHINode>(V)) {
680 if (
Value *W = PN->hasConstantValue())
681 return findValueImpl(W, OffsetOk, Visited);
682 }
else if (
CastInst *CI = dyn_cast<CastInst>(V)) {
683 if (CI->isNoopCast(*
DL))
684 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
689 return findValueImpl(W, OffsetOk, Visited);
690 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
694 CE->getOperand(0)->getType(),
CE->getType(),
696 return findValueImpl(
CE->getOperand(0), OffsetOk, Visited);
701 if (
Instruction *Inst = dyn_cast<Instruction>(V)) {
703 return findValueImpl(W, OffsetOk, Visited);
704 }
else if (
auto *
C = dyn_cast<Constant>(V)) {
707 return findValueImpl(W, OffsetOk, Visited);
714 auto *
Mod =
F.getParent();
715 auto *
DL = &
F.getParent()->getDataLayout();
720 Lint L(
Mod,
DL, AA, AC, DT, TLI);
722 dbgs() << L.MessagesStr.str();
738 assert(!
F.isDeclaration() &&
"Cannot lint external functions");
758 if (!
F.isDeclaration())
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements a class to represent arbitrary precision integral constant values and operations...
This is the interface for LLVM's primary stateless and local alias analysis.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
static const char LintAbortOnErrorArgName[]
static cl::opt< bool > LintAbortOnError(LintAbortOnErrorArgName, cl::init(false), cl::desc("In the Lint pass, abort on errors."))
This file provides utility analysis objects describing memory locations.
Module.h This file contains the declarations for the Module class.
FunctionAnalysisManager FAM
This header defines various interfaces for pass management in LLVM.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This is the interface for a metadata-based scoped no-alias analysis.
This file defines the SmallPtrSet class.
This is the interface for a metadata-based TBAA.
A manager for alias analyses.
void registerFunctionAnalysis()
Register a specific AA result.
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
The possible results of an alias query.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
an instruction to allocate memory on the stack
A container for analyses that lazily runs them and caches their results.
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
Type * getParamStructRetType() const
If this is an sret argument, return its type.
bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
Analysis pass providing a never-invalidated alias analysis result.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This is the base class for all instructions that perform data casts.
static bool isNoopCast(Instruction::CastOps Opcode, Type *SrcTy, Type *DstTy, const DataLayout &DL)
A no-op cast is one that can be effected without changing any bits.
A constant value that is initialized with an expression using other constant values.
This is the shared class of boolean and integer constants.
const APInt & getValue() const
Return the constant as an APInt value reference.
This is an important base class in LLVM.
A parsed version of the target data layout string in and methods for querying it.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Indirect Branch Instruction.
This instruction inserts a single (scalar) element into a VectorType value.
Base class for instruction visitors.
RetTy visitIndirectBrInst(IndirectBrInst &I)
RetTy visitExtractElementInst(ExtractElementInst &I)
RetTy visitCallBase(CallBase &I)
void visitFunction(Function &F)
RetTy visitUnreachableInst(UnreachableInst &I)
RetTy visitReturnInst(ReturnInst &I)
RetTy visitStoreInst(StoreInst &I)
RetTy visitInsertElementInst(InsertElementInst &I)
RetTy visitAllocaInst(AllocaInst &I)
RetTy visitLoadInst(LoadInst &I)
RetTy visitVAArgInst(VAArgInst &I)
A wrapper class for inspecting calls to intrinsic functions.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
An instruction for reading from memory.
static LocationSize precise(uint64_t Value)
TypeSize getValue() const
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
This class wraps the llvm.memcpy.inline intrinsic.
ConstantInt * getLength() const
This class wraps the llvm.memcpy intrinsic.
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
MaybeAlign getDestAlign() const
This class wraps the llvm.memmove intrinsic.
This class wraps the llvm.memset.inline intrinsic.
This class wraps the llvm.memset and llvm.memset.inline intrinsics.
MaybeAlign getSourceAlign() const
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it,...
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
const Value * Ptr
The address of the start of the location.
static MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
static MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
A Module instance is used to store all the information related to an LLVM module.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Return a value (possibly void), from a function.
Analysis pass providing a never-invalidated alias analysis result.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
An instruction for storing to memory.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Analysis pass providing a never-invalidated alias analysis result.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isPointerTy() const
True if this is an instance of PointerType.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
A raw_ostream that writes to an std::string.
@ C
The default llvm calling convention, compatible with C.
@ CE
Windows NT (Windows on ARM)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value,...
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *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 ...
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
void lintModule(const Module &M)
Lint a module.
cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
@ Mod
The access may modify the value stored in memory.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
void lintFunction(const Function &F)
lintFunction - Check a function for errors, printing messages on stderr.
This struct is a compact representation of a valid (non-zero power of two) alignment.
bool isZero() const
Returns true if value is all zero.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.