<commit_before>/*! \file RenderViewer.inl
 *  \author Jared Hoberock
 *  \brief Inline file for RenderViewer.h.
 */

#include "RenderViewer.h"
#include <qstring.h>
#include "../renderers/MetropolisRenderer.h"
#include "../renderers/EnergyRedistributionRenderer.h"
#include "../records/GpuFilm.h"
#include "../records/GpuFilterFilm.h"

#include <boost/thread/thread.hpp>
using boost::thread;
using namespace boost;

RenderViewer
  ::RenderViewer(void)
    :Parent()
{
  ;
} // end RenderViewer::RenderViewer()

void RenderViewer
  ::draw(void)
{
  if(!mDrawPreview)
  {
    shared_ptr<const Record> rec = mRenderer->getRecord();

    const Texture *texture = &mTexture;
    const GpuFilm<RenderFilm> *gpuFilm = dynamic_cast<const GpuFilm<RenderFilm> *>(rec.get());
    if(gpuFilm != 0)
    {
      // XXX yuck fix this
      const_cast<GpuFilm<RenderFilm> *>(gpuFilm)->renderPendingDeposits();
      texture = &gpuFilm->mTexture;
    } // end if

    shared_ptr<const RenderFilm> film = dynamic_pointer_cast<const RenderFilm,const Record>(rec);

    const float *data = reinterpret_cast<const float*>(&film->raster(0,0));
    GLenum datatype = GL_FLOAT_RGB16_NV;

    mTexture.init(datatype,
                  width(), height(),
                  0,
                  GL_RGB, data);

    // choose which program to use
    Program &p = mDoTonemap ? mTexture2DRectTonemapProgram : mTexture2DRectGammaProgram;

    p.bind();

    // scale by 1/spp if we haven't finished the render
    float scale = 1.0f;
    //if(!mDoTonemap && mProgress.count() < mProgress.expected_count())
    if(mProgress.count() < mProgress.expected_count())
    {
      // XXX DESIGN kill this dynamic_cast somehow
      const MonteCarloRenderer *mc = dynamic_cast<const MonteCarloRenderer*>(mRenderer.get());
      if(mc)
      {
        float spp = mc->getNumSamples();
        spp /= (film->getWidth() * film->getHeight());
        scale = 1.0f / spp;
      } // end if
    } // end else

    p.setUniform1f("scale", powf(2.0f, mExposure) * scale);
    p.setUniform1f("gamma", mGamma);
    float meanLogL = film->getSumLogLuminance() / (film->getWidth() * film->getHeight());
    float Lwa = expf(meanLogL);
    p.setUniform1f("Lwa", Lwa);
    p.setUniform1f("Lwhite", film->getMaximumLuminance());
    p.setUniform1f("a", mMiddleGrey);

    printGLError(__FILE__, __LINE__);

    p.unbind();

    glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT);

    drawTexture(*texture, p);
    glPopAttrib();
  } // end if
  else
  {
    drawScenePreview();
  } // end else
} // end RenderViewer::draw()

void RenderViewer
  ::drawScenePreview(void)
{
  Parent::draw();
} // end RenderViewer::drawScenePreview()

void RenderViewer
  ::init(void)
{
  glewInit();

  // first init the parent
  Parent::init();

  // init other stuff
  mTexture.create();

  mDrawPreview = true;
  mExposure = 0.0f;
  mGamma = 1.0f;

  mDoTonemap = false;
  mMiddleGrey = 0.5f;

  // resize
  resize(512,512);

  shared_ptr<const RenderFilm> film = dynamic_pointer_cast<const RenderFilm,const Record>(mRenderer->getRecord());
  if(film.get() != 0)
  {
    resize(film->getWidth(), film->getHeight());
  } // end if
} // end RenderViewer::init()

void RenderViewer
  ::keyPressEvent(KeyEvent *e)
{
  switch(e->key())
  {
    case Qt::Key_R:
    {
      startRender();
      mDrawPreview = false;
      updateGL();
      break;
    } // end case Qt::Key_R

    case Qt::Key_P:
    {
      mDrawPreview = !mDrawPreview;
      updateGL();
      break;
    } // end case Qt::Key_P

    case '(':
    {
      mGamma -= 0.1f;
      mGamma = std::max(mGamma, 0.1f);

      char msg[32];
      sprintf(msg, "Gamma: %f", mGamma);
      displayMessage(msg);
      updateGL();
      break;
    } // end case (

    case ')':
    {
      mGamma += 0.1f;

      char msg[32];
      sprintf(msg, "Gamma: %f", mGamma);
      displayMessage(msg);
      updateGL();
      break;
    } // end case )

    case '{':
    {
      mExposure -= 1.0f;

      char msg[32];
      sprintf(msg, "Exposure: %f", mExposure);
      displayMessage(msg);
      updateGL();
      break;
    } // end case '{'

    case '[':
    {
      char msg[32];
      if(mDoTonemap)
      {
        mMiddleGrey -= 0.01f;

        sprintf(msg, "Middle grey: %f", mMiddleGrey);
      } // end if
      else
      {
        mExposure -= 0.1f;

        sprintf(msg, "Exposure: %f", mExposure);
      } // end else

      displayMessage(msg);
      updateGL();
      break;
    } // end case '['

    case '}':
    {
      mExposure += 1.0f;

      char msg[32];
      sprintf(msg, "Exposure: %f", mExposure);
      displayMessage(msg);
      updateGL();
      break;
    } // end case '}'

    case ']':
    {
      char msg[32];

      if(mDoTonemap)
      {
        mMiddleGrey += 0.01f;

        sprintf(msg, "Middle grey: %f", mMiddleGrey);
      } // end if
      else
      {
        mExposure += 0.1f;

        sprintf(msg, "Exposure: %f", mExposure);
      } // end else

      displayMessage(msg);
      updateGL();
      break;
    } // end case ']'

    case 'T':
    {
      mDoTonemap = !mDoTonemap;
      updateGL();
      break;
    } // end case 'T'

    default:
    {
      Parent::keyPressEvent(e);
      break;
    } // end default
  } // end switch
} // end RenderViewer::keyPressEvent()

void RenderViewer
  ::resizeGL(int w, int h)
{
  Parent::resizeGL(w,h);

  char buffer[32];
  sprintf(buffer, "%d", width());
  std::string message = buffer;
  message += "x";
  sprintf(buffer, "%d", height());
  message += buffer;

  displayMessage(message);
  updateGL();
} // end RenderViewer::resizeGL()

class RenderThunk
{
  public:

  inline RenderThunk(Renderer *renderer,
                     Renderer::ProgressCallback *progress)
    :mRenderer(renderer),mProgress(progress)
  {
    ;
  }

  inline virtual ~RenderThunk(void){;};

  virtual void run(void)
  {
    (*this)();
  }

  void operator()(void)
  {
    mRenderer->render(*mProgress);
  }

  Renderer *mRenderer;
  Renderer::ProgressCallback *mProgress;
};

void RenderViewer
  ::postSelection(const QPoint &p)
{
  ;
} // end RenderViewer::postSelection()

void RenderViewer
  ::setRenderer(shared_ptr<Renderer> r)
{
  mRenderer = r;

  shared_ptr<const Record> rec = mRenderer->getRecord();
  const RandomAccessFilm *image = dynamic_cast<const RandomAccessFilm*>(rec.get());
  if(image != 0)
  {
    resizeGL(image->getWidth(), image->getHeight());
  } // end if
} // end Renderer::setRenderer()

void RenderViewer
  ::startRender(void)
{
  // XXX make RenderThunk refer to a shared_ptr
  RenderThunk render = RenderThunk(mRenderer.get(), &mProgress);
  boost::thread renderThread(render);

  // update the visualization every second
  setAnimationPeriod(1000);

  // update the frame automatically
  startAnimation();
} // end RenderViewer::startRender()

<commit_msg>Disable writing to state file on exit.<commit_after>/*! \file RenderViewer.inl
 *  \author Jared Hoberock
 *  \brief Inline file for RenderViewer.h.
 */

#include "RenderViewer.h"
#include <qstring.h>
#include "../renderers/MetropolisRenderer.h"
#include "../renderers/EnergyRedistributionRenderer.h"
#include "../records/GpuFilm.h"
#include "../records/GpuFilterFilm.h"

#include <boost/thread/thread.hpp>
using boost::thread;
using namespace boost;

RenderViewer
  ::RenderViewer(void)
    :Parent()
{
  ;
} // end RenderViewer::RenderViewer()

