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