83static const unsigned Read = 1;
84static const unsigned Write = 2;
85static const unsigned Callee = 4;
86static const unsigned Branchee = 8;
119 Value *findValue(
Value *V,
bool OffsetOk)
const;
132 std::string Messages;
138 TLI(TLI), MessagesStr(Messages) {}
141 for (
const Value *V : Vs) {
145 MessagesStr << *
V <<
'\n';
147 V->printAsOperand(MessagesStr,
true, Mod);
157 void CheckFailed(
const Twine &Message) { MessagesStr << Message <<
'\n'; }
163 template <
typename T1,
typename... Ts>
164 void CheckFailed(
const Twine &Message,
const T1 &
V1,
const Ts &... Vs) {
165 CheckFailed(Message);
166 WriteValues({
V1, Vs...});
172#define Check(C, ...) \
175 CheckFailed(__VA_ARGS__); \
183 Check(
F.hasName() ||
F.hasLocalLinkage(),
184 "Unusual: Unnamed function with non-local linkage", &
F);
189void Lint::visitCallBase(CallBase &
I) {
193 nullptr, MemRef::Callee);
197 Check(
I.getCallingConv() ==
F->getCallingConv(),
198 "Undefined behavior: Caller and callee calling convention differ",
201 FunctionType *FT =
F->getFunctionType();
202 unsigned NumActualArgs =
I.arg_size();
204 Check(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
205 : FT->getNumParams() == NumActualArgs,
206 "Undefined behavior: Call argument count mismatches callee "
210 Check(FT->getReturnType() ==
I.getType(),
211 "Undefined behavior: Call return type mismatches "
212 "callee return type",
218 auto AI =
I.arg_begin(), AE =
I.arg_end();
219 for (; AI != AE; ++AI) {
224 "Undefined behavior: Call argument type mismatches "
225 "callee parameter type",
232 AttributeList PAL =
I.getAttributes();
234 for (
auto *BI =
I.arg_begin(); BI != AE; ++BI, ++ArgNo) {
237 if (PAL.hasParamAttr(ArgNo, Attribute::ByVal))
244 if (
I.doesNotAccessMemory(ArgNo))
246 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);
266 unsigned ArgNo = AI->getOperandNo();
268 for (Attribute::AttrKind Attr :
271 if (!Attribute::isABIAttr(Attr))
277 Twine(
"Undefined behavior: ABI attribute ") +
278 Attribute::getNameFromAttrKind(Attr) +
279 " not present on both function and call-site",
283 Twine(
"Undefined behavior: ABI attribute ") +
284 Attribute::getNameFromAttrKind(Attr) +
285 " does not have same argument for function and call-site",
294 if (CI->isTailCall()) {
295 const AttributeList &PAL = CI->getAttributes();
297 for (
Value *Arg :
I.args()) {
300 if (PAL.hasParamAttr(ArgNo++, Attribute::ByVal))
304 "Undefined behavior: Call with \"tail\" keyword references "
312 switch (
II->getIntrinsicID()) {
318 case Intrinsic::memcpy:
319 case Intrinsic::memcpy_inline: {
330 if (
const ConstantInt *Len =
333 if (
Len->getValue().isIntN(32))
337 "Undefined behavior: memcpy source and destination overlap", &
I);
340 case Intrinsic::memmove: {
348 case Intrinsic::memset:
349 case Intrinsic::memset_inline: {
355 case Intrinsic::vastart:
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);
381void Lint::visitReturnInst(ReturnInst &
I) {
383 Check(!
F->doesNotReturn(),
384 "Unusual: Return statement in function with noreturn attribute", &
I);
386 if (
Value *V =
I.getReturnValue()) {
394void Lint::visitMemoryReference(Instruction &
I,
const MemoryLocation &Loc,
395 MaybeAlign Align,
Type *Ty,
unsigned Flags) {
402 Value *UnderlyingObject = findValue(Ptr,
true);
404 "Undefined behavior: Null pointer dereference", &
I);
406 "Undefined behavior: Undef pointer dereference", &
I);
409 "Unusual: All-ones pointer dereference", &
I);
412 "Unusual: Address one pointer dereference", &
I);
414 if (Flags & MemRef::Write) {
418 "Undefined behavior: Write to memory in const addrspace", &
I);
421 Check(!GV->isConstant(),
"Undefined behavior: Write to read-only memory",
425 "Undefined behavior: Write to text section", &
I);
427 if (Flags & MemRef::Read) {
431 "Undefined behavior: Load from block address", &
I);
433 if (Flags & MemRef::Callee) {
435 "Undefined behavior: Call to block address", &
I);
437 if (Flags & MemRef::Branchee) {
440 "Undefined behavior: Branch to non-blockaddress", &
I);
452 MaybeAlign BaseAlign;
455 std::optional<TypeSize> ATy = AI->getAllocationSize(*
DL);
456 if (ATy && !ATy->isScalable())
457 BaseSize = ATy->getFixedValue();
458 BaseAlign = AI->getAlign();
462 if (GV->hasDefinitiveInitializer()) {
463 Type *GTy = GV->getValueType();
465 BaseSize =
DL->getTypeAllocSize(GTy);
466 BaseAlign = GV->getAlign();
467 if (!BaseAlign && GTy->
isSized())
468 BaseAlign =
DL->getABITypeAlign(GTy);
477 "Undefined behavior: Buffer overflow", &
I);
481 if (!Align && Ty && Ty->
isSized())
482 Align =
DL->getABITypeAlign(Ty);
483 if (BaseAlign && Align)
485 "Undefined behavior: Memory reference address is misaligned", &
I);
489void Lint::visitLoadInst(LoadInst &
I) {
494void Lint::visitStoreInst(StoreInst &
I) {
496 I.getOperand(0)->getType(), MemRef::Write);
499void Lint::visitAtomicCmpXchgInst(AtomicCmpXchgInst &
I) {
501 I.getOperand(0)->getType(), MemRef::Write);
504void Lint::visitAtomicRMWInst(AtomicRMWInst &
I) {
506 I.getOperand(0)->getType(), MemRef::Write);
509void Lint::visitXor(BinaryOperator &
I) {
511 "Undefined result: xor(undef, undef)", &
I);
514void Lint::visitSub(BinaryOperator &
I) {
516 "Undefined result: sub(undef, undef)", &
I);
519void Lint::visitLShr(BinaryOperator &
I) {
523 "Undefined result: Shift count out of range", &
I);
526void Lint::visitAShr(BinaryOperator &
I) {
527 if (ConstantInt *CI =
530 "Undefined result: Shift count out of range", &
I);
533void Lint::visitShl(BinaryOperator &
I) {
534 if (ConstantInt *CI =
537 "Undefined result: Shift count out of range", &
I);
549 return Known.isZero();
557 if (
C->isNullValue())
576void Lint::visitSDiv(BinaryOperator &
I) {
578 "Undefined behavior: Division by zero", &
I);
581void Lint::visitUDiv(BinaryOperator &
I) {
583 "Undefined behavior: Division by zero", &
I);
586void Lint::visitSRem(BinaryOperator &
I) {
588 "Undefined behavior: Division by zero", &
I);
591void Lint::visitURem(BinaryOperator &
I) {
593 "Undefined behavior: Division by zero", &
I);
596void Lint::visitAllocaInst(AllocaInst &
I) {
599 Check(&
I.getParent()->getParent()->getEntryBlock() ==
I.getParent(),
600 "Pessimization: Static alloca outside of entry block", &
I);
605void Lint::visitVAArgInst(VAArgInst &
I) {
607 MemRef::Read | MemRef::Write);
610void Lint::visitIndirectBrInst(IndirectBrInst &
I) {
612 std::nullopt,
nullptr, MemRef::Branchee);
614 Check(
I.getNumDestinations() != 0,
615 "Undefined behavior: indirectbr with no destinations", &
I);
618void Lint::visitExtractElementInst(ExtractElementInst &
I) {
621 ElementCount
EC =
I.getVectorOperandType()->getElementCount();
622 Check(
EC.isScalable() || CI->getValue().ult(
EC.getFixedValue()),
623 "Undefined result: extractelement index out of range", &
I);
627void Lint::visitInsertElementInst(InsertElementInst &
I) {
630 ElementCount
EC =
I.getType()->getElementCount();
631 Check(
EC.isScalable() || CI->getValue().ult(
EC.getFixedValue()),
632 "Undefined result: insertelement index out of range", &
I);
636void Lint::visitUnreachableInst(UnreachableInst &
I) {
638 Check(&
I == &
I.getParent()->front() ||
639 std::prev(
I.getIterator())->mayHaveSideEffects(),
640 "Unusual: unreachable immediately preceded by instruction without "
652Value *Lint::findValue(
Value *V,
bool OffsetOk)
const {
653 SmallPtrSet<Value *, 4> Visited;
654 return findValueImpl(V, OffsetOk, Visited);
658Value *Lint::findValueImpl(
Value *V,
bool OffsetOk,
659 SmallPtrSetImpl<Value *> &Visited)
const {
661 if (!Visited.
insert(V).second)
674 BatchAAResults BatchAA(*AA);
680 return findValueImpl(U, OffsetOk, Visited);
681 if (BBI != BB->
begin())
689 if (
Value *W = PN->hasConstantValue())
690 return findValueImpl(W, OffsetOk, Visited);
692 if (CI->isNoopCast(*
DL))
693 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
698 return findValueImpl(W, OffsetOk, Visited);
703 CE->getOperand(0)->getType(),
CE->getType(),
705 return findValueImpl(
CE->getOperand(0), OffsetOk, Visited);
712 return findValueImpl(W, OffsetOk, Visited);
716 return findValueImpl(W, OffsetOk, Visited);
723 auto *
Mod =
F.getParent();
724 auto *
DL = &
F.getDataLayout();
729 Lint L(
Mod,
DL,
AA, AC, DT, TLI);
731 dbgs() << L.MessagesStr.str();
732 if (AbortOnError && !L.MessagesStr.str().empty())
734 "linter found errors, aborting. (enabled by abort-on-error)",
false);
740 PassInfoMixin<LintPass>::printPipeline(OS, MapClassName2PassName);
742 OS <<
"<abort-on-error>";
753 assert(!
F.isDeclaration() &&
"Cannot lint external functions");
759 FAM.registerPass([&] {
773 if (!
F.isDeclaration())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU address space definition.
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
This file provides utility analysis objects describing memory locations.
uint64_t IntrinsicInst * II
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
FunctionAnalysisManager FAM
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.
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
@ 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
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_ABI bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
LLVM_ABI bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
LLVM_ABI Type * getParamStructRetType() const
If this is an sret argument, return its type.
LLVM_ABI bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
bool isValid() const
Return true if the attribute is any kind of attribute.
Analysis pass providing a never-invalidated alias analysis result.
iterator begin()
Instruction iterator methods.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static LLVM_ABI 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.
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.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
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).
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
MaybeAlign getDestAlign() const
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 LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static LLVM_ABI 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 LLVM_ABI MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
static LLVM_ABI 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.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Triple - Helper class for working with autoconf configuration names.
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.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this 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.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
Abstract Attribute helper functions.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool isConstantAddressSpace(unsigned AS)
@ BasicBlock
Various leaf nodes.
@ CE
Windows NT (Windows on ARM)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
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.
constexpr force_iteration_on_noniterable_enum_t force_iteration_on_noniterable_enum
LLVM_ABI 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 ...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
constexpr auto enum_seq(EnumT Begin, EnumT End)
Iterate over an enum type from Begin up to - but not including - End.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI void lintModule(const Module &M, bool AbortOnError=false)
Lint a module.
LLVM_ABI cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
@ Mod
The access may modify the value stored in memory.
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI 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...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI void lintFunction(const Function &F, bool AbortOnError=false)
lintFunction - Check a function for errors, printing messages on stderr.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.