void RenderViewer
  ::draw(void)
{
  if(!mDrawPreview)
  {
    shared_ptr<const Record> rec = mRenderer->getRecord();

    const Texture *texture = &mTexture;
    const GpuFilm<RenderFilm> *gpuFilm = dynamic_cast<const GpuFilm<RenderFilm> *>(rec.get());
    if(gpuFilm != 0)
    {
      // XXX yuck fix this
      const_cast<GpuFilm<RenderFilm> *>(gpuFilm)->renderPendingDeposits();
      texture = &gpuFilm->mTexture;
    } // end if

    shared_ptr<const RenderFilm> film = dynamic_pointer_cast<const RenderFilm,const Record>(rec);

    const float *data = reinterpret_cast<const float*>(&film->raster(0,0));
    GLenum datatype = GL_FLOAT_RGB16_NV;

    mTexture.init(datatype,
                  width(), height(),
                  0,
                  GL_RGB, data);

    // choose which program to use
    Program &p = mDoTonemap ? mTexture2DRectTonemapProgram : mTexture2DRectGammaProgram;

    p.bind();

    // scale by 1/spp if we haven't finished the render
    float scale = 1.0f;
    //if(!mDoTonemap && mProgress.count() < mProgress.expected_count())
    if(mProgress.count() < mProgress.expected_count())
    {
      // XXX DESIGN kill this dynamic_cast somehow
      const MonteCarloRenderer *mc = dynamic_cast<const MonteCarloRenderer*>(mRenderer.get());
      if(mc)
      {
        float spp = mc->getNumSamples();
        spp /= (film->getWidth() * film->getHeight());
        scale = 1.0f / spp;
      } // end if
    } // end else

    p.setUniform1f("scale", powf(2.0f, mExposure) * scale);
    p.setUniform1f("gamma", mGamma);
    float meanLogL = film->getSumLogLuminance() / (film->getWidth() * film->getHeight());
    float Lwa = expf(meanLogL);
    p.setUniform1f("Lwa", Lwa);
    p.setUniform1f("Lwhite", film->getMaximumLuminance());
    p.setUniform1f("a", mMiddleGrey);

    printGLError(__FILE__, __LINE__);

    p.unbind();

    glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT);

    drawTexture(*texture, p);
    glPopAttrib();
  } // end if
  else
  {
    drawScenePreview();
  } // end else
} // end RenderViewer::draw()

void RenderViewer
  ::drawScenePreview(void)
{
  Parent::draw();
} // end RenderViewer::drawScenePreview()

void RenderViewer
  ::init(void)
{
  glewInit();

  // first init the parent
  Parent::init();

  // no state file please
  setStateFileName(QString::null);

  // init other stuff
  mTexture.create();

  mDrawPreview = true;
  mExposure = 0.0f;
  mGamma = 1.0f;

  mDoTonemap = false;
  mMiddleGrey = 0.5f;

  // resize
  resize(512,512);

  shared_ptr<const RenderFilm> film = dynamic_pointer_cast<const RenderFilm,const Record>(mRenderer->getRecord());
  if(film.get() != 0)
  {
    resize(film->getWidth(), film->getHeight());
  } // end if
} // end RenderViewer::init()

void RenderViewer
  ::keyPressEvent(KeyEvent *e)
{
  switch(e->key())
  {
    case Qt::Key_R:
    {
      startRender();
      mDrawPreview = false;
      updateGL();
      break;
    } // end case Qt::Key_R

    case Qt::Key_P:
    {
      mDrawPreview = !mDrawPreview;
      updateGL();
      break;
    } // end case Qt::Key_P

    case '(':
    {
      mGamma -= 0.1f;
      mGamma = std::max(mGamma, 0.1f);

      char msg[32];
      sprintf(msg, "Gamma: %f", mGamma);
      displayMessage(msg);
      updateGL();
      break;
    } // end case (

    case ')':
    {
      mGamma += 0.1f;

      char msg[32];
      sprintf(msg, "Gamma: %f", mGamma);
      displayMessage(msg);
      updateGL();
      break;
    } // end case )

    case '{':
    {
      mExposure -= 1.0f;

      char msg[32];
      sprintf(msg, "Exposure: %f", mExposure);
      displayMessage(msg);
      updateGL();
      break;
    } // end case '{'

    case '[':
    {
      char msg[32];
      if(mDoTonemap)
      {
        mMiddleGrey -= 0.01f;

        sprintf(msg, "Middle grey: %f", mMiddleGrey);
      } // end if
      else
      {
        mExposure -= 0.1f;

        sprintf(msg, "Exposure: %f", mExposure);
      } // end else

      displayMessage(msg);
      updateGL();
      break;
    } // end case '['

    case '}':
    {
      mExposure += 1.0f;

      char msg[32];
      sprintf(msg, "Exposure: %f", mExposure);
      displayMessage(msg);
      updateGL();
      break;
    } // end case '}'

    case ']':
    {
      char msg[32];

      if(mDoTonemap)
      {
        mMiddleGrey += 0.01f;

        sprintf(msg, "Middle grey: %f", mMiddleGrey);
      } // end if
      else
      {
        mExposure += 0.1f;

        sprintf(msg, "Exposure: %f", mExposure);
      } // end else

      displayMessage(msg);
      updateGL();
      break;
    } // end case ']'

    case 'T':
    {
      mDoTonemap = !mDoTonemap;
      updateGL();
      break;
    } // end case 'T'

    default:
    {
      Parent::keyPressEvent(e);
      break;
    } // end default
  } // end switch
} // end RenderViewer::keyPressEvent()

void RenderViewer
  ::resizeGL(int w, int h)
{
  Parent::resizeGL(w,h);

  char buffer[32];
  sprintf(buffer, "%d", width());
  std::string message = buffer;
  message += "x";
  sprintf(buffer, "%d", height());
  message += buffer;

  displayMessage(message);
  updateGL();
} // end RenderViewer::resizeGL()

class RenderThunk
{
  public:

  inline RenderThunk(Renderer *renderer,
                     Renderer::ProgressCallback *progress)
    :mRenderer(renderer),mProgress(progress)
  {
    ;
  }

  inline virtual ~RenderThunk(void){;};

  virtual void run(void)
  {
    (*this)();
  }

  void operator()(void)
  {
    mRenderer->render(*mProgress);
  }

  Renderer *mRenderer;
  Renderer::ProgressCallback *mProgress;
};

void RenderViewer
  ::postSelection(const QPoint &p)
{
  ;
} // end RenderViewer::postSelection()

void RenderViewer
  ::setRenderer(shared_ptr<Renderer> r)
{
  mRenderer = r;

  shared_ptr<const Record> rec = mRenderer->getRecord();
  const RandomAccessFilm *image = dynamic_cast<const RandomAccessFilm*>(rec.get());
  if(image != 0)
  {
    resizeGL(image->getWidth(), image->getHeight());
  } // end if
} // end Renderer::setRenderer()

void RenderViewer
  ::startRender(void)
{
  // XXX make RenderThunk refer to a shared_ptr
  RenderThunk render = RenderThunk(mRenderer.get(), &mProgress);
  boost::thread renderThread(render);

  // update the visualization every second
  setAnimationPeriod(1000);

  // update the frame automatically
  startAnimation();
} // end RenderViewer::startRender()

<|endoftext|>


<commit_before>//===-- gccas.cpp - The "optimizing assembler" used by the GCC frontend ---===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility is designed to be used by the GCC frontend for creating bytecode
// files from its intermediate LLVM assembly.  The requirements for this utility
// are thus slightly different than that of the standard `as' util.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/LoadValueNumbering.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/System/Signals.h"
#include <memory>
#include <fstream>

using namespace llvm;

namespace {
  cl::opt<std::string>
  InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-"));

  cl::opt<std::string>
  OutputFilename("o", cl::desc("Override output filename"),
                 cl::value_desc("filename"));

  cl::opt<bool>
  Verify("verify", cl::desc("Verify each pass result"));

  cl::opt<bool>
  DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));

  cl::opt<bool>
  DisableOptimizations("disable-opt",
                       cl::desc("Do not run any optimization passes"));

  cl::opt<bool>
  DisableDSE("disable-dse", cl::desc("Do not run dead store elimination"));
}

static inline void addPass(PassManager &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);

  // If we are verifying all of the intermediate steps, add the verifier...
  if (Verify) PM.add(createVerifierPass());
}

