1 //==-- handle_llvm.cpp - Helper function for Clang fuzzers -----------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
11 // vectorizer optimization pass over the given IR code. Then mimics lli on both
12 // versions to JIT the generated code and execute it. Currently, functions are
13 // executed on dummy inputs.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "handle_llvm.h"
18 
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/CodeGen/CommandFlags.inc"
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/LegacyPassManager.h"
33 #include "llvm/IR/LegacyPassNameParser.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/Pass.h"
39 #include "llvm/PassRegistry.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/Vectorize.h"
48 
49 using namespace llvm;
50 
51 // Helper function to parse command line args and find the optimization level
getOptLevel(const std::vector<const char * > & ExtraArgs,CodeGenOpt::Level & OLvl)52 static void getOptLevel(const std::vector<const char *> &ExtraArgs,
53                               CodeGenOpt::Level &OLvl) {
54   // Find the optimization level from the command line args
55   OLvl = CodeGenOpt::Default;
56   for (auto &A : ExtraArgs) {
57     if (A[0] == '-' && A[1] == 'O') {
58       switch(A[2]) {
59         case '0': OLvl = CodeGenOpt::None; break;
60         case '1': OLvl = CodeGenOpt::Less; break;
61         case '2': OLvl = CodeGenOpt::Default; break;
62         case '3': OLvl = CodeGenOpt::Aggressive; break;
63         default:
64           errs() << "error: opt level must be between 0 and 3.\n";
65           std::exit(1);
66       }
67     }
68   }
69 }
70 
ErrorAndExit(std::string message)71 void ErrorAndExit(std::string message) {
72   errs()<< "ERROR: " << message << "\n";
73   std::exit(1);
74 }
75 
76 // Helper function to add optimization passes to the TargetMachine at the
77 // specified optimization level, OptLevel
AddOptimizationPasses(legacy::PassManagerBase & MPM,CodeGenOpt::Level OptLevel,unsigned SizeLevel)78 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
79                                   CodeGenOpt::Level OptLevel,
80                                   unsigned SizeLevel) {
81   // Create and initialize a PassManagerBuilder
82   PassManagerBuilder Builder;
83   Builder.OptLevel = OptLevel;
84   Builder.SizeLevel = SizeLevel;
85   Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
86   Builder.LoopVectorize = true;
87   Builder.populateModulePassManager(MPM);
88 }
89 
90 // Mimics the opt tool to run an optimization pass over the provided IR
OptLLVM(const std::string & IR,CodeGenOpt::Level OLvl)91 std::string OptLLVM(const std::string &IR, CodeGenOpt::Level OLvl) {
92   // Create a module that will run the optimization passes
93   SMDiagnostic Err;
94   LLVMContext Context;
95   std::unique_ptr<Module> M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
96   if (!M || verifyModule(*M, &errs()))
97     ErrorAndExit("Could not parse IR");
98 
99   setFunctionAttributes(getCPUStr(), getFeaturesStr(), *M);
100 
101   legacy::PassManager Passes;
102   Triple ModuleTriple(M->getTargetTriple());
103 
104   Passes.add(new TargetLibraryInfoWrapperPass(ModuleTriple));
105   Passes.add(createTargetTransformInfoWrapperPass(TargetIRAnalysis()));
106   Passes.add(createVerifierPass());
107 
108   AddOptimizationPasses(Passes, OLvl, 0);
109 
110   // Add a pass that writes the optimized IR to an output stream
111   std::string outString;
112   raw_string_ostream OS(outString);
113   Passes.add(createPrintModulePass(OS, "", false));
114 
115   Passes.run(*M);
116 
117   return OS.str();
118 }
119 
CreateAndRunJITFun(const std::string & IR,CodeGenOpt::Level OLvl)120 void CreateAndRunJITFun(const std::string &IR, CodeGenOpt::Level OLvl) {
121   SMDiagnostic Err;
122   LLVMContext Context;
123   std::unique_ptr<Module> M = parseIR(MemoryBufferRef(IR, "IR"), Err,
124                                           Context);
125   if (!M)
126     ErrorAndExit("Could not parse IR");
127 
128   Function *EntryFunc = M->getFunction("foo");
129   if (!EntryFunc)
130     ErrorAndExit("Function not found in module");
131 
132   std::string ErrorMsg;
133   EngineBuilder builder(std::move(M));
134   builder.setMArch(MArch);
135   builder.setMCPU(getCPUStr());
136   builder.setMAttrs(getFeatureList());
137   builder.setErrorStr(&ErrorMsg);
138   builder.setEngineKind(EngineKind::JIT);
139   builder.setUseOrcMCJITReplacement(false);
140   builder.setMCJITMemoryManager(make_unique<SectionMemoryManager>());
141   builder.setOptLevel(OLvl);
142   builder.setTargetOptions(InitTargetOptionsFromCodeGenFlags());
143 
144   std::unique_ptr<ExecutionEngine> EE(builder.create());
145   if (!EE)
146     ErrorAndExit("Could not create execution engine");
147 
148   EE->finalizeObject();
149   EE->runStaticConstructorsDestructors(false);
150 
151   typedef void (*func)(int*, int*, int*, int);
152   func f = reinterpret_cast<func>(EE->getPointerToFunction(EntryFunc));
153 
154   // Define some dummy arrays to use an input for now
155   int a[] = {1};
156   int b[] = {1};
157   int c[] = {1};
158   f(a, b, c, 1);
159 
160   EE->runStaticConstructorsDestructors(true);
161 }
162 
163 // Main fuzz target called by ExampleClangLLVMProtoFuzzer.cpp
164 // Mimics the lli tool to JIT the LLVM IR code and execute it
HandleLLVM(const std::string & IR,const std::vector<const char * > & ExtraArgs)165 void clang_fuzzer::HandleLLVM(const std::string &IR,
166                               const std::vector<const char *> &ExtraArgs) {
167   // Parse ExtraArgs to set the optimization level
168   CodeGenOpt::Level OLvl;
169   getOptLevel(ExtraArgs, OLvl);
170 
171   // First we optimize the IR by running a loop vectorizer pass
172   std::string OptIR = OptLLVM(IR, OLvl);
173 
174   CreateAndRunJITFun(OptIR, OLvl);
175   CreateAndRunJITFun(IR, CodeGenOpt::None);
176 
177   return;
178 }
179