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