void AddConfiguredTransformationPasses(PassManager &PM) {
  PM.add(createVerifierPass());                  // Verify that input is correct
  addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
  addPass(PM, createFunctionResolvingPass());    // Resolve (...) functions

  if (DisableOptimizations) return;

  addPass(PM, createRaiseAllocationsPass());     // call %malloc -> malloc inst
  addPass(PM, createCFGSimplificationPass());    // Clean up disgusting code
  addPass(PM, createPromoteMemoryToRegister());  // Kill useless allocas
  addPass(PM, createGlobalOptimizerPass());      // Optimize out global vars
  addPass(PM, createGlobalDCEPass());            // Remove unused fns and globs
  addPass(PM, createIPConstantPropagationPass());// IP Constant Propagation
  addPass(PM, createDeadArgEliminationPass());   // Dead argument elimination
  addPass(PM, createInstructionCombiningPass()); // Clean up after IPCP & DAE
  addPass(PM, createCFGSimplificationPass());    // Clean up after IPCP & DAE

  addPass(PM, createPruneEHPass());              // Remove dead EH info

  if (!DisableInline)
    addPass(PM, createFunctionInliningPass());   // Inline small functions
  addPass(PM, createArgumentPromotionPass());    // Scalarize uninlined fn args

  addPass(PM, createRaisePointerReferencesPass());// Recover type information
  addPass(PM, createTailDuplicationPass());      // Simplify cfg by copying code
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's

  addPass(PM, createReassociatePass());          // Reassociate expressions
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
  addPass(PM, createTailCallEliminationPass());  // Eliminate tail calls
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createLICMPass());                 // Hoist loop invariants
  addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
  addPass(PM, createIndVarSimplifyPass());       // Canonicalize indvars
  addPass(PM, createLoopUnrollPass());           // Unroll small loops
  addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
  addPass(PM, createLoadValueNumberingPass());   // GVN for load instructions
  addPass(PM, createGCSEPass());                 // Remove common subexprs
  addPass(PM, createSCCPPass());                 // Constant prop with SCCP

  // Run instcombine after redundancy elimination to exploit opportunities
  // opened up by them.
  addPass(PM, createInstructionCombiningPass());
  if (!DisableDSE)
    addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
  addPass(PM, createAggressiveDCEPass());        // SSA based 'Aggressive DCE'
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createDeadTypeEliminationPass());  // Eliminate dead types
  addPass(PM, createConstantMergePass());        // Merge dup global constants
}

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");
  sys::PrintStackTraceOnErrorSignal();

  std::auto_ptr<Module> M;
  try {
    // Parse the file now...
    M.reset(ParseAssemblyFile(InputFilename));
  } catch (const ParseException &E) {
    std::cerr << argv[0] << ": " << E.getMessage() << "\n";
    return 1;
  }

  if (M.get() == 0) {
    std::cerr << argv[0] << ": assembly didn't read correctly.\n";
    return 1;
  }

  std::ostream *Out = 0;
  if (OutputFilename == "") {   // Didn't specify an output filename?
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      std::string IFN = InputFilename;
      int Len = IFN.length();
      if (IFN[Len-2] == '.' && IFN[Len-1] == 's') {   // Source ends in .s?
        OutputFilename = std::string(IFN.begin(), IFN.end()-2);
      } else {
        OutputFilename = IFN;   // Append a .o to it
      }
      OutputFilename += ".o";
    }
  }

  if (OutputFilename == "-")
    Out = &std::cout;
  else {
    Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);

    // Make sure that the Out file gets unlinked from the disk if we get a
    // signal
    sys::RemoveFileOnSignal(OutputFilename);
  }

  if (!Out->good()) {
    std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
    return 1;
  }

  // In addition to just parsing the input from GCC, we also want to spiff it up
  // a little bit.  Do this now.
  //
  PassManager Passes;

  // Add an appropriate TargetData instance for this module...
  Passes.add(new TargetData("gccas", M.get()));

  // Add all of the transformation passes to the pass manager to do the cleanup
  // and optimization of the GCC output.
  //
  AddConfiguredTransformationPasses(Passes);

  // Make sure everything is still good.
  Passes.add(createVerifierPass());

  // Write bytecode to file...
  Passes.add(new WriteBytecodePass(Out));

  // Run our queue of passes all at once now, efficiently.
  Passes.run(*M.get());

  if (Out != &std::cout) delete Out;
  return 0;
}
<commit_msg>Add a --disable-compression option to gccas so the default compression of bytecode can be defeated.<commit_after>//===-- gccas.cpp - The "optimizing assembler" used by the GCC frontend ---===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility is designed to be used by the GCC frontend for creating bytecode
// files from its intermediate LLVM assembly.  The requirements for this utility
// are thus slightly different than that of the standard `as' util.
//
//===----------------------------------------------------------------------===//

#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/LoadValueNumbering.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/System/Signals.h"
#include <memory>
#include <fstream>

using namespace llvm;

namespace {
  cl::opt<std::string>
  InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-"));

  cl::opt<std::string>
  OutputFilename("o", cl::desc("Override output filename"),
                 cl::value_desc("filename"));

  cl::opt<bool>
  Verify("verify", cl::desc("Verify each pass result"));

  cl::opt<bool>
  DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));

  cl::opt<bool>
  DisableOptimizations("disable-opt",
                       cl::desc("Do not run any optimization passes"));

  cl::opt<bool>
  DisableDSE("disable-dse", cl::desc("Do not run dead store elimination"));
  cl::opt<bool>
  NoCompress("disable-compression", cl::init(false),
             cl::desc("Don't ompress the generated bytecode"));
}

static inline void addPass(PassManager &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);

  // If we are verifying all of the intermediate steps, add the verifier...
  if (Verify) PM.add(createVerifierPass());
}

void AddConfiguredTransformationPasses(PassManager &PM) {
  PM.add(createVerifierPass());                  // Verify that input is correct
  addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
  addPass(PM, createFunctionResolvingPass());    // Resolve (...) functions

  if (DisableOptimizations) return;

  addPass(PM, createRaiseAllocationsPass());     // call %malloc -> malloc inst
  addPass(PM, createCFGSimplificationPass());    // Clean up disgusting code
  addPass(PM, createPromoteMemoryToRegister());  // Kill useless allocas
  addPass(PM, createGlobalOptimizerPass());      // Optimize out global vars
  addPass(PM, createGlobalDCEPass());            // Remove unused fns and globs
  addPass(PM, createIPConstantPropagationPass());// IP Constant Propagation
  addPass(PM, createDeadArgEliminationPass());   // Dead argument elimination
  addPass(PM, createInstructionCombiningPass()); // Clean up after IPCP & DAE
  addPass(PM, createCFGSimplificationPass());    // Clean up after IPCP & DAE

  addPass(PM, createPruneEHPass());              // Remove dead EH info

  if (!DisableInline)
    addPass(PM, createFunctionInliningPass());   // Inline small functions
  addPass(PM, createArgumentPromotionPass());    // Scalarize uninlined fn args

  addPass(PM, createRaisePointerReferencesPass());// Recover type information
  addPass(PM, createTailDuplicationPass());      // Simplify cfg by copying code
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's

  addPass(PM, createReassociatePass());          // Reassociate expressions
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
  addPass(PM, createTailCallEliminationPass());  // Eliminate tail calls
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createLICMPass());                 // Hoist loop invariants
  addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
  addPass(PM, createIndVarSimplifyPass());       // Canonicalize indvars
  addPass(PM, createLoopUnrollPass());           // Unroll small loops
  addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
  addPass(PM, createLoadValueNumberingPass());   // GVN for load instructions
  addPass(PM, createGCSEPass());                 // Remove common subexprs
  addPass(PM, createSCCPPass());                 // Constant prop with SCCP

  // Run instcombine after redundancy elimination to exploit opportunities
  // opened up by them.
  addPass(PM, createInstructionCombiningPass());
  if (!DisableDSE)
    addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
  addPass(PM, createAggressiveDCEPass());        // SSA based 'Aggressive DCE'
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createDeadTypeEliminationPass());  // Eliminate dead types
  addPass(PM, createConstantMergePass());        // Merge dup global constants
}

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");
  sys::PrintStackTraceOnErrorSignal();

  std::auto_ptr<Module> M;
  try {
    // Parse the file now...
    M.reset(ParseAssemblyFile(InputFilename));
  } catch (const ParseException &E) {
    std::cerr << argv[0] << ": " << E.getMessage() << "\n";
    return 1;
  }

  if (M.get() == 0) {
    std::cerr << argv[0] << ": assembly didn't read correctly.\n";
    return 1;
  }

  std::ostream *Out = 0;
  if (OutputFilename == "") {   // Didn't specify an output filename?
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      std::string IFN = InputFilename;
      int Len = IFN.length();
      if (IFN[Len-2] == '.' && IFN[Len-1] == 's') {   // Source ends in .s?
        OutputFilename = std::string(IFN.begin(), IFN.end()-2);
      } else {
        OutputFilename = IFN;   // Append a .o to it
      }
      OutputFilename += ".o";
    }
  }

  if (OutputFilename == "-")
    Out = &std::cout;
  else {
    Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);

    // Make sure that the Out file gets unlinked from the disk if we get a
    // signal
    sys::RemoveFileOnSignal(OutputFilename);
  }

  if (!Out->good()) {
    std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
    return 1;
  }

  // In addition to just parsing the input from GCC, we also want to spiff it up
  // a little bit.  Do this now.
  //
  PassManager Passes;

  // Add an appropriate TargetData instance for this module...
  Passes.add(new TargetData("gccas", M.get()));

  // Add all of the transformation passes to the pass manager to do the cleanup
  // and optimization of the GCC output.
  //
  AddConfiguredTransformationPasses(Passes);

  // Make sure everything is still good.
  Passes.add(createVerifierPass());

  // Write bytecode to file...
  Passes.add(new WriteBytecodePass(Out,false,!NoCompress));

  // Run our queue of passes all at once now, efficiently.
  Passes.run(*M.get());

  if (Out != &std::cout) delete Out;
  return 0;
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <cstdio>
#include <limits>
#include <type_traits>
#include <iostream>
#include <stack>
#include <random>

#include "utility/bithacks.h"

#include "cppunit-header.h"

template <typename T>
void printBits(T x)
{
	for (int i = ((sizeof(x) * 8) - 1); i >= 0; --i)
	{
		if (x & (static_cast<T>(1) << i))
			putchar('1');
		else
			putchar('0');

		if ((i % 16) == 0)
			putchar(' ');
		else if ((i % 8) == 0)
			putchar('_');
	}

	putchar('\n');
}

class Test_bit_width : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_bit_width);
	CPPUNIT_TEST(test_width<char>);
	CPPUNIT_TEST(test_width<signed char>);
	CPPUNIT_TEST(test_width<unsigned char>);
	CPPUNIT_TEST(test_width<short>);
	CPPUNIT_TEST(test_width<unsigned short>);
	CPPUNIT_TEST(test_width<int>);
	CPPUNIT_TEST(test_width<unsigned int>);
	CPPUNIT_TEST(test_width<long>);
	CPPUNIT_TEST(test_width<unsigned long>);
	CPPUNIT_TEST(test_width<long long>);
	CPPUNIT_TEST(test_width<unsigned long long>);
	CPPUNIT_TEST(test_width<float>);
	CPPUNIT_TEST(test_width<double>);
	CPPUNIT_TEST(test_width<long double>);
	CPPUNIT_TEST_SUITE_END();
 protected:
	template <typename T>
	void test_width()
	{
		T val = 0;
		CPPUNIT_ASSERT(bit_width<T>() == (sizeof(T) * 8));
		CPPUNIT_ASSERT(bit_width(val) == (sizeof(T) * 8));
	}
};

