brintos

brintos / llvm-project-archived public Read only

0
0
Text · 12.3 KiB · 71a5aa1 Raw
291 lines · c
1//===- BugDriver.h - Top-Level BugPoint class -------------------*- C++ -*-===//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-exception6//7//===----------------------------------------------------------------------===//8//9// This class contains all of the shared state and information that is used by10// the BugPoint tool to track down errors in optimizations.  This class is the11// main driver class that invokes all sub-functionality.12//13//===----------------------------------------------------------------------===//14 15#ifndef LLVM_TOOLS_BUGPOINT_BUGDRIVER_H16#define LLVM_TOOLS_BUGPOINT_BUGDRIVER_H17 18#include "llvm/IR/ValueMap.h"19#include "llvm/Support/CommandLine.h"20#include "llvm/Support/Error.h"21#include "llvm/Support/FileSystem.h"22#include "llvm/Transforms/Utils/ValueMapper.h"23#include <memory>24#include <string>25#include <vector>26 27namespace llvm {28 29class Module;30class GlobalVariable;31class Function;32class BasicBlock;33class AbstractInterpreter;34class Instruction;35class LLVMContext;36 37class CC;38 39extern bool DisableSimplifyCFG;40 41/// BugpointIsInterrupted - Set to true when the user presses ctrl-c.42///43extern bool BugpointIsInterrupted;44 45/// Command line options used across files.46extern cl::list<std::string> InputArgv;47extern cl::opt<std::string> OutputPrefix;48 49class BugDriver {50  LLVMContext &Context;51  const char *ToolName;            // argv[0] of bugpoint52  std::string ReferenceOutputFile; // Name of `good' output file53  std::unique_ptr<Module> Program; // The raw program, linked together54  std::vector<std::string> PassesToRun;55  AbstractInterpreter *Interpreter;     // How to run the program56  AbstractInterpreter *SafeInterpreter; // To generate reference output, etc.57  CC *cc;58  bool run_find_bugs;59  unsigned Timeout;60  unsigned MemoryLimit;61  bool UseValgrind;62 63  // FIXME: sort out public/private distinctions...64  friend class ReducePassList;65 66public:67  BugDriver(const char *toolname, bool find_bugs, unsigned timeout,68            unsigned memlimit, bool use_valgrind, LLVMContext &ctxt);69  ~BugDriver();70 71  const char *getToolName() const { return ToolName; }72 73  LLVMContext &getContext() const { return Context; }74 75  // Set up methods... these methods are used to copy information about the76  // command line arguments into instance variables of BugDriver.77  //78  bool addSources(const std::vector<std::string> &FileNames);79  void addPass(std::string p) { PassesToRun.push_back(std::move(p)); }80  void setPassesToRun(const std::vector<std::string> &PTR) {81    PassesToRun = PTR;82  }83  ArrayRef<std::string> getPassesToRun() const { return PassesToRun; }84 85  /// run - The top level method that is invoked after all of the instance86  /// variables are set up from command line arguments. The \p as_child argument87  /// indicates whether the driver is to run in parent mode or child mode.88  ///89  Error run();90 91  /// debugOptimizerCrash - This method is called when some optimizer pass92  /// crashes on input.  It attempts to prune down the testcase to something93  /// reasonable, and figure out exactly which pass is crashing.94  ///95  Error debugOptimizerCrash(const std::string &ID = "passes");96 97  /// debugCodeGeneratorCrash - This method is called when the code generator98  /// crashes on an input.  It attempts to reduce the input as much as possible99  /// while still causing the code generator to crash.100  Error debugCodeGeneratorCrash();101 102  /// debugMiscompilation - This method is used when the passes selected are not103  /// crashing, but the generated output is semantically different from the104  /// input.105  Error debugMiscompilation();106 107  /// compileSharedObject - This method creates a SharedObject from a given108  /// BitcodeFile for debugging a code generator.109  ///110  Expected<std::string> compileSharedObject(const std::string &BitcodeFile);111 112  /// debugCodeGenerator - This method narrows down a module to a function or113  /// set of functions, using the CBE as a ``safe'' code generator for other114  /// functions that are not under consideration.115  Error debugCodeGenerator();116 117  /// isExecutingJIT - Returns true if bugpoint is currently testing the JIT118  bool isExecutingJIT();119 120  Module &getProgram() const { return *Program; }121 122  /// Set the current module to the specified module, returning the old one.123  std::unique_ptr<Module> swapProgramIn(std::unique_ptr<Module> M);124 125  AbstractInterpreter *switchToSafeInterpreter() {126    AbstractInterpreter *Old = Interpreter;127    Interpreter = (AbstractInterpreter *)SafeInterpreter;128    return Old;129  }130 131  void switchToInterpreter(AbstractInterpreter *AI) { Interpreter = AI; }132 133  /// If we reduce or update the program somehow, call this method to update134  /// bugdriver with it.  This deletes the old module and sets the specified one135  /// as the current program.136  void setNewProgram(std::unique_ptr<Module> M);137 138  /// Try to compile the specified module. This is used for code generation139  /// crash testing.140  Error compileProgram(Module &M) const;141 142  /// This method runs "Program", capturing the output of the program to a file.143  /// A recommended filename may be optionally specified.144  Expected<std::string> executeProgram(const Module &Program,145                                       std::string OutputFilename,146                                       std::string Bitcode,147                                       const std::string &SharedObjects,148                                       AbstractInterpreter *AI) const;149 150  /// Used to create reference output with the "safe" backend, if reference151  /// output is not provided.  If there is a problem with the code generator152  /// (e.g., llc crashes), this will return false and set Error.153  Expected<std::string>154  executeProgramSafely(const Module &Program,155                       const std::string &OutputFile) const;156 157  /// Calls compileProgram and then records the output into ReferenceOutputFile.158  /// Returns true if reference file created, false otherwise. Note:159  /// initializeExecutionEnvironment should be called BEFORE this function.160  Error createReferenceFile(Module &M, const std::string &Filename =161                                           "bugpoint.reference.out-%%%%%%%");162 163  /// This method executes the specified module and diffs the output against the164  /// file specified by ReferenceOutputFile.  If the output is different, 1 is165  /// returned.  If there is a problem with the code generator (e.g., llc166  /// crashes), this will return -1 and set Error.167  Expected<bool> diffProgram(const Module &Program,168                             const std::string &BitcodeFile = "",169                             const std::string &SharedObj = "",170                             bool RemoveBitcode = false) const;171 172  /// This function is used to output M to a file named "bugpoint-ID.bc".173  void emitProgressBitcode(const Module &M, const std::string &ID,174                           bool NoFlyer = false) const;175 176  /// This method clones the current Program and deletes the specified177  /// instruction from the cloned module.  It then runs a series of cleanup178  /// passes (ADCE and SimplifyCFG) to eliminate any code which depends on the179  /// value. The modified module is then returned.180  ///181  std::unique_ptr<Module> deleteInstructionFromProgram(const Instruction *I,182                                                       unsigned Simp);183 184  /// This method clones the current Program and performs a series of cleanups185  /// intended to get rid of extra cruft on the module. If the186  /// MayModifySemantics argument is true, then the cleanups is allowed to187  /// modify how the code behaves.188  ///189  std::unique_ptr<Module> performFinalCleanups(std::unique_ptr<Module> M,190                                               bool MayModifySemantics = false);191 192  /// Given a module, extract up to one loop from it into a new function. This193  /// returns null if there are no extractable loops in the program or if the194  /// loop extractor crashes.195  std::unique_ptr<Module> extractLoop(Module *M);196 197  /// Extract all but the specified basic blocks into their own functions. The198  /// only detail is that M is actually a module cloned from the one the BBs are199  /// in, so some mapping needs to be performed. If this operation fails for200  /// some reason (ie the implementation is buggy), this function should return201  /// null, otherwise it returns a new Module.202  std::unique_ptr<Module>203  extractMappedBlocksFromModule(const std::vector<BasicBlock *> &BBs,204                                Module *M);205 206  /// Carefully run the specified set of pass on the specified/ module,207  /// returning the transformed module on success, or a null pointer on failure.208  std::unique_ptr<Module> runPassesOn(Module *M,209                                      const std::vector<std::string> &Passes,210                                      ArrayRef<std::string> ExtraArgs = {});211 212  /// runPasses - Run the specified passes on Program, outputting a bitcode213  /// file and writting the filename into OutputFile if successful.  If the214  /// optimizations fail for some reason (optimizer crashes), return true,215  /// otherwise return false.  If DeleteOutput is set to true, the bitcode is216  /// deleted on success, and the filename string is undefined.  This prints to217  /// outs() a single line message indicating whether compilation was successful218  /// or failed, unless Quiet is set.  ExtraArgs specifies additional arguments219  /// to pass to the child bugpoint instance.220  bool runPasses(Module &Program, const std::vector<std::string> &PassesToRun,221                 std::string &OutputFilename, bool DeleteOutput = false,222                 bool Quiet = false,223                 ArrayRef<std::string> ExtraArgs = {}) const;224 225  /// runPasses - Just like the method above, but this just returns true or226  /// false indicating whether or not the optimizer crashed on the specified227  /// input (true = crashed).  Does not produce any output.228  bool runPasses(Module &M, const std::vector<std::string> &PassesToRun) const {229    std::string Filename;230    return runPasses(M, PassesToRun, Filename, true);231  }232 233  /// Take the specified pass list and create different combinations of passes234  /// to compile the program with. Compile the program with each set and mark235  /// test to see if it compiled correctly. If the passes compiled correctly236  /// output nothing and rearrange the passes into a new order. If the passes237  /// did not compile correctly, output the command required to recreate the238  /// failure.239  Error runManyPasses(const std::vector<std::string> &AllPasses);240 241  /// This writes the current "Program" to the named bitcode file.  If an error242  /// occurs, true is returned.243  bool writeProgramToFile(const std::string &Filename, const Module &M) const;244  bool writeProgramToFile(const std::string &Filename, int FD,245                          const Module &M) const;246  bool writeProgramToFile(int FD, const Module &M) const;247 248private:249  /// initializeExecutionEnvironment - This method is used to set up the250  /// environment for executing LLVM programs.251  Error initializeExecutionEnvironment();252};253 254struct DiscardTemp {255  sys::fs::TempFile &File;256  ~DiscardTemp();257};258 259///  Given a bitcode or assembly input filename, parse and return it, or return260///  null if not possible.261std::unique_ptr<Module> parseInputFile(StringRef InputFilename,262                                       LLVMContext &ctxt);263 264/// getPassesString - Turn a list of passes into a string which indicates the265/// command line options that must be passed to add the passes.266std::string getPassesString(const std::vector<std::string> &Passes);267 268/// Prints out list of problematic functions269void printFunctionList(const std::vector<Function *> &Funcs);270 271/// Prints out list of problematic global variables272void printGlobalVariableList(const std::vector<GlobalVariable *> &GVs);273 274/// "Remove" the global variable by deleting its initializer, making it275/// external.276void deleteGlobalInitializer(GlobalVariable *GV);277 278/// "Remove" the function by deleting all of it's basic blocks, making it279/// external.280void deleteFunctionBody(Function *F);281 282/// Given a module and a list of functions in the module, split the functions283/// OUT of the specified module, and place them in the new module.284std::unique_ptr<Module>285splitFunctionsOutOfModule(Module *M, const std::vector<Function *> &F,286                          ValueToValueMapTy &VMap);287 288} // End llvm namespace289 290#endif291