[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / llvm / tools / verify-uselistorder / verify-uselistorder.cpp
blob9afe6817fefb9f7f6fb7b7e0ab931c3c617844a6
1 //===- verify-uselistorder.cpp - The LLVM Modular Optimizer ---------------===//
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 // Verify that use-list order can be serialized correctly. After reading the
10 // provided IR, this tool shuffles the use-lists and then writes and reads to a
11 // separate Module whose use-list orders are compared to the original.
13 // The shuffles are deterministic, but guarantee that use-lists will change.
14 // The algorithm per iteration is as follows:
16 // 1. Seed the random number generator. The seed is different for each
17 // shuffle. Shuffle 0 uses default+0, shuffle 1 uses default+1, and so on.
19 // 2. Visit every Value in a deterministic order.
21 // 3. Assign a random number to each Use in the Value's use-list in order.
23 // 4. If the numbers are already in order, reassign numbers until they aren't.
25 // 5. Sort the use-list using Value::sortUseList(), which is a stable sort.
27 //===----------------------------------------------------------------------===//
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/AsmParser/Parser.h"
32 #include "llvm/Bitcode/BitcodeReader.h"
33 #include "llvm/Bitcode/BitcodeWriter.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/InitLLVM.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/SystemUtils.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <random>
50 #include <vector>
52 using namespace llvm;
54 #define DEBUG_TYPE "uselistorder"
56 static cl::OptionCategory Cat("verify-uselistorder Options");
58 static cl::opt<std::string> InputFilename(cl::Positional,
59 cl::desc("<input bitcode file>"),
60 cl::init("-"),
61 cl::value_desc("filename"));
63 static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temp files"),
64 cl::cat(Cat));
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), cl::cat(Cat));
71 namespace {
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;
83 struct ValueMapping {
84 DenseMap<const Value *, unsigned> IDs;
85 std::vector<const Value *> Values;
87 /// 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);
100 /// 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); }
107 } // end namespace
109 bool TempFile::init(const std::string &Ext) {
110 SmallVector<char, 64> Vector;
111 LLVM_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;
116 assert(!Vector.empty());
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;
125 bool TempFile::writeBitcode(const Module &M) const {
126 LLVM_DEBUG(dbgs() << " - write bitcode\n");
127 std::error_code EC;
128 raw_fd_ostream OS(Filename, EC, sys::fs::OF_None);
129 if (EC) {
130 errs() << "verify-uselistorder: error: " << EC.message() << "\n";
131 return true;
134 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
135 return false;
138 bool TempFile::writeAssembly(const Module &M) const {
139 LLVM_DEBUG(dbgs() << " - write assembly\n");
140 std::error_code EC;
141 raw_fd_ostream OS(Filename, EC, sys::fs::OF_TextWithCRLF);
142 if (EC) {
143 errs() << "verify-uselistorder: error: " << EC.message() << "\n";
144 return true;
147 M.print(OS, nullptr, /* ShouldPreserveUseListOrder */ true);
148 return false;
151 std::unique_ptr<Module> TempFile::readBitcode(LLVMContext &Context) const {
152 LLVM_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;
161 MemoryBuffer *Buffer = BufferOr.get().get();
162 Expected<std::unique_ptr<Module>> ModuleOr =
163 parseBitcodeFile(Buffer->getMemBufferRef(), Context);
164 if (!ModuleOr) {
165 logAllUnhandledErrors(ModuleOr.takeError(), errs(),
166 "verify-uselistorder: error: ");
167 return nullptr;
169 return std::move(ModuleOr.get());
172 std::unique_ptr<Module> TempFile::readAssembly(LLVMContext &Context) const {
173 LLVM_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;
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.
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 GlobalIFunc &IF : M.ifuncs())
195 map(&IF);
196 for (const Function &F : M)
197 map(&F);
199 // Constants used by globals.
200 for (const GlobalVariable &G : M.globals())
201 if (G.hasInitializer())
202 map(G.getInitializer());
203 for (const GlobalAlias &A : M.aliases())
204 map(A.getAliasee());
205 for (const GlobalIFunc &IF : M.ifuncs())
206 map(IF.getResolver());
207 for (const Function &F : M)
208 for (Value *Op : F.operands())
209 map(Op);
211 // Function bodies.
212 for (const Function &F : M) {
213 for (const Argument &A : F.args())
214 map(&A);
215 for (const BasicBlock &BB : F)
216 map(&BB);
217 for (const BasicBlock &BB : F)
218 for (const Instruction &I : BB)
219 map(&I);
221 // Constants used by instructions.
222 for (const BasicBlock &BB : F)
223 for (const Instruction &I : BB)
224 for (const Value *Op : I.operands()) {
225 // Look through a metadata wrapper.
226 if (const auto *MAV = dyn_cast<MetadataAsValue>(Op))
227 if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
228 Op = VAM->getValue();
230 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
231 isa<InlineAsm>(Op))
232 map(Op);
237 void ValueMapping::map(const Value *V) {
238 if (IDs.lookup(V))
239 return;
241 if (auto *C = dyn_cast<Constant>(V))
242 if (!isa<GlobalValue>(C))
243 for (const Value *Op : C->operands())
244 map(Op);
246 Values.push_back(V);
247 IDs[V] = Values.size();
250 #ifndef NDEBUG
251 static void dumpMapping(const ValueMapping &VM) {
252 dbgs() << "value-mapping (size = " << VM.Values.size() << "):\n";
253 for (unsigned I = 0, E = VM.Values.size(); I != E; ++I) {
254 dbgs() << " - id = " << I << ", value = ";
255 VM.Values[I]->dump();
259 static void debugValue(const ValueMapping &M, unsigned I, StringRef Desc) {
260 const Value *V = M.Values[I];
261 dbgs() << " - " << Desc << " value = ";
262 V->dump();
263 for (const Use &U : V->uses()) {
264 dbgs() << " => use: op = " << U.getOperandNo()
265 << ", user-id = " << M.IDs.lookup(U.getUser()) << ", user = ";
266 U.getUser()->dump();
270 static void debugUserMismatch(const ValueMapping &L, const ValueMapping &R,
271 unsigned I) {
272 dbgs() << " - fail: user mismatch: ID = " << I << "\n";
273 debugValue(L, I, "LHS");
274 debugValue(R, I, "RHS");
276 dbgs() << "\nlhs-";
277 dumpMapping(L);
278 dbgs() << "\nrhs-";
279 dumpMapping(R);
282 static void debugSizeMismatch(const ValueMapping &L, const ValueMapping &R) {
283 dbgs() << " - fail: map size: " << L.Values.size()
284 << " != " << R.Values.size() << "\n";
285 dbgs() << "\nlhs-";
286 dumpMapping(L);
287 dbgs() << "\nrhs-";
288 dumpMapping(R);
290 #endif
292 static bool matches(const ValueMapping &LM, const ValueMapping &RM) {
293 LLVM_DEBUG(dbgs() << "compare value maps\n");
294 if (LM.Values.size() != RM.Values.size()) {
295 LLVM_DEBUG(debugSizeMismatch(LM, RM));
296 return false;
299 // This mapping doesn't include dangling constant users, since those don't
300 // get serialized. However, checking if users are constant and calling
301 // isConstantUsed() on every one is very expensive. Instead, just check if
302 // the user is mapped.
303 auto skipUnmappedUsers =
304 [&](Value::const_use_iterator &U, Value::const_use_iterator E,
305 const ValueMapping &M) {
306 while (U != E && !M.lookup(U->getUser()))
307 ++U;
310 // Iterate through all values, and check that both mappings have the same
311 // users.
312 for (unsigned I = 0, E = LM.Values.size(); I != E; ++I) {
313 const Value *L = LM.Values[I];
314 const Value *R = RM.Values[I];
315 auto LU = L->use_begin(), LE = L->use_end();
316 auto RU = R->use_begin(), RE = R->use_end();
317 skipUnmappedUsers(LU, LE, LM);
318 skipUnmappedUsers(RU, RE, RM);
320 while (LU != LE) {
321 if (RU == RE) {
322 LLVM_DEBUG(debugUserMismatch(LM, RM, I));
323 return false;
325 if (LM.lookup(LU->getUser()) != RM.lookup(RU->getUser())) {
326 LLVM_DEBUG(debugUserMismatch(LM, RM, I));
327 return false;
329 if (LU->getOperandNo() != RU->getOperandNo()) {
330 LLVM_DEBUG(debugUserMismatch(LM, RM, I));
331 return false;
333 skipUnmappedUsers(++LU, LE, LM);
334 skipUnmappedUsers(++RU, RE, RM);
336 if (RU != RE) {
337 LLVM_DEBUG(debugUserMismatch(LM, RM, I));
338 return false;
342 return true;
345 static void verifyAfterRoundTrip(const Module &M,
346 std::unique_ptr<Module> OtherM) {
347 if (!OtherM)
348 report_fatal_error("parsing failed");
349 if (verifyModule(*OtherM, &errs()))
350 report_fatal_error("verification failed");
351 if (!matches(ValueMapping(M), ValueMapping(*OtherM)))
352 report_fatal_error("use-list order changed");
355 static void verifyBitcodeUseListOrder(const Module &M) {
356 TempFile F;
357 if (F.init("bc"))
358 report_fatal_error("failed to initialize bitcode file");
360 if (F.writeBitcode(M))
361 report_fatal_error("failed to write bitcode");
363 LLVMContext Context;
364 verifyAfterRoundTrip(M, F.readBitcode(Context));
367 static void verifyAssemblyUseListOrder(const Module &M) {
368 TempFile F;
369 if (F.init("ll"))
370 report_fatal_error("failed to initialize assembly file");
372 if (F.writeAssembly(M))
373 report_fatal_error("failed to write assembly");
375 LLVMContext Context;
376 verifyAfterRoundTrip(M, F.readAssembly(Context));
379 static void verifyUseListOrder(const Module &M) {
380 outs() << "verify bitcode\n";
381 verifyBitcodeUseListOrder(M);
382 outs() << "verify assembly\n";
383 verifyAssemblyUseListOrder(M);
386 static void shuffleValueUseLists(Value *V, std::minstd_rand0 &Gen,
387 DenseSet<Value *> &Seen) {
388 if (!Seen.insert(V).second)
389 return;
391 if (auto *C = dyn_cast<Constant>(V))
392 if (!isa<GlobalValue>(C))
393 for (Value *Op : C->operands())
394 shuffleValueUseLists(Op, Gen, Seen);
396 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
397 // Nothing to shuffle for 0 or 1 users.
398 return;
400 // Generate random numbers between 10 and 99, which will line up nicely in
401 // debug output. We're not worried about collisions here.
402 LLVM_DEBUG(dbgs() << "V = "; V->dump());
403 std::uniform_int_distribution<short> Dist(10, 99);
404 SmallDenseMap<const Use *, short, 16> Order;
405 auto compareUses =
406 [&Order](const Use &L, const Use &R) { return Order[&L] < Order[&R]; };
407 do {
408 for (const Use &U : V->uses()) {
409 auto I = Dist(Gen);
410 Order[&U] = I;
411 LLVM_DEBUG(dbgs() << " - order: " << I << ", op = " << U.getOperandNo()
412 << ", U = ";
413 U.getUser()->dump());
415 } while (std::is_sorted(V->use_begin(), V->use_end(), compareUses));
417 LLVM_DEBUG(dbgs() << " => shuffle\n");
418 V->sortUseList(compareUses);
420 LLVM_DEBUG({
421 for (const Use &U : V->uses()) {
422 dbgs() << " - order: " << Order.lookup(&U)
423 << ", op = " << U.getOperandNo() << ", U = ";
424 U.getUser()->dump();
429 static void reverseValueUseLists(Value *V, DenseSet<Value *> &Seen) {
430 if (!Seen.insert(V).second)
431 return;
433 if (auto *C = dyn_cast<Constant>(V))
434 if (!isa<GlobalValue>(C))
435 for (Value *Op : C->operands())
436 reverseValueUseLists(Op, Seen);
438 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
439 // Nothing to shuffle for 0 or 1 users.
440 return;
442 LLVM_DEBUG({
443 dbgs() << "V = ";
444 V->dump();
445 for (const Use &U : V->uses()) {
446 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
447 U.getUser()->dump();
449 dbgs() << " => reverse\n";
452 V->reverseUseList();
454 LLVM_DEBUG({
455 for (const Use &U : V->uses()) {
456 dbgs() << " - order: op = " << U.getOperandNo() << ", U = ";
457 U.getUser()->dump();
462 template <class Changer>
463 static void changeUseLists(Module &M, Changer changeValueUseList) {
464 // Visit every value that would be serialized to an IR file.
466 // Globals.
467 for (GlobalVariable &G : M.globals())
468 changeValueUseList(&G);
469 for (GlobalAlias &A : M.aliases())
470 changeValueUseList(&A);
471 for (GlobalIFunc &IF : M.ifuncs())
472 changeValueUseList(&IF);
473 for (Function &F : M)
474 changeValueUseList(&F);
476 // Constants used by globals.
477 for (GlobalVariable &G : M.globals())
478 if (G.hasInitializer())
479 changeValueUseList(G.getInitializer());
480 for (GlobalAlias &A : M.aliases())
481 changeValueUseList(A.getAliasee());
482 for (GlobalIFunc &IF : M.ifuncs())
483 changeValueUseList(IF.getResolver());
484 for (Function &F : M)
485 for (Value *Op : F.operands())
486 changeValueUseList(Op);
488 // Function bodies.
489 for (Function &F : M) {
490 for (Argument &A : F.args())
491 changeValueUseList(&A);
492 for (BasicBlock &BB : F)
493 changeValueUseList(&BB);
494 for (BasicBlock &BB : F)
495 for (Instruction &I : BB)
496 changeValueUseList(&I);
498 // Constants used by instructions.
499 for (BasicBlock &BB : F)
500 for (Instruction &I : BB)
501 for (Value *Op : I.operands()) {
502 // Look through a metadata wrapper.
503 if (auto *MAV = dyn_cast<MetadataAsValue>(Op))
504 if (auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
505 Op = VAM->getValue();
506 if ((isa<Constant>(Op) && !isa<GlobalValue>(*Op)) ||
507 isa<InlineAsm>(Op))
508 changeValueUseList(Op);
512 if (verifyModule(M, &errs()))
513 report_fatal_error("verification failed");
516 static void shuffleUseLists(Module &M, unsigned SeedOffset) {
517 std::minstd_rand0 Gen(std::minstd_rand0::default_seed + SeedOffset);
518 DenseSet<Value *> Seen;
519 changeUseLists(M, [&](Value *V) { shuffleValueUseLists(V, Gen, Seen); });
520 LLVM_DEBUG(dbgs() << "\n");
523 static void reverseUseLists(Module &M) {
524 DenseSet<Value *> Seen;
525 changeUseLists(M, [&](Value *V) { reverseValueUseLists(V, Seen); });
526 LLVM_DEBUG(dbgs() << "\n");
529 int main(int argc, char **argv) {
530 InitLLVM X(argc, argv);
532 // Enable debug stream buffering.
533 EnableDebugBuffering = true;
535 cl::HideUnrelatedOptions(Cat);
536 cl::ParseCommandLineOptions(argc, argv,
537 "llvm tool to verify use-list order\n");
539 LLVMContext Context;
540 SMDiagnostic Err;
542 // Load the input module...
543 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
545 if (!M.get()) {
546 Err.print(argv[0], errs());
547 return 1;
549 if (verifyModule(*M, &errs())) {
550 errs() << argv[0] << ": " << InputFilename
551 << ": error: input module is broken!\n";
552 return 1;
555 // Verify the use lists now and after reversing them.
556 outs() << "*** verify-uselistorder ***\n";
557 verifyUseListOrder(*M);
558 outs() << "reverse\n";
559 reverseUseLists(*M);
560 verifyUseListOrder(*M);
562 for (unsigned I = 0, E = NumShuffles; I != E; ++I) {
563 outs() << "\n";
565 // Shuffle with a different (deterministic) seed each time.
566 outs() << "shuffle (" << I + 1 << " of " << E << ")\n";
567 shuffleUseLists(*M, I);
569 // Verify again before and after reversing.
570 verifyUseListOrder(*M);
571 outs() << "reverse\n";
572 reverseUseLists(*M);
573 verifyUseListOrder(*M);
576 return 0;