class Test_pop_count : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_pop_count);
	CPPUNIT_TEST(single_bit<char>);
	CPPUNIT_TEST(single_bit<signed char>);
	CPPUNIT_TEST(single_bit<unsigned char>);
	CPPUNIT_TEST(single_bit<short>);
	CPPUNIT_TEST(single_bit<unsigned short>);
	CPPUNIT_TEST(single_bit<int>);
	CPPUNIT_TEST(single_bit<unsigned int>);
	CPPUNIT_TEST(single_bit<long>);
	CPPUNIT_TEST(single_bit<unsigned long>);
	CPPUNIT_TEST(single_bit<long long>);
	CPPUNIT_TEST(single_bit<unsigned long long>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template <typename T>
	  void single_bit()
	{
		const T one = 1; // used to avoid unwanted implict conversion

		for (size_t i = 0; i < bit_width<T>(); ++i)
		{
			T value = (one << i);
			size_t res = pop_count<T>(value);
			CPPUNIT_ASSERT(res == 1);
		}
	}
};

class Test_bitReverse : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_bitReverse);
	CPPUNIT_TEST(single_bit<uint8_t>);
	CPPUNIT_TEST(single_bit<uint16_t>);
	CPPUNIT_TEST(single_bit<uint32_t>);
	CPPUNIT_TEST(single_bit<uint64_t>);

	CPPUNIT_TEST(randomPattern<uint8_t>);
	CPPUNIT_TEST(randomPattern<uint16_t>);
	CPPUNIT_TEST(randomPattern<uint32_t>);
	CPPUNIT_TEST(randomPattern<uint64_t>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template<typename T> void single_bit()
	{
		T x = 1, y = 1;
		y <<= ((sizeof(x) * 8) - 1);

		for (size_t i = 0; i < bit_width<T>(); ++i)
		{
			CPPUNIT_ASSERT(bitReverse(x) == y);
			CPPUNIT_ASSERT(bitReverse(bitReverse(x)) == x);
			x <<= 1;
			y >>= 1;
		}
	}

	template<typename T> void randomPattern()
	{
		std::stack<bool> s;
		std::default_random_engine engine;
		std::uniform_int_distribution<T> dist(std::numeric_limits<T>::min(),
		                                      std::numeric_limits<T>::max());

		for (int num = 0; num < 256; ++num)
		{
			T x = dist(engine);
			const T one = 1;

			for (size_t i = 0; i < bit_width<T>(); ++i)
			{
				if (x & (one << i))
					s.push(true);
				else
					s.push(false);
			}

			T rx = bitReverse(x);

			CPPUNIT_ASSERT(x == bitReverse(rx));

			for (size_t i = 0; i < bit_width<T>(); ++i)
			{
				if (rx & (one << i))
					CPPUNIT_ASSERT(s.top());
				else
					CPPUNIT_ASSERT(! s.top());
				s.pop();
			}
		}
	}

};

class Test_byteReverse : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_byteReverse);
	CPPUNIT_TEST(single_bit<uint8_t>);
	CPPUNIT_TEST(single_bit<uint16_t>);
	CPPUNIT_TEST(single_bit<uint32_t>);
	CPPUNIT_TEST(single_bit<uint64_t>);

	CPPUNIT_TEST(randomPattern<uint8_t>);
	CPPUNIT_TEST(randomPattern<uint16_t>);
	CPPUNIT_TEST(randomPattern<uint32_t>);
	CPPUNIT_TEST(randomPattern<uint64_t>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template <typename T>
	static T getByte (T v, size_t i)
	{
		const T mask = 0xFF;
//		std::cout << "-> " << i << ": "<< std::hex << v << ' ';
		T ret = (v & (mask << (bit_width<uint8_t>() * i)));
//		std::cout << std::hex << ret << ' ';
		ret >>= (bit_width<uint8_t>() * i);
//		std::cout << ret << std::endl;
		return ret;
	}

	template<typename T> void single_bit()
	{
		for (size_t i = 0; i < (bit_width<uint8_t>()); ++i)
		{
			T x = 1;
			x <<= i;

			for (size_t j = 0; j < sizeof(T); ++j)
			{
				T rx = byteReverse(x);

//				std::cout << '\n' << std::hex
//				          << static_cast<uint64_t>(rx) << ' '
//				          << static_cast<uint64_t>(x) << std::dec;

				CPPUNIT_ASSERT(getByte(x, j) == getByte(rx, sizeof(T) - 1 - j));

				if (sizeof(T) > 1)
					x <<= 8;
			}
		}
	}

	template<typename T> void randomPattern()
	{
		std::stack<uint8_t> s;
		std::default_random_engine engine;
		std::uniform_int_distribution<T> dist(std::numeric_limits<T>::min(),
		                                      std::numeric_limits<T>::max());

		for (int num = 0; num < 256; ++num)
		{
			T x = dist(engine);

//			std::cout << "Testing with " << std::hex << x << std::endl;

			for (size_t i = 0; i < sizeof(T); ++i)
			{
				uint8_t b = getByte(x, i);
//				std::cout << i << ": " << std::hex << static_cast<uint32_t>(b)
//				          << std::endl;
				s.push(b);
			}

			T rx = byteReverse(x);

			CPPUNIT_ASSERT(x == byteReverse(rx));

			for (size_t i = 0; i < sizeof(T); ++i)
			{
#if 0
				if (s.top() != getByte(rx, i))
				{
					std::cout << std::hex << static_cast<uint32_t>(s.top())
					          << " and " << std::hex
					          << static_cast<uint32_t>(getByte(rx, i))
					          << " do not match" << std::endl;
					std::cout << std::dec;
				}
#else
				CPPUNIT_ASSERT(s.top() == getByte(rx, i));
#endif
				s.pop();
			}
		}

	}

};

class Test_numLeadingZeros : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_numLeadingZeros);
	CPPUNIT_TEST(numLeadingZerosTest<uint8_t>);
	CPPUNIT_TEST(numLeadingZerosTest<uint16_t>);
	CPPUNIT_TEST(numLeadingZerosTest<uint32_t>);
	CPPUNIT_TEST(numLeadingZerosTest<uint64_t>);

	CPPUNIT_TEST(nlzTest<uint8_t>);
	CPPUNIT_TEST(nlzTest<uint16_t>);
	CPPUNIT_TEST(nlzTest<uint32_t>);
	CPPUNIT_TEST(nlzTest<uint64_t>);

	CPPUNIT_TEST(testLog<uint8_t>);
	CPPUNIT_TEST(testLog<uint16_t>);
	CPPUNIT_TEST(testLog<uint32_t>);
	CPPUNIT_TEST(testLog<uint64_t>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template<typename T>
	void nlzTest()
	{
		T value = 1;

		for (size_t i = 0; i < bit_width<T>(); ++i)
		{
			size_t correctValue = bit_width<T>() - i - 1;

			CPPUNIT_ASSERT(nlz<T>(value << i) == correctValue);
		}
	}

	template<typename T>
	void numLeadingZerosTest()
	{
		T value = 1;

		for (size_t i = 0; i < bit_width<T>(); ++i)
		{
			size_t correctValue = bit_width<T>() - i - 1;

			CPPUNIT_ASSERT(numLeadingZeros<T>(value << i) == correctValue);
		}
	}

	template<typename T>
	void testLog()
	{
		T value = 1;
		CPPUNIT_ASSERT( intLog2Floor(value) == 0);
		CPPUNIT_ASSERT( intLog2Ceiling(value) == 0);

		value = 2;
		CPPUNIT_ASSERT( intLog2Floor(value) == 1);
		CPPUNIT_ASSERT( intLog2Ceiling(value) == 1);

		value = 3;
		CPPUNIT_ASSERT( intLog2Floor(value) == 1);
		CPPUNIT_ASSERT( intLog2Ceiling(value) == 2);

		for (T i = 4; i != 0; i <<= 1)
		{
			T prev = i - 1;
			T next = i + 1;

			CPPUNIT_ASSERT( intLog2Ceiling(prev) == intLog2Floor(i) );
			CPPUNIT_ASSERT( intLog2Ceiling(i) == intLog2Floor(i) );
			CPPUNIT_ASSERT( intLog2Ceiling(i) == intLog2Floor(next) );
		}
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(Test_bit_width);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_pop_count);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_bitReverse);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_byteReverse);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_numLeadingZeros);

<commit_msg>Added tests for nlz before removing the other versions of it from bithacks.h<commit_after>#include <cstdint>
#include <cstdio>
#include <limits>
#include <type_traits>
#include <iostream>
#include <stack>
#include <random>

#include "utility/bithacks.h"

#include "cppunit-header.h"

template <typename T>
void printBits(T x)
{
	for (int i = ((sizeof(x) * 8) - 1); i >= 0; --i)
	{
		if (x & (static_cast<T>(1) << i))
			putchar('1');
		else
			putchar('0');

		if ((i % 16) == 0)
			putchar(' ');
		else if ((i % 8) == 0)
			putchar('_');
	}

	putchar('\n');
}

