1 //===- llvm-reduce.cpp - The LLVM Delta Reduction utility -----------------===//
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 // This program tries to reduce an IR test case for a given interesting-ness
10 // test. It runs multiple delta debugging passes in order to minimize the input
11 // file. It's worth noting that this is a part of the bugpoint redesign
12 // proposal, and thus a *temporary* tool that will eventually be integrated
13 // into the bugpoint tool itself.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "DeltaManager.h"
18 #include "ReducerWorkItem.h"
19 #include "TestRunner.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/CodeGen/CommandFlags.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/MC/TargetRegistry.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Host.h"
28 #include "llvm/Support/InitLLVM.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/TargetSelect.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/WithColor.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include <system_error>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 cl::OptionCategory LLVMReduceOptions("llvm-reduce options");
40 
41 static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden,
42                           cl::cat(LLVMReduceOptions));
43 static cl::opt<bool> Version("v", cl::desc("Alias for -version"), cl::Hidden,
44                              cl::cat(LLVMReduceOptions));
45 
46 static cl::opt<bool>
47     PrintDeltaPasses("print-delta-passes",
48                      cl::desc("Print list of delta passes, passable to "
49                               "--delta-passes as a comma separated list"),
50                      cl::cat(LLVMReduceOptions));
51 
52 static cl::opt<std::string> InputFilename(cl::Positional, cl::Required,
53                                           cl::desc("<input llvm ll/bc file>"),
54                                           cl::cat(LLVMReduceOptions));
55 
56 static cl::opt<std::string>
57     TestFilename("test", cl::Required,
58                  cl::desc("Name of the interesting-ness test to be run"),
59                  cl::cat(LLVMReduceOptions));
60 
61 static cl::list<std::string>
62     TestArguments("test-arg", cl::ZeroOrMore,
63                   cl::desc("Arguments passed onto the interesting-ness test"),
64                   cl::cat(LLVMReduceOptions));
65 
66 static cl::opt<std::string> OutputFilename(
67     "output", cl::desc("Specify the output file. default: reduced.ll|mir"));
68 static cl::alias OutputFileAlias("o", cl::desc("Alias for -output"),
69                                  cl::aliasopt(OutputFilename),
70                                  cl::cat(LLVMReduceOptions));
71 
72 static cl::opt<bool>
73     ReplaceInput("in-place",
74                  cl::desc("WARNING: This option will replace your input file "
75                           "with the reduced version!"),
76                  cl::cat(LLVMReduceOptions));
77 
78 enum class InputLanguages { None, IR, MIR };
79 
80 static cl::opt<InputLanguages>
81     InputLanguage("x", cl::ValueOptional,
82                   cl::desc("Input language ('ir' or 'mir')"),
83                   cl::init(InputLanguages::None),
84                   cl::values(clEnumValN(InputLanguages::IR, "ir", ""),
85                              clEnumValN(InputLanguages::MIR, "mir", "")),
86                   cl::cat(LLVMReduceOptions));
87 
88 static cl::opt<std::string> TargetTriple("mtriple",
89                                          cl::desc("Set the target triple"),
90                                          cl::cat(LLVMReduceOptions));
91 
92 static cl::opt<int>
93     MaxPassIterations("max-pass-iterations",
94                       cl::desc("Maximum number of times to run the full set "
95                                "of delta passes (default=1)"),
96                       cl::init(1), cl::cat(LLVMReduceOptions));
97 
98 static codegen::RegisterCodeGenFlags CGF;
99 
100 void writeOutput(ReducerWorkItem &M, StringRef Message) {
101   if (ReplaceInput) // In-place
102     OutputFilename = InputFilename.c_str();
103   else if (OutputFilename.empty() || OutputFilename == "-")
104     OutputFilename = M.isMIR() ? "reduced.mir" : "reduced.ll";
105   std::error_code EC;
106   raw_fd_ostream Out(OutputFilename, EC);
107   if (EC) {
108     errs() << "Error opening output file: " << EC.message() << "!\n";
109     exit(1);
110   }
111   M.print(Out, /*AnnotationWriter=*/nullptr);
112   errs() << Message << OutputFilename << "\n";
113 }
114 
115 static std::unique_ptr<LLVMTargetMachine> createTargetMachine() {
116   InitializeAllTargets();
117   InitializeAllTargetMCs();
118   InitializeAllAsmPrinters();
119   InitializeAllAsmParsers();
120 
121   if (TargetTriple == "")
122     TargetTriple = sys::getDefaultTargetTriple();
123   auto TT(Triple::normalize(TargetTriple));
124   std::string CPU(codegen::getCPUStr());
125   std::string FS(codegen::getFeaturesStr());
126 
127   std::string Error;
128   const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error);
129 
130   return std::unique_ptr<LLVMTargetMachine>(
131       static_cast<LLVMTargetMachine *>(TheTarget->createTargetMachine(
132           TT, CPU, FS, TargetOptions(), None, None, CodeGenOpt::Default)));
133 }
134 
135 int main(int Argc, char **Argv) {
136   InitLLVM X(Argc, Argv);
137 
138   cl::HideUnrelatedOptions({&LLVMReduceOptions, &getColorCategory()});
139   cl::ParseCommandLineOptions(Argc, Argv, "LLVM automatic testcase reducer.\n");
140 
141   bool ReduceModeMIR = false;
142   if (InputLanguage != InputLanguages::None) {
143     if (InputLanguage == InputLanguages::MIR)
144       ReduceModeMIR = true;
145   } else if (StringRef(InputFilename).endswith(".mir")) {
146     ReduceModeMIR = true;
147   }
148 
149   if (PrintDeltaPasses) {
150     printDeltaPasses(errs());
151     return 0;
152   }
153 
154   LLVMContext Context;
155   std::unique_ptr<LLVMTargetMachine> TM;
156   std::unique_ptr<MachineModuleInfo> MMI;
157   std::unique_ptr<ReducerWorkItem> OriginalProgram;
158   if (ReduceModeMIR) {
159     TM = createTargetMachine();
160     MMI = std::make_unique<MachineModuleInfo>(TM.get());
161   }
162   OriginalProgram = parseReducerWorkItem(InputFilename, Context, MMI.get());
163   if (!OriginalProgram) {
164     return 1;
165   }
166 
167   // Initialize test environment
168   TestRunner Tester(TestFilename, TestArguments, std::move(OriginalProgram));
169 
170   // Try to reduce code
171   runDeltaPasses(Tester, MaxPassIterations);
172 
173   // Print reduced file to STDOUT
174   if (OutputFilename == "-")
175     Tester.getProgram().print(outs(), nullptr);
176   else
177     writeOutput(Tester.getProgram(), "\nDone reducing! Reduced testcase: ");
178 
179   return 0;
180 }
181