1 //===- verify-uselistorder.cpp - The LLVM Modular Optimizer ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 // The shuffles are deterministic, but guarantee that use-lists will change.
15 // The algorithm per iteration is as follows:
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.
20 // 2. Visit every Value in a deterministic order.
22 // 3. Assign a random number to each Use in the Value's use-list in order.
24 // 4. If the numbers are already in order, reassign numbers until they aren't.
26 // 5. Sort the use-list using Value::sortUseList(), which is a stable sort.
28 //===----------------------------------------------------------------------===//
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"
56 #define DEBUG_TYPE "uselistorder"
58 static cl::opt<std::string> InputFilename(cl::Positional,
59 cl::desc("<input bitcode file>"),
61 cl::value_desc("filename"));
63 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
66 static cl::opt<unsigned>
67 NumShuffles("num-shuffles",
68 cl::desc("Number of times to shuffle and verify use-lists"),
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;
84 DenseMap<const Value *, unsigned> IDs;
85 std::vector<const Value *> Values;
87 /// \brief Construct a value mapping for module.
89 /// Creates mapping from every value in \c M to an ID. This mapping includes
90 /// un-referencable values.
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.
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);
100 /// \brief Map a value.
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); }
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";
116 assert(!Vector.empty());
118 Filename.assign(Vector.data(), Vector.data() + Vector.size());
119 Remover.setFile(Filename, !SaveTemps);
121 outs() << " - filename = " << Filename << "\n";
125 bool TempFile::writeBitcode(const Module &M) const {
126 DEBUG(dbgs() << " - write bitcode\n");
128 raw_fd_ostream OS(Filename, EC, sys::fs::F_None);
130 errs() << "verify-uselistorder: error: " << EC.message() << "\n";
134 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
138 bool TempFile::writeAssembly(const Module &M) const {
139 DEBUG(dbgs() << " - write assembly\n");
141 raw_fd_ostream OS(Filename, EC, sys::fs::F_Text);
143 errs() << "verify-uselistorder: error: " << EC.message() << "\n";
147 M.print(OS, nullptr, /* ShouldPreserveUseListOrder */ true);
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);
156 errs() << "verify-uselistorder: error: " << BufferOr.getError().message()
161 MemoryBuffer *Buffer = BufferOr.get().get();
162 ErrorOr<std::unique_ptr<Module>> ModuleOr =
163 parseBitcodeFile(Buffer->getMemBufferRef(), Context);
165 errs() << "verify-uselistorder: error: " << ModuleOr.getError().message()
169 return std::move(ModuleOr.get());
172 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
173 DEBUG(dbgs() << " - read assembly\n");
175 std::unique_ptr<Module> M = parseAssemblyFile(Filename, Err, Context);
177 Err.print("verify-uselistorder", errs());
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.
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.
190 for (const GlobalVariable &G : M.globals())
192 for (const GlobalAlias &A : M.aliases())
194 for (const Function &F : M)
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())
203 for (const Function &F : M) {
204 if (F.hasPrefixData())
205 map(F.getPrefixData());
206 if (F.hasPrologueData())
207 map(F.getPrologueData());
211 for (const Function &F : M) {
212 for (const Argument &A : F.args())
214 for (const BasicBlock &BB : F)
216 for (const BasicBlock &BB : F)
217 for (const Instruction &I : BB)
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)) ||
230 void ValueMapping::map(const Value *V) {
234 if (auto *C = dyn_cast<Constant>(V))
235 if (!isa<GlobalValue>(C))
236 for (const Value *Op : C->operands())
240 IDs[V] = Values.size();
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();
252 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
253 const Value *V = M.Values[I];
254 dbgs() << " - " << Desc << " value = ";
256 for (const Use &U : V->uses()) {
257 dbgs() << " => use: op = " << U.getOperandNo()
258 << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
263 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
265 dbgs() << " - fail: user mismatch: ID = " << I << "\n";
266 debugValue(L, I, "LHS");
267 debugValue(R, I, "RHS");
275 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
276 dbgs() << " - fail: map size: " << L.Values.size()
277 << " != " << R.Values.size() << "\n";
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));
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()))
303 // Iterate through all values, and check that both mappings have the same
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);
315 DEBUG(debugUserMismatch(LM, RM, I));
318 if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
319 DEBUG(debugUserMismatch(LM, RM, I));
322 if (LU->getOperandNo() != RU->getOperandNo()) {
323 DEBUG(debugUserMismatch(LM, RM, I));
326 skipUnmappedUsers(++LU, LE, LM);
327 skipUnmappedUsers(++RU, RE, RM);
330 DEBUG(debugUserMismatch(LM, RM, I));
338 static void verifyAfterRoundTrip(const Module &M,
339 std::unique_ptr<Module> 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");
347 static void verifyBitcodeUseListOrder(const Module &M) {
350 report_fatal_error("failed to initialize bitcode file");
352 if (F.writeBitcode(M))
353 report_fatal_error("failed to write bitcode");
356 verifyAfterRoundTrip(M, F.readBitcode(Context));
359 static void verifyAssemblyUseListOrder(const Module &M) {
362 report_fatal_error("failed to initialize assembly file");
364 if (F.writeAssembly(M))
365 report_fatal_error("failed to write assembly");
368 verifyAfterRoundTrip(M, F.readAssembly(Context));
371 static void verifyUseListOrder(const Module &M) {
372 outs() << "verify bitcode\n";
373 verifyBitcodeUseListOrder(M);
374 outs() << "verify assembly\n";
375 verifyAssemblyUseListOrder(M);
378 static void shuffleValueUseLists(Value *V, std::minstd_rand0 &Gen,
379 DenseSet<Value *> &Seen) {
380 if (!Seen.insert(V).second)
383 if (auto *C = dyn_cast<Constant>(V))
384 if (!isa<GlobalValue>(C))
385 for (Value *Op : C->operands())
386 shuffleValueUseLists(Op, Gen, Seen);
388 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
389 // Nothing to shuffle for 0 or 1 users.
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;
398 [&Order](const Use &L, const Use &R) { return Order[&L] < Order[&R]; };
400 for (const Use &U : V->uses()) {
403 DEBUG(dbgs() << " - order: " << I << ", op = " << U.getOperandNo()
405 U.getUser()->dump());
407 } while (std::is_sorted(V->use_begin(), V->use_end(), compareUses));
409 DEBUG(dbgs() << " => shuffle\n");
410 V->sortUseList(compareUses);
413 for (const Use &U : V->uses()) {
414 dbgs() << " - order: " << Order.lookup(&U)
415 << ", op = " << U.getOperandNo() << ", U = ";
421 static void reverseValueUseLists(Value *V, DenseSet<Value *> &Seen) {
422 if (!Seen.insert(V).second)
425 if (auto *C = dyn_cast<Constant>(V))
426 if (!isa<GlobalValue>(C))
427 for (Value *Op : C->operands())
428 reverseValueUseLists(Op, Seen);
430 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
431 // Nothing to shuffle for 0 or 1 users.
437 for (const Use &U : V->uses()) {
438 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
441 dbgs() << " => reverse\n";
447 for (const Use &U : V->uses()) {
448 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
454 template <class Changer>
455 static void changeUseLists(Module &M, Changer changeValueUseList) {
456 // Visit every value that would be serialized to an IR file.
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);
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());
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);
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)) ||
495 changeValueUseList(Op);
498 if (verifyModule(M, &errs()))
499 report_fatal_error("verification failed");
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");
509 static void reverseUseLists(Module &M) {
510 DenseSet<Value *> Seen;
511 changeUseLists(M, [&](Value *V) { reverseValueUseLists(V, Seen); });
512 DEBUG(dbgs() << "\n");
515 int main(int argc, char **argv) {
516 sys::PrintStackTraceOnErrorSignal();
517 llvm::PrettyStackTraceProgram X(argc, argv);
519 // Enable debug stream buffering.
520 EnableDebugBuffering = true;
522 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
523 LLVMContext &Context = getGlobalContext();
525 cl::ParseCommandLineOptions(argc, argv,
526 "llvm tool to verify use-list order\n");
530 // Load the input module...
531 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
534 Err.print(argv[0], errs());
537 if (verifyModule(*M, &errs())) {
538 errs() << argv[0] << ": " << InputFilename
539 << ": error: input module is broken!\n";
543 // Verify the use lists now and after reversing them.
544 outs() << "*** verify-uselistorder ***\n";
545 verifyUseListOrder(*M);
546 outs() << "reverse\n";
548 verifyUseListOrder(*M);
550 for (unsigned I = 0, E = NumShuffles; I != E; ++I) {
553 // Shuffle with a different (deterministic) seed each time.
554 outs() << "shuffle (" << I + 1 << " of " << E << ")\n";
555 shuffleUseLists(*M, I);
557 // Verify again before and after reversing.
558 verifyUseListOrder(*M);
559 outs() << "reverse\n";
561 verifyUseListOrder(*M);