class Test_bit_width : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_bit_width);
	CPPUNIT_TEST(test_width<char>);
	CPPUNIT_TEST(test_width<signed char>);
	CPPUNIT_TEST(test_width<unsigned char>);
	CPPUNIT_TEST(test_width<short>);
	CPPUNIT_TEST(test_width<unsigned short>);
	CPPUNIT_TEST(test_width<int>);
	CPPUNIT_TEST(test_width<unsigned int>);
	CPPUNIT_TEST(test_width<long>);
	CPPUNIT_TEST(test_width<unsigned long>);
	CPPUNIT_TEST(test_width<long long>);
	CPPUNIT_TEST(test_width<unsigned long long>);
	CPPUNIT_TEST(test_width<float>);
	CPPUNIT_TEST(test_width<double>);
	CPPUNIT_TEST(test_width<long double>);
	CPPUNIT_TEST_SUITE_END();
 protected:
	template <typename T>
	void test_width()
	{
		T val = 0;
		CPPUNIT_ASSERT(bit_width<T>() == (sizeof(T) * 8));
		CPPUNIT_ASSERT(bit_width(val) == (sizeof(T) * 8));
	}
};

class Test_pop_count : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_pop_count);
	CPPUNIT_TEST(single_bit<char>);
	CPPUNIT_TEST(single_bit<signed char>);
	CPPUNIT_TEST(single_bit<unsigned char>);
	CPPUNIT_TEST(single_bit<short>);
	CPPUNIT_TEST(single_bit<unsigned short>);
	CPPUNIT_TEST(single_bit<int>);
	CPPUNIT_TEST(single_bit<unsigned int>);
	CPPUNIT_TEST(single_bit<long>);
	CPPUNIT_TEST(single_bit<unsigned long>);
	CPPUNIT_TEST(single_bit<long long>);
	CPPUNIT_TEST(single_bit<unsigned long long>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template <typename T>
	  void single_bit()
	{
		const T one = 1; // used to avoid unwanted implict conversion

		for (size_t i = 0; i < bit_width<T>(); ++i)
		{
			T value = (one << i);
			size_t res = pop_count<T>(value);
			CPPUNIT_ASSERT(res == 1);
		}
	}
};

class Test_bitReverse : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_bitReverse);
	CPPUNIT_TEST(single_bit<uint8_t>);
	CPPUNIT_TEST(single_bit<uint16_t>);
	CPPUNIT_TEST(single_bit<uint32_t>);
	CPPUNIT_TEST(single_bit<uint64_t>);

	CPPUNIT_TEST(randomPattern<uint8_t>);
	CPPUNIT_TEST(randomPattern<uint16_t>);
	CPPUNIT_TEST(randomPattern<uint32_t>);
	CPPUNIT_TEST(randomPattern<uint64_t>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template<typename T> void single_bit()
	{
		T x = 1, y = 1;
		y <<= ((sizeof(x) * 8) - 1);

		for (size_t i = 0; i < bit_width<T>(); ++i)
		{
			CPPUNIT_ASSERT(bitReverse(x) == y);
			CPPUNIT_ASSERT(bitReverse(bitReverse(x)) == x);
			x <<= 1;
			y >>= 1;
		}
	}

	template<typename T> void randomPattern()
	{
		std::stack<bool> s;
		std::default_random_engine engine;
		std::uniform_int_distribution<T> dist(std::numeric_limits<T>::min(),
		                                      std::numeric_limits<T>::max());

		for (int num = 0; num < 256; ++num)
		{
			T x = dist(engine);
			const T one = 1;

			for (size_t i = 0; i < bit_width<T>(); ++i)
			{
				if (x & (one << i))
					s.push(true);
				else
					s.push(false);
			}

			T rx = bitReverse(x);

			CPPUNIT_ASSERT(x == bitReverse(rx));

			for (size_t i = 0; i < bit_width<T>(); ++i)
			{
				if (rx & (one << i))
					CPPUNIT_ASSERT(s.top());
				else
					CPPUNIT_ASSERT(! s.top());
				s.pop();
			}
		}
	}

};

class Test_byteReverse : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_byteReverse);
	CPPUNIT_TEST(single_bit<uint8_t>);
	CPPUNIT_TEST(single_bit<uint16_t>);
	CPPUNIT_TEST(single_bit<uint32_t>);
	CPPUNIT_TEST(single_bit<uint64_t>);

	CPPUNIT_TEST(randomPattern<uint8_t>);
	CPPUNIT_TEST(randomPattern<uint16_t>);
	CPPUNIT_TEST(randomPattern<uint32_t>);
	CPPUNIT_TEST(randomPattern<uint64_t>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template <typename T>
	static T getByte (T v, size_t i)
	{
		const T mask = 0xFF;
//		std::cout << "-> " << i << ": "<< std::hex << v << ' ';
		T ret = (v & (mask << (bit_width<uint8_t>() * i)));
//		std::cout << std::hex << ret << ' ';
		ret >>= (bit_width<uint8_t>() * i);
//		std::cout << ret << std::endl;
		return ret;
	}

	template<typename T> void single_bit()
	{
		for (size_t i = 0; i < (bit_width<uint8_t>()); ++i)
		{
			T x = 1;
			x <<= i;

			for (size_t j = 0; j < sizeof(T); ++j)
			{
				T rx = byteReverse(x);

//				std::cout << '\n' << std::hex
//				          << static_cast<uint64_t>(rx) << ' '
//				          << static_cast<uint64_t>(x) << std::dec;

				CPPUNIT_ASSERT(getByte(x, j) == getByte(rx, sizeof(T) - 1 - j));

				if (sizeof(T) > 1)
					x <<= 8;
			}
		}
	}

	template<typename T> void randomPattern()
	{
		std::stack<uint8_t> s;
		std::default_random_engine engine;
		std::uniform_int_distribution<T> dist(std::numeric_limits<T>::min(),
		                                      std::numeric_limits<T>::max());

		for (int num = 0; num < 256; ++num)
		{
			T x = dist(engine);

//			std::cout << "Testing with " << std::hex << x << std::endl;

			for (size_t i = 0; i < sizeof(T); ++i)
			{
				uint8_t b = getByte(x, i);
//				std::cout << i << ": " << std::hex << static_cast<uint32_t>(b)
//				          << std::endl;
				s.push(b);
			}

			T rx = byteReverse(x);

			CPPUNIT_ASSERT(x == byteReverse(rx));

			for (size_t i = 0; i < sizeof(T); ++i)
			{
#if 0
				if (s.top() != getByte(rx, i))
				{
					std::cout << std::hex << static_cast<uint32_t>(s.top())
					          << " and " << std::hex
					          << static_cast<uint32_t>(getByte(rx, i))
					          << " do not match" << std::endl;
					std::cout << std::dec;
				}
#else
				CPPUNIT_ASSERT(s.top() == getByte(rx, i));
#endif
				s.pop();
			}
		}

	}

};

class Test_nlz : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_nlz);
	CPPUNIT_TEST(top_bit<char>);
	CPPUNIT_TEST(top_bit<signed char>);
	CPPUNIT_TEST(top_bit<unsigned char>);
	CPPUNIT_TEST(top_bit<short>);
	CPPUNIT_TEST(top_bit<unsigned short>);
	CPPUNIT_TEST(top_bit<int>);
	CPPUNIT_TEST(top_bit<unsigned int>);
	CPPUNIT_TEST(top_bit<long>);
	CPPUNIT_TEST(top_bit<unsigned long>);
	CPPUNIT_TEST(top_bit<long long>);
	CPPUNIT_TEST(top_bit<unsigned long long>);

	CPPUNIT_TEST(pentultimate_bit<char>);
	CPPUNIT_TEST(pentultimate_bit<signed char>);
	CPPUNIT_TEST(pentultimate_bit<unsigned char>);
	CPPUNIT_TEST(pentultimate_bit<short>);
	CPPUNIT_TEST(pentultimate_bit<unsigned short>);
	CPPUNIT_TEST(pentultimate_bit<int>);
	CPPUNIT_TEST(pentultimate_bit<unsigned int>);
	CPPUNIT_TEST(pentultimate_bit<long>);
	CPPUNIT_TEST(pentultimate_bit<unsigned long>);
	CPPUNIT_TEST(pentultimate_bit<long long>);
	CPPUNIT_TEST(pentultimate_bit<unsigned long long>);

	CPPUNIT_TEST(least_bit<char>);
	CPPUNIT_TEST(least_bit<signed char>);
	CPPUNIT_TEST(least_bit<unsigned char>);
	CPPUNIT_TEST(least_bit<short>);
	CPPUNIT_TEST(least_bit<unsigned short>);
	CPPUNIT_TEST(least_bit<int>);
	CPPUNIT_TEST(least_bit<unsigned int>);
	CPPUNIT_TEST(least_bit<long>);
	CPPUNIT_TEST(least_bit<unsigned long>);
	CPPUNIT_TEST(least_bit<long long>);
	CPPUNIT_TEST(least_bit<unsigned long long>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template<typename T>
	void top_bit()
	{
		size_t type_width = bit_width<T>();

		T value = 1;
		value <<= (type_width - 1);

		CPPUNIT_ASSERT(nlz(value) == 0);
	}

	template<typename T>
	void pentultimate_bit()
	{
		size_t type_width = bit_width<T>();

		T value = 1;
		value <<= (type_width - 2);

		CPPUNIT_ASSERT(nlz(value) == 1);
	}

	template<typename T>
	void least_bit()
	{
		size_t type_width = bit_width<T>();
		T value = 1;
		CPPUNIT_ASSERT(nlz(value) == (type_width - 1));
	}
};

