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