llvm-uselistorder: Add -save-temps option
[oota-llvm.git] / tools / llvm-uselistorder / llvm-uselistorder.cpp
1 //===- opt.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 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/AsmParser/Parser.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/UseListOrder.h"
21 #include "llvm/IRReader/IRReader.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/FileUtilities.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/SystemUtils.h"
33
34 using namespace llvm;
35
36 #define DEBUG_TYPE "use-list-order"
37
38 static cl::opt<std::string> InputFilename(cl::Positional,
39                                           cl::desc("<input bitcode file>"),
40                                           cl::init("-"),
41                                           cl::value_desc("filename"));
42
43 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
44                                cl::init(false));
45
46 namespace {
47
48 struct TempFile {
49   std::string Filename;
50   FileRemover Remover;
51   bool init(const std::string &Ext);
52   bool writeBitcode(const Module &M) const;
53   bool writeAssembly(const Module &M) const;
54   std::unique_ptr<Module> readBitcode(LLVMContext &Context) const;
55   std::unique_ptr<Module> readAssembly(LLVMContext &Context) const;
56 };
57
58 struct ValueMapping {
59   DenseMap<const Value *, unsigned> IDs;
60   std::vector<const Value *> Values;
61
62   /// \brief Construct a value mapping for module.
63   ///
64   /// Creates mapping from every value in \c M to an ID.  This mapping includes
65   /// un-referencable values.
66   ///
67   /// Every \a Value that gets serialized in some way should be represented
68   /// here.  The order needs to be deterministic, but it's unnecessary to match
69   /// the value-ids in the bitcode writer.
70   ///
71   /// All constants that are referenced by other values are included in the
72   /// mapping, but others -- which wouldn't be serialized -- are not.
73   ValueMapping(const Module &M);
74
75   /// \brief Map a value.
76   ///
77   /// Maps a value.  If it's a constant, maps all of its operands first.
78   void map(const Value *V);
79   unsigned lookup(const Value *V) const { return IDs.lookup(V); }
80 };
81
82 } // end namespace
83
84 bool TempFile::init(const std::string &Ext) {
85   SmallVector<char, 64> Vector;
86   DEBUG(dbgs() << " - create-temp-file\n");
87   if (auto EC = sys::fs::createTemporaryFile("use-list-order", Ext, Vector)) {
88     (void)EC;
89     DEBUG(dbgs() << "error: " << EC.message() << "\n");
90     return true;
91   }
92   assert(!Vector.empty());
93
94   Filename.assign(Vector.data(), Vector.data() + Vector.size());
95   Remover.setFile(Filename, !SaveTemps);
96   DEBUG(dbgs() << " - filename = " << Filename << "\n");
97   return false;
98 }
99
100 bool TempFile::writeBitcode(const Module &M) const {
101   DEBUG(dbgs() << " - write bitcode\n");
102   std::string ErrorInfo;
103   raw_fd_ostream OS(Filename.c_str(), ErrorInfo, sys::fs::F_None);
104   if (!ErrorInfo.empty()) {
105     DEBUG(dbgs() << "error: " << ErrorInfo << "\n");
106     return true;
107   }
108
109   WriteBitcodeToFile(&M, OS);
110   return false;
111 }
112
113 bool TempFile::writeAssembly(const Module &M) const {
114   DEBUG(dbgs() << " - write assembly\n");
115   std::string ErrorInfo;
116   raw_fd_ostream OS(Filename.c_str(), ErrorInfo, sys::fs::F_Text);
117   if (!ErrorInfo.empty()) {
118     DEBUG(dbgs() << "error: " << ErrorInfo << "\n");
119     return true;
120   }
121
122   OS << M;
123   return false;
124 }
125
126 std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const {
127   DEBUG(dbgs() << " - read bitcode\n");
128   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOr =
129       MemoryBuffer::getFile(Filename);
130   if (!BufferOr) {
131     DEBUG(dbgs() << "error: " << BufferOr.getError().message() << "\n");
132     return nullptr;
133   }
134
135   std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOr.get());
136   ErrorOr<Module *> ModuleOr = parseBitcodeFile(Buffer.release(), Context);
137   if (!ModuleOr) {
138     DEBUG(dbgs() << "error: " << ModuleOr.getError().message() << "\n");
139     return nullptr;
140   }
141   return std::unique_ptr<Module>(ModuleOr.get());
142 }
143
144 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
145   DEBUG(dbgs() << " - read assembly\n");
146   SMDiagnostic Err;
147   std::unique_ptr<Module> M(ParseAssemblyFile(Filename, Err, Context));
148   if (!M.get())
149     DEBUG(dbgs() << "error: "; Err.print("verify-use-list-order", dbgs()));
150   return M;
151 }
152
153 ValueMapping::ValueMapping(const Module &M) {
154   // Every value should be mapped, including things like void instructions and
155   // basic blocks that are kept out of the ValueEnumerator.
156   //
157   // The current mapping order makes it easier to debug the tables.  It happens
158   // to be similar to the ID mapping when writing ValueEnumerator, but they
159   // aren't (and needn't be) in sync.
160
161   // Globals.
162   for (const GlobalVariable &G : M.globals())
163     map(&G);
164   for (const GlobalAlias &A : M.aliases())
165     map(&A);
166   for (const Function &F : M)
167     map(&F);
168
169   // Constants used by globals.
170   for (const GlobalVariable &G : M.globals())
171     if (G.hasInitializer())
172       map(G.getInitializer());
173   for (const GlobalAlias &A : M.aliases())
174     map(A.getAliasee());
175   for (const Function &F : M)
176     if (F.hasPrefixData())
177       map(F.getPrefixData());
178
179   // Function bodies.
180   for (const Function &F : M) {
181     for (const Argument &A : F.args())
182       map(&A);
183     for (const BasicBlock &BB : F)
184       map(&BB);
185     for (const BasicBlock &BB : F)
186       for (const Instruction &I : BB)
187         map(&I);
188
189     // Constants used by instructions.
190     for (const BasicBlock &BB : F)
191       for (const Instruction &I : BB)
192         for (const Value *Op : I.operands())
193           if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
194               isa<InlineAsm>(Op))
195             map(Op);
196   }
197 }
198
199 void ValueMapping::map(const Value *V) {
200   if (IDs.lookup(V))
201     return;
202
203   if (auto *C = dyn_cast<Constant>(V))
204     if (!isa<GlobalValue>(C))
205       for (const Value *Op : C->operands())
206         map(Op);
207
208   Values.push_back(V);
209   IDs[V] = Values.size();
210 }
211
212 #ifndef NDEBUG
213 static void dumpMapping(const ValueMapping &VM) {
214   dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n";
215   for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) {
216     dbgs() << " - id = " << I << ", value = ";
217     VM.Values[I]->dump();
218   }
219 }
220
221 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
222   const Value *V = M.Values[I];
223   dbgs() << " - " << Desc << " value = ";
224   V->dump();
225   for (const Use &U : V->uses()) {
226     dbgs() << "   => use: op = " << U.getOperandNo()
227            << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
228     U.getUser()->dump();
229   }
230 }
231
232 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
233                               unsigned I) {
234   dbgs() << " - fail: user mismatch: ID = " << I << "\n";
235   debugValue(L, I, "LHS");
236   debugValue(R, I, "RHS");
237
238   dbgs() << "\nlhs-";
239   dumpMapping(L);
240   dbgs() << "\nrhs-";
241   dumpMapping(R);
242 }
243
244 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
245   dbgs() << " - fail: map size: " << L.Values.size()
246          << " != " << R.Values.size() << "\n";
247   dbgs() << "\nlhs-";
248   dumpMapping(L);
249   dbgs() << "\nrhs-";
250   dumpMapping(R);
251 }
252 #endif
253
254 static bool matches(const ValueMapping &LM, const ValueMapping &RM) {
255   DEBUG(dbgs() << "compare value maps\n");
256   if (LM.Values.size() != RM.Values.size()) {
257     DEBUG(debugSizeMismatch(LM, RM));
258     return false;
259   }
260
261   // This mapping doesn't include dangling constant users, since those don't
262   // get serialized.  However, checking if users are constant and calling
263   // isConstantUsed() on every one is very expensive.  Instead, just check if
264   // the user is mapped.
265   auto skipUnmappedUsers =
266       [&](Value::const_use_iterator &U, Value::const_use_iterator E,
267           const ValueMapping &M) {
268     while (U != E && !M.lookup(U->getUser()))
269       ++U;
270   };
271
272   // Iterate through all values, and check that both mappings have the same
273   // users.
274   for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) {
275     const Value *L = LM.Values[I];
276     const Value *R = RM.Values[I];
277     auto LU = L->use_begin(), LE = L->use_end();
278     auto RU = R->use_begin(), RE = R->use_end();
279     skipUnmappedUsers(LU, LE, LM);
280     skipUnmappedUsers(RU, RE, RM);
281
282     while (LU != LE) {
283       if (RU == RE) {
284         DEBUG(debugUserMismatch(LM, RM, I));
285         return false;
286       }
287       if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
288         DEBUG(debugUserMismatch(LM, RM, I));
289         return false;
290       }
291       if (LU->getOperandNo() != RU->getOperandNo()) {
292         DEBUG(debugUserMismatch(LM, RM, I));
293         return false;
294       }
295       skipUnmappedUsers(++LU, LE, LM);
296       skipUnmappedUsers(++RU, RE, RM);
297     }
298     if (RU != RE) {
299       DEBUG(debugUserMismatch(LM, RM, I));
300       return false;
301     }
302   }
303
304   return true;
305 }
306
307 static bool verifyBitcodeUseListOrder(const Module &M) {
308   DEBUG(dbgs() << "*** verify-use-list-order: bitcode ***\n");
309   TempFile F;
310   if (F.init("bc"))
311     return false;
312
313   if (F.writeBitcode(M))
314     return false;
315
316   LLVMContext Context;
317   std::unique_ptr<Module> OtherM = F.readBitcode(Context);
318   if (!OtherM)
319     return false;
320
321   return matches(ValueMapping(M), ValueMapping(*OtherM));
322 }
323
324 static bool verifyAssemblyUseListOrder(const Module &M) {
325   DEBUG(dbgs() << "*** verify-use-list-order: assembly ***\n");
326   TempFile F;
327   if (F.init("ll"))
328     return false;
329
330   if (F.writeAssembly(M))
331     return false;
332
333   LLVMContext Context;
334   std::unique_ptr<Module> OtherM = F.readAssembly(Context);
335   if (!OtherM)
336     return false;
337
338   return matches(ValueMapping(M), ValueMapping(*OtherM));
339 }
340
341 int main(int argc, char **argv) {
342   sys::PrintStackTraceOnErrorSignal();
343   llvm::PrettyStackTraceProgram X(argc, argv);
344
345   // Enable debug stream buffering.
346   EnableDebugBuffering = true;
347
348   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
349   LLVMContext &Context = getGlobalContext();
350
351   cl::ParseCommandLineOptions(argc, argv,
352                               "llvm tool to verify use-list order\n");
353
354   SMDiagnostic Err;
355
356   // Load the input module...
357   std::unique_ptr<Module> M;
358   M.reset(ParseIRFile(InputFilename, Err, Context));
359
360   if (!M.get()) {
361     Err.print(argv[0], errs());
362     return 1;
363   }
364
365   DEBUG(dbgs() << "*** verify-use-list-order ***\n");
366   if (!shouldPreserveBitcodeUseListOrder()) {
367     // Can't verify if order isn't preserved.
368     DEBUG(dbgs() << "warning: cannot verify bitcode; "
369                     "try -preserve-bc-use-list-order\n");
370     return 0;
371   }
372
373   shuffleUseLists(*M);
374   if (!verifyBitcodeUseListOrder(*M))
375     report_fatal_error("bitcode use-list order changed");
376
377   if (shouldPreserveAssemblyUseListOrder())
378     if (!verifyAssemblyUseListOrder(*M))
379       report_fatal_error("assembly use-list order changed");
380
381   return 0;
382 }