class Test_numLeadingZeros : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_numLeadingZeros);
	CPPUNIT_TEST(numLeadingZerosTest<uint8_t>);
	CPPUNIT_TEST(numLeadingZerosTest<uint16_t>);
	CPPUNIT_TEST(numLeadingZerosTest<uint32_t>);
	CPPUNIT_TEST(numLeadingZerosTest<uint64_t>);

	CPPUNIT_TEST(nlzTest<uint8_t>);
	CPPUNIT_TEST(nlzTest<uint16_t>);
	CPPUNIT_TEST(nlzTest<uint32_t>);
	CPPUNIT_TEST(nlzTest<uint64_t>);

	CPPUNIT_TEST(testLog<uint8_t>);
	CPPUNIT_TEST(testLog<uint16_t>);
	CPPUNIT_TEST(testLog<uint32_t>);
	CPPUNIT_TEST(testLog<uint64_t>);
	CPPUNIT_TEST_SUITE_END();

 protected:
	template<typename T>
	void nlzTest()
	{
		T value = 1;

		for (size_t i = 0; i < bit_width<T>(); ++i)
		{
			size_t correctValue = bit_width<T>() - i - 1;

			CPPUNIT_ASSERT(nlz<T>(value << i) == correctValue);
		}
	}

	template<typename T>
	void numLeadingZerosTest()
	{
		T value = 1;

		for (size_t i = 0; i < bit_width<T>(); ++i)
		{
			size_t correctValue = bit_width<T>() - i - 1;

			CPPUNIT_ASSERT(numLeadingZeros<T>(value << i) == correctValue);
		}
	}

	template<typename T>
	void testLog()
	{
		T value = 1;
		CPPUNIT_ASSERT( intLog2Floor(value) == 0);
		CPPUNIT_ASSERT( intLog2Ceiling(value) == 0);

		value = 2;
		CPPUNIT_ASSERT( intLog2Floor(value) == 1);
		CPPUNIT_ASSERT( intLog2Ceiling(value) == 1);

		value = 3;
		CPPUNIT_ASSERT( intLog2Floor(value) == 1);
		CPPUNIT_ASSERT( intLog2Ceiling(value) == 2);

		for (T i = 4; i != 0; i <<= 1)
		{
			T prev = i - 1;
			T next = i + 1;

			CPPUNIT_ASSERT( intLog2Ceiling(prev) == intLog2Floor(i) );
			CPPUNIT_ASSERT( intLog2Ceiling(i) == intLog2Floor(i) );
			CPPUNIT_ASSERT( intLog2Ceiling(i) == intLog2Floor(next) );
		}
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(Test_bit_width);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_pop_count);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_bitReverse);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_byteReverse);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_numLeadingZeros);
CPPUNIT_TEST_SUITE_REGISTRATION(Test_nlz);

<|endoftext|>


<commit_before>//===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility is intended to be compatible with GCC, and follows standard
// system 'ld' conventions.  As such, the default output file is ./a.out.
// Additionally, this program outputs a shell script that is used to invoke LLI
// to execute the program.  In this manner, the generated executable (a.out for
// example), is directly executable, whereas the bytecode file actually lives in
// the a.out.bc file generated by this program.  Also, Force is on by default.
//
// Note that if someone (or a script) deletes the executable program generated,
// the .bc file will be left around.  Considering that this is a temporary hack,
// I'm not too worried about this.
//
//===----------------------------------------------------------------------===//

#include "gccld.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "Support/CommandLine.h"
#include "Support/FileUtilities.h"
#include "Support/Signals.h"
#include "Support/SystemUtils.h"
#include <fstream>
#include <memory>

using namespace llvm;

namespace {
  cl::list<std::string>
  InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
                 cl::OneOrMore);

  cl::opt<std::string>
  OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
                 cl::value_desc("filename"));

  cl::opt<bool>
  Verbose("v", cl::desc("Print information about actions taken"));

  cl::list<std::string>
  LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
           cl::value_desc("directory"));

  cl::list<std::string>
  Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
            cl::value_desc("library prefix"));

  cl::opt<bool>
  Strip("s", cl::desc("Strip symbol info from executable"));

  cl::opt<bool>
  NoInternalize("disable-internalize",
                cl::desc("Do not mark all symbols as internal"));
  cl::alias
  ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
                cl::aliasopt(NoInternalize));

  cl::opt<bool>
  LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
                                            " library, not an executable"));
  cl::alias
  Relink("r", cl::desc("Alias for -link-as-library"),
         cl::aliasopt(LinkAsLibrary));

  cl::opt<bool>
  Native("native",
         cl::desc("Generate a native binary instead of a shell script"));
  cl::opt<bool>
  NativeCBE("native-cbe",
            cl::desc("Generate a native binary with the C backend and GCC"));

  // Compatibility options that are ignored but supported by LD
  cl::opt<std::string>
  CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
  cl::opt<std::string>
  CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
  cl::opt<bool>
  CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
  cl::opt<std::string>
  CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
}

namespace llvm {

/// PrintAndReturn - Prints a message to standard error and returns a value
/// usable for an exit status.
///
/// Inputs:
///  progname - The name of the program (i.e. argv[0]).
///  Message  - The message to print to standard error.
///  Extra    - Extra information to print between the program name and thei
///             message.  It is optional.
///
/// Return value:
///  Returns a value that can be used as the exit status (i.e. for exit()).
///
int
PrintAndReturn(const char *progname,
               const std::string &Message,
               const std::string &Extra)
{
  std::cerr << progname << Extra << ": " << Message << "\n";
  return 1;
}

/// CopyEnv - This function takes an array of environment variables and makes a
/// copy of it.  This copy can then be manipulated any way the caller likes
/// without affecting the process's real environment.
///
/// Inputs:
///  envp - An array of C strings containing an environment.
///
/// Return value:
///  NULL - An error occurred.
///
///  Otherwise, a pointer to a new array of C strings is returned.  Every string
///  in the array is a duplicate of the one in the original array (i.e. we do
///  not copy the char *'s from one array to another).
///
char ** CopyEnv(char ** const envp) {
  // Count the number of entries in the old list;
  unsigned entries;   // The number of entries in the old environment list
  for (entries = 0; envp[entries] != NULL; entries++)
    /*empty*/;

  // Add one more entry for the NULL pointer that ends the list.
  ++entries;

  // If there are no entries at all, just return NULL.
  if (entries == 0)
    return NULL;

  // Allocate a new environment list.
  char **newenv = new char* [entries];
  if ((newenv = new char* [entries]) == NULL)
    return NULL;

  // Make a copy of the list.  Don't forget the NULL that ends the list.
  entries = 0;
  while (envp[entries] != NULL) {
    newenv[entries] = new char[strlen (envp[entries]) + 1];
    strcpy (newenv[entries], envp[entries]);
    ++entries;
  }
  newenv[entries] = NULL;

  return newenv;
}

/// RemoveEnv - Remove the specified environment variable from the environment
/// array.
///
/// Inputs:
///  name - The name of the variable to remove.  It cannot be NULL.
///  envp - The array of environment variables.  It cannot be NULL.
///
/// Notes:
///  This is mainly done because functions to remove items from the environment
///  are not available across all platforms.  In particular, Solaris does not
///  seem to have an unsetenv() function or a setenv() function (or they are
///  undocumented if they do exist).
///
void RemoveEnv(const char * name, char ** const envp) {
  for (unsigned index=0; envp[index] != NULL; index++) {
    // Find the first equals sign in the array and make it an EOS character.
    char *p = strchr (envp[index], '=');
    if (p == NULL)
      continue;
    else
      *p = '\0';

    // Compare the two strings.  If they are equal, zap this string.
    // Otherwise, restore it.
    if (!strcmp(name, envp[index]))
      *envp[index] = '\0';
    else
      *p = '=';
  }

  return;
}

} // End llvm namespace

