/src/llvm-project/llvm/lib/Analysis/Lint.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===// |
2 | | // |
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 |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This pass statically checks for common and easily-identified constructs |
10 | | // which produce undefined or likely unintended behavior in LLVM IR. |
11 | | // |
12 | | // It is not a guarantee of correctness, in two ways. First, it isn't |
13 | | // comprehensive. There are checks which could be done statically which are |
14 | | // not yet implemented. Some of these are indicated by TODO comments, but |
15 | | // those aren't comprehensive either. Second, many conditions cannot be |
16 | | // checked statically. This pass does no dynamic instrumentation, so it |
17 | | // can't check for all possible problems. |
18 | | // |
19 | | // Another limitation is that it assumes all code will be executed. A store |
20 | | // through a null pointer in a basic block which is never reached is harmless, |
21 | | // but this pass will warn about it anyway. This is the main reason why most |
22 | | // of these checks live here instead of in the Verifier pass. |
23 | | // |
24 | | // Optimization passes may make conditions that this pass checks for more or |
25 | | // less obvious. If an optimization pass appears to be introducing a warning, |
26 | | // it may be that the optimization pass is merely exposing an existing |
27 | | // condition in the code. |
28 | | // |
29 | | // This code may be run before instcombine. In many cases, instcombine checks |
30 | | // for the same kinds of things and turns instructions with undefined behavior |
31 | | // into unreachable (or equivalent). Because of this, this pass makes some |
32 | | // effort to look through bitcasts and so on. |
33 | | // |
34 | | //===----------------------------------------------------------------------===// |
35 | | |
36 | | #include "llvm/Analysis/Lint.h" |
37 | | #include "llvm/ADT/APInt.h" |
38 | | #include "llvm/ADT/ArrayRef.h" |
39 | | #include "llvm/ADT/SmallPtrSet.h" |
40 | | #include "llvm/ADT/Twine.h" |
41 | | #include "llvm/Analysis/AliasAnalysis.h" |
42 | | #include "llvm/Analysis/AssumptionCache.h" |
43 | | #include "llvm/Analysis/BasicAliasAnalysis.h" |
44 | | #include "llvm/Analysis/ConstantFolding.h" |
45 | | #include "llvm/Analysis/InstructionSimplify.h" |
46 | | #include "llvm/Analysis/Loads.h" |
47 | | #include "llvm/Analysis/MemoryLocation.h" |
48 | | #include "llvm/Analysis/ScopedNoAliasAA.h" |
49 | | #include "llvm/Analysis/TargetLibraryInfo.h" |
50 | | #include "llvm/Analysis/TypeBasedAliasAnalysis.h" |
51 | | #include "llvm/Analysis/ValueTracking.h" |
52 | | #include "llvm/IR/Argument.h" |
53 | | #include "llvm/IR/BasicBlock.h" |
54 | | #include "llvm/IR/Constant.h" |
55 | | #include "llvm/IR/Constants.h" |
56 | | #include "llvm/IR/DataLayout.h" |
57 | | #include "llvm/IR/DerivedTypes.h" |
58 | | #include "llvm/IR/Dominators.h" |
59 | | #include "llvm/IR/Function.h" |
60 | | #include "llvm/IR/GlobalVariable.h" |
61 | | #include "llvm/IR/InstVisitor.h" |
62 | | #include "llvm/IR/InstrTypes.h" |
63 | | #include "llvm/IR/Instruction.h" |
64 | | #include "llvm/IR/Instructions.h" |
65 | | #include "llvm/IR/IntrinsicInst.h" |
66 | | #include "llvm/IR/Module.h" |
67 | | #include "llvm/IR/PassManager.h" |
68 | | #include "llvm/IR/Type.h" |
69 | | #include "llvm/IR/Value.h" |
70 | | #include "llvm/Support/Casting.h" |
71 | | #include "llvm/Support/KnownBits.h" |
72 | | #include "llvm/Support/raw_ostream.h" |
73 | | #include <cassert> |
74 | | #include <cstdint> |
75 | | #include <iterator> |
76 | | #include <string> |
77 | | |
78 | | using namespace llvm; |
79 | | |
80 | | namespace { |
81 | | namespace MemRef { |
82 | | static const unsigned Read = 1; |
83 | | static const unsigned Write = 2; |
84 | | static const unsigned Callee = 4; |
85 | | static const unsigned Branchee = 8; |
86 | | } // end namespace MemRef |
87 | | |
88 | | class Lint : public InstVisitor<Lint> { |
89 | | friend class InstVisitor<Lint>; |
90 | | |
91 | | void visitFunction(Function &F); |
92 | | |
93 | | void visitCallBase(CallBase &CB); |
94 | | void visitMemoryReference(Instruction &I, const MemoryLocation &Loc, |
95 | | MaybeAlign Alignment, Type *Ty, unsigned Flags); |
96 | | |
97 | | void visitReturnInst(ReturnInst &I); |
98 | | void visitLoadInst(LoadInst &I); |
99 | | void visitStoreInst(StoreInst &I); |
100 | | void visitXor(BinaryOperator &I); |
101 | | void visitSub(BinaryOperator &I); |
102 | | void visitLShr(BinaryOperator &I); |
103 | | void visitAShr(BinaryOperator &I); |
104 | | void visitShl(BinaryOperator &I); |
105 | | void visitSDiv(BinaryOperator &I); |
106 | | void visitUDiv(BinaryOperator &I); |
107 | | void visitSRem(BinaryOperator &I); |
108 | | void visitURem(BinaryOperator &I); |
109 | | void visitAllocaInst(AllocaInst &I); |
110 | | void visitVAArgInst(VAArgInst &I); |
111 | | void visitIndirectBrInst(IndirectBrInst &I); |
112 | | void visitExtractElementInst(ExtractElementInst &I); |
113 | | void visitInsertElementInst(InsertElementInst &I); |
114 | | void visitUnreachableInst(UnreachableInst &I); |
115 | | |
116 | | Value *findValue(Value *V, bool OffsetOk) const; |
117 | | Value *findValueImpl(Value *V, bool OffsetOk, |
118 | | SmallPtrSetImpl<Value *> &Visited) const; |
119 | | |
120 | | public: |
121 | | Module *Mod; |
122 | | const DataLayout *DL; |
123 | | AliasAnalysis *AA; |
124 | | AssumptionCache *AC; |
125 | | DominatorTree *DT; |
126 | | TargetLibraryInfo *TLI; |
127 | | |
128 | | std::string Messages; |
129 | | raw_string_ostream MessagesStr; |
130 | | |
131 | | Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA, |
132 | | AssumptionCache *AC, DominatorTree *DT, TargetLibraryInfo *TLI) |
133 | | : Mod(Mod), DL(DL), AA(AA), AC(AC), DT(DT), TLI(TLI), |
134 | 0 | MessagesStr(Messages) {} |
135 | | |
136 | 0 | void WriteValues(ArrayRef<const Value *> Vs) { |
137 | 0 | for (const Value *V : Vs) { |
138 | 0 | if (!V) |
139 | 0 | continue; |
140 | 0 | if (isa<Instruction>(V)) { |
141 | 0 | MessagesStr << *V << '\n'; |
142 | 0 | } else { |
143 | 0 | V->printAsOperand(MessagesStr, true, Mod); |
144 | 0 | MessagesStr << '\n'; |
145 | 0 | } |
146 | 0 | } |
147 | 0 | } |
148 | | |
149 | | /// A check failed, so printout out the condition and the message. |
150 | | /// |
151 | | /// This provides a nice place to put a breakpoint if you want to see why |
152 | | /// something is not correct. |
153 | 0 | void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; } |
154 | | |
155 | | /// A check failed (with values to print). |
156 | | /// |
157 | | /// This calls the Message-only version so that the above is easier to set |
158 | | /// a breakpoint on. |
159 | | template <typename T1, typename... Ts> |
160 | 0 | void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) { |
161 | 0 | CheckFailed(Message); |
162 | 0 | WriteValues({V1, Vs...}); |
163 | 0 | } Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::Function*>(llvm::Twine const&, llvm::Function* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::ReturnInst*>(llvm::Twine const&, llvm::ReturnInst* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::Instruction*>(llvm::Twine const&, llvm::Instruction* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::IndirectBrInst*>(llvm::Twine const&, llvm::IndirectBrInst* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::CallBase*>(llvm::Twine const&, llvm::CallBase* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::UnreachableInst*>(llvm::Twine const&, llvm::UnreachableInst* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::BinaryOperator*>(llvm::Twine const&, llvm::BinaryOperator* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::AllocaInst*>(llvm::Twine const&, llvm::AllocaInst* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::ExtractElementInst*>(llvm::Twine const&, llvm::ExtractElementInst* const&) Unexecuted instantiation: Lint.cpp:void (anonymous namespace)::Lint::CheckFailed<llvm::InsertElementInst*>(llvm::Twine const&, llvm::InsertElementInst* const&) |
164 | | }; |
165 | | } // end anonymous namespace |
166 | | |
167 | | // Check - We know that cond should be true, if not print an error message. |
168 | | #define Check(C, ...) \ |
169 | 0 | do { \ |
170 | 0 | if (!(C)) { \ |
171 | 0 | CheckFailed(__VA_ARGS__); \ |
172 | 0 | return; \ |
173 | 0 | } \ |
174 | 0 | } while (false) |
175 | | |
176 | 0 | void Lint::visitFunction(Function &F) { |
177 | | // This isn't undefined behavior, it's just a little unusual, and it's a |
178 | | // fairly common mistake to neglect to name a function. |
179 | 0 | Check(F.hasName() || F.hasLocalLinkage(), |
180 | 0 | "Unusual: Unnamed function with non-local linkage", &F); |
181 | | |
182 | | // TODO: Check for irreducible control flow. |
183 | 0 | } |
184 | | |
185 | 0 | void Lint::visitCallBase(CallBase &I) { |
186 | 0 | Value *Callee = I.getCalledOperand(); |
187 | |
|
188 | 0 | visitMemoryReference(I, MemoryLocation::getAfter(Callee), std::nullopt, |
189 | 0 | nullptr, MemRef::Callee); |
190 | |
|
191 | 0 | if (Function *F = dyn_cast<Function>(findValue(Callee, |
192 | 0 | /*OffsetOk=*/false))) { |
193 | 0 | Check(I.getCallingConv() == F->getCallingConv(), |
194 | 0 | "Undefined behavior: Caller and callee calling convention differ", |
195 | 0 | &I); |
196 | | |
197 | 0 | FunctionType *FT = F->getFunctionType(); |
198 | 0 | unsigned NumActualArgs = I.arg_size(); |
199 | |
|
200 | 0 | Check(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs |
201 | 0 | : FT->getNumParams() == NumActualArgs, |
202 | 0 | "Undefined behavior: Call argument count mismatches callee " |
203 | 0 | "argument count", |
204 | 0 | &I); |
205 | | |
206 | 0 | Check(FT->getReturnType() == I.getType(), |
207 | 0 | "Undefined behavior: Call return type mismatches " |
208 | 0 | "callee return type", |
209 | 0 | &I); |
210 | | |
211 | | // Check argument types (in case the callee was casted) and attributes. |
212 | | // TODO: Verify that caller and callee attributes are compatible. |
213 | 0 | Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end(); |
214 | 0 | auto AI = I.arg_begin(), AE = I.arg_end(); |
215 | 0 | for (; AI != AE; ++AI) { |
216 | 0 | Value *Actual = *AI; |
217 | 0 | if (PI != PE) { |
218 | 0 | Argument *Formal = &*PI++; |
219 | 0 | Check(Formal->getType() == Actual->getType(), |
220 | 0 | "Undefined behavior: Call argument type mismatches " |
221 | 0 | "callee parameter type", |
222 | 0 | &I); |
223 | | |
224 | | // Check that noalias arguments don't alias other arguments. This is |
225 | | // not fully precise because we don't know the sizes of the dereferenced |
226 | | // memory regions. |
227 | 0 | if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy()) { |
228 | 0 | AttributeList PAL = I.getAttributes(); |
229 | 0 | unsigned ArgNo = 0; |
230 | 0 | for (auto *BI = I.arg_begin(); BI != AE; ++BI, ++ArgNo) { |
231 | | // Skip ByVal arguments since they will be memcpy'd to the callee's |
232 | | // stack so we're not really passing the pointer anyway. |
233 | 0 | if (PAL.hasParamAttr(ArgNo, Attribute::ByVal)) |
234 | 0 | continue; |
235 | | // If both arguments are readonly, they have no dependence. |
236 | 0 | if (Formal->onlyReadsMemory() && I.onlyReadsMemory(ArgNo)) |
237 | 0 | continue; |
238 | | // Skip readnone arguments since those are guaranteed not to be |
239 | | // dereferenced anyway. |
240 | 0 | if (I.doesNotAccessMemory(ArgNo)) |
241 | 0 | continue; |
242 | 0 | if (AI != BI && (*BI)->getType()->isPointerTy()) { |
243 | 0 | AliasResult Result = AA->alias(*AI, *BI); |
244 | 0 | Check(Result != AliasResult::MustAlias && |
245 | 0 | Result != AliasResult::PartialAlias, |
246 | 0 | "Unusual: noalias argument aliases another argument", &I); |
247 | 0 | } |
248 | 0 | } |
249 | 0 | } |
250 | | |
251 | | // Check that an sret argument points to valid memory. |
252 | 0 | if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) { |
253 | 0 | Type *Ty = Formal->getParamStructRetType(); |
254 | 0 | MemoryLocation Loc( |
255 | 0 | Actual, LocationSize::precise(DL->getTypeStoreSize(Ty))); |
256 | 0 | visitMemoryReference(I, Loc, DL->getABITypeAlign(Ty), Ty, |
257 | 0 | MemRef::Read | MemRef::Write); |
258 | 0 | } |
259 | 0 | } |
260 | 0 | } |
261 | 0 | } |
262 | | |
263 | 0 | if (const auto *CI = dyn_cast<CallInst>(&I)) { |
264 | 0 | if (CI->isTailCall()) { |
265 | 0 | const AttributeList &PAL = CI->getAttributes(); |
266 | 0 | unsigned ArgNo = 0; |
267 | 0 | for (Value *Arg : I.args()) { |
268 | | // Skip ByVal arguments since they will be memcpy'd to the callee's |
269 | | // stack anyway. |
270 | 0 | if (PAL.hasParamAttr(ArgNo++, Attribute::ByVal)) |
271 | 0 | continue; |
272 | 0 | Value *Obj = findValue(Arg, /*OffsetOk=*/true); |
273 | 0 | Check(!isa<AllocaInst>(Obj), |
274 | 0 | "Undefined behavior: Call with \"tail\" keyword references " |
275 | 0 | "alloca", |
276 | 0 | &I); |
277 | 0 | } |
278 | 0 | } |
279 | 0 | } |
280 | | |
281 | 0 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) |
282 | 0 | switch (II->getIntrinsicID()) { |
283 | 0 | default: |
284 | 0 | break; |
285 | | |
286 | | // TODO: Check more intrinsics |
287 | | |
288 | 0 | case Intrinsic::memcpy: { |
289 | 0 | MemCpyInst *MCI = cast<MemCpyInst>(&I); |
290 | 0 | visitMemoryReference(I, MemoryLocation::getForDest(MCI), |
291 | 0 | MCI->getDestAlign(), nullptr, MemRef::Write); |
292 | 0 | visitMemoryReference(I, MemoryLocation::getForSource(MCI), |
293 | 0 | MCI->getSourceAlign(), nullptr, MemRef::Read); |
294 | | |
295 | | // Check that the memcpy arguments don't overlap. The AliasAnalysis API |
296 | | // isn't expressive enough for what we really want to do. Known partial |
297 | | // overlap is not distinguished from the case where nothing is known. |
298 | 0 | auto Size = LocationSize::afterPointer(); |
299 | 0 | if (const ConstantInt *Len = |
300 | 0 | dyn_cast<ConstantInt>(findValue(MCI->getLength(), |
301 | 0 | /*OffsetOk=*/false))) |
302 | 0 | if (Len->getValue().isIntN(32)) |
303 | 0 | Size = LocationSize::precise(Len->getValue().getZExtValue()); |
304 | 0 | Check(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) != |
305 | 0 | AliasResult::MustAlias, |
306 | 0 | "Undefined behavior: memcpy source and destination overlap", &I); |
307 | 0 | break; |
308 | 0 | } |
309 | 0 | case Intrinsic::memcpy_inline: { |
310 | 0 | MemCpyInlineInst *MCII = cast<MemCpyInlineInst>(&I); |
311 | 0 | const uint64_t Size = MCII->getLength()->getValue().getLimitedValue(); |
312 | 0 | visitMemoryReference(I, MemoryLocation::getForDest(MCII), |
313 | 0 | MCII->getDestAlign(), nullptr, MemRef::Write); |
314 | 0 | visitMemoryReference(I, MemoryLocation::getForSource(MCII), |
315 | 0 | MCII->getSourceAlign(), nullptr, MemRef::Read); |
316 | | |
317 | | // Check that the memcpy arguments don't overlap. The AliasAnalysis API |
318 | | // isn't expressive enough for what we really want to do. Known partial |
319 | | // overlap is not distinguished from the case where nothing is known. |
320 | 0 | const LocationSize LS = LocationSize::precise(Size); |
321 | 0 | Check(AA->alias(MCII->getSource(), LS, MCII->getDest(), LS) != |
322 | 0 | AliasResult::MustAlias, |
323 | 0 | "Undefined behavior: memcpy source and destination overlap", &I); |
324 | 0 | break; |
325 | 0 | } |
326 | 0 | case Intrinsic::memmove: { |
327 | 0 | MemMoveInst *MMI = cast<MemMoveInst>(&I); |
328 | 0 | visitMemoryReference(I, MemoryLocation::getForDest(MMI), |
329 | 0 | MMI->getDestAlign(), nullptr, MemRef::Write); |
330 | 0 | visitMemoryReference(I, MemoryLocation::getForSource(MMI), |
331 | 0 | MMI->getSourceAlign(), nullptr, MemRef::Read); |
332 | 0 | break; |
333 | 0 | } |
334 | 0 | case Intrinsic::memset: { |
335 | 0 | MemSetInst *MSI = cast<MemSetInst>(&I); |
336 | 0 | visitMemoryReference(I, MemoryLocation::getForDest(MSI), |
337 | 0 | MSI->getDestAlign(), nullptr, MemRef::Write); |
338 | 0 | break; |
339 | 0 | } |
340 | 0 | case Intrinsic::memset_inline: { |
341 | 0 | MemSetInlineInst *MSII = cast<MemSetInlineInst>(&I); |
342 | 0 | visitMemoryReference(I, MemoryLocation::getForDest(MSII), |
343 | 0 | MSII->getDestAlign(), nullptr, MemRef::Write); |
344 | 0 | break; |
345 | 0 | } |
346 | | |
347 | 0 | case Intrinsic::vastart: |
348 | 0 | Check(I.getParent()->getParent()->isVarArg(), |
349 | 0 | "Undefined behavior: va_start called in a non-varargs function", |
350 | 0 | &I); |
351 | | |
352 | 0 | visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), |
353 | 0 | std::nullopt, nullptr, MemRef::Read | MemRef::Write); |
354 | 0 | break; |
355 | 0 | case Intrinsic::vacopy: |
356 | 0 | visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), |
357 | 0 | std::nullopt, nullptr, MemRef::Write); |
358 | 0 | visitMemoryReference(I, MemoryLocation::getForArgument(&I, 1, TLI), |
359 | 0 | std::nullopt, nullptr, MemRef::Read); |
360 | 0 | break; |
361 | 0 | case Intrinsic::vaend: |
362 | 0 | visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), |
363 | 0 | std::nullopt, nullptr, MemRef::Read | MemRef::Write); |
364 | 0 | break; |
365 | | |
366 | 0 | case Intrinsic::stackrestore: |
367 | | // Stackrestore doesn't read or write memory, but it sets the |
368 | | // stack pointer, which the compiler may read from or write to |
369 | | // at any time, so check it for both readability and writeability. |
370 | 0 | visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), |
371 | 0 | std::nullopt, nullptr, MemRef::Read | MemRef::Write); |
372 | 0 | break; |
373 | 0 | case Intrinsic::get_active_lane_mask: |
374 | 0 | if (auto *TripCount = dyn_cast<ConstantInt>(I.getArgOperand(1))) |
375 | 0 | Check(!TripCount->isZero(), |
376 | 0 | "get_active_lane_mask: operand #2 " |
377 | 0 | "must be greater than 0", |
378 | 0 | &I); |
379 | 0 | break; |
380 | 0 | } |
381 | 0 | } |
382 | | |
383 | 0 | void Lint::visitReturnInst(ReturnInst &I) { |
384 | 0 | Function *F = I.getParent()->getParent(); |
385 | 0 | Check(!F->doesNotReturn(), |
386 | 0 | "Unusual: Return statement in function with noreturn attribute", &I); |
387 | | |
388 | 0 | if (Value *V = I.getReturnValue()) { |
389 | 0 | Value *Obj = findValue(V, /*OffsetOk=*/true); |
390 | 0 | Check(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I); |
391 | 0 | } |
392 | 0 | } |
393 | | |
394 | | // TODO: Check that the reference is in bounds. |
395 | | // TODO: Check readnone/readonly function attributes. |
396 | | void Lint::visitMemoryReference(Instruction &I, const MemoryLocation &Loc, |
397 | 0 | MaybeAlign Align, Type *Ty, unsigned Flags) { |
398 | | // If no memory is being referenced, it doesn't matter if the pointer |
399 | | // is valid. |
400 | 0 | if (Loc.Size.isZero()) |
401 | 0 | return; |
402 | | |
403 | 0 | Value *Ptr = const_cast<Value *>(Loc.Ptr); |
404 | 0 | Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true); |
405 | 0 | Check(!isa<ConstantPointerNull>(UnderlyingObject), |
406 | 0 | "Undefined behavior: Null pointer dereference", &I); |
407 | 0 | Check(!isa<UndefValue>(UnderlyingObject), |
408 | 0 | "Undefined behavior: Undef pointer dereference", &I); |
409 | 0 | Check(!isa<ConstantInt>(UnderlyingObject) || |
410 | 0 | !cast<ConstantInt>(UnderlyingObject)->isMinusOne(), |
411 | 0 | "Unusual: All-ones pointer dereference", &I); |
412 | 0 | Check(!isa<ConstantInt>(UnderlyingObject) || |
413 | 0 | !cast<ConstantInt>(UnderlyingObject)->isOne(), |
414 | 0 | "Unusual: Address one pointer dereference", &I); |
415 | | |
416 | 0 | if (Flags & MemRef::Write) { |
417 | 0 | if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject)) |
418 | 0 | Check(!GV->isConstant(), "Undefined behavior: Write to read-only memory", |
419 | 0 | &I); |
420 | 0 | Check(!isa<Function>(UnderlyingObject) && |
421 | 0 | !isa<BlockAddress>(UnderlyingObject), |
422 | 0 | "Undefined behavior: Write to text section", &I); |
423 | 0 | } |
424 | 0 | if (Flags & MemRef::Read) { |
425 | 0 | Check(!isa<Function>(UnderlyingObject), "Unusual: Load from function body", |
426 | 0 | &I); |
427 | 0 | Check(!isa<BlockAddress>(UnderlyingObject), |
428 | 0 | "Undefined behavior: Load from block address", &I); |
429 | 0 | } |
430 | 0 | if (Flags & MemRef::Callee) { |
431 | 0 | Check(!isa<BlockAddress>(UnderlyingObject), |
432 | 0 | "Undefined behavior: Call to block address", &I); |
433 | 0 | } |
434 | 0 | if (Flags & MemRef::Branchee) { |
435 | 0 | Check(!isa<Constant>(UnderlyingObject) || |
436 | 0 | isa<BlockAddress>(UnderlyingObject), |
437 | 0 | "Undefined behavior: Branch to non-blockaddress", &I); |
438 | 0 | } |
439 | | |
440 | | // Check for buffer overflows and misalignment. |
441 | | // Only handles memory references that read/write something simple like an |
442 | | // alloca instruction or a global variable. |
443 | 0 | int64_t Offset = 0; |
444 | 0 | if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) { |
445 | | // OK, so the access is to a constant offset from Ptr. Check that Ptr is |
446 | | // something we can handle and if so extract the size of this base object |
447 | | // along with its alignment. |
448 | 0 | uint64_t BaseSize = MemoryLocation::UnknownSize; |
449 | 0 | MaybeAlign BaseAlign; |
450 | |
|
451 | 0 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) { |
452 | 0 | Type *ATy = AI->getAllocatedType(); |
453 | 0 | if (!AI->isArrayAllocation() && ATy->isSized()) |
454 | 0 | BaseSize = DL->getTypeAllocSize(ATy); |
455 | 0 | BaseAlign = AI->getAlign(); |
456 | 0 | } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) { |
457 | | // If the global may be defined differently in another compilation unit |
458 | | // then don't warn about funky memory accesses. |
459 | 0 | if (GV->hasDefinitiveInitializer()) { |
460 | 0 | Type *GTy = GV->getValueType(); |
461 | 0 | if (GTy->isSized()) |
462 | 0 | BaseSize = DL->getTypeAllocSize(GTy); |
463 | 0 | BaseAlign = GV->getAlign(); |
464 | 0 | if (!BaseAlign && GTy->isSized()) |
465 | 0 | BaseAlign = DL->getABITypeAlign(GTy); |
466 | 0 | } |
467 | 0 | } |
468 | | |
469 | | // Accesses from before the start or after the end of the object are not |
470 | | // defined. |
471 | 0 | Check(!Loc.Size.hasValue() || BaseSize == MemoryLocation::UnknownSize || |
472 | 0 | (Offset >= 0 && Offset + Loc.Size.getValue() <= BaseSize), |
473 | 0 | "Undefined behavior: Buffer overflow", &I); |
474 | | |
475 | | // Accesses that say that the memory is more aligned than it is are not |
476 | | // defined. |
477 | 0 | if (!Align && Ty && Ty->isSized()) |
478 | 0 | Align = DL->getABITypeAlign(Ty); |
479 | 0 | if (BaseAlign && Align) |
480 | 0 | Check(*Align <= commonAlignment(*BaseAlign, Offset), |
481 | 0 | "Undefined behavior: Memory reference address is misaligned", &I); |
482 | 0 | } |
483 | 0 | } |
484 | | |
485 | 0 | void Lint::visitLoadInst(LoadInst &I) { |
486 | 0 | visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(), I.getType(), |
487 | 0 | MemRef::Read); |
488 | 0 | } |
489 | | |
490 | 0 | void Lint::visitStoreInst(StoreInst &I) { |
491 | 0 | visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(), |
492 | 0 | I.getOperand(0)->getType(), MemRef::Write); |
493 | 0 | } |
494 | | |
495 | 0 | void Lint::visitXor(BinaryOperator &I) { |
496 | 0 | Check(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)), |
497 | 0 | "Undefined result: xor(undef, undef)", &I); |
498 | 0 | } |
499 | | |
500 | 0 | void Lint::visitSub(BinaryOperator &I) { |
501 | 0 | Check(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)), |
502 | 0 | "Undefined result: sub(undef, undef)", &I); |
503 | 0 | } |
504 | | |
505 | 0 | void Lint::visitLShr(BinaryOperator &I) { |
506 | 0 | if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1), |
507 | 0 | /*OffsetOk=*/false))) |
508 | 0 | Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), |
509 | 0 | "Undefined result: Shift count out of range", &I); |
510 | 0 | } |
511 | | |
512 | 0 | void Lint::visitAShr(BinaryOperator &I) { |
513 | 0 | if (ConstantInt *CI = |
514 | 0 | dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false))) |
515 | 0 | Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), |
516 | 0 | "Undefined result: Shift count out of range", &I); |
517 | 0 | } |
518 | | |
519 | 0 | void Lint::visitShl(BinaryOperator &I) { |
520 | 0 | if (ConstantInt *CI = |
521 | 0 | dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false))) |
522 | 0 | Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), |
523 | 0 | "Undefined result: Shift count out of range", &I); |
524 | 0 | } |
525 | | |
526 | | static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, |
527 | 0 | AssumptionCache *AC) { |
528 | | // Assume undef could be zero. |
529 | 0 | if (isa<UndefValue>(V)) |
530 | 0 | return true; |
531 | | |
532 | 0 | VectorType *VecTy = dyn_cast<VectorType>(V->getType()); |
533 | 0 | if (!VecTy) { |
534 | 0 | KnownBits Known = |
535 | 0 | computeKnownBits(V, DL, 0, AC, dyn_cast<Instruction>(V), DT); |
536 | 0 | return Known.isZero(); |
537 | 0 | } |
538 | | |
539 | | // Per-component check doesn't work with zeroinitializer |
540 | 0 | Constant *C = dyn_cast<Constant>(V); |
541 | 0 | if (!C) |
542 | 0 | return false; |
543 | | |
544 | 0 | if (C->isZeroValue()) |
545 | 0 | return true; |
546 | | |
547 | | // For a vector, KnownZero will only be true if all values are zero, so check |
548 | | // this per component |
549 | 0 | for (unsigned I = 0, N = cast<FixedVectorType>(VecTy)->getNumElements(); |
550 | 0 | I != N; ++I) { |
551 | 0 | Constant *Elem = C->getAggregateElement(I); |
552 | 0 | if (isa<UndefValue>(Elem)) |
553 | 0 | return true; |
554 | | |
555 | 0 | KnownBits Known = computeKnownBits(Elem, DL); |
556 | 0 | if (Known.isZero()) |
557 | 0 | return true; |
558 | 0 | } |
559 | | |
560 | 0 | return false; |
561 | 0 | } |
562 | | |
563 | 0 | void Lint::visitSDiv(BinaryOperator &I) { |
564 | 0 | Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC), |
565 | 0 | "Undefined behavior: Division by zero", &I); |
566 | 0 | } |
567 | | |
568 | 0 | void Lint::visitUDiv(BinaryOperator &I) { |
569 | 0 | Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC), |
570 | 0 | "Undefined behavior: Division by zero", &I); |
571 | 0 | } |
572 | | |
573 | 0 | void Lint::visitSRem(BinaryOperator &I) { |
574 | 0 | Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC), |
575 | 0 | "Undefined behavior: Division by zero", &I); |
576 | 0 | } |
577 | | |
578 | 0 | void Lint::visitURem(BinaryOperator &I) { |
579 | 0 | Check(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC), |
580 | 0 | "Undefined behavior: Division by zero", &I); |
581 | 0 | } |
582 | | |
583 | 0 | void Lint::visitAllocaInst(AllocaInst &I) { |
584 | 0 | if (isa<ConstantInt>(I.getArraySize())) |
585 | | // This isn't undefined behavior, it's just an obvious pessimization. |
586 | 0 | Check(&I.getParent()->getParent()->getEntryBlock() == I.getParent(), |
587 | 0 | "Pessimization: Static alloca outside of entry block", &I); |
588 | | |
589 | | // TODO: Check for an unusual size (MSB set?) |
590 | 0 | } |
591 | | |
592 | 0 | void Lint::visitVAArgInst(VAArgInst &I) { |
593 | 0 | visitMemoryReference(I, MemoryLocation::get(&I), std::nullopt, nullptr, |
594 | 0 | MemRef::Read | MemRef::Write); |
595 | 0 | } |
596 | | |
597 | 0 | void Lint::visitIndirectBrInst(IndirectBrInst &I) { |
598 | 0 | visitMemoryReference(I, MemoryLocation::getAfter(I.getAddress()), |
599 | 0 | std::nullopt, nullptr, MemRef::Branchee); |
600 | |
|
601 | 0 | Check(I.getNumDestinations() != 0, |
602 | 0 | "Undefined behavior: indirectbr with no destinations", &I); |
603 | 0 | } |
604 | | |
605 | 0 | void Lint::visitExtractElementInst(ExtractElementInst &I) { |
606 | 0 | if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(), |
607 | 0 | /*OffsetOk=*/false))) |
608 | 0 | Check( |
609 | 0 | CI->getValue().ult( |
610 | 0 | cast<FixedVectorType>(I.getVectorOperandType())->getNumElements()), |
611 | 0 | "Undefined result: extractelement index out of range", &I); |
612 | 0 | } |
613 | | |
614 | 0 | void Lint::visitInsertElementInst(InsertElementInst &I) { |
615 | 0 | if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2), |
616 | 0 | /*OffsetOk=*/false))) |
617 | 0 | Check(CI->getValue().ult( |
618 | 0 | cast<FixedVectorType>(I.getType())->getNumElements()), |
619 | 0 | "Undefined result: insertelement index out of range", &I); |
620 | 0 | } |
621 | | |
622 | 0 | void Lint::visitUnreachableInst(UnreachableInst &I) { |
623 | | // This isn't undefined behavior, it's merely suspicious. |
624 | 0 | Check(&I == &I.getParent()->front() || |
625 | 0 | std::prev(I.getIterator())->mayHaveSideEffects(), |
626 | 0 | "Unusual: unreachable immediately preceded by instruction without " |
627 | 0 | "side effects", |
628 | 0 | &I); |
629 | 0 | } |
630 | | |
631 | | /// findValue - Look through bitcasts and simple memory reference patterns |
632 | | /// to identify an equivalent, but more informative, value. If OffsetOk |
633 | | /// is true, look through getelementptrs with non-zero offsets too. |
634 | | /// |
635 | | /// Most analysis passes don't require this logic, because instcombine |
636 | | /// will simplify most of these kinds of things away. But it's a goal of |
637 | | /// this Lint pass to be useful even on non-optimized IR. |
638 | 0 | Value *Lint::findValue(Value *V, bool OffsetOk) const { |
639 | 0 | SmallPtrSet<Value *, 4> Visited; |
640 | 0 | return findValueImpl(V, OffsetOk, Visited); |
641 | 0 | } |
642 | | |
643 | | /// findValueImpl - Implementation helper for findValue. |
644 | | Value *Lint::findValueImpl(Value *V, bool OffsetOk, |
645 | 0 | SmallPtrSetImpl<Value *> &Visited) const { |
646 | | // Detect self-referential values. |
647 | 0 | if (!Visited.insert(V).second) |
648 | 0 | return UndefValue::get(V->getType()); |
649 | | |
650 | | // TODO: Look through sext or zext cast, when the result is known to |
651 | | // be interpreted as signed or unsigned, respectively. |
652 | | // TODO: Look through eliminable cast pairs. |
653 | | // TODO: Look through calls with unique return values. |
654 | | // TODO: Look through vector insert/extract/shuffle. |
655 | 0 | V = OffsetOk ? getUnderlyingObject(V) : V->stripPointerCasts(); |
656 | 0 | if (LoadInst *L = dyn_cast<LoadInst>(V)) { |
657 | 0 | BasicBlock::iterator BBI = L->getIterator(); |
658 | 0 | BasicBlock *BB = L->getParent(); |
659 | 0 | SmallPtrSet<BasicBlock *, 4> VisitedBlocks; |
660 | 0 | for (;;) { |
661 | 0 | if (!VisitedBlocks.insert(BB).second) |
662 | 0 | break; |
663 | 0 | if (Value *U = |
664 | 0 | FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, AA)) |
665 | 0 | return findValueImpl(U, OffsetOk, Visited); |
666 | 0 | if (BBI != BB->begin()) |
667 | 0 | break; |
668 | 0 | BB = BB->getUniquePredecessor(); |
669 | 0 | if (!BB) |
670 | 0 | break; |
671 | 0 | BBI = BB->end(); |
672 | 0 | } |
673 | 0 | } else if (PHINode *PN = dyn_cast<PHINode>(V)) { |
674 | 0 | if (Value *W = PN->hasConstantValue()) |
675 | 0 | return findValueImpl(W, OffsetOk, Visited); |
676 | 0 | } else if (CastInst *CI = dyn_cast<CastInst>(V)) { |
677 | 0 | if (CI->isNoopCast(*DL)) |
678 | 0 | return findValueImpl(CI->getOperand(0), OffsetOk, Visited); |
679 | 0 | } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) { |
680 | 0 | if (Value *W = |
681 | 0 | FindInsertedValue(Ex->getAggregateOperand(), Ex->getIndices())) |
682 | 0 | if (W != V) |
683 | 0 | return findValueImpl(W, OffsetOk, Visited); |
684 | 0 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { |
685 | | // Same as above, but for ConstantExpr instead of Instruction. |
686 | 0 | if (Instruction::isCast(CE->getOpcode())) { |
687 | 0 | if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()), |
688 | 0 | CE->getOperand(0)->getType(), CE->getType(), |
689 | 0 | *DL)) |
690 | 0 | return findValueImpl(CE->getOperand(0), OffsetOk, Visited); |
691 | 0 | } |
692 | 0 | } |
693 | | |
694 | | // As a last resort, try SimplifyInstruction or constant folding. |
695 | 0 | if (Instruction *Inst = dyn_cast<Instruction>(V)) { |
696 | 0 | if (Value *W = simplifyInstruction(Inst, {*DL, TLI, DT, AC})) |
697 | 0 | return findValueImpl(W, OffsetOk, Visited); |
698 | 0 | } else if (auto *C = dyn_cast<Constant>(V)) { |
699 | 0 | Value *W = ConstantFoldConstant(C, *DL, TLI); |
700 | 0 | if (W != V) |
701 | 0 | return findValueImpl(W, OffsetOk, Visited); |
702 | 0 | } |
703 | | |
704 | 0 | return V; |
705 | 0 | } |
706 | | |
707 | 0 | PreservedAnalyses LintPass::run(Function &F, FunctionAnalysisManager &AM) { |
708 | 0 | auto *Mod = F.getParent(); |
709 | 0 | auto *DL = &F.getParent()->getDataLayout(); |
710 | 0 | auto *AA = &AM.getResult<AAManager>(F); |
711 | 0 | auto *AC = &AM.getResult<AssumptionAnalysis>(F); |
712 | 0 | auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); |
713 | 0 | auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F); |
714 | 0 | Lint L(Mod, DL, AA, AC, DT, TLI); |
715 | 0 | L.visit(F); |
716 | 0 | dbgs() << L.MessagesStr.str(); |
717 | 0 | return PreservedAnalyses::all(); |
718 | 0 | } |
719 | | |
720 | | //===----------------------------------------------------------------------===// |
721 | | // Implement the public interfaces to this file... |
722 | | //===----------------------------------------------------------------------===// |
723 | | |
724 | | /// lintFunction - Check a function for errors, printing messages on stderr. |
725 | | /// |
726 | 0 | void llvm::lintFunction(const Function &f) { |
727 | 0 | Function &F = const_cast<Function &>(f); |
728 | 0 | assert(!F.isDeclaration() && "Cannot lint external functions"); |
729 | | |
730 | 0 | FunctionAnalysisManager FAM; |
731 | 0 | FAM.registerPass([&] { return TargetLibraryAnalysis(); }); |
732 | 0 | FAM.registerPass([&] { return DominatorTreeAnalysis(); }); |
733 | 0 | FAM.registerPass([&] { return AssumptionAnalysis(); }); |
734 | 0 | FAM.registerPass([&] { |
735 | 0 | AAManager AA; |
736 | 0 | AA.registerFunctionAnalysis<BasicAA>(); |
737 | 0 | AA.registerFunctionAnalysis<ScopedNoAliasAA>(); |
738 | 0 | AA.registerFunctionAnalysis<TypeBasedAA>(); |
739 | 0 | return AA; |
740 | 0 | }); |
741 | 0 | LintPass().run(F, FAM); |
742 | 0 | } |
743 | | |
744 | | /// lintModule - Check a module for errors, printing messages on stderr. |
745 | | /// |
746 | 0 | void llvm::lintModule(const Module &M) { |
747 | 0 | for (const Function &F : M) { |
748 | 0 | if (!F.isDeclaration()) |
749 | 0 | lintFunction(F); |
750 | 0 | } |
751 | 0 | } |