1 //===- verify-uselistorder.cpp - The LLVM Modular Optimizer ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Verify that use-list order can be serialized correctly. After reading the 11 // provided IR, this tool shuffles the use-lists and then writes and reads to a 12 // separate Module whose use-list orders are compared to the original. 13 // 14 // The shuffles are deterministic, but guarantee that use-lists will change. 15 // The algorithm per iteration is as follows: 16 // 17 // 1. Seed the random number generator. The seed is different for each 18 // shuffle. Shuffle 0 uses default+0, shuffle 1 uses default+1, and so on. 19 // 20 // 2. Visit every Value in a deterministic order. 21 // 22 // 3. Assign a random number to each Use in the Value's use-list in order. 23 // 24 // 4. If the numbers are already in order, reassign numbers until they aren't. 25 // 26 // 5. Sort the use-list using Value::sortUseList(), which is a stable sort. 27 // 28 //===----------------------------------------------------------------------===// 29 30 #include "llvm/ADT/DenseMap.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/AsmParser/Parser.h" 33 #include "llvm/Bitcode/ReaderWriter.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/UseListOrder.h" 37 #include "llvm/IR/Verifier.h" 38 #include "llvm/IRReader/IRReader.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/FileSystem.h" 43 #include "llvm/Support/FileUtilities.h" 44 #include "llvm/Support/ManagedStatic.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/PrettyStackTrace.h" 47 #include "llvm/Support/Signals.h" 48 #include "llvm/Support/SourceMgr.h" 49 #include "llvm/Support/SystemUtils.h" 50 #include "llvm/Support/raw_ostream.h" 51 #include <random> 52 #include <vector> 53 54 using namespace llvm; 55 56 #define DEBUG_TYPE "uselistorder" 57 58 static cl::opt<std::string> InputFilename(cl::Positional, 59 cl::desc("<input bitcode file>"), 60 cl::init("-"), 61 cl::value_desc("filename")); 62 63 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"), 64 cl::init(false)); 65 66 static cl::opt<unsigned> 67 NumShuffles("num-shuffles", 68 cl::desc("Number of times to shuffle and verify use-lists"), 69 cl::init(1)); 70 71 namespace { 72 73 struct TempFile { 74 std::string Filename; 75 FileRemover Remover; 76 bool init(const std::string &Ext); 77 bool writeBitcode(const Module &M) const; 78 bool writeAssembly(const Module &M) const; 79 std::unique_ptr<Module> readBitcode(LLVMContext &Context) const; 80 std::unique_ptr<Module> readAssembly(LLVMContext &Context) const; 81 }; 82 83 struct ValueMapping { 84 DenseMap<const Value *, unsigned> IDs; 85 std::vector<const Value *> Values; 86 87 /// \brief Construct a value mapping for module. 88 /// 89 /// Creates mapping from every value in \c M to an ID. This mapping includes 90 /// un-referencable values. 91 /// 92 /// Every \a Value that gets serialized in some way should be represented 93 /// here. The order needs to be deterministic, but it's unnecessary to match 94 /// the value-ids in the bitcode writer. 95 /// 96 /// All constants that are referenced by other values are included in the 97 /// mapping, but others -- which wouldn't be serialized -- are not. 98 ValueMapping(const Module &M); 99 100 /// \brief Map a value. 101 /// 102 /// Maps a value. If it's a constant, maps all of its operands first. 103 void map(const Value *V); 104 unsigned lookup(const Value *V) const { return IDs.lookup(V); } 105 }; 106 107 } // end namespace 108 109 bool TempFile::init(const std::string &Ext) { 110 SmallVector<char, 64> Vector; 111 DEBUG(dbgs() << " - create-temp-file\n"); 112 if (auto EC = sys::fs::createTemporaryFile("uselistorder", Ext, Vector)) { 113 errs() << "verify-uselistorder: error: " << EC.message() << "\n"; 114 return true; 115 } 116 assert(!Vector.empty()); 117 118 Filename.assign(Vector.data(), Vector.data() + Vector.size()); 119 Remover.setFile(Filename, !SaveTemps); 120 if (SaveTemps) 121 outs() << " - filename = " << Filename << "\n"; 122 return false; 123 } 124 125 bool TempFile::writeBitcode(const Module &M) const { 126 DEBUG(dbgs() << " - write bitcode\n"); 127 std::error_code EC; 128 raw_fd_ostream OS(Filename, EC, sys::fs::F_None); 129 if (EC) { 130 errs() << "verify-uselistorder: error: " << EC.message() << "\n"; 131 return true; 132 } 133 134 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true); 135 return false; 136 } 137 138 bool TempFile::writeAssembly(const Module &M) const { 139 DEBUG(dbgs() << " - write assembly\n"); 140 std::error_code EC; 141 raw_fd_ostream OS(Filename, EC, sys::fs::F_Text); 142 if (EC) { 143 errs() << "verify-uselistorder: error: " << EC.message() << "\n"; 144 return true; 145 } 146 147 M.print(OS, nullptr, /* ShouldPreserveUseListOrder */ true); 148 return false; 149 } 150 151 std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const { 152 DEBUG(dbgs() << " - read bitcode\n"); 153 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOr = 154 MemoryBuffer::getFile(Filename); 155 if (!BufferOr) { 156 errs() << "verify-uselistorder: error: " << BufferOr.getError().message() 157 << "\n"; 158 return nullptr; 159 } 160 161 MemoryBuffer *Buffer = BufferOr.get().get(); 162 ErrorOr<Module *> ModuleOr = 163 parseBitcodeFile(Buffer->getMemBufferRef(), Context); 164 if (!ModuleOr) { 165 errs() << "verify-uselistorder: error: " << ModuleOr.getError().message() 166 << "\n"; 167 return nullptr; 168 } 169 return std::unique_ptr<Module>(ModuleOr.get()); 170 } 171 172 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const { 173 DEBUG(dbgs() << " - read assembly\n"); 174 SMDiagnostic Err; 175 std::unique_ptr<Module> M = parseAssemblyFile(Filename, Err, Context); 176 if (!M.get()) 177 Err.print("verify-uselistorder", errs()); 178 return M; 179 } 180 181 ValueMapping::ValueMapping(const Module &M) { 182 // Every value should be mapped, including things like void instructions and 183 // basic blocks that are kept out of the ValueEnumerator. 184 // 185 // The current mapping order makes it easier to debug the tables. It happens 186 // to be similar to the ID mapping when writing ValueEnumerator, but they 187 // aren't (and needn't be) in sync. 188 189 // Globals. 190 for (const GlobalVariable &G : M.globals()) 191 map(&G); 192 for (const GlobalAlias &A : M.aliases()) 193 map(&A); 194 for (const Function &F : M) 195 map(&F); 196 197 // Constants used by globals. 198 for (const GlobalVariable &G : M.globals()) 199 if (G.hasInitializer()) 200 map(G.getInitializer()); 201 for (const GlobalAlias &A : M.aliases()) 202 map(A.getAliasee()); 203 for (const Function &F : M) { 204 if (F.hasPrefixData()) 205 map(F.getPrefixData()); 206 if (F.hasPrologueData()) 207 map(F.getPrologueData()); 208 } 209 210 // Function bodies. 211 for (const Function &F : M) { 212 for (const Argument &A : F.args()) 213 map(&A); 214 for (const BasicBlock &BB : F) 215 map(&BB); 216 for (const BasicBlock &BB : F) 217 for (const Instruction &I : BB) 218 map(&I); 219 220 // Constants used by instructions. 221 for (const BasicBlock &BB : F) 222 for (const Instruction &I : BB) 223 for (const Value *Op : I.operands()) 224 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) || 225 isa<InlineAsm>(Op)) 226 map(Op); 227 } 228 } 229 230 void ValueMapping::map(const Value *V) { 231 if (IDs.lookup(V)) 232 return; 233 234 if (auto *C = dyn_cast<Constant>(V)) 235 if (!isa<GlobalValue>(C)) 236 for (const Value *Op : C->operands()) 237 map(Op); 238 239 Values.push_back(V); 240 IDs[V] = Values.size(); 241 } 242 243 #ifndef NDEBUG 244 static void dumpMapping(const ValueMapping &VM) { 245 dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n"; 246 for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) { 247 dbgs() << " - id = " << I << ", value = "; 248 VM.Values[I]->dump(); 249 } 250 } 251 252 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) { 253 const Value *V = M.Values[I]; 254 dbgs() << " - " << Desc << " value = "; 255 V->dump(); 256 for (const Use &U : V->uses()) { 257 dbgs() << " => use: op = " << U.getOperandNo() 258 << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = "; 259 U.getUser()->dump(); 260 } 261 } 262 263 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R, 264 unsigned I) { 265 dbgs() << " - fail: user mismatch: ID = " << I << "\n"; 266 debugValue(L, I, "LHS"); 267 debugValue(R, I, "RHS"); 268 269 dbgs() << "\nlhs-"; 270 dumpMapping(L); 271 dbgs() << "\nrhs-"; 272 dumpMapping(R); 273 } 274 275 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) { 276 dbgs() << " - fail: map size: " << L.Values.size() 277 << " != " << R.Values.size() << "\n"; 278 dbgs() << "\nlhs-"; 279 dumpMapping(L); 280 dbgs() << "\nrhs-"; 281 dumpMapping(R); 282 } 283 #endif 284 285 static bool matches(const ValueMapping &LM, const ValueMapping &RM) { 286 DEBUG(dbgs() << "compare value maps\n"); 287 if (LM.Values.size() != RM.Values.size()) { 288 DEBUG(debugSizeMismatch(LM, RM)); 289 return false; 290 } 291 292 // This mapping doesn't include dangling constant users, since those don't 293 // get serialized. However, checking if users are constant and calling 294 // isConstantUsed() on every one is very expensive. Instead, just check if 295 // the user is mapped. 296 auto skipUnmappedUsers = 297 [&](Value::const_use_iterator &U, Value::const_use_iterator E, 298 const ValueMapping &M) { 299 while (U != E && !M.lookup(U->getUser())) 300 ++U; 301 }; 302 303 // Iterate through all values, and check that both mappings have the same 304 // users. 305 for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) { 306 const Value *L = LM.Values[I]; 307 const Value *R = RM.Values[I]; 308 auto LU = L->use_begin(), LE = L->use_end(); 309 auto RU = R->use_begin(), RE = R->use_end(); 310 skipUnmappedUsers(LU, LE, LM); 311 skipUnmappedUsers(RU, RE, RM); 312 313 while (LU != LE) { 314 if (RU == RE) { 315 DEBUG(debugUserMismatch(LM, RM, I)); 316 return false; 317 } 318 if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) { 319 DEBUG(debugUserMismatch(LM, RM, I)); 320 return false; 321 } 322 if (LU->getOperandNo() != RU->getOperandNo()) { 323 DEBUG(debugUserMismatch(LM, RM, I)); 324 return false; 325 } 326 skipUnmappedUsers(++LU, LE, LM); 327 skipUnmappedUsers(++RU, RE, RM); 328 } 329 if (RU != RE) { 330 DEBUG(debugUserMismatch(LM, RM, I)); 331 return false; 332 } 333 } 334 335 return true; 336 } 337 338 static void verifyAfterRoundTrip(const Module &M, 339 std::unique_ptr<Module> OtherM) { 340 if (!OtherM) 341 report_fatal_error("parsing failed"); 342 if (verifyModule(*OtherM, &errs())) 343 report_fatal_error("verification failed"); 344 if (!matches(ValueMapping(M), ValueMapping(*OtherM))) 345 report_fatal_error("use-list order changed"); 346 } 347 static void verifyBitcodeUseListOrder(const Module &M) { 348 TempFile F; 349 if (F.init("bc")) 350 report_fatal_error("failed to initialize bitcode file"); 351 352 if (F.writeBitcode(M)) 353 report_fatal_error("failed to write bitcode"); 354 355 LLVMContext Context; 356 verifyAfterRoundTrip(M, F.readBitcode(Context)); 357 } 358 359 static void verifyAssemblyUseListOrder(const Module &M) { 360 TempFile F; 361 if (F.init("ll")) 362 report_fatal_error("failed to initialize assembly file"); 363 364 if (F.writeAssembly(M)) 365 report_fatal_error("failed to write assembly"); 366 367 LLVMContext Context; 368 verifyAfterRoundTrip(M, F.readAssembly(Context)); 369 } 370 371 static void verifyUseListOrder(const Module &M) { 372 outs() << "verify bitcode\n"; 373 verifyBitcodeUseListOrder(M); 374 outs() << "verify assembly\n"; 375 verifyAssemblyUseListOrder(M); 376 } 377 378 static void shuffleValueUseLists(Value *V, std::minstd_rand0 &Gen, 379 DenseSet<Value *> &Seen) { 380 if (!Seen.insert(V).second) 381 return; 382 383 if (auto *C = dyn_cast<Constant>(V)) 384 if (!isa<GlobalValue>(C)) 385 for (Value *Op : C->operands()) 386 shuffleValueUseLists(Op, Gen, Seen); 387 388 if (V->use_empty() || std::next(V->use_begin()) == V->use_end()) 389 // Nothing to shuffle for 0 or 1 users. 390 return; 391 392 // Generate random numbers between 10 and 99, which will line up nicely in 393 // debug output. We're not worried about collisons here. 394 DEBUG(dbgs() << "V = "; V->dump()); 395 std::uniform_int_distribution<short> Dist(10, 99); 396 SmallDenseMap<const Use *, short, 16> Order; 397 auto compareUses = 398 [&Order](const Use &L, const Use &R) { return Order[&L] < Order[&R]; }; 399 do { 400 for (const Use &U : V->uses()) { 401 auto I = Dist(Gen); 402 Order[&U] = I; 403 DEBUG(dbgs() << " - order: " << I << ", op = " << U.getOperandNo() 404 << ", U = "; 405 U.getUser()->dump()); 406 } 407 } while (std::is_sorted(V->use_begin(), V->use_end(), compareUses)); 408 409 DEBUG(dbgs() << " => shuffle\n"); 410 V->sortUseList(compareUses); 411 412 DEBUG({ 413 for (const Use &U : V->uses()) { 414 dbgs() << " - order: " << Order.lookup(&U) 415 << ", op = " << U.getOperandNo() << ", U = "; 416 U.getUser()->dump(); 417 } 418 }); 419 } 420 421 static void reverseValueUseLists(Value *V, DenseSet<Value *> &Seen) { 422 if (!Seen.insert(V).second) 423 return; 424 425 if (auto *C = dyn_cast<Constant>(V)) 426 if (!isa<GlobalValue>(C)) 427 for (Value *Op : C->operands()) 428 reverseValueUseLists(Op, Seen); 429 430 if (V->use_empty() || std::next(V->use_begin()) == V->use_end()) 431 // Nothing to shuffle for 0 or 1 users. 432 return; 433 434 DEBUG({ 435 dbgs() << "V = "; 436 V->dump(); 437 for (const Use &U : V->uses()) { 438 dbgs() << " - order: op = " << U.getOperandNo() << ", U = "; 439 U.getUser()->dump(); 440 } 441 dbgs() << " => reverse\n"; 442 }); 443 444 V->reverseUseList(); 445 446 DEBUG({ 447 for (const Use &U : V->uses()) { 448 dbgs() << " - order: op = " << U.getOperandNo() << ", U = "; 449 U.getUser()->dump(); 450 } 451 }); 452 } 453 454 template <class Changer> 455 static void changeUseLists(Module &M, Changer changeValueUseList) { 456 // Visit every value that would be serialized to an IR file. 457 // 458 // Globals. 459 for (GlobalVariable &G : M.globals()) 460 changeValueUseList(&G); 461 for (GlobalAlias &A : M.aliases()) 462 changeValueUseList(&A); 463 for (Function &F : M) 464 changeValueUseList(&F); 465 466 // Constants used by globals. 467 for (GlobalVariable &G : M.globals()) 468 if (G.hasInitializer()) 469 changeValueUseList(G.getInitializer()); 470 for (GlobalAlias &A : M.aliases()) 471 changeValueUseList(A.getAliasee()); 472 for (Function &F : M) { 473 if (F.hasPrefixData()) 474 changeValueUseList(F.getPrefixData()); 475 if (F.hasPrologueData()) 476 changeValueUseList(F.getPrologueData()); 477 } 478 479 // Function bodies. 480 for (Function &F : M) { 481 for (Argument &A : F.args()) 482 changeValueUseList(&A); 483 for (BasicBlock &BB : F) 484 changeValueUseList(&BB); 485 for (BasicBlock &BB : F) 486 for (Instruction &I : BB) 487 changeValueUseList(&I); 488 489 // Constants used by instructions. 490 for (BasicBlock &BB : F) 491 for (Instruction &I : BB) 492 for (Value *Op : I.operands()) 493 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) || 494 isa<InlineAsm>(Op)) 495 changeValueUseList(Op); 496 } 497 498 if (verifyModule(M, &errs())) 499 report_fatal_error("verification failed"); 500 } 501 502 static void shuffleUseLists(Module &M, unsigned SeedOffset) { 503 std::minstd_rand0 Gen(std::minstd_rand0::default_seed + SeedOffset); 504 DenseSet<Value *> Seen; 505 changeUseLists(M, [&](Value *V) { shuffleValueUseLists(V, Gen, Seen); }); 506 DEBUG(dbgs() << "\n"); 507 } 508 509 static void reverseUseLists(Module &M) { 510 DenseSet<Value *> Seen; 511 changeUseLists(M, [&](Value *V) { reverseValueUseLists(V, Seen); }); 512 DEBUG(dbgs() << "\n"); 513 } 514 515 int main(int argc, char **argv) { 516 sys::PrintStackTraceOnErrorSignal(); 517 llvm::PrettyStackTraceProgram X(argc, argv); 518 519 // Enable debug stream buffering. 520 EnableDebugBuffering = true; 521 522 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 523 LLVMContext &Context = getGlobalContext(); 524 525 cl::ParseCommandLineOptions(argc, argv, 526 "llvm tool to verify use-list order\n"); 527 528 SMDiagnostic Err; 529 530 // Load the input module... 531 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context); 532 533 if (!M.get()) { 534 Err.print(argv[0], errs()); 535 return 1; 536 } 537 if (verifyModule(*M, &errs())) { 538 errs() << argv[0] << ": " << InputFilename 539 << ": error: input module is broken!\n"; 540 return 1; 541 } 542 543 // Verify the use lists now and after reversing them. 544 outs() << "*** verify-uselistorder ***\n"; 545 verifyUseListOrder(*M); 546 outs() << "reverse\n"; 547 reverseUseLists(*M); 548 verifyUseListOrder(*M); 549 550 for (unsigned I = 0, E = NumShuffles; I != E; ++I) { 551 outs() << "\n"; 552 553 // Shuffle with a different (deterministic) seed each time. 554 outs() << "shuffle (" << I + 1 << " of " << E << ")\n"; 555 shuffleUseLists(*M, I); 556 557 // Verify again before and after reversing. 558 verifyUseListOrder(*M); 559 outs() << "reverse\n"; 560 reverseUseLists(*M); 561 verifyUseListOrder(*M); 562 } 563 564 return 0; 565 } 566