int main(int argc, char **argv, char **envp) {
  cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
  PrintStackTraceOnErrorSignal();

  std::string ModuleID("gccld-output");
  std::auto_ptr<Module> Composite(new Module(ModuleID));

  // We always look first in the current directory when searching for libraries.
  LibPaths.insert(LibPaths.begin(), ".");

  // If the user specified an extra search path in their environment, respect
  // it.
  if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
    LibPaths.push_back(SearchPath);

  // Remove any consecutive duplicates of the same library...
  Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
                  Libraries.end());

  // Link in all of the files
  if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
    return 1; // Error already printed

  if (!LinkAsLibrary)
    LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
                  Verbose, Native);

  // Link in all of the libraries next...

  // Create the output file.
  std::string RealBytecodeOutput = OutputFilename;
  if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
  std::ofstream Out(RealBytecodeOutput.c_str());
  if (!Out.good())
    return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
                                   "' for writing!");

  // Ensure that the bytecode file gets removed from the disk if we get a
  // SIGINT signal.
  RemoveFileOnSignal(RealBytecodeOutput);

  // Generate the bytecode file.
  if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
    Out.close();
    return PrintAndReturn(argv[0], "error generating bytecode");
  }

  // Close the bytecode file.
  Out.close();

  // If we are not linking a library, generate either a native executable
  // or a JIT shell script, depending upon what the user wants.
  if (!LinkAsLibrary) {
    // If the user wants to generate a native executable, compile it from the
    // bytecode file.
    //
    // Otherwise, create a script that will run the bytecode through the JIT.
    if (Native) {
      // Name of the Assembly Language output file
      std::string AssemblyFile = OutputFilename + ".s";

      // Mark the output files for removal if we get an interrupt.
      RemoveFileOnSignal(AssemblyFile);
      RemoveFileOnSignal(OutputFilename);

      // Determine the locations of the llc and gcc programs.
      std::string llc = FindExecutable("llc", argv[0]);
      std::string gcc = FindExecutable("gcc", argv[0]);
      if (llc.empty())
        return PrintAndReturn(argv[0], "Failed to find llc");

      if (gcc.empty())
        return PrintAndReturn(argv[0], "Failed to find gcc");

      // Generate an assembly language file for the bytecode.
      if (Verbose) std::cout << "Generating Assembly Code\n";
      GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
      if (Verbose) std::cout << "Generating Native Code\n";
      GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
                     gcc, envp);

      // Remove the assembly language file.
      removeFile (AssemblyFile);
    } else if (NativeCBE) {
      std::string CFile = OutputFilename + ".cbe.c";

      // Mark the output files for removal if we get an interrupt.
      RemoveFileOnSignal(CFile);
      RemoveFileOnSignal(OutputFilename);

      // Determine the locations of the llc and gcc programs.
      std::string llc = FindExecutable("llc", argv[0]);
      std::string gcc = FindExecutable("gcc", argv[0]);
      if (llc.empty())
        return PrintAndReturn(argv[0], "Failed to find llc");
      if (gcc.empty())
        return PrintAndReturn(argv[0], "Failed to find gcc");

      // Generate an assembly language file for the bytecode.
      if (Verbose) std::cout << "Generating Assembly Code\n";
      GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
      if (Verbose) std::cout << "Generating Native Code\n";
      GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);

      // Remove the assembly language file.
      removeFile(CFile);

    } else {
      // Output the script to start the program...
      std::ofstream Out2(OutputFilename.c_str());
      if (!Out2.good())
        return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
                                       "' for writing!");
      Out2 << "#!/bin/sh\nlli \\\n";
      // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
      LibPaths.push_back("/lib");
      LibPaths.push_back("/usr/lib");
      LibPaths.push_back("/usr/X11R6/lib");
      // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
      // shared object at all! See RH 8: plain text.
      std::vector<std::string>::iterator libc =
        std::find(Libraries.begin(), Libraries.end(), "c");
      if (libc != Libraries.end()) Libraries.erase(libc);
      // List all the shared object (native) libraries this executable will need
      // on the command line, so that we don't have to do this manually!
      for (std::vector<std::string>::iterator i = Libraries.begin(),
             e = Libraries.end(); i != e; ++i) {
        std::string FullLibraryPath = FindLib(*i, LibPaths, true);
        if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
          Out2 << "    -load=" << FullLibraryPath << " \\\n";
      }
      Out2 << "    $0.bc $*\n";
      Out2.close();
    }

    // Make the script executable...
    MakeFileExecutable(OutputFilename);

    // Make the bytecode file readable and directly executable in LLEE as well
    MakeFileExecutable(RealBytecodeOutput);
    MakeFileReadable(RealBytecodeOutput);
  }

  return 0;
}
<commit_msg>Allow the user to set the LLVMINTERP environment variable as a workaround, for when they have to run a gccld shell script without having lli in their path. This is intended to address Bug 289.<commit_after>//===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility is intended to be compatible with GCC, and follows standard
// system 'ld' conventions.  As such, the default output file is ./a.out.
// Additionally, this program outputs a shell script that is used to invoke LLI
// to execute the program.  In this manner, the generated executable (a.out for
// example), is directly executable, whereas the bytecode file actually lives in
// the a.out.bc file generated by this program.  Also, Force is on by default.
//
// Note that if someone (or a script) deletes the executable program generated,
// the .bc file will be left around.  Considering that this is a temporary hack,
// I'm not too worried about this.
//
//===----------------------------------------------------------------------===//

#include "gccld.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "Support/CommandLine.h"
#include "Support/FileUtilities.h"
#include "Support/Signals.h"
#include "Support/SystemUtils.h"
#include <fstream>
#include <memory>

using namespace llvm;

namespace {
  cl::list<std::string>
  InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
                 cl::OneOrMore);

  cl::opt<std::string>
  OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
                 cl::value_desc("filename"));

  cl::opt<bool>
  Verbose("v", cl::desc("Print information about actions taken"));

  cl::list<std::string>
  LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
           cl::value_desc("directory"));

  cl::list<std::string>
  Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
            cl::value_desc("library prefix"));

  cl::opt<bool>
  Strip("s", cl::desc("Strip symbol info from executable"));

  cl::opt<bool>
  NoInternalize("disable-internalize",
                cl::desc("Do not mark all symbols as internal"));
  cl::alias
  ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
                cl::aliasopt(NoInternalize));

  cl::opt<bool>
  LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
                                            " library, not an executable"));
  cl::alias
  Relink("r", cl::desc("Alias for -link-as-library"),
         cl::aliasopt(LinkAsLibrary));

  cl::opt<bool>
  Native("native",
         cl::desc("Generate a native binary instead of a shell script"));
  cl::opt<bool>
  NativeCBE("native-cbe",
            cl::desc("Generate a native binary with the C backend and GCC"));

  // Compatibility options that are ignored but supported by LD
  cl::opt<std::string>
  CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
  cl::opt<std::string>
  CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
  cl::opt<bool>
  CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
  cl::opt<std::string>
  CO6("h", cl::Hidden, cl::desc("Compatibility option: ignored"));
}

namespace llvm {

/// PrintAndReturn - Prints a message to standard error and returns a value
/// usable for an exit status.
///
/// Inputs:
///  progname - The name of the program (i.e. argv[0]).
///  Message  - The message to print to standard error.
///  Extra    - Extra information to print between the program name and thei
///             message.  It is optional.
///
/// Return value:
///  Returns a value that can be used as the exit status (i.e. for exit()).
///
int
PrintAndReturn(const char *progname,
               const std::string &Message,
               const std::string &Extra)
{
  std::cerr << progname << Extra << ": " << Message << "\n";
  return 1;
}

/// CopyEnv - This function takes an array of environment variables and makes a
/// copy of it.  This copy can then be manipulated any way the caller likes
/// without affecting the process's real environment.
///
/// Inputs:
///  envp - An array of C strings containing an environment.
///
/// Return value:
///  NULL - An error occurred.
///
///  Otherwise, a pointer to a new array of C strings is returned.  Every string
///  in the array is a duplicate of the one in the original array (i.e. we do
///  not copy the char *'s from one array to another).
///
char ** CopyEnv(char ** const envp) {
  // Count the number of entries in the old list;
  unsigned entries;   // The number of entries in the old environment list
  for (entries = 0; envp[entries] != NULL; entries++)
    /*empty*/;

  // Add one more entry for the NULL pointer that ends the list.
  ++entries;

  // If there are no entries at all, just return NULL.
  if (entries == 0)
    return NULL;

  // Allocate a new environment list.
  char **newenv = new char* [entries];
  if ((newenv = new char* [entries]) == NULL)
    return NULL;

  // Make a copy of the list.  Don't forget the NULL that ends the list.
  entries = 0;
  while (envp[entries] != NULL) {
    newenv[entries] = new char[strlen (envp[entries]) + 1];
    strcpy (newenv[entries], envp[entries]);
    ++entries;
  }
  newenv[entries] = NULL;

  return newenv;
}

/// RemoveEnv - Remove the specified environment variable from the environment
/// array.
///
/// Inputs:
///  name - The name of the variable to remove.  It cannot be NULL.
///  envp - The array of environment variables.  It cannot be NULL.
///
/// Notes:
///  This is mainly done because functions to remove items from the environment
///  are not available across all platforms.  In particular, Solaris does not
///  seem to have an unsetenv() function or a setenv() function (or they are
///  undocumented if they do exist).
///
void RemoveEnv(const char * name, char ** const envp) {
  for (unsigned index=0; envp[index] != NULL; index++) {
    // Find the first equals sign in the array and make it an EOS character.
    char *p = strchr (envp[index], '=');
    if (p == NULL)
      continue;
    else
      *p = '\0';

    // Compare the two strings.  If they are equal, zap this string.
    // Otherwise, restore it.
    if (!strcmp(name, envp[index]))
      *envp[index] = '\0';
    else
      *p = '=';
  }

  return;
}

} // End llvm namespace

