1//===--- llvm-isel-fuzzer.cpp - Fuzzer for instruction selection ----------===//
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// Tool to fuzz instruction selection using libFuzzer.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/StringRef.h"
14#include "llvm/Analysis/TargetLibraryInfo.h"
15#include "llvm/Bitcode/BitcodeReader.h"
16#include "llvm/Bitcode/BitcodeWriter.h"
17#include "llvm/CodeGen/CommandFlags.h"
18#include "llvm/FuzzMutate/FuzzerCLI.h"
19#include "llvm/FuzzMutate/IRMutator.h"
20#include "llvm/FuzzMutate/Operations.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/LegacyPassManager.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Verifier.h"
26#include "llvm/IRReader/IRReader.h"
27#include "llvm/MC/TargetRegistry.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/DataTypes.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/LibraryOptionsContext.h"
32#include "llvm/Support/SourceMgr.h"
33#include "llvm/Support/TargetSelect.h"
34#include "llvm/Target/TargetMachine.h"
35
36#define DEBUG_TYPE "isel-fuzzer"
37
38using namespace llvm;
39
40static codegen::RegisterCodeGenFlags CGF;
41
42static cl::opt<char>
43 OptLevel("O",
44 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
45 "(default = '-O2')"),
46 cl::Prefix, cl::init(Val: '2'));
47
48static cl::opt<std::string>
49 TargetTriple("mtriple", cl::desc("Override target triple for module"));
50
51static std::unique_ptr<TargetMachine> TM;
52static std::unique_ptr<IRMutator> Mutator;
53
54std::unique_ptr<IRMutator> createISelMutator() {
55 std::vector<TypeGetter> Types{
56 Type::getInt1Ty, Type::getInt8Ty, Type::getInt16Ty, Type::getInt32Ty,
57 Type::getInt64Ty, Type::getFloatTy, Type::getDoubleTy};
58
59 std::vector<std::unique_ptr<IRMutationStrategy>> Strategies;
60 Strategies.emplace_back(
61 args: new InjectorIRStrategy(InjectorIRStrategy::getDefaultOps()));
62 Strategies.emplace_back(args: new InstDeleterIRStrategy());
63
64 return std::make_unique<IRMutator>(args: std::move(Types), args: std::move(Strategies));
65}
66
67extern "C" LLVM_ATTRIBUTE_USED size_t LLVMFuzzerCustomMutator(
68 uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) {
69 LLVMContext Context;
70 std::unique_ptr<Module> M;
71 if (Size <= 1)
72 // We get bogus data given an empty corpus - just create a new module.
73 M.reset(p: new Module("M", Context));
74 else
75 M = parseModule(Data, Size, Context);
76
77 Mutator->mutateModule(M&: *M, Seed, MaxSize); // use max bitcode size as a guide
78
79 return writeModule(M: *M, Dest: Data, MaxSize);
80}
81
82extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
83 if (Size <= 1)
84 // We get bogus data given an empty corpus - ignore it.
85 return 0;
86
87 LLVMContext Context;
88 auto M = parseAndVerify(Data, Size, Context);
89 if (!M) {
90 errs() << "error: input module is broken!\n";
91 return 0;
92 }
93
94 // Set up the module to build for our target.
95 M->setTargetTriple(TM->getTargetTriple());
96 M->setDataLayout(TM->getTargetTriple().computeDataLayout());
97
98 // Build up a PM to do instruction selection.
99 legacy::PassManager PM;
100 TargetLibraryInfoImpl TLII(TM->getTargetTriple());
101 PM.add(P: new TargetLibraryInfoWrapperPass(TLII));
102 raw_null_ostream OS;
103 TM->addPassesToEmitFile(PM, OS, nullptr, CodeGenFileType::Null);
104 PM.run(M&: *M);
105
106 return 0;
107}
108
109static void handleLLVMFatalError(void *, const char *Message, bool) {
110 // TODO: Would it be better to call into the fuzzer internals directly?
111 dbgs() << "LLVM ERROR: " << Message << "\n"
112 << "Aborting to trigger fuzzer exit handling.\n";
113 abort();
114}
115
116extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(int *argc,
117 char ***argv) {
118 EnableDebugBuffering = true;
119 StringRef ExecName = *argv[0];
120
121 InitializeAllTargets();
122 InitializeAllTargetMCs();
123 InitializeAllAsmPrinters();
124 InitializeAllAsmParsers();
125
126 // Created after the targets register their library options.
127 static cl::LibraryOptionsContext LibraryOptions;
128 handleExecNameEncodedBEOpts(LibraryOptions, ExecName);
129 parseFuzzerCLOpts(LibraryOptions, ArgC: *argc, ArgV: *argv);
130
131 if (TargetTriple.empty()) {
132 errs() << ExecName << ": -mtriple must be specified\n";
133 exit(status: 1);
134 }
135
136 // Set up the pipeline like llc does.
137
138 CodeGenOptLevel OLvl;
139 if (auto Level = CodeGenOpt::parseLevel(C: OptLevel)) {
140 OLvl = *Level;
141 } else {
142 errs() << ExecName << ": invalid optimization level.\n";
143 return 1;
144 }
145 ExitOnError ExitOnErr(std::string(ExecName) + ": error:");
146
147 Triple TT(Triple::normalize(Str: TargetTriple));
148
149 TM = ExitOnErr(
150 codegen::createTargetMachineForTriple(LibraryOptions, TargetTriple: TT, OptLevel: OLvl));
151 assert(TM && "Could not allocate target machine!");
152
153 // Make sure we print the summary and the current unit when LLVM errors out.
154 install_fatal_error_handler(handler: handleLLVMFatalError, user_data: nullptr);
155
156 // Finally, create our mutator.
157 Mutator = createISelMutator();
158 return 0;
159}
160