1 //==-- handle_llvm.cpp - Helper function for Clang fuzzers -----------------==//
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
7 //===----------------------------------------------------------------------===//
9 // Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
10 // vectorizer optimization pass over the given IR code. Then mimics lli on both
11 // versions to JIT the generated code and execute it. Currently, functions are
12 // executed on dummy inputs.
14 //===----------------------------------------------------------------------===//
16 #include "handle_llvm.h"
17 #include "input_arrays.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/CodeGen/CommandFlags.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/ExecutionEngine/JITEventListener.h"
26 #include "llvm/ExecutionEngine/JITSymbol.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/ExecutionEngine/ObjectCache.h"
29 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
30 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/LegacyPassNameParser.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/MC/TargetRegistry.h"
39 #include "llvm/Pass.h"
40 #include "llvm/PassRegistry.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/SourceMgr.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Transforms/IPO.h"
46 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 #include "llvm/Transforms/Vectorize.h"
51 static codegen::RegisterCodeGenFlags CGF
;
53 // Define a type for the functions that are compiled and executed
54 typedef void (*LLVMFunc
)(int*, int*, int*, int);
56 // Helper function to parse command line args and find the optimization level
57 static void getOptLevel(const std::vector
<const char *> &ExtraArgs
,
58 CodeGenOpt::Level
&OLvl
) {
59 // Find the optimization level from the command line args
60 OLvl
= CodeGenOpt::Default
;
61 for (auto &A
: ExtraArgs
) {
62 if (A
[0] == '-' && A
[1] == 'O') {
64 case '0': OLvl
= CodeGenOpt::None
; break;
65 case '1': OLvl
= CodeGenOpt::Less
; break;
66 case '2': OLvl
= CodeGenOpt::Default
; break;
67 case '3': OLvl
= CodeGenOpt::Aggressive
; break;
69 errs() << "error: opt level must be between 0 and 3.\n";
76 static void ErrorAndExit(std::string message
) {
77 errs()<< "ERROR: " << message
<< "\n";
81 // Helper function to add optimization passes to the TargetMachine at the
82 // specified optimization level, OptLevel
83 static void AddOptimizationPasses(legacy::PassManagerBase
&MPM
,
84 CodeGenOpt::Level OptLevel
,
86 // Create and initialize a PassManagerBuilder
87 PassManagerBuilder Builder
;
88 Builder
.OptLevel
= OptLevel
;
89 Builder
.SizeLevel
= SizeLevel
;
90 Builder
.Inliner
= createFunctionInliningPass(OptLevel
, SizeLevel
, false);
91 Builder
.LoopVectorize
= true;
92 Builder
.populateModulePassManager(MPM
);
95 // Mimics the opt tool to run an optimization pass over the provided IR
96 static std::string
OptLLVM(const std::string
&IR
, CodeGenOpt::Level OLvl
) {
97 // Create a module that will run the optimization passes
100 std::unique_ptr
<Module
> M
= parseIR(MemoryBufferRef(IR
, "IR"), Err
, Context
);
101 if (!M
|| verifyModule(*M
, &errs()))
102 ErrorAndExit("Could not parse IR");
104 Triple
ModuleTriple(M
->getTargetTriple());
105 const TargetOptions Options
=
106 codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple
);
108 const Target
*TheTarget
=
109 TargetRegistry::lookupTarget(codegen::getMArch(), ModuleTriple
, E
);
113 std::unique_ptr
<TargetMachine
> TM(TheTarget
->createTargetMachine(
114 M
->getTargetTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
115 Options
, codegen::getExplicitRelocModel(),
116 codegen::getExplicitCodeModel(), OLvl
));
118 ErrorAndExit("Could not create target machine");
120 codegen::setFunctionAttributes(codegen::getCPUStr(),
121 codegen::getFeaturesStr(), *M
);
123 legacy::PassManager Passes
;
125 Passes
.add(new TargetLibraryInfoWrapperPass(ModuleTriple
));
126 Passes
.add(createTargetTransformInfoWrapperPass(TM
->getTargetIRAnalysis()));
128 LLVMTargetMachine
<M
= static_cast<LLVMTargetMachine
&>(*TM
);
129 Passes
.add(LTM
.createPassConfig(Passes
));
131 Passes
.add(createVerifierPass());
133 AddOptimizationPasses(Passes
, OLvl
, 0);
135 // Add a pass that writes the optimized IR to an output stream
136 std::string outString
;
137 raw_string_ostream
OS(outString
);
138 Passes
.add(createPrintModulePass(OS
, "", false));
145 // Takes a function and runs it on a set of inputs
146 // First determines whether f is the optimized or unoptimized function
147 static void RunFuncOnInputs(LLVMFunc f
, int Arr
[kNumArrays
][kArraySize
]) {
148 for (int i
= 0; i
< kNumArrays
/ 3; i
++)
149 f(Arr
[i
], Arr
[i
+ (kNumArrays
/ 3)], Arr
[i
+ (2 * kNumArrays
/ 3)],
153 // Takes a string of IR and compiles it using LLVM's JIT Engine
154 static void CreateAndRunJITFunc(const std::string
&IR
, CodeGenOpt::Level OLvl
) {
157 std::unique_ptr
<Module
> M
= parseIR(MemoryBufferRef(IR
, "IR"), Err
, Context
);
159 ErrorAndExit("Could not parse IR");
161 Function
*EntryFunc
= M
->getFunction("foo");
163 ErrorAndExit("Function not found in module");
165 std::string ErrorMsg
;
166 Triple
ModuleTriple(M
->getTargetTriple());
168 EngineBuilder
builder(std::move(M
));
169 builder
.setMArch(codegen::getMArch());
170 builder
.setMCPU(codegen::getCPUStr());
171 builder
.setMAttrs(codegen::getFeatureList());
172 builder
.setErrorStr(&ErrorMsg
);
173 builder
.setEngineKind(EngineKind::JIT
);
174 builder
.setMCJITMemoryManager(std::make_unique
<SectionMemoryManager
>());
175 builder
.setOptLevel(OLvl
);
176 builder
.setTargetOptions(
177 codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple
));
179 std::unique_ptr
<ExecutionEngine
> EE(builder
.create());
181 ErrorAndExit("Could not create execution engine");
183 EE
->finalizeObject();
184 EE
->runStaticConstructorsDestructors(false);
186 #if defined(__GNUC__) && !defined(__clang) && \
187 ((__GNUC__ == 4) && (__GNUC_MINOR__ < 9))
190 // warning: ISO C++ forbids casting between pointer-to-function and
191 // pointer-to-object [-Wpedantic]
193 // Since C++11 this casting is conditionally supported and GCC versions
194 // starting from 4.9.0 don't warn about the cast.
195 #pragma GCC diagnostic push
196 #pragma GCC diagnostic ignored "-Wpedantic"
198 LLVMFunc f
= reinterpret_cast<LLVMFunc
>(EE
->getPointerToFunction(EntryFunc
));
199 #if defined(__GNUC__) && !defined(__clang) && \
200 ((__GNUC__ == 4) && (__GNUC_MINOR__ < 9))
201 #pragma GCC diagnostic pop
204 // Figure out if we are running the optimized func or the unoptimized func
205 RunFuncOnInputs(f
, (OLvl
== CodeGenOpt::None
) ? UnoptArrays
: OptArrays
);
207 EE
->runStaticConstructorsDestructors(true);
210 // Main fuzz target called by ExampleClangLLVMProtoFuzzer.cpp
211 // Mimics the lli tool to JIT the LLVM IR code and execute it
212 void clang_fuzzer::HandleLLVM(const std::string
&IR
,
213 const std::vector
<const char *> &ExtraArgs
) {
214 // Populate OptArrays and UnoptArrays with the arrays from InputArrays
215 memcpy(OptArrays
, InputArrays
, kTotalSize
);
216 memcpy(UnoptArrays
, InputArrays
, kTotalSize
);
218 // Parse ExtraArgs to set the optimization level
219 CodeGenOpt::Level OLvl
;
220 getOptLevel(ExtraArgs
, OLvl
);
222 // First we optimize the IR by running a loop vectorizer pass
223 std::string OptIR
= OptLLVM(IR
, OLvl
);
225 CreateAndRunJITFunc(OptIR
, OLvl
);
226 CreateAndRunJITFunc(IR
, CodeGenOpt::None
);
228 if (memcmp(OptArrays
, UnoptArrays
, kTotalSize
))
229 ErrorAndExit("!!!BUG!!!");