int main(int argc, char **argv, char **envp) {
  cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
  PrintStackTraceOnErrorSignal();

  std::string ModuleID("gccld-output");
  std::auto_ptr<Module> Composite(new Module(ModuleID));

  // We always look first in the current directory when searching for libraries.
  LibPaths.insert(LibPaths.begin(), ".");

  // If the user specified an extra search path in their environment, respect
  // it.
  if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
    LibPaths.push_back(SearchPath);

  // Remove any consecutive duplicates of the same library...
  Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
                  Libraries.end());

  // Link in all of the files
  if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
    return 1; // Error already printed

  if (!LinkAsLibrary)
    LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
                  Verbose, Native);

  // Link in all of the libraries next...

  // Create the output file.
  std::string RealBytecodeOutput = OutputFilename;
  if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
  std::ofstream Out(RealBytecodeOutput.c_str());
  if (!Out.good())
    return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
                                   "' for writing!");

  // Ensure that the bytecode file gets removed from the disk if we get a
  // SIGINT signal.
  RemoveFileOnSignal(RealBytecodeOutput);

  // Generate the bytecode file.
  if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
    Out.close();
    return PrintAndReturn(argv[0], "error generating bytecode");
  }

  // Close the bytecode file.
  Out.close();

  // If we are not linking a library, generate either a native executable
  // or a JIT shell script, depending upon what the user wants.
  if (!LinkAsLibrary) {
    // If the user wants to generate a native executable, compile it from the
    // bytecode file.
    //
    // Otherwise, create a script that will run the bytecode through the JIT.
    if (Native) {
      // Name of the Assembly Language output file
      std::string AssemblyFile = OutputFilename + ".s";

      // Mark the output files for removal if we get an interrupt.
      RemoveFileOnSignal(AssemblyFile);
      RemoveFileOnSignal(OutputFilename);

      // Determine the locations of the llc and gcc programs.
      std::string llc = FindExecutable("llc", argv[0]);
      std::string gcc = FindExecutable("gcc", argv[0]);
      if (llc.empty())
        return PrintAndReturn(argv[0], "Failed to find llc");

      if (gcc.empty())
        return PrintAndReturn(argv[0], "Failed to find gcc");

      // Generate an assembly language file for the bytecode.
      if (Verbose) std::cout << "Generating Assembly Code\n";
      GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
      if (Verbose) std::cout << "Generating Native Code\n";
      GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
                     gcc, envp);

      // Remove the assembly language file.
      removeFile (AssemblyFile);
    } else if (NativeCBE) {
      std::string CFile = OutputFilename + ".cbe.c";

      // Mark the output files for removal if we get an interrupt.
      RemoveFileOnSignal(CFile);
      RemoveFileOnSignal(OutputFilename);

      // Determine the locations of the llc and gcc programs.
      std::string llc = FindExecutable("llc", argv[0]);
      std::string gcc = FindExecutable("gcc", argv[0]);
      if (llc.empty())
        return PrintAndReturn(argv[0], "Failed to find llc");
      if (gcc.empty())
        return PrintAndReturn(argv[0], "Failed to find gcc");

      // Generate an assembly language file for the bytecode.
      if (Verbose) std::cout << "Generating Assembly Code\n";
      GenerateCFile(CFile, RealBytecodeOutput, llc, envp);
      if (Verbose) std::cout << "Generating Native Code\n";
      GenerateNative(OutputFilename, CFile, Libraries, LibPaths, gcc, envp);

      // Remove the assembly language file.
      removeFile(CFile);

    } else {
      // Output the script to start the program...
      std::ofstream Out2(OutputFilename.c_str());
      if (!Out2.good())
        return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
                                       "' for writing!");
      Out2 << "#!/bin/sh\n";
      // Allow user to setenv LLVMINTERP if lli is not in their PATH.
      Out2 << "lli=${LLVMINTERP-lli}\n";
      Out2 << "exec $lli \\\n";
      // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
      LibPaths.push_back("/lib");
      LibPaths.push_back("/usr/lib");
      LibPaths.push_back("/usr/X11R6/lib");
      // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
      // shared object at all! See RH 8: plain text.
      std::vector<std::string>::iterator libc =
        std::find(Libraries.begin(), Libraries.end(), "c");
      if (libc != Libraries.end()) Libraries.erase(libc);
      // List all the shared object (native) libraries this executable will need
      // on the command line, so that we don't have to do this manually!
      for (std::vector<std::string>::iterator i = Libraries.begin(),
             e = Libraries.end(); i != e; ++i) {
        std::string FullLibraryPath = FindLib(*i, LibPaths, true);
        if (!FullLibraryPath.empty() && IsSharedObject(FullLibraryPath))
          Out2 << "    -load=" << FullLibraryPath << " \\\n";
      }
      Out2 << "    $0.bc ${1+\"$@\"}\n";
      Out2.close();
    }

    // Make the script executable...
    MakeFileExecutable(OutputFilename);

    // Make the bytecode file readable and directly executable in LLEE as well
    MakeFileExecutable(RealBytecodeOutput);
    MakeFileReadable(RealBytecodeOutput);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "time/timeutil.h"

#include <iostream>
#include <iomanip>

#include "cppunit-header.h"
/*
	realtime = CLOCK_REALTIME,
	course_realtime = CLOCK_REALTIME_COARSE,
	monotonic = CLOCK_MONOTONIC,
	course_monotonic = CLOCK_MONOTONIC_COARSE,
	raw_monotonic = CLOCK_MONOTONIC_RAW,
	bootime = CLOCK_BOOTTIME,
	process_cputime = CLOCK_PROCESS_CPUTIME_ID,
	thread_cputime = CLOCK_THREAD_CPUTIME_ID,
*/

class Test_timeutil : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_timeutil);
	CPPUNIT_TEST(clock_info);
	CPPUNIT_TEST(clock_time);
	CPPUNIT_TEST(duration_manipulation);
	CPPUNIT_TEST_SUITE_END();

	void clock_info()
	{
		using std::chrono::seconds;
		using std::chrono::duration_cast;
		if (config::verbose) std::cout << "\nClock resolotions:\n";

		std::string name;
		std::chrono::duration<double> d;

		name = posix_clock<clock_source::realtime>::name();
		d = posix_clock<clock_source::realtime>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::course_realtime>::name();
		d = posix_clock<clock_source::course_realtime>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::monotonic>::name();
		d = posix_clock<clock_source::monotonic>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::course_monotonic>::name();
		d = posix_clock<clock_source::course_monotonic>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::raw_monotonic>::name();
		d = posix_clock<clock_source::raw_monotonic>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::boot_time>::name();
		d = posix_clock<clock_source::boot_time>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::process_cpu_time>::name();
		d = posix_clock<clock_source::process_cpu_time>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::thread_cpu_time>::name();
		d = posix_clock<clock_source::thread_cpu_time>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;
	}

	void clock_time()
	{
		using clk = posix_clock<clock_source::realtime>;

		struct timespec ts1, ts2;
		auto t = clk::now();
		clock_gettime(CLOCK_REALTIME, &ts1);

		auto u = to_timepoint<clk, clk::duration>(ts1);

		CPPUNIT_ASSERT((u - t) < std::chrono::microseconds(500));

		ts2 = to_timespec(t);

		printf("%lu.%09lu %lu.%09lu\n",
		       ts1.tv_sec, ts1.tv_nsec,
		       ts2.tv_sec, ts2.tv_nsec);
	}

	void duration_manipulation()
	{
		struct timespec ts1 = { 1, 500000000};
		struct timespec ts2 = { 2, 300000000};

		auto d1 = to_duration<std::chrono::nanoseconds>(ts1);
		auto d2 = to_duration<std::chrono::nanoseconds>(ts2);

		auto difference = d2 - d1;

		CPPUNIT_ASSERT(difference.count() == 800000000);
		ts1 = to_timespec(difference);
		CPPUNIT_ASSERT(ts1.tv_nsec == 800000000);
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(Test_timeutil);
<commit_msg>Suppress debug output<commit_after>#include "time/timeutil.h"

#include <iostream>
#include <iomanip>

#include "cppunit-header.h"
/*
	realtime = CLOCK_REALTIME,
	course_realtime = CLOCK_REALTIME_COARSE,
	monotonic = CLOCK_MONOTONIC,
	course_monotonic = CLOCK_MONOTONIC_COARSE,
	raw_monotonic = CLOCK_MONOTONIC_RAW,
	bootime = CLOCK_BOOTTIME,
	process_cputime = CLOCK_PROCESS_CPUTIME_ID,
	thread_cputime = CLOCK_THREAD_CPUTIME_ID,
*/

class Test_timeutil : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_timeutil);
	CPPUNIT_TEST(clock_info);
	CPPUNIT_TEST(clock_time);
	CPPUNIT_TEST(duration_manipulation);
	CPPUNIT_TEST_SUITE_END();

	void clock_info()
	{
		using std::chrono::seconds;
		using std::chrono::duration_cast;
		if (config::verbose) std::cout << "\nClock resolotions:\n";

		std::string name;
		std::chrono::duration<double> d;

		name = posix_clock<clock_source::realtime>::name();
		d = posix_clock<clock_source::realtime>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::course_realtime>::name();
		d = posix_clock<clock_source::course_realtime>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::monotonic>::name();
		d = posix_clock<clock_source::monotonic>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::course_monotonic>::name();
		d = posix_clock<clock_source::course_monotonic>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::raw_monotonic>::name();
		d = posix_clock<clock_source::raw_monotonic>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::boot_time>::name();
		d = posix_clock<clock_source::boot_time>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::process_cpu_time>::name();
		d = posix_clock<clock_source::process_cpu_time>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;

		name = posix_clock<clock_source::thread_cpu_time>::name();
		d = posix_clock<clock_source::thread_cpu_time>::resolution();
		CPPUNIT_ASSERT(d < seconds(1));
		if (config::verbose)
			std::cout << std::setw(20) << name << ": "
			          << std::fixed << std::setprecision(9)
			          << d.count() << std::endl;
	}

	void clock_time()
	{
		using clk = posix_clock<clock_source::realtime>;

		struct timespec ts1, ts2;
		auto t = clk::now();
		clock_gettime(CLOCK_REALTIME, &ts1);

		auto u = to_timepoint<clk, clk::duration>(ts1);

		CPPUNIT_ASSERT((u - t) < std::chrono::microseconds(500));

		ts2 = to_timespec(t);

		if (config::verbose)
			printf("%lu.%09lu %lu.%09lu\n",
			       ts1.tv_sec, ts1.tv_nsec,
			       ts2.tv_sec, ts2.tv_nsec);
	}

	void duration_manipulation()
	{
		struct timespec ts1 = { 1, 500000000};
		struct timespec ts2 = { 2, 300000000};

		auto d1 = to_duration<std::chrono::nanoseconds>(ts1);
		auto d2 = to_duration<std::chrono::nanoseconds>(ts2);

		auto difference = d2 - d1;

		CPPUNIT_ASSERT(difference.count() == 800000000);
		ts1 = to_timespec(difference);
		CPPUNIT_ASSERT(ts1.tv_nsec == 800000000);
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(Test_timeutil);
<|endoftext|>