PoisonChecking.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. //===- PoisonChecking.cpp - -----------------------------------------------===//
  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. // Implements a transform pass which instruments IR such that poison semantics
  10. // are made explicit. That is, it provides a (possibly partial) executable
  11. // semantics for every instruction w.r.t. poison as specified in the LLVM
  12. // LangRef. There are obvious parallels to the sanitizer tools, but this pass
  13. // is focused purely on the semantics of LLVM IR, not any particular source
  14. // language. If you're looking for something to see if your C/C++ contains
  15. // UB, this is not it.
  16. //
  17. // The rewritten semantics of each instruction will include the following
  18. // components:
  19. //
  20. // 1) The original instruction, unmodified.
  21. // 2) A propagation rule which translates dynamic information about the poison
  22. // state of each input to whether the dynamic output of the instruction
  23. // produces poison.
  24. // 3) A creation rule which validates any poison producing flags on the
  25. // instruction itself (e.g. checks for overflow on nsw).
  26. // 4) A check rule which traps (to a handler function) if this instruction must
  27. // execute undefined behavior given the poison state of it's inputs.
  28. //
  29. // This is a must analysis based transform; that is, the resulting code may
  30. // produce a false negative result (not report UB when actually exists
  31. // according to the LangRef spec), but should never produce a false positive
  32. // (report UB where it doesn't exist).
  33. //
  34. // Use cases for this pass include:
  35. // - Understanding (and testing!) the implications of the definition of poison
  36. // from the LangRef.
  37. // - Validating the output of a IR fuzzer to ensure that all programs produced
  38. // are well defined on the specific input used.
  39. // - Finding/confirming poison specific miscompiles by checking the poison
  40. // status of an input/IR pair is the same before and after an optimization
  41. // transform.
  42. // - Checking that a bugpoint reduction does not introduce UB which didn't
  43. // exist in the original program being reduced.
  44. //
  45. // The major sources of inaccuracy are currently:
  46. // - Most validation rules not yet implemented for instructions with poison
  47. // relavant flags. At the moment, only nsw/nuw on add/sub are supported.
  48. // - UB which is control dependent on a branch on poison is not yet
  49. // reported. Currently, only data flow dependence is modeled.
  50. // - Poison which is propagated through memory is not modeled. As such,
  51. // storing poison to memory and then reloading it will cause a false negative
  52. // as we consider the reloaded value to not be poisoned.
  53. // - Poison propagation across function boundaries is not modeled. At the
  54. // moment, all arguments and return values are assumed not to be poison.
  55. // - Undef is not modeled. In particular, the optimizer's freedom to pick
  56. // concrete values for undef bits so as to maximize potential for producing
  57. // poison is not modeled.
  58. //
  59. //===----------------------------------------------------------------------===//
  60. #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
  61. #include "llvm/ADT/DenseMap.h"
  62. #include "llvm/Analysis/ValueTracking.h"
  63. #include "llvm/IR/IRBuilder.h"
  64. #include "llvm/Support/CommandLine.h"
  65. using namespace llvm;
  66. #define DEBUG_TYPE "poison-checking"
  67. static cl::opt<bool>
  68. LocalCheck("poison-checking-function-local",
  69. cl::init(false),
  70. cl::desc("Check that returns are non-poison (for testing)"));
  71. static bool isConstantFalse(Value* V) {
  72. assert(V->getType()->isIntegerTy(1));
  73. if (auto *CI = dyn_cast<ConstantInt>(V))
  74. return CI->isZero();
  75. return false;
  76. }
  77. static Value *buildOrChain(IRBuilder<> &B, ArrayRef<Value*> Ops) {
  78. if (Ops.size() == 0)
  79. return B.getFalse();
  80. unsigned i = 0;
  81. for (; i < Ops.size() && isConstantFalse(Ops[i]); i++) {}
  82. if (i == Ops.size())
  83. return B.getFalse();
  84. Value *Accum = Ops[i++];
  85. for (Value *Op : llvm::drop_begin(Ops, i))
  86. if (!isConstantFalse(Op))
  87. Accum = B.CreateOr(Accum, Op);
  88. return Accum;
  89. }
  90. static void generateCreationChecksForBinOp(Instruction &I,
  91. SmallVectorImpl<Value*> &Checks) {
  92. assert(isa<BinaryOperator>(I));
  93. IRBuilder<> B(&I);
  94. Value *LHS = I.getOperand(0);
  95. Value *RHS = I.getOperand(1);
  96. switch (I.getOpcode()) {
  97. default:
  98. return;
  99. case Instruction::Add: {
  100. if (I.hasNoSignedWrap()) {
  101. auto *OverflowOp =
  102. B.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow, LHS, RHS);
  103. Checks.push_back(B.CreateExtractValue(OverflowOp, 1));
  104. }
  105. if (I.hasNoUnsignedWrap()) {
  106. auto *OverflowOp =
  107. B.CreateBinaryIntrinsic(Intrinsic::uadd_with_overflow, LHS, RHS);
  108. Checks.push_back(B.CreateExtractValue(OverflowOp, 1));
  109. }
  110. break;
  111. }
  112. case Instruction::Sub: {
  113. if (I.hasNoSignedWrap()) {
  114. auto *OverflowOp =
  115. B.CreateBinaryIntrinsic(Intrinsic::ssub_with_overflow, LHS, RHS);
  116. Checks.push_back(B.CreateExtractValue(OverflowOp, 1));
  117. }
  118. if (I.hasNoUnsignedWrap()) {
  119. auto *OverflowOp =
  120. B.CreateBinaryIntrinsic(Intrinsic::usub_with_overflow, LHS, RHS);
  121. Checks.push_back(B.CreateExtractValue(OverflowOp, 1));
  122. }
  123. break;
  124. }
  125. case Instruction::Mul: {
  126. if (I.hasNoSignedWrap()) {
  127. auto *OverflowOp =
  128. B.CreateBinaryIntrinsic(Intrinsic::smul_with_overflow, LHS, RHS);
  129. Checks.push_back(B.CreateExtractValue(OverflowOp, 1));
  130. }
  131. if (I.hasNoUnsignedWrap()) {
  132. auto *OverflowOp =
  133. B.CreateBinaryIntrinsic(Intrinsic::umul_with_overflow, LHS, RHS);
  134. Checks.push_back(B.CreateExtractValue(OverflowOp, 1));
  135. }
  136. break;
  137. }
  138. case Instruction::UDiv: {
  139. if (I.isExact()) {
  140. auto *Check =
  141. B.CreateICmp(ICmpInst::ICMP_NE, B.CreateURem(LHS, RHS),
  142. ConstantInt::get(LHS->getType(), 0));
  143. Checks.push_back(Check);
  144. }
  145. break;
  146. }
  147. case Instruction::SDiv: {
  148. if (I.isExact()) {
  149. auto *Check =
  150. B.CreateICmp(ICmpInst::ICMP_NE, B.CreateSRem(LHS, RHS),
  151. ConstantInt::get(LHS->getType(), 0));
  152. Checks.push_back(Check);
  153. }
  154. break;
  155. }
  156. case Instruction::AShr:
  157. case Instruction::LShr:
  158. case Instruction::Shl: {
  159. Value *ShiftCheck =
  160. B.CreateICmp(ICmpInst::ICMP_UGE, RHS,
  161. ConstantInt::get(RHS->getType(),
  162. LHS->getType()->getScalarSizeInBits()));
  163. Checks.push_back(ShiftCheck);
  164. break;
  165. }
  166. };
  167. }
  168. /// Given an instruction which can produce poison on non-poison inputs
  169. /// (i.e. canCreatePoison returns true), generate runtime checks to produce
  170. /// boolean indicators of when poison would result.
  171. static void generateCreationChecks(Instruction &I,
  172. SmallVectorImpl<Value*> &Checks) {
  173. IRBuilder<> B(&I);
  174. if (isa<BinaryOperator>(I) && !I.getType()->isVectorTy())
  175. generateCreationChecksForBinOp(I, Checks);
  176. // Handle non-binops separately
  177. switch (I.getOpcode()) {
  178. default:
  179. // Note there are a couple of missing cases here, once implemented, this
  180. // should become an llvm_unreachable.
  181. break;
  182. case Instruction::ExtractElement: {
  183. Value *Vec = I.getOperand(0);
  184. auto *VecVTy = dyn_cast<FixedVectorType>(Vec->getType());
  185. if (!VecVTy)
  186. break;
  187. Value *Idx = I.getOperand(1);
  188. unsigned NumElts = VecVTy->getNumElements();
  189. Value *Check =
  190. B.CreateICmp(ICmpInst::ICMP_UGE, Idx,
  191. ConstantInt::get(Idx->getType(), NumElts));
  192. Checks.push_back(Check);
  193. break;
  194. }
  195. case Instruction::InsertElement: {
  196. Value *Vec = I.getOperand(0);
  197. auto *VecVTy = dyn_cast<FixedVectorType>(Vec->getType());
  198. if (!VecVTy)
  199. break;
  200. Value *Idx = I.getOperand(2);
  201. unsigned NumElts = VecVTy->getNumElements();
  202. Value *Check =
  203. B.CreateICmp(ICmpInst::ICMP_UGE, Idx,
  204. ConstantInt::get(Idx->getType(), NumElts));
  205. Checks.push_back(Check);
  206. break;
  207. }
  208. };
  209. }
  210. static Value *getPoisonFor(DenseMap<Value *, Value *> &ValToPoison, Value *V) {
  211. auto Itr = ValToPoison.find(V);
  212. if (Itr != ValToPoison.end())
  213. return Itr->second;
  214. if (isa<Constant>(V)) {
  215. return ConstantInt::getFalse(V->getContext());
  216. }
  217. // Return false for unknwon values - this implements a non-strict mode where
  218. // unhandled IR constructs are simply considered to never produce poison. At
  219. // some point in the future, we probably want a "strict mode" for testing if
  220. // nothing else.
  221. return ConstantInt::getFalse(V->getContext());
  222. }
  223. static void CreateAssert(IRBuilder<> &B, Value *Cond) {
  224. assert(Cond->getType()->isIntegerTy(1));
  225. if (auto *CI = dyn_cast<ConstantInt>(Cond))
  226. if (CI->isAllOnesValue())
  227. return;
  228. Module *M = B.GetInsertBlock()->getModule();
  229. M->getOrInsertFunction("__poison_checker_assert",
  230. Type::getVoidTy(M->getContext()),
  231. Type::getInt1Ty(M->getContext()));
  232. Function *TrapFunc = M->getFunction("__poison_checker_assert");
  233. B.CreateCall(TrapFunc, Cond);
  234. }
  235. static void CreateAssertNot(IRBuilder<> &B, Value *Cond) {
  236. assert(Cond->getType()->isIntegerTy(1));
  237. CreateAssert(B, B.CreateNot(Cond));
  238. }
  239. static bool rewrite(Function &F) {
  240. auto * const Int1Ty = Type::getInt1Ty(F.getContext());
  241. DenseMap<Value *, Value *> ValToPoison;
  242. for (BasicBlock &BB : F)
  243. for (auto I = BB.begin(); isa<PHINode>(&*I); I++) {
  244. auto *OldPHI = cast<PHINode>(&*I);
  245. auto *NewPHI = PHINode::Create(Int1Ty, OldPHI->getNumIncomingValues());
  246. for (unsigned i = 0; i < OldPHI->getNumIncomingValues(); i++)
  247. NewPHI->addIncoming(UndefValue::get(Int1Ty),
  248. OldPHI->getIncomingBlock(i));
  249. NewPHI->insertBefore(OldPHI);
  250. ValToPoison[OldPHI] = NewPHI;
  251. }
  252. for (BasicBlock &BB : F)
  253. for (Instruction &I : BB) {
  254. if (isa<PHINode>(I)) continue;
  255. IRBuilder<> B(cast<Instruction>(&I));
  256. // Note: There are many more sources of documented UB, but this pass only
  257. // attempts to find UB triggered by propagation of poison.
  258. SmallVector<const Value *, 4> NonPoisonOps;
  259. SmallPtrSet<const Value *, 4> SeenNonPoisonOps;
  260. getGuaranteedNonPoisonOps(&I, NonPoisonOps);
  261. for (const Value *Op : NonPoisonOps)
  262. if (SeenNonPoisonOps.insert(Op).second)
  263. CreateAssertNot(B,
  264. getPoisonFor(ValToPoison, const_cast<Value *>(Op)));
  265. if (LocalCheck)
  266. if (auto *RI = dyn_cast<ReturnInst>(&I))
  267. if (RI->getNumOperands() != 0) {
  268. Value *Op = RI->getOperand(0);
  269. CreateAssertNot(B, getPoisonFor(ValToPoison, Op));
  270. }
  271. SmallVector<Value*, 4> Checks;
  272. for (const Use &U : I.operands()) {
  273. if (ValToPoison.count(U) && propagatesPoison(U))
  274. Checks.push_back(getPoisonFor(ValToPoison, U));
  275. }
  276. if (canCreatePoison(cast<Operator>(&I)))
  277. generateCreationChecks(I, Checks);
  278. ValToPoison[&I] = buildOrChain(B, Checks);
  279. }
  280. for (BasicBlock &BB : F)
  281. for (auto I = BB.begin(); isa<PHINode>(&*I); I++) {
  282. auto *OldPHI = cast<PHINode>(&*I);
  283. if (!ValToPoison.count(OldPHI))
  284. continue; // skip the newly inserted phis
  285. auto *NewPHI = cast<PHINode>(ValToPoison[OldPHI]);
  286. for (unsigned i = 0; i < OldPHI->getNumIncomingValues(); i++) {
  287. auto *OldVal = OldPHI->getIncomingValue(i);
  288. NewPHI->setIncomingValue(i, getPoisonFor(ValToPoison, OldVal));
  289. }
  290. }
  291. return true;
  292. }
  293. PreservedAnalyses PoisonCheckingPass::run(Module &M,
  294. ModuleAnalysisManager &AM) {
  295. bool Changed = false;
  296. for (auto &F : M)
  297. Changed |= rewrite(F);
  298. return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
  299. }
  300. PreservedAnalyses PoisonCheckingPass::run(Function &F,
  301. FunctionAnalysisManager &AM) {
  302. return rewrite(F) ? PreservedAnalyses::none() : PreservedAnalyses::all();
  303. }
  304. /* Major TODO Items:
  305. - Control dependent poison UB
  306. - Strict mode - (i.e. must analyze every operand)
  307. - Poison through memory
  308. - Function ABIs
  309. - Full coverage of intrinsics, etc.. (ouch)
  310. Instructions w/Unclear Semantics:
  311. - shufflevector - It would seem reasonable for an out of bounds mask element
  312. to produce poison, but the LangRef does not state.
  313. - all binary ops w/vector operands - The likely interpretation would be that
  314. any element overflowing should produce poison for the entire result, but
  315. the LangRef does not state.
  316. - Floating point binary ops w/fmf flags other than (nnan, noinfs). It seems
  317. strange that only certian flags should be documented as producing poison.
  318. Cases of clear poison semantics not yet implemented:
  319. - Exact flags on ashr/lshr produce poison
  320. - NSW/NUW flags on shl produce poison
  321. - Inbounds flag on getelementptr produce poison
  322. - fptosi/fptoui (out of bounds input) produce poison
  323. - Scalable vector types for insertelement/extractelement
  324. - Floating point binary ops w/fmf nnan/noinfs flags produce poison
  325. */