Clang Project

clang_source_code/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
1//==-- handle_llvm.cpp - Helper function for Clang fuzzers -----------------==//
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// 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.
13//
14//===----------------------------------------------------------------------===//
15
16#include "handle_llvm.h"
17#include "input_arrays.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
49using namespace llvm;
50
51// Define a type for the functions that are compiled and executed
52typedef void (*LLVMFunc)(int*, int*, int*, int);
53
54// Helper function to parse command line args and find the optimization level
55static void getOptLevel(const std::vector<const char *> &ExtraArgs,
56                              CodeGenOpt::Level &OLvl) {
57  // Find the optimization level from the command line args
58  OLvl = CodeGenOpt::Default;
59  for (auto &A : ExtraArgs) {
60    if (A[0] == '-' && A[1] == 'O') {
61      switch(A[2]) {
62        case '0': OLvl = CodeGenOpt::None; break;
63        case '1': OLvl = CodeGenOpt::Less; break;
64        case '2': OLvl = CodeGenOpt::Default; break;
65        case '3': OLvl = CodeGenOpt::Aggressive; break;
66        default:
67          errs() << "error: opt level must be between 0 and 3.\n";
68          std::exit(1);
69      }
70    }
71  }
72}
73
74static void ErrorAndExit(std::string message) {
75  errs()<< "ERROR: " << message << "\n";
76  std::exit(1);
77}
78
79// Helper function to add optimization passes to the TargetMachine at the 
80// specified optimization level, OptLevel
81static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
82                                  CodeGenOpt::Level OptLevel,
83                                  unsigned SizeLevel) {
84  // Create and initialize a PassManagerBuilder
85  PassManagerBuilder Builder;
86  Builder.OptLevel = OptLevel;
87  Builder.SizeLevel = SizeLevel;
88  Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
89  Builder.LoopVectorize = true;
90  Builder.populateModulePassManager(MPM);
91}
92
93// Mimics the opt tool to run an optimization pass over the provided IR
94static std::string OptLLVM(const std::string &IR, CodeGenOpt::Level OLvl) {
95  // Create a module that will run the optimization passes
96  SMDiagnostic Err;
97  LLVMContext Context;
98  std::unique_ptr<Module> M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
99  if (!M || verifyModule(*M, &errs()))
100    ErrorAndExit("Could not parse IR");
101
102  Triple ModuleTriple(M->getTargetTriple());
103  const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
104  std::string E;
105  const Target *TheTarget = TargetRegistry::lookupTarget(MArch, ModuleTriple, E);
106  TargetMachine *Machine =
107      TheTarget->createTargetMachine(M->getTargetTriple(), getCPUStr(),
108                                     getFeaturesStr(), Options, getRelocModel(),
109                                     getCodeModel(), OLvl);
110  std::unique_ptr<TargetMachine> TM(Machine);
111  setFunctionAttributes(getCPUStr(), getFeaturesStr(), *M);
112
113  legacy::PassManager Passes;
114  
115  Passes.add(new TargetLibraryInfoWrapperPass(ModuleTriple));
116  Passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
117
118  LLVMTargetMachine &LTM = static_cast<LLVMTargetMachine &>(*TM);
119  Passes.add(LTM.createPassConfig(Passes));
120
121  Passes.add(createVerifierPass());
122
123  AddOptimizationPasses(Passes, OLvl, 0);
124
125  // Add a pass that writes the optimized IR to an output stream
126  std::string outString;
127  raw_string_ostream OS(outString);
128  Passes.add(createPrintModulePass(OS, ""false));
129
130  Passes.run(*M);
131
132  return OS.str();
133}
134
135// Takes a function and runs it on a set of inputs
136// First determines whether f is the optimized or unoptimized function
137static void RunFuncOnInputs(LLVMFunc fint Arr[kNumArrays][kArraySize]) {
138  for (int i = 0i < kNumArrays / 3i++)
139    f(Arr[i], Arr[i + (kNumArrays / 3)], Arr[i + (2 * kNumArrays / 3)],
140      kArraySize);
141}
142
143// Takes a string of IR and compiles it using LLVM's JIT Engine
144static void CreateAndRunJITFunc(const std::string &IR, CodeGenOpt::Level OLvl) {
145  SMDiagnostic Err;
146  LLVMContext Context;
147  std::unique_ptr<Module> M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
148  if (!M)
149    ErrorAndExit("Could not parse IR");
150
151  Function *EntryFunc = M->getFunction("foo");
152  if (!EntryFunc)
153    ErrorAndExit("Function not found in module");
154
155  std::string ErrorMsg;
156  EngineBuilder builder(std::move(M));
157  builder.setMArch(MArch);
158  builder.setMCPU(getCPUStr());
159  builder.setMAttrs(getFeatureList());
160  builder.setErrorStr(&ErrorMsg);
161  builder.setEngineKind(EngineKind::JIT);
162  builder.setUseOrcMCJITReplacement(false);
163  builder.setMCJITMemoryManager(make_unique<SectionMemoryManager>());
164  builder.setOptLevel(OLvl);
165  builder.setTargetOptions(InitTargetOptionsFromCodeGenFlags());
166
167  std::unique_ptr<ExecutionEngine> EE(builder.create());
168  if (!EE)
169    ErrorAndExit("Could not create execution engine");
170
171  EE->finalizeObject();
172  EE->runStaticConstructorsDestructors(false);
173
174#if defined(__GNUC__) && !defined(__clang) &&                                  \
175    ((__GNUC__ == 4) && (__GNUC_MINOR__ < 9))
176// Silence
177//
178//   warning: ISO C++ forbids casting between pointer-to-function and
179//   pointer-to-object [-Wpedantic]
180//
181// Since C++11 this casting is conditionally supported and GCC versions
182// starting from 4.9.0 don't warn about the cast.
183#pragma GCC diagnostic push
184#pragma GCC diagnostic ignored "-Wpedantic"
185#endif
186  LLVMFunc f = reinterpret_cast<LLVMFunc>(EE->getPointerToFunction(EntryFunc));
187#if defined(__GNUC__) && !defined(__clang) &&                                  \
188    ((__GNUC__ == 4) && (__GNUC_MINOR__ < 9))
189#pragma GCC diagnostic pop
190#endif
191
192  // Figure out if we are running the optimized func or the unoptimized func
193  RunFuncOnInputs(f, (OLvl == CodeGenOpt::None) ? UnoptArrays : OptArrays);
194
195  EE->runStaticConstructorsDestructors(true);
196}
197
198// Main fuzz target called by ExampleClangLLVMProtoFuzzer.cpp
199// Mimics the lli tool to JIT the LLVM IR code and execute it
200void clang_fuzzer::HandleLLVM(const std::string &IR,
201                              const std::vector<const char *> &ExtraArgs) {
202  // Populate OptArrays and UnoptArrays with the arrays from InputArrays
203  memcpy(OptArraysInputArrayskTotalSize);
204  memcpy(UnoptArraysInputArrayskTotalSize);
205
206  // Parse ExtraArgs to set the optimization level
207  CodeGenOpt::Level OLvl;
208  getOptLevel(ExtraArgs, OLvl);
209
210  // First we optimize the IR by running a loop vectorizer pass
211  std::string OptIR = OptLLVM(IR, OLvl);
212
213  CreateAndRunJITFunc(OptIR, OLvl);
214  CreateAndRunJITFunc(IR, CodeGenOpt::None);
215
216  if (memcmp(OptArraysUnoptArrayskTotalSize))
217    ErrorAndExit("!!!BUG!!!");
218
219  return;
220}
221