<commit_before>///
// crabllvm-pp -- LLVM bitcode Pre-Processor for static analysis
///

#include "llvm/LinkAllPasses.h"
#include "llvm/PassManager.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"

#include "crab_llvm/config.h"
#include "crab_llvm/Passes.hh"

#ifdef HAVE_LLVM_SEAHORN
#include "llvm_seahorn/Transforms/Scalar.h"
#endif

static llvm::cl::opt<std::string>
InputFilename(llvm::cl::Positional, llvm::cl::desc("<input LLVM bitcode file>"),
              llvm::cl::Required, llvm::cl::value_desc("filename"));

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

static llvm::cl::opt<bool>
OutputAssembly("S", llvm::cl::desc("Write output as LLVM assembly"));

static llvm::cl::opt<std::string>
AsmOutputFilename("oll", llvm::cl::desc("Output analyzed bitcode"),
               llvm::cl::init(""), llvm::cl::value_desc("filename"));

static llvm::cl::opt<std::string>
DefaultDataLayout("default-data-layout",
                  llvm::cl::desc("data layout string to use if not specified by module"),
                  llvm::cl::init(""), llvm::cl::value_desc("layout-string"));

static llvm::cl::opt<bool>
InlineAll ("crab-inline-all", llvm::cl::desc ("Inline all functions"),
           llvm::cl::init (false));

static llvm::cl::opt<bool>
Devirtualize ("crab-devirt",
              llvm::cl::desc ("Resolve indirect calls"),
              llvm::cl::init (false));

static llvm::cl::opt<bool>
LowerSelect ("crab-lower-select", llvm::cl::desc ("Lower all select instructions"),
             llvm::cl::init (false));

static llvm::cl::opt<bool>
LowerInvoke ("crab-lower-invoke", llvm::cl::desc ("Lower all invoke instructions"),
             llvm::cl::init (false));

static llvm::cl::opt<bool>
LowerGv ("crab-lower-gv", llvm::cl::desc ("Lower global initializers in main"),
             llvm::cl::init (false));

static llvm::cl::opt<bool>
OptimizeLoops ("crab-llvm-pp-loops",
               llvm::cl::desc ("Perform loop optimizations"),
               llvm::cl::init (false));

static llvm::cl::opt<bool>
TurnUndefNondet ("crab-turn-undef-nondet",
                 llvm::cl::desc ("Turn undefined behaviour into non-determinism"),
                 llvm::cl::init (false));

static llvm::cl::opt<int>
SROA_Threshold ("sroa-threshold",
                llvm::cl::desc ("Threshold for ScalarReplAggregates pass"),
                llvm::cl::init(INT_MAX));
static llvm::cl::opt<int>
SROA_StructMemThreshold ("sroa-struct",
                         llvm::cl::desc ("Structure threshold for ScalarReplAggregates"),
                         llvm::cl::init (INT_MAX));
static llvm::cl::opt<int>
SROA_ArrayElementThreshold ("sroa-array",
                            llvm::cl::desc ("Array threshold for ScalarReplAggregates"),
                            llvm::cl::init (INT_MAX));
static llvm::cl::opt<int>
SROA_ScalarLoadThreshold ("sroa-scalar-load",
                          llvm::cl::desc ("Scalar load threshold for ScalarReplAggregates"),
                          llvm::cl::init (-1));

// removes extension from filename if there is one
std::string getFileName(const std::string &str) {
  std::string filename = str;
  size_t lastdot = str.find_last_of(".");
  if (lastdot != std::string::npos)
    filename = str.substr(0, lastdot);
  return filename;
}

int main(int argc, char **argv) {
  llvm::llvm_shutdown_obj shutdown;  // calls llvm_shutdown() on exit
  llvm::cl::ParseCommandLineOptions(argc, argv,
                                    "llvmpp-- LLVM bitcode Pre-Processor for static analysis\n");

  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram PSTP(argc, argv);
  llvm::EnableDebugBuffering = true;

  std::error_code error_code;
  llvm::SMDiagnostic err;
  llvm::LLVMContext &context = llvm::getGlobalContext();
  std::unique_ptr<llvm::Module> module;
  std::unique_ptr<llvm::tool_output_file> output;
  std::unique_ptr<llvm::tool_output_file> asmOutput;

  module = llvm::parseIRFile(InputFilename, err, context);
  if (module.get() == 0)
  {
    if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);
    llvm::errs() << "error: "
                 << "Bitcode was not properly read; " << err.getMessage() << "\n";
    if (llvm::errs().has_colors()) llvm::errs().resetColor();
    return 3;
  }

  if (!AsmOutputFilename.empty ())
    asmOutput =
      llvm::make_unique<llvm::tool_output_file>(AsmOutputFilename.c_str(), error_code,
                                                llvm::sys::fs::F_Text);
  if (error_code) {
    if (llvm::errs().has_colors())
      llvm::errs().changeColor(llvm::raw_ostream::RED);
    llvm::errs() << "error: Could not open " << AsmOutputFilename << ": "
                 << error_code.message () << "\n";
    if (llvm::errs().has_colors()) llvm::errs().resetColor();
    return 3;
  }

  if (!OutputFilename.empty ())
    output = llvm::make_unique<llvm::tool_output_file>
      (OutputFilename.c_str(), error_code, llvm::sys::fs::F_None);

  if (error_code) {
    if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED);
    llvm::errs() << "error: Could not open " << OutputFilename << ": "
                 << error_code.message () << "\n";
    if (llvm::errs().has_colors()) llvm::errs().resetColor();
    return 3;
  }

  ///////////////////////////////
  // initialise and run passes //
  ///////////////////////////////

  llvm::PassManager pass_manager;
  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
  llvm::initializeAnalysis(Registry);

  /// call graph and other IPA passes
  llvm::initializeIPA (Registry);

  // add an appropriate DataLayout instance for the module
  const llvm::DataLayout *dl = module->getDataLayout ();
  if (!dl && !DefaultDataLayout.empty ())
  {
    module->setDataLayout (DefaultDataLayout);
    dl = module->getDataLayout ();
  }
  if (dl) pass_manager.add (new llvm::DataLayoutPass ());

  // -- turn all functions internal so that we can apply some global
  // -- optimizations inline them if requested
  pass_manager.add (llvm::createInternalizePass (llvm::ArrayRef<const char*>("main")));

  if (Devirtualize) {
    // -- resolve indirect calls
    pass_manager.add (crab_llvm::createDevirtualizeFunctionsPass ());
  }

  pass_manager.add (llvm::createGlobalDCEPass ()); // kill unused internal global
  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());
  // -- global optimizations
  pass_manager.add (llvm::createGlobalOptimizerPass());

  // -- SSA
  pass_manager.add(llvm::createPromoteMemoryToRegisterPass());
  #ifdef HAVE_LLVM_SEAHORN
  if (TurnUndefNondet) {
    // -- Turn undef into nondet
    pass_manager.add (llvm_seahorn::createNondetInitPass ());
  }
  #endif

  // -- cleanup after SSA
  #ifdef HAVE_LLVM_SEAHORN
  pass_manager.add (llvm_seahorn::createInstructionCombiningPass ());
  #endif
  pass_manager.add (llvm::createCFGSimplificationPass ());

  // -- break aggregates
  pass_manager.add (llvm::createScalarReplAggregatesPass (SROA_Threshold,
                                                          true,
                                                          SROA_StructMemThreshold,
                                                          SROA_ArrayElementThreshold,
                                                          SROA_ScalarLoadThreshold));
  #ifdef HAVE_LLVM_SEAHORN
  if (TurnUndefNondet) {
     // -- Turn undef into nondet (undef are created by SROA when it calls mem2reg)
     pass_manager.add (llvm_seahorn::createNondetInitPass ());
  }
  #endif

  // -- global value numbering and redundant load elimination
  pass_manager.add (llvm::createGVNPass());

  // -- cleanup after break aggregates
  #ifdef HAVE_LLVM_SEAHORN
  pass_manager.add (llvm_seahorn::createInstructionCombiningPass ());
  #endif
  pass_manager.add (llvm::createCFGSimplificationPass ());

  #ifdef HAVE_LLVM_SEAHORN
  if (TurnUndefNondet) {
     // eliminate unused calls to verifier.nondet() functions
     pass_manager.add (llvm_seahorn::createDeadNondetElimPass ());
  }
  #endif

  if (LowerInvoke)
  {
    // -- lower invoke's
    pass_manager.add(llvm::createLowerInvokePass());
    // cleanup after lowering invoke's
    pass_manager.add (llvm::createCFGSimplificationPass ());
  }

  if (InlineAll)
  {
    pass_manager.add (crab_llvm::createMarkInternalInlinePass ());
    pass_manager.add (llvm::createAlwaysInlinerPass ());
    pass_manager.add (llvm::createGlobalDCEPass ()); // kill unused internal global
  }

  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());
  pass_manager.add(llvm::createDeadInstEliminationPass());

  if (OptimizeLoops) {
    // canonical form for loops
    pass_manager.add (llvm::createLoopSimplifyPass());
    pass_manager.add (llvm::createCFGSimplificationPass ());  // cleanup unnecessary blocks
    // loop-closed SSA
    pass_manager.add (llvm::createLCSSAPass());
    #ifdef HAVE_LLVM_SEAHORN
    // induction variable
    pass_manager.add (llvm_seahorn::createIndVarSimplifyPass ());
    #endif
  }

  // trivial invariants outside loops
  pass_manager.add (llvm::createBasicAliasAnalysisPass());
  pass_manager.add (llvm::createLICMPass()); //LICM needs alias analysis
  pass_manager.add (llvm::createPromoteMemoryToRegisterPass());
  // dead loop elimination
  pass_manager.add (llvm::createLoopDeletionPass());
  pass_manager.add (llvm::createCFGSimplificationPass ()); // cleanup unnecessary blocks

  if (LowerGv) {
    // -- lower initializers of global variables
    pass_manager.add (crab_llvm::createLowerGvInitializersPass ());
  }

  // -- ensure one single exit point per function
  pass_manager.add (llvm::createUnifyFunctionExitNodesPass ());
  pass_manager.add (llvm::createGlobalDCEPass ());
  pass_manager.add (llvm::createDeadCodeEliminationPass());
  // -- remove unreachable blocks also dead cycles
  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());

  // -- remove switch constructions
  pass_manager.add (llvm::createLowerSwitchPass());

  // -- lower constant expressions to instructions
  pass_manager.add (crab_llvm::createLowerCstExprPass ());
  pass_manager.add (llvm::createDeadCodeEliminationPass());

  // -- must be the last ones:
  if (LowerSelect)
    pass_manager.add (crab_llvm::createLowerSelectPass ());

  if (!AsmOutputFilename.empty ())
    pass_manager.add (createPrintModulePass (asmOutput->os ()));

  if (!OutputFilename.empty ())
  {
    if (OutputAssembly)
      pass_manager.add (createPrintModulePass (output->os ()));
    else
      pass_manager.add (createBitcodeWriterPass (output->os ()));
  }

  pass_manager.run(*module.get());

  if (!AsmOutputFilename.empty ()) asmOutput->keep ();
  if (!OutputFilename.empty ()) output->keep();
  return 0;
}
<commit_msg>Updating options<commit_after>///
// crabllvm-pp -- LLVM bitcode Pre-Processor for static analysis
///

#include "llvm/LinkAllPasses.h"
#include "llvm/PassManager.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"

#include "crab_llvm/config.h"
#include "crab_llvm/Passes.hh"

#ifdef HAVE_LLVM_SEAHORN
#include "llvm_seahorn/Transforms/Scalar.h"
#endif

static llvm::cl::opt<std::string>
InputFilename(llvm::cl::Positional, llvm::cl::desc("<input LLVM bitcode file>"),
              llvm::cl::Required, llvm::cl::value_desc("filename"));

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

static llvm::cl::opt<bool>
OutputAssembly("S", llvm::cl::desc("Write output as LLVM assembly"));

static llvm::cl::opt<std::string>
AsmOutputFilename("oll",
	llvm::cl::desc("Output analyzed bitcode"),
        llvm::cl::init(""), llvm::cl::value_desc("filename"));

static llvm::cl::opt<std::string>
DefaultDataLayout("default-data-layout",
        llvm::cl::desc("data layout string to use if not specified by module"),
        llvm::cl::init(""), llvm::cl::value_desc("layout-string"));

static llvm::cl::opt<bool>
InlineAll ("crab-inline-all",
	   llvm::cl::desc ("Inline all functions"),
           llvm::cl::init (false));

static llvm::cl::opt<bool>
Devirtualize ("crab-devirt",
              llvm::cl::desc ("Resolve indirect calls"),
              llvm::cl::init (false));

static llvm::cl::opt<bool>
LowerSelect ("crab-lower-select",
	     llvm::cl::desc ("Lower all select instructions"),
             llvm::cl::init (false));

static llvm::cl::opt<bool>
LowerGv ("crab-lower-gv",
	 llvm::cl::desc ("Lower global initializers in main"),
	 llvm::cl::init (true));

static llvm::cl::opt<bool>
LowerUnsignedICmp("crab-lower-unsigned-icmp",
	 llvm::cl::desc ("Lower ULT and ULE instructions"),
	 llvm::cl::init (false));

static llvm::cl::opt<bool>
OptimizeLoops ("crab-llvm-pp-loops",
               llvm::cl::desc ("Perform loop optimizations"),
               llvm::cl::init (false));

static llvm::cl::opt<bool>
TurnUndefNondet ("crab-turn-undef-nondet",
                 llvm::cl::desc ("Turn undefined behaviour into non-determinism"),
                 llvm::cl::init (false));

static llvm::cl::opt<int>
SROA_Threshold ("sroa-threshold",
                llvm::cl::desc ("Threshold for ScalarReplAggregates pass"),
                llvm::cl::init(INT_MAX));
static llvm::cl::opt<int>
SROA_StructMemThreshold ("sroa-struct",
                llvm::cl::desc ("Structure threshold for ScalarReplAggregates"),
                llvm::cl::init (INT_MAX));
static llvm::cl::opt<int>
SROA_ArrayElementThreshold ("sroa-array",
                llvm::cl::desc ("Array threshold for ScalarReplAggregates"),
                llvm::cl::init (INT_MAX));
static llvm::cl::opt<int>
SROA_ScalarLoadThreshold ("sroa-scalar-load",
                llvm::cl::desc ("Scalar load threshold for ScalarReplAggregates"),
                llvm::cl::init (-1));

// removes extension from filename if there is one
std::string getFileName(const std::string &str) {
  std::string filename = str;
  size_t lastdot = str.find_last_of(".");
  if (lastdot != std::string::npos)
    filename = str.substr(0, lastdot);
  return filename;
}

int main(int argc, char **argv) {
  llvm::llvm_shutdown_obj shutdown;  // calls llvm_shutdown() on exit
  llvm::cl::ParseCommandLineOptions(argc, argv,
  "llvmpp-- LLVM bitcode Pre-Processor for static analysis\n");

  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram PSTP(argc, argv);
  llvm::EnableDebugBuffering = true;

  std::error_code error_code;
  llvm::SMDiagnostic err;
  llvm::LLVMContext &context = llvm::getGlobalContext();
  std::unique_ptr<llvm::Module> module;
  std::unique_ptr<llvm::tool_output_file> output;
  std::unique_ptr<llvm::tool_output_file> asmOutput;

  module = llvm::parseIRFile(InputFilename, err, context);
  if (module.get() == 0)
  {
    if (llvm::errs().has_colors())
      llvm::errs().changeColor(llvm::raw_ostream::RED);
    llvm::errs() << "error: "
                 << "Bitcode was not properly read; " << err.getMessage() << "\n";
    if (llvm::errs().has_colors()) llvm::errs().resetColor();
    return 3;
  }

  if (!AsmOutputFilename.empty ())
    asmOutput =
      llvm::make_unique<llvm::tool_output_file>
      (AsmOutputFilename.c_str(), error_code, llvm::sys::fs::F_Text);

  if (error_code) {
    if (llvm::errs().has_colors())
      llvm::errs().changeColor(llvm::raw_ostream::RED);
    llvm::errs() << "error: Could not open " << AsmOutputFilename << ": "
                 << error_code.message () << "\n";
    if (llvm::errs().has_colors()) llvm::errs().resetColor();
    return 3;
  }

  if (!OutputFilename.empty ())
    output = llvm::make_unique<llvm::tool_output_file>
      (OutputFilename.c_str(), error_code, llvm::sys::fs::F_None);

  if (error_code) {
    if (llvm::errs().has_colors())
      llvm::errs().changeColor(llvm::raw_ostream::RED);
    llvm::errs() << "error: Could not open " << OutputFilename << ": "
                 << error_code.message () << "\n";
    if (llvm::errs().has_colors()) llvm::errs().resetColor();
    return 3;
  }

  ///////////////////////////////
  // initialise and run passes //
  ///////////////////////////////

  llvm::PassManager pass_manager;
  llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();
  llvm::initializeAnalysis(Registry);

  /// call graph and other IPA passes
  llvm::initializeIPA (Registry);

  // add an appropriate DataLayout instance for the module
  const llvm::DataLayout *dl = module->getDataLayout ();
  if (!dl && !DefaultDataLayout.empty ()) {
    module->setDataLayout (DefaultDataLayout);
    dl = module->getDataLayout ();
  }
  if (dl)
    pass_manager.add (new llvm::DataLayoutPass ());

  // -- turn all functions internal so that we can apply some global
  // -- optimizations inline them if requested
  pass_manager.add (llvm::createInternalizePass (llvm::ArrayRef<const char*>("main")));

  if (Devirtualize) {
    // -- resolve indirect calls
    pass_manager.add (crab_llvm::createDevirtualizeFunctionsPass ());
  }

  // kill unused internal global
  pass_manager.add (llvm::createGlobalDCEPass ());
  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());
  // -- global optimizations
  pass_manager.add (llvm::createGlobalOptimizerPass());

  // -- SSA
  pass_manager.add(llvm::createPromoteMemoryToRegisterPass());
  #ifdef HAVE_LLVM_SEAHORN
  if (TurnUndefNondet) {
    // -- Turn undef into nondet
    pass_manager.add (llvm_seahorn::createNondetInitPass ());
  }
  #endif

  // -- cleanup after SSA
  #ifdef HAVE_LLVM_SEAHORN
  pass_manager.add (llvm_seahorn::createInstructionCombiningPass ());
  #endif
  pass_manager.add (llvm::createCFGSimplificationPass ());

  // -- break aggregates
  pass_manager.add (llvm::createScalarReplAggregatesPass
		    (SROA_Threshold,
		     true,
		     SROA_StructMemThreshold,
		     SROA_ArrayElementThreshold,
		     SROA_ScalarLoadThreshold));

  #ifdef HAVE_LLVM_SEAHORN
  if (TurnUndefNondet) {
     // -- Turn undef into nondet (undef are created by SROA when it calls mem2reg)
     pass_manager.add (llvm_seahorn::createNondetInitPass ());
  }
  #endif

  // -- global value numbering and redundant load elimination
  pass_manager.add (llvm::createGVNPass());

  // -- cleanup after break aggregates
  #ifdef HAVE_LLVM_SEAHORN
  pass_manager.add (llvm_seahorn::createInstructionCombiningPass ());
  #endif
  pass_manager.add (llvm::createCFGSimplificationPass ());

  #ifdef HAVE_LLVM_SEAHORN
  if (TurnUndefNondet) {
     // eliminate unused calls to verifier.nondet() functions
     pass_manager.add (llvm_seahorn::createDeadNondetElimPass ());
  }
  #endif

  // -- lower invoke's
  pass_manager.add(llvm::createLowerInvokePass());
  // cleanup after lowering invoke's
  pass_manager.add (llvm::createCFGSimplificationPass ());

  if (InlineAll) {
    pass_manager.add (crab_llvm::createMarkInternalInlinePass ());
    pass_manager.add (llvm::createAlwaysInlinerPass ());
    // kill unused internal global
    pass_manager.add (llvm::createGlobalDCEPass ());
  }

  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());
  pass_manager.add(llvm::createDeadInstEliminationPass());

  if (OptimizeLoops) {
    // canonical form for loops
    pass_manager.add (llvm::createLoopSimplifyPass());
    // cleanup unnecessary blocks
    pass_manager.add (llvm::createCFGSimplificationPass ());
    // loop-closed SSA
    pass_manager.add (llvm::createLCSSAPass());
    #ifdef HAVE_LLVM_SEAHORN
    // induction variable
    pass_manager.add (llvm_seahorn::createIndVarSimplifyPass ());
    #endif
  }

  // trivial invariants outside loops
  pass_manager.add (llvm::createBasicAliasAnalysisPass());
  //LICM needs alias analysis
  pass_manager.add (llvm::createLICMPass());
  pass_manager.add (llvm::createPromoteMemoryToRegisterPass());
  // dead loop elimination
  pass_manager.add (llvm::createLoopDeletionPass());
  // cleanup unnecessary blocks
  pass_manager.add (llvm::createCFGSimplificationPass ());

  if (LowerGv) {
    // -- lower initializers of global variables
    pass_manager.add (crab_llvm::createLowerGvInitializersPass ());
  }

  // -- ensure one single exit point per function
  pass_manager.add (llvm::createUnifyFunctionExitNodesPass ());
  pass_manager.add (llvm::createGlobalDCEPass ());
  pass_manager.add (llvm::createDeadCodeEliminationPass());
  // -- remove unreachable blocks also dead cycles
  pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());

  // -- remove switch constructions
  pass_manager.add (llvm::createLowerSwitchPass());

  // -- lower constant expressions to instructions
  pass_manager.add (crab_llvm::createLowerCstExprPass ());
  pass_manager.add (llvm::createDeadCodeEliminationPass());

  // -- lower ULT and ULE instructions
  if (LowerUnsignedICmp) {
    pass_manager.add (crab_llvm::createLowerUnsignedICmpPass ());
    // cleanup unnecessary and unreachable blocks
    pass_manager.add (llvm::createCFGSimplificationPass ());
    pass_manager.add (crab_llvm::createRemoveUnreachableBlocksPass ());
  }

  // -- must be the last ones:
  if (LowerSelect)
    pass_manager.add (crab_llvm::createLowerSelectPass ());

  if (!AsmOutputFilename.empty ())
    pass_manager.add (createPrintModulePass (asmOutput->os ()));

  if (!OutputFilename.empty ())  {
    if (OutputAssembly)
      pass_manager.add (createPrintModulePass (output->os ()));
    else
      pass_manager.add (createBitcodeWriterPass (output->os ()));
  }

  pass_manager.run(*module.get());

  if (!AsmOutputFilename.empty ()) asmOutput->keep ();
  if (!OutputFilename.empty ()) output->keep();

  return 0;
}
<|endoftext|>


<commit_before>// We don't use this cpp file...
<commit_msg>Delete blynk.cpp<commit_after><|endoftext|>


<commit_before>//
// Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.
//
#include "top.hpp"
#include "os/os.hpp"
#include "device/device.hpp"
#include "device/pal/paldefs.hpp"
#include "device/pal/palsettings.hpp"

#include <algorithm>

namespace pal {

/*! \brief information for adjusting maximum workload time
 *
 *  This structure contains the time and OS minor version for max workload time
 *  adjustment for Windows 7 or 8.
 */
struct ModifyMaxWorkload
{
    uint32_t time;          //!< max work load time (10x ms)
    uint32_t minorVersion;  //!< OS minor version
};

Settings::Settings()
{
    // Initialize the GPU device default settings
    oclVersion_         = OpenCL12;
    debugFlags_         = 0;
    syncObject_         = GPU_USE_SYNC_OBJECTS;
    remoteAlloc_        = REMOTE_ALLOC;

    stagedXferRead_   = true;
    stagedXferWrite_  = true;
    stagedXferSize_   = GPU_STAGING_BUFFER_SIZE * Ki;

    // We will enable staged read/write if we use local memory
    disablePersistent_ = false;

    // By Default persistent writes will be disabled.
    stagingWritePersistent_ = GPU_STAGING_WRITE_PERSISTENT;

    maxRenames_         = 4;
    maxRenameSize_      = 4 * Mi;

    imageSupport_       = false;
    hwLDSSize_          = 0;

    // Set this to true when we drop the flag
    doublePrecision_    = ::CL_KHR_FP64;

    // Fill workgroup info size
    // @todo: revisit the 256 limitation on workgroup size
    maxWorkGroupSize_   = 256;

    hostMemDirectAccess_  = HostMemDisable;

    libSelector_    = amd::LibraryUndefined;

    // Enable workload split by default (for 24 bit arithmetic or timeout)
    workloadSplitSize_  = 1 << GPU_WORKLOAD_SPLIT;

    // By default use host blit
    blitEngine_         = BlitEngineHost;
    const static size_t MaxPinnedXferSize = 32;
    pinnedXferSize_     = std::min(GPU_PINNED_XFER_SIZE, MaxPinnedXferSize) * Mi;
    pinnedMinXferSize_  = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_);

    // Disable FP_FAST_FMA defines by default
    reportFMAF_ = false;
    reportFMA_  = false;

    // GPU device by default
    apuSystem_  = false;

    // Disable 64 bit pointers support by default
    use64BitPtr_ = false;

    // Max alloc size is 16GB
    maxAllocSize_ = 16 * static_cast<uint64_t>(Gi);

    // Disable memory dependency tracking by default
    numMemDependencies_ = 0;

    // By default cache isn't present
    cacheLineSize_  = 0;
    cacheSize_      = 0;

    // Initialize transfer buffer size to 1MB by default
    xferBufSize_    = 1024 * Ki;

    // Use image DMA if requested
    imageDMA_       = GPU_IMAGE_DMA;

    // Disable ASIC specific features by default
    viPlus_         = false;
    aiPlus_         = false;

    // Number of compute rings.
    numComputeRings_ = 0;

    minWorkloadTime_ = 1;       // 0.1 ms
    maxWorkloadTime_ = 5000;    // 500 ms

    // Controls tiled images in persistent
    //!@note IOL for Linux doesn't setup tiling aperture in CMM/QS
    linearPersistentImage_ = false;

    useSingleScratch_ = GPU_USE_SINGLE_SCRATCH;

    // Device enqueuing settings
    numDeviceEvents_ = 1024;
    numWaitEvents_   = 8;

    // Don't support platform atomics by default.
    svmAtomics_ = false;

    // Use host queue for device enqueuing by default
    useDeviceQueue_ = GPU_USE_DEVICE_QUEUE;

    // Don't support Denormals for single precision by default
    singleFpDenorm_ = false;

    // Disable SDMA workaround by default
    sdamPageFaultWar_ = false;
}

bool
Settings::create(
    const Pal::DeviceProperties& palProp,
    const Pal::GpuMemoryHeapProperties* heaps,
    bool reportAsOCL12Device
)
{
//    uint    target = calAttr.target;
    uint32_t osVer = 0x0;

    // Disable thread trace by default for all devices
    threadTraceEnable_ = false;
    bool doublePrecision = true;

    if (doublePrecision) {
        // Report FP_FAST_FMA define if double precision HW
        reportFMA_ = true;
        // FMA is 1/4 speed on Pitcairn, Cape Verde, Devastator and Scrapper
        // Bonaire, Kalindi, Spectre and Spooky so disable
        // FP_FMA_FMAF for those parts in switch below
        reportFMAF_ = true;
    }

    // Update GPU specific settings and info structure if we have any
    ModifyMaxWorkload modifyMaxWorkload = {0};

    switch (palProp.revision) {
    case Pal::AsicRevision::Unknown:
        switch (palProp.gfxLevel) {
        case Pal::GfxIpLevel::GfxIp9:
            aiPlus_ = true;
            break;
        default:
            assert(0 && "Unknown GfxIP type!");
            return false;
        }
        // Fall through to VI ...
    case Pal::AsicRevision::Carrizo:
    case Pal::AsicRevision::Stoney:
        if (!aiPlus_) {
            // APU systems for VI
            apuSystem_  = true;
        }
    case Pal::AsicRevision::Iceland:
    case Pal::AsicRevision::Tonga:
    case Pal::AsicRevision::Fiji:
    case Pal::AsicRevision::Ellesmere:
    case Pal::AsicRevision::Baffin:
        // Disable tiling aperture on VI+
        linearPersistentImage_ = true;
        // Keep this false even though we have support
        // singleFpDenorm_ = true;
        viPlus_ = true;
        // SDMA may have memory access outside of
        // the valid buffer range and cause a page fault
        sdamPageFaultWar_ = true;
        // Fall through to CI ...
    case Pal::AsicRevision::Kalindi:
    case Pal::AsicRevision::Spectre:
        if (!viPlus_) {
            // APU systems for CI
            apuSystem_  = true;
            // Fix BSOD/TDR issues observed on Kaveri Win7 (EPR#416903)
            modifyMaxWorkload.time = 2500;      // 250ms
            modifyMaxWorkload.minorVersion = 1; // Win 7
        }
        // Fall through ...
    case Pal::AsicRevision::Bonaire:
    case Pal::AsicRevision::Hawaii:
        threadTraceEnable_ = AMD_THREAD_TRACE_ENABLE;
        reportFMAF_ = false;
        if (palProp.revision == Pal::AsicRevision::Hawaii) {
            reportFMAF_ = true;
        }
        // Cache line size is 64 bytes
        cacheLineSize_  = 64;
        // L1 cache size is 16KB
        cacheSize_      = 16 * Ki;

        libSelector_ = amd::GPU_Library_CI;
        if (LP64_SWITCH(WINDOWS_SWITCH(viPlus_, false), true)) {
            oclVersion_ = !reportAsOCL12Device /*&& calAttr.isOpenCL200Device*/ ?
                XCONCAT(OpenCL, XCONCAT(OPENCL_MAJOR, OPENCL_MINOR)) : OpenCL12;
        }
        if (GPU_FORCE_OCL20_32BIT) {
            force32BitOcl20_ = true;
            oclVersion_ = !reportAsOCL12Device /*&& calAttr.isOpenCL200Device*/ ?
                XCONCAT(OpenCL, XCONCAT(OPENCL_MAJOR, OPENCL_MINOR)) : OpenCL12;
        }
        if (OPENCL_VERSION < 200) {
            oclVersion_ = OpenCL12;
        }
        numComputeRings_ = 8;

        // This needs to be cleaned once 64bit addressing is stable
        if (oclVersion_ < OpenCL20) {
            use64BitPtr_ = flagIsDefault(GPU_FORCE_64BIT_PTR) ? LP64_SWITCH(false,
                /*calAttr.isWorkstation ||*/ true) : GPU_FORCE_64BIT_PTR;
        }
        else {
            if (GPU_FORCE_64BIT_PTR || LP64_SWITCH(false, true)) {
                use64BitPtr_    = true;
            }
        }

        if (oclVersion_ >= OpenCL20) {
            supportDepthsRGB_ = true;
        }
        if (use64BitPtr_) {
            if (GPU_ENABLE_LARGE_ALLOCATION /*&& calAttr.isWorkstation*/) {
                maxAllocSize_   = 64ULL * Gi;
            }
            else {
                maxAllocSize_   = 4048 * Mi;
            }
        }
        else {
            maxAllocSize_   = 3ULL * Gi;
        }

        supportRA_  = false;
        partialDispatch_    = GPU_PARTIAL_DISPATCH;
        numMemDependencies_ = GPU_NUM_MEM_DEPENDENCY;
        break;
    default:
        assert(0 && "Unknown ASIC type!");
        return false;
    }

    // Enable atomics support
    enableExtension(ClKhrInt64BaseAtomics);
    enableExtension(ClKhrInt64ExtendedAtomics);
    enableExtension(ClKhrGlobalInt32BaseAtomics);
    enableExtension(ClKhrGlobalInt32ExtendedAtomics);
    enableExtension(ClKhrLocalInt32BaseAtomics);
    enableExtension(ClKhrLocalInt32ExtendedAtomics);
    enableExtension(ClKhrByteAddressableStore);
    enableExtension(ClKhrGlSharing);
    enableExtension(ClKhrGlEvent);
    enableExtension(ClAmdMediaOps);
    enableExtension(ClAmdMediaOps2);
    enableExtension(ClAmdPopcnt);
    enableExtension(ClKhr3DImageWrites);
    enableExtension(ClAmdVec3);
    enableExtension(ClAmdPrintf);
    enableExtension(ClKhrImage2dFromBuffer);
    // Enable some platform extensions
    enableExtension(ClAmdDeviceAttributeQuery);
    enableExtension(ClKhrSpir);
    enableExtension(ClAMDLiquidFlash);

    hwLDSSize_      = 32 * Ki;

    imageSupport_       = true;

    // Use kernels for blit if appropriate
    blitEngine_     = BlitEngineKernel;

    hostMemDirectAccess_ |= HostMemBuffer;
    // HW doesn't support untiled image writes
    // hostMemDirectAccess_ |= HostMemImage;

    // Make sure device actually supports double precision
    doublePrecision_ = (doublePrecision) ? doublePrecision_ : false;
    if (doublePrecision_) {
        // Enable KHR double precision extension
        enableExtension(ClKhrFp64);
    }

    if (doublePrecision) {
        // Enable AMD double precision extension
        doublePrecision_ = true;
        enableExtension(ClAmdFp64);
    }

//! @todo
/*
    if (calAttr.totalSDIHeap > 0) {
        //Enable bus addressable memory extension
        enableExtension(ClAMDBusAddressableMemory);
    }

    if (calAttr.longIdleDetect) {
        // KMD is unable to detect if we map the visible memory for CPU access, so
        // accessing persistent staged buffer may fail if LongIdleDetct is enabled.
        disablePersistent_ = true;
    }

    svmFineGrainSystem_ = calAttr.isSVMFineGrainSystem;

    svmAtomics_ = (calAttr.svmAtomics || calAttr.isSVMFineGrainSystem) ? true : false;
*/

    // SVM is not currently supported for DX Interop
#if defined(_WIN32)
    enableExtension(ClKhrD3d9Sharing);
    enableExtension(ClKhrD3d10Sharing);
    enableExtension(ClKhrD3d11Sharing);
#endif // _WIN32

    // Enable some OpenCL 2.0 extensions
    if (oclVersion_ >= OpenCL20) {
        enableExtension(ClKhrGLDepthImages);
        enableExtension(ClKhrSubGroups);
        enableExtension(ClKhrDepthImages);

        if (GPU_MIPMAP) {
            enableExtension(ClKhrMipMapImage);
            enableExtension(ClKhrMipMapImageWrites);
        }

        // Enable HW debug
        if (GPU_ENABLE_HW_DEBUG) {
            enableHwDebug_ = true;
        }
    }

    if (apuSystem_ &&
       ((heaps[Pal::GpuHeapLocal].heapSize + heaps[Pal::GpuHeapInvisible].heapSize) < (150*Mi))) {
        remoteAlloc_ = true;
    }

    // Save resource cache size
#ifdef ATI_OS_LINUX
    // Due to EPR#406216, set the default value for Linux for now
    resourceCacheSize_ = GPU_RESOURCE_CACHE_SIZE * Mi;
#else
    if (remoteAlloc_) {
        resourceCacheSize_ = std::max((heaps[Pal::GpuHeapGartUswc].heapSize / 8),
            (uint64_t)GPU_RESOURCE_CACHE_SIZE * Mi);
    }
    else {
        resourceCacheSize_ = std::max(((heaps[Pal::GpuHeapLocal].heapSize +
            heaps[Pal::GpuHeapInvisible].heapSize) / 8),
            (uint64_t)GPU_RESOURCE_CACHE_SIZE * Mi);
    }
    resourceCacheSize_ = std::min(resourceCacheSize_, 512 * Mi);
#endif

    // Override current device settings
    override();

    return true;
}

void
Settings::override()
{
    // Limit reported workgroup size
    if (GPU_MAX_WORKGROUP_SIZE != 0) {
        maxWorkGroupSize_ = GPU_MAX_WORKGROUP_SIZE;
    }

    // Override blit engine type
    if (GPU_BLIT_ENGINE_TYPE != BlitEngineDefault) {
        blitEngine_ = GPU_BLIT_ENGINE_TYPE;
    }

    if (!flagIsDefault(DEBUG_GPU_FLAGS)) {
        debugFlags_ = DEBUG_GPU_FLAGS;
    }

    if (!flagIsDefault(DEBUG_GPU_FLAGS)) {
        debugFlags_ = DEBUG_GPU_FLAGS;
    }

    if (!flagIsDefault(GPU_XFER_BUFFER_SIZE)) {
        xferBufSize_ = GPU_XFER_BUFFER_SIZE * Ki;
    }

    if (!flagIsDefault(GPU_USE_SYNC_OBJECTS)) {
        syncObject_ = GPU_USE_SYNC_OBJECTS;
    }

    if (!flagIsDefault(GPU_NUM_COMPUTE_RINGS)) {
        numComputeRings_ = GPU_NUM_COMPUTE_RINGS;
    }

    if (!flagIsDefault(GPU_RESOURCE_CACHE_SIZE)) {
        resourceCacheSize_ = GPU_RESOURCE_CACHE_SIZE * Mi;
    }

    if (!flagIsDefault(AMD_GPU_FORCE_SINGLE_FP_DENORM)) {
        switch (AMD_GPU_FORCE_SINGLE_FP_DENORM) {
        case 0:
            singleFpDenorm_ = false;
            break;
        case 1:
            singleFpDenorm_ = true;
            break;
        default:
            break;
        }
    }
}

} // namespace pal
<commit_msg>P4 to Git Change 1319372 by gandryey@gera-w8 on 2016/09/27 12:16:18<commit_after>//
// Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.
//
#include "top.hpp"
#include "os/os.hpp"
#include "device/device.hpp"
#include "device/pal/paldefs.hpp"
#include "device/pal/palsettings.hpp"

#include <algorithm>

namespace pal {

/*! \brief information for adjusting maximum workload time
 *
 *  This structure contains the time and OS minor version for max workload time
 *  adjustment for Windows 7 or 8.
 */
struct ModifyMaxWorkload
{
    uint32_t time;          //!< max work load time (10x ms)
    uint32_t minorVersion;  //!< OS minor version
};

Settings::Settings()
{
    // Initialize the GPU device default settings
    oclVersion_         = OpenCL12;
    debugFlags_         = 0;
    syncObject_         = GPU_USE_SYNC_OBJECTS;
    remoteAlloc_        = REMOTE_ALLOC;

    stagedXferRead_   = true;
    stagedXferWrite_  = true;
    stagedXferSize_   = GPU_STAGING_BUFFER_SIZE * Ki;

    // We will enable staged read/write if we use local memory
    disablePersistent_ = false;

    // By Default persistent writes will be disabled.
    stagingWritePersistent_ = GPU_STAGING_WRITE_PERSISTENT;

    maxRenames_         = 4;
    maxRenameSize_      = 4 * Mi;

    imageSupport_       = false;
    hwLDSSize_          = 0;

    // Set this to true when we drop the flag
    doublePrecision_    = ::CL_KHR_FP64;

    // Fill workgroup info size
    // @todo: revisit the 256 limitation on workgroup size
    maxWorkGroupSize_   = 256;

    hostMemDirectAccess_  = HostMemDisable;

    libSelector_    = amd::LibraryUndefined;

    // Enable workload split by default (for 24 bit arithmetic or timeout)
    workloadSplitSize_  = 1 << GPU_WORKLOAD_SPLIT;

    // By default use host blit
    blitEngine_         = BlitEngineHost;
    const static size_t MaxPinnedXferSize = 32;
    pinnedXferSize_     = std::min(GPU_PINNED_XFER_SIZE, MaxPinnedXferSize) * Mi;
    pinnedMinXferSize_  = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_);

    // Disable FP_FAST_FMA defines by default
    reportFMAF_ = false;
    reportFMA_  = false;

    // GPU device by default
    apuSystem_  = false;

    // Disable 64 bit pointers support by default
    use64BitPtr_ = false;

    // Max alloc size is 16GB
    maxAllocSize_ = 16 * static_cast<uint64_t>(Gi);

    // Disable memory dependency tracking by default
    numMemDependencies_ = 0;

    // By default cache isn't present
    cacheLineSize_  = 0;
    cacheSize_      = 0;

    // Initialize transfer buffer size to 1MB by default
    xferBufSize_    = 1024 * Ki;

    // Use image DMA if requested
    imageDMA_       = GPU_IMAGE_DMA;

    // Disable ASIC specific features by default
    viPlus_         = false;
    aiPlus_         = false;

    // Number of compute rings.
    numComputeRings_ = 0;

    minWorkloadTime_ = 1;       // 0.1 ms
    maxWorkloadTime_ = 5000;    // 500 ms

    // Controls tiled images in persistent
    //!@note IOL for Linux doesn't setup tiling aperture in CMM/QS
    linearPersistentImage_ = false;

    useSingleScratch_ = GPU_USE_SINGLE_SCRATCH;

    // Device enqueuing settings
    numDeviceEvents_ = 1024;
    numWaitEvents_   = 8;

    // Don't support platform atomics by default.
    svmAtomics_ = false;

    // Use host queue for device enqueuing by default
    useDeviceQueue_ = GPU_USE_DEVICE_QUEUE;

    // Don't support Denormals for single precision by default
    singleFpDenorm_ = false;

    // Disable SDMA workaround by default
    sdamPageFaultWar_ = false;
}

bool
Settings::create(
    const Pal::DeviceProperties& palProp,
    const Pal::GpuMemoryHeapProperties* heaps,
    bool reportAsOCL12Device
)
{
//    uint    target = calAttr.target;
    uint32_t osVer = 0x0;

    // Disable thread trace by default for all devices
    threadTraceEnable_ = false;
    bool doublePrecision = true;

    if (doublePrecision) {
        // Report FP_FAST_FMA define if double precision HW
        reportFMA_ = true;
        // FMA is 1/4 speed on Pitcairn, Cape Verde, Devastator and Scrapper
        // Bonaire, Kalindi, Spectre and Spooky so disable
        // FP_FMA_FMAF for those parts in switch below
        reportFMAF_ = true;
    }

    // Update GPU specific settings and info structure if we have any
    ModifyMaxWorkload modifyMaxWorkload = {0};

    switch (palProp.revision) {
    case Pal::AsicRevision::Unknown:
        switch (palProp.gfxLevel) {
        case Pal::GfxIpLevel::GfxIp9:
            aiPlus_ = true;
            break;
        default:
            assert(0 && "Unknown GfxIP type!");
            return false;
        }
        // Fall through to VI ...
    case Pal::AsicRevision::Carrizo:
    case Pal::AsicRevision::Stoney:
        if (!aiPlus_) {
            // APU systems for VI
            apuSystem_  = true;
        }
    case Pal::AsicRevision::Iceland:
    case Pal::AsicRevision::Tonga:
    case Pal::AsicRevision::Fiji:
    case Pal::AsicRevision::Ellesmere:
    case Pal::AsicRevision::Baffin:
        // Disable tiling aperture on VI+
        linearPersistentImage_ = true;
        // Keep this false even though we have support
        // singleFpDenorm_ = true;
        viPlus_ = true;
        // SDMA may have memory access outside of
        // the valid buffer range and cause a page fault
        sdamPageFaultWar_ = true;
        // Fall through to CI ...
    case Pal::AsicRevision::Kalindi:
    case Pal::AsicRevision::Spectre:
        if (!viPlus_) {
            // APU systems for CI
            apuSystem_  = true;
            // Fix BSOD/TDR issues observed on Kaveri Win7 (EPR#416903)
            modifyMaxWorkload.time = 2500;      // 250ms
            modifyMaxWorkload.minorVersion = 1; // Win 7
        }
        // Fall through ...
    case Pal::AsicRevision::Bonaire:
    case Pal::AsicRevision::Hawaii:
        threadTraceEnable_ = AMD_THREAD_TRACE_ENABLE;
        reportFMAF_ = false;
        if (palProp.revision == Pal::AsicRevision::Hawaii) {
            reportFMAF_ = true;
        }
        // Cache line size is 64 bytes
        cacheLineSize_  = 64;
        // L1 cache size is 16KB
        cacheSize_      = 16 * Ki;

        libSelector_ = amd::GPU_Library_CI;
        if (LP64_SWITCH(false, true)) {
            oclVersion_ = !reportAsOCL12Device /*&& calAttr.isOpenCL200Device*/ ?
                XCONCAT(OpenCL, XCONCAT(OPENCL_MAJOR, OPENCL_MINOR)) : OpenCL12;
        }
        if (GPU_FORCE_OCL20_32BIT) {
            force32BitOcl20_ = true;
            oclVersion_ = !reportAsOCL12Device /*&& calAttr.isOpenCL200Device*/ ?
                XCONCAT(OpenCL, XCONCAT(OPENCL_MAJOR, OPENCL_MINOR)) : OpenCL12;
        }
        if (OPENCL_VERSION < 200) {
            oclVersion_ = OpenCL12;
        }
        numComputeRings_ = 8;

        // This needs to be cleaned once 64bit addressing is stable
        if (oclVersion_ < OpenCL20) {
            use64BitPtr_ = flagIsDefault(GPU_FORCE_64BIT_PTR) ? LP64_SWITCH(false,
                /*calAttr.isWorkstation ||*/ true) : GPU_FORCE_64BIT_PTR;
        }
        else {
            if (GPU_FORCE_64BIT_PTR || LP64_SWITCH(false, true)) {
                use64BitPtr_    = true;
            }
        }

        if (oclVersion_ >= OpenCL20) {
            supportDepthsRGB_ = true;
        }
        if (use64BitPtr_) {
            if (GPU_ENABLE_LARGE_ALLOCATION /*&& calAttr.isWorkstation*/) {
                maxAllocSize_   = 64ULL * Gi;
            }
            else {
                maxAllocSize_   = 4048 * Mi;
            }
        }
        else {
            maxAllocSize_   = 3ULL * Gi;
        }

        supportRA_  = false;
        partialDispatch_    = GPU_PARTIAL_DISPATCH;
        numMemDependencies_ = GPU_NUM_MEM_DEPENDENCY;
        break;
    default:
        assert(0 && "Unknown ASIC type!");
        return false;
    }

    // Enable atomics support
    enableExtension(ClKhrInt64BaseAtomics);
    enableExtension(ClKhrInt64ExtendedAtomics);
    enableExtension(ClKhrGlobalInt32BaseAtomics);
    enableExtension(ClKhrGlobalInt32ExtendedAtomics);
    enableExtension(ClKhrLocalInt32BaseAtomics);
    enableExtension(ClKhrLocalInt32ExtendedAtomics);
    enableExtension(ClKhrByteAddressableStore);
    enableExtension(ClKhrGlSharing);
    enableExtension(ClKhrGlEvent);
    enableExtension(ClAmdMediaOps);
    enableExtension(ClAmdMediaOps2);
    enableExtension(ClAmdPopcnt);
    enableExtension(ClKhr3DImageWrites);
    enableExtension(ClAmdVec3);
    enableExtension(ClAmdPrintf);
    enableExtension(ClKhrImage2dFromBuffer);
    // Enable some platform extensions
    enableExtension(ClAmdDeviceAttributeQuery);
    enableExtension(ClKhrSpir);
    enableExtension(ClAMDLiquidFlash);

    hwLDSSize_      = 32 * Ki;

    imageSupport_       = true;

    // Use kernels for blit if appropriate
    blitEngine_     = BlitEngineKernel;

    hostMemDirectAccess_ |= HostMemBuffer;
    // HW doesn't support untiled image writes
    // hostMemDirectAccess_ |= HostMemImage;

    // Make sure device actually supports double precision
    doublePrecision_ = (doublePrecision) ? doublePrecision_ : false;
    if (doublePrecision_) {
        // Enable KHR double precision extension
        enableExtension(ClKhrFp64);
    }

    if (doublePrecision) {
        // Enable AMD double precision extension
        doublePrecision_ = true;
        enableExtension(ClAmdFp64);
    }

//! @todo
/*
    if (calAttr.totalSDIHeap > 0) {
        //Enable bus addressable memory extension
        enableExtension(ClAMDBusAddressableMemory);
    }

    if (calAttr.longIdleDetect) {
        // KMD is unable to detect if we map the visible memory for CPU access, so
        // accessing persistent staged buffer may fail if LongIdleDetct is enabled.
        disablePersistent_ = true;
    }

    svmFineGrainSystem_ = calAttr.isSVMFineGrainSystem;

    svmAtomics_ = (calAttr.svmAtomics || calAttr.isSVMFineGrainSystem) ? true : false;
*/

    // SVM is not currently supported for DX Interop
#if defined(_WIN32)
    enableExtension(ClKhrD3d9Sharing);
    enableExtension(ClKhrD3d10Sharing);
    enableExtension(ClKhrD3d11Sharing);
#endif // _WIN32

    // Enable some OpenCL 2.0 extensions
    if (oclVersion_ >= OpenCL20) {
        enableExtension(ClKhrGLDepthImages);
        enableExtension(ClKhrSubGroups);
        enableExtension(ClKhrDepthImages);

        if (GPU_MIPMAP) {
            enableExtension(ClKhrMipMapImage);
            enableExtension(ClKhrMipMapImageWrites);
        }

        // Enable HW debug
        if (GPU_ENABLE_HW_DEBUG) {
            enableHwDebug_ = true;
        }
    }

    if (apuSystem_ &&
       ((heaps[Pal::GpuHeapLocal].heapSize + heaps[Pal::GpuHeapInvisible].heapSize) < (150*Mi))) {
        remoteAlloc_ = true;
    }

    // Save resource cache size
#ifdef ATI_OS_LINUX
    // Due to EPR#406216, set the default value for Linux for now
    resourceCacheSize_ = GPU_RESOURCE_CACHE_SIZE * Mi;
#else
    if (remoteAlloc_) {
        resourceCacheSize_ = std::max((heaps[Pal::GpuHeapGartUswc].heapSize / 8),
            (uint64_t)GPU_RESOURCE_CACHE_SIZE * Mi);
    }
    else {
        resourceCacheSize_ = std::max(((heaps[Pal::GpuHeapLocal].heapSize +
            heaps[Pal::GpuHeapInvisible].heapSize) / 8),
            (uint64_t)GPU_RESOURCE_CACHE_SIZE * Mi);
    }
    resourceCacheSize_ = std::min(resourceCacheSize_, 512 * Mi);
#endif

    // Override current device settings
    override();

    return true;
}

void
Settings::override()
{
    // Limit reported workgroup size
    if (GPU_MAX_WORKGROUP_SIZE != 0) {
        maxWorkGroupSize_ = GPU_MAX_WORKGROUP_SIZE;
    }

    // Override blit engine type
    if (GPU_BLIT_ENGINE_TYPE != BlitEngineDefault) {
        blitEngine_ = GPU_BLIT_ENGINE_TYPE;
    }

    if (!flagIsDefault(DEBUG_GPU_FLAGS)) {
        debugFlags_ = DEBUG_GPU_FLAGS;
    }

    if (!flagIsDefault(DEBUG_GPU_FLAGS)) {
        debugFlags_ = DEBUG_GPU_FLAGS;
    }

    if (!flagIsDefault(GPU_XFER_BUFFER_SIZE)) {
        xferBufSize_ = GPU_XFER_BUFFER_SIZE * Ki;
    }

    if (!flagIsDefault(GPU_USE_SYNC_OBJECTS)) {
        syncObject_ = GPU_USE_SYNC_OBJECTS;
    }

    if (!flagIsDefault(GPU_NUM_COMPUTE_RINGS)) {
        numComputeRings_ = GPU_NUM_COMPUTE_RINGS;
    }

    if (!flagIsDefault(GPU_RESOURCE_CACHE_SIZE)) {
        resourceCacheSize_ = GPU_RESOURCE_CACHE_SIZE * Mi;
    }

    if (!flagIsDefault(AMD_GPU_FORCE_SINGLE_FP_DENORM)) {
        switch (AMD_GPU_FORCE_SINGLE_FP_DENORM) {
        case 0:
            singleFpDenorm_ = false;
            break;
        case 1:
            singleFpDenorm_ = true;
            break;
        default:
            break;
        }
    }
}

} // namespace pal
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
// FILE:          DeviceUtils.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     MMDevice - Device adapter kit
//-----------------------------------------------------------------------------
// DESCRIPTION:   Class with utility methods for building device adapters
// AUTHOR:        Nenad Amodaj, nenad@amodaj.com 06/08/2005
// COPYRIGHT:     University of California, San Francisco, 2006
// LICENSE:       This file is distributed under the BSD license.
//                License text is included with the source distribution.
//
//                This file is distributed in the hope that it will be useful,
//                but WITHOUT ANY WARRANTY; without even the implied warranty
//                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
// CVS:           $Id$
//
#include "DeviceUtils.h"
#include "../MMcore/CoreUtils.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#ifdef WIN32
   #define WIN32_LEAN_AND_MEAN
   #include <windows.h>
   #define snprintf _snprintf
#pragma warning(disable : 4996)
#endif

char CDeviceUtils::m_pszBuffer[MM::MaxStrLength]={""};

/**
 * Copies strings with predefined size limit.
 */
bool CDeviceUtils::CopyLimitedString(char* target, const char* source)
{
   strncpy(target, source, MM::MaxStrLength - 1);
   if ((MM::MaxStrLength - 1) < strlen(source))
   {
      target[MM::MaxStrLength - 1] = 0;
      return false; // string truncated
   }
   else
      return true;
}

/**
 * Programmatic access to the system-wide string size limit.
 */
unsigned CDeviceUtils::GetMaxStringLength()
{
   return MM::MaxStrLength;
}

/**
 * Convert long value to string.
 */
const char* CDeviceUtils::ConvertToString(long lnVal)
{
   // return ltoa(lnVal, m_pszBuffer, 10);
   snprintf(m_pszBuffer, MM::MaxStrLength-1, "%ld", lnVal);
   return m_pszBuffer;
}

/**
 * Convert int value to string.
 */
const char* CDeviceUtils::ConvertToString(int intVal)
{
   return ConvertToString((long)intVal);
}

/**
 * Convert double value to string.
 */
const char* CDeviceUtils::ConvertToString(double dVal)
{
   //return _gcvt(dVal, 12, m_pszBuffer);
   snprintf(m_pszBuffer, MM::MaxStrLength-1, "%.2f", dVal);
   return m_pszBuffer;
}

/**
 * Convert boolean value to string.
 */
const char* CDeviceUtils::ConvertToString(bool val)
{
   snprintf(m_pszBuffer, MM::MaxStrLength-1, "%s", val ? "1" : "0");
   return m_pszBuffer;
}

/**
 * Parse the string and return an array of tokens.
 * @param str - input string
 * @param tokens - output array of tokens
 * @param delimiters - a string containing a set of single-character token delimiters
 */
void CDeviceUtils::Tokenize(const std::string& str, std::vector<std::string>& tokens, const std::string& delimiters)
{
    // Skip delimiters at beginning.
   std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
   std::string::size_type pos     = str.find_first_of(delimiters, lastPos);

   while (std::string::npos != pos || std::string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}

/**
 * Block the current thread for the specified interval in milliseconds.
 */
void CDeviceUtils::SleepMs(long periodMs)
{
#ifdef WIN32
   Sleep(periodMs);
#else
   usleep(periodMs * 1000);
#endif
}

#ifdef _WINDOWS

int gettimeofday(struct timeval *tv, struct timezone *tz)
{
  FILETIME ft;
  unsigned __int64 tmpres = 0;
  static int tzflag;

  if (NULL != tv)
  {
    GetSystemTimeAsFileTime(&ft);

    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;

    /*converting file time to unix epoch*/
    tmpres -= DELTA_EPOCH_IN_MICROSECS;
    tmpres /= 10;  /*convert into microseconds*/
    tv->tv_sec = (long)(tmpres / 1000000UL);
    tv->tv_usec = (long)(tmpres % 1000000UL);
  }

  if (NULL != tz)
  {
    if (!tzflag)
    {
      _tzset();
      tzflag++;
    }
    tz->tz_minuteswest = _timezone / 60;
    tz->tz_dsttime = _daylight;
  }

  return 0;
}

#endif
<commit_msg>Johannes: fix type<commit_after>///////////////////////////////////////////////////////////////////////////////
// FILE:          DeviceUtils.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     MMDevice - Device adapter kit
//-----------------------------------------------------------------------------
// DESCRIPTION:   Class with utility methods for building device adapters
// AUTHOR:        Nenad Amodaj, nenad@amodaj.com 06/08/2005
// COPYRIGHT:     University of California, San Francisco, 2006
// LICENSE:       This file is distributed under the BSD license.
//                License text is included with the source distribution.
//
//                This file is distributed in the hope that it will be useful,
//                but WITHOUT ANY WARRANTY; without even the implied warranty
//                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
// CVS:           $Id$
//
#include "DeviceUtils.h"
#include "../MMCore/CoreUtils.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#ifdef WIN32
   #define WIN32_LEAN_AND_MEAN
   #include <windows.h>
   #define snprintf _snprintf
#pragma warning(disable : 4996)
#endif

char CDeviceUtils::m_pszBuffer[MM::MaxStrLength]={""};

/**
 * Copies strings with predefined size limit.
 */
bool CDeviceUtils::CopyLimitedString(char* target, const char* source)
{
   strncpy(target, source, MM::MaxStrLength - 1);
   if ((MM::MaxStrLength - 1) < strlen(source))
   {
      target[MM::MaxStrLength - 1] = 0;
      return false; // string truncated
   }
   else
      return true;
}

/**
 * Programmatic access to the system-wide string size limit.
 */
unsigned CDeviceUtils::GetMaxStringLength()
{
   return MM::MaxStrLength;
}

/**
 * Convert long value to string.
 */
const char* CDeviceUtils::ConvertToString(long lnVal)
{
   // return ltoa(lnVal, m_pszBuffer, 10);
   snprintf(m_pszBuffer, MM::MaxStrLength-1, "%ld", lnVal);
   return m_pszBuffer;
}

/**
 * Convert int value to string.
 */
const char* CDeviceUtils::ConvertToString(int intVal)
{
   return ConvertToString((long)intVal);
}

/**
 * Convert double value to string.
 */
const char* CDeviceUtils::ConvertToString(double dVal)
{
   //return _gcvt(dVal, 12, m_pszBuffer);
   snprintf(m_pszBuffer, MM::MaxStrLength-1, "%.2f", dVal);
   return m_pszBuffer;
}

/**
 * Convert boolean value to string.
 */
const char* CDeviceUtils::ConvertToString(bool val)
{
   snprintf(m_pszBuffer, MM::MaxStrLength-1, "%s", val ? "1" : "0");
   return m_pszBuffer;
}

/**
 * Parse the string and return an array of tokens.
 * @param str - input string
 * @param tokens - output array of tokens
 * @param delimiters - a string containing a set of single-character token delimiters
 */
void CDeviceUtils::Tokenize(const std::string& str, std::vector<std::string>& tokens, const std::string& delimiters)
{
    // Skip delimiters at beginning.
   std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
   std::string::size_type pos     = str.find_first_of(delimiters, lastPos);

   while (std::string::npos != pos || std::string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}

/**
 * Block the current thread for the specified interval in milliseconds.
 */
void CDeviceUtils::SleepMs(long periodMs)
{
#ifdef WIN32
   Sleep(periodMs);
#else
   usleep(periodMs * 1000);
#endif
}

#ifdef _WINDOWS

int gettimeofday(struct timeval *tv, struct timezone *tz)
{
  FILETIME ft;
  unsigned __int64 tmpres = 0;
  static int tzflag;

  if (NULL != tv)
  {
    GetSystemTimeAsFileTime(&ft);

    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;

    /*converting file time to unix epoch*/
    tmpres -= DELTA_EPOCH_IN_MICROSECS;
    tmpres /= 10;  /*convert into microseconds*/
    tv->tv_sec = (long)(tmpres / 1000000UL);
    tv->tv_usec = (long)(tmpres % 1000000UL);
  }

  if (NULL != tz)
  {
    if (!tzflag)
    {
      _tzset();
      tzflag++;
    }
    tz->tz_minuteswest = _timezone / 60;
    tz->tz_dsttime = _daylight;
  }

  return 0;
}

#endif
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "Sk64.h"
#include "SkCornerPathEffect.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkKernel33MaskFilter.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkXfermode.h"

#include "SkStream.h"
#include "SkXMLParser.h"
#include "SkColorPriv.h"
#include "SkImageDecoder.h"
#include "SkBlurMaskFilter.h"

static void setNamedTypeface(SkPaint* paint, const char name[]) {
    SkTypeface* face = SkTypeface::CreateFromName(name, SkTypeface::kNormal);
    paint->setTypeface(face);
    SkSafeUnref(face);
}

static uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF };

class XfermodesBlurView : public SampleView {
    SkBitmap    fBG;
    SkBitmap    fSrcB, fDstB;

    void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha,
                   SkScalar x, SkScalar y) {
        SkPaint p;
        SkMaskFilter* mf = SkBlurMaskFilter::Create(5, SkBlurMaskFilter::kNormal_BlurStyle, 0);
        p.setMaskFilter(mf)->unref();

        SkScalar ww = SkIntToScalar(W);
        SkScalar hh = SkIntToScalar(H);

        // draw a circle covering the upper
        // left three quarters of the canvas
        p.setColor(0xFFCC44FF);
        SkRect r;
        r.set(0, 0, ww*3/4, hh*3/4);
        r.offset(x, y);
        canvas->drawOval(r, p);

        p.setXfermode(mode);

        // draw a square overlapping the circle
        // in the lower right of the canvas
        p.setColor(0x00AA6633 | alpha << 24);
        r.set(ww/3, hh/3, ww*19/20, hh*19/20);
        r.offset(x, y);
        canvas->drawRect(r, p);
    }

public:
    const static int W = 64;
    const static int H = 64;
    XfermodesBlurView() {
        const int W = 64;
        const int H = 64;

        fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4);
        fBG.setPixels(gBG);
        fBG.setIsOpaque(true);
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt) {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "XfermodesBlur");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        canvas->translate(SkIntToScalar(10), SkIntToScalar(20));

        if (false) {
            SkPaint paint;
            paint.setAntiAlias(true);
            paint.setTextSize(50);
            paint.setTypeface(SkTypeface::CreateFromName("Arial Unicode MS", SkTypeface::kNormal));
            SkSafeUnref(paint.getTypeface());
            char buffer[10];
            size_t len = SkUTF8_FromUnichar(0x8500, buffer);
            canvas->drawText(buffer, len, 40, 40, paint);
            return;
        }
        if (true) {
            SkPaint paint;
            paint.setAntiAlias(true);

            SkRect r0 = { 0, 0, 10.5f, 20 };
            SkRect r1 = { 10.5f, 10, 20, 30 };
            paint.setColor(SK_ColorRED);
            canvas->drawRect(r0, paint);
            paint.setColor(SK_ColorBLUE);
            canvas->drawRect(r1, paint);
            return;
        }

        const struct {
            SkXfermode::Mode  fMode;
            const char*         fLabel;
        } gModes[] = {
            { SkXfermode::kClear_Mode,    "Clear"     },
            { SkXfermode::kSrc_Mode,      "Src"       },
            { SkXfermode::kDst_Mode,      "Dst"       },
            { SkXfermode::kSrcOver_Mode,  "SrcOver"   },
            { SkXfermode::kDstOver_Mode,  "DstOver"   },
            { SkXfermode::kSrcIn_Mode,    "SrcIn"     },
            { SkXfermode::kDstIn_Mode,    "DstIn"     },
            { SkXfermode::kSrcOut_Mode,   "SrcOut"    },
            { SkXfermode::kDstOut_Mode,   "DstOut"    },
            { SkXfermode::kSrcATop_Mode,  "SrcATop"   },
            { SkXfermode::kDstATop_Mode,  "DstATop"   },
            { SkXfermode::kXor_Mode,      "Xor"       },

            { SkXfermode::kPlus_Mode,         "Plus"          },
            /*{ SkXfermode::kMultiply_Mode,     "Multiply"      },
            { SkXfermode::kScreen_Mode,       "Screen"        },
            { SkXfermode::kOverlay_Mode,      "Overlay"       },
            { SkXfermode::kDarken_Mode,       "Darken"        },
            { SkXfermode::kLighten_Mode,      "Lighten"       },
            { SkXfermode::kColorDodge_Mode,   "ColorDodge"    },
            { SkXfermode::kColorBurn_Mode,    "ColorBurn"     },
            { SkXfermode::kHardLight_Mode,    "HardLight"     },
            { SkXfermode::kSoftLight_Mode,    "SoftLight"     },
            { SkXfermode::kDifference_Mode,   "Difference"    },
            { SkXfermode::kExclusion_Mode,    "Exclusion"     },*/
        };

        const SkScalar w = SkIntToScalar(W);
        const SkScalar h = SkIntToScalar(H);
        SkShader* s = SkShader::CreateBitmapShader(fBG,
                                                   SkShader::kRepeat_TileMode,
                                                   SkShader::kRepeat_TileMode);
        SkMatrix m;
        m.setScale(SkIntToScalar(6), SkIntToScalar(6));
        s->setLocalMatrix(m);

        SkPaint labelP;
        labelP.setAntiAlias(true);
        labelP.setLCDRenderText(true);
        labelP.setTextAlign(SkPaint::kCenter_Align);
        setNamedTypeface(&labelP, "Menlo Regular");

        const int W = 5;

        SkScalar x0 = 0;
        for (int twice = 0; twice < 2; twice++) {
            SkScalar x = x0, y = 0;
            for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) {
                SkXfermode* mode = SkXfermode::Create(gModes[i].fMode);
                SkAutoUnref aur(mode);
                SkRect r;
                r.set(x, y, x+w, y+h);

                SkPaint p;
                p.setStyle(SkPaint::kFill_Style);
                p.setShader(s);
                canvas->drawRect(r, p);

                canvas->saveLayer(&r, NULL, SkCanvas::kARGB_ClipLayer_SaveFlag);
                draw_mode(canvas, mode, twice ? 0x88 : 0xFF, r.fLeft, r.fTop);
                canvas->restore();

                r.inset(-SK_ScalarHalf, -SK_ScalarHalf);
                p.setStyle(SkPaint::kStroke_Style);
                p.setShader(NULL);
                canvas->drawRect(r, p);

                canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel),
                                 x + w/2, y - labelP.getTextSize()/2, labelP);
                x += w + SkIntToScalar(10);
                if ((i % W) == W - 1) {
                    x = x0;
                    y += h + SkIntToScalar(30);
                }
            }
            x0 += SkIntToScalar(400);
        }
        s->unref();
    }

private:
    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new XfermodesBlurView; }
static SkViewRegister reg(MyFactory);
<commit_msg>disable test<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "Sk64.h"
#include "SkCornerPathEffect.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkKernel33MaskFilter.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkXfermode.h"

#include "SkStream.h"
#include "SkXMLParser.h"
#include "SkColorPriv.h"
#include "SkImageDecoder.h"
#include "SkBlurMaskFilter.h"

static void setNamedTypeface(SkPaint* paint, const char name[]) {
    SkTypeface* face = SkTypeface::CreateFromName(name, SkTypeface::kNormal);
    paint->setTypeface(face);
    SkSafeUnref(face);
}

static uint16_t gBG[] = { 0xFFFF, 0xCCCF, 0xCCCF, 0xFFFF };

class XfermodesBlurView : public SampleView {
    SkBitmap    fBG;
    SkBitmap    fSrcB, fDstB;

    void draw_mode(SkCanvas* canvas, SkXfermode* mode, int alpha,
                   SkScalar x, SkScalar y) {
        SkPaint p;
        SkMaskFilter* mf = SkBlurMaskFilter::Create(5, SkBlurMaskFilter::kNormal_BlurStyle, 0);
        p.setMaskFilter(mf)->unref();

        SkScalar ww = SkIntToScalar(W);
        SkScalar hh = SkIntToScalar(H);

        // draw a circle covering the upper
        // left three quarters of the canvas
        p.setColor(0xFFCC44FF);
        SkRect r;
        r.set(0, 0, ww*3/4, hh*3/4);
        r.offset(x, y);
        canvas->drawOval(r, p);

        p.setXfermode(mode);

        // draw a square overlapping the circle
        // in the lower right of the canvas
        p.setColor(0x00AA6633 | alpha << 24);
        r.set(ww/3, hh/3, ww*19/20, hh*19/20);
        r.offset(x, y);
        canvas->drawRect(r, p);
    }

public:
    const static int W = 64;
    const static int H = 64;
    XfermodesBlurView() {
        const int W = 64;
        const int H = 64;

        fBG.setConfig(SkBitmap::kARGB_4444_Config, 2, 2, 4);
        fBG.setPixels(gBG);
        fBG.setIsOpaque(true);
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt) {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "XfermodesBlur");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        canvas->translate(SkIntToScalar(10), SkIntToScalar(20));

        if (false) {
            SkPaint paint;
            paint.setAntiAlias(true);
            paint.setTextSize(50);
            paint.setTypeface(SkTypeface::CreateFromName("Arial Unicode MS", SkTypeface::kNormal));
            SkSafeUnref(paint.getTypeface());
            char buffer[10];
            size_t len = SkUTF8_FromUnichar(0x8500, buffer);
            canvas->drawText(buffer, len, 40, 40, paint);
            return;
        }
        if (false) {
            SkPaint paint;
            paint.setAntiAlias(true);

            SkRect r0 = { 0, 0, 10.5f, 20 };
            SkRect r1 = { 10.5f, 10, 20, 30 };
            paint.setColor(SK_ColorRED);
            canvas->drawRect(r0, paint);
            paint.setColor(SK_ColorBLUE);
            canvas->drawRect(r1, paint);
            return;
        }

        const struct {
            SkXfermode::Mode  fMode;
            const char*         fLabel;
        } gModes[] = {
            { SkXfermode::kClear_Mode,    "Clear"     },
            { SkXfermode::kSrc_Mode,      "Src"       },
            { SkXfermode::kDst_Mode,      "Dst"       },
            { SkXfermode::kSrcOver_Mode,  "SrcOver"   },
            { SkXfermode::kDstOver_Mode,  "DstOver"   },
            { SkXfermode::kSrcIn_Mode,    "SrcIn"     },
            { SkXfermode::kDstIn_Mode,    "DstIn"     },
            { SkXfermode::kSrcOut_Mode,   "SrcOut"    },
            { SkXfermode::kDstOut_Mode,   "DstOut"    },
            { SkXfermode::kSrcATop_Mode,  "SrcATop"   },
            { SkXfermode::kDstATop_Mode,  "DstATop"   },
            { SkXfermode::kXor_Mode,      "Xor"       },

            { SkXfermode::kPlus_Mode,         "Plus"          },
            /*{ SkXfermode::kMultiply_Mode,     "Multiply"      },
            { SkXfermode::kScreen_Mode,       "Screen"        },
            { SkXfermode::kOverlay_Mode,      "Overlay"       },
            { SkXfermode::kDarken_Mode,       "Darken"        },
            { SkXfermode::kLighten_Mode,      "Lighten"       },
            { SkXfermode::kColorDodge_Mode,   "ColorDodge"    },
            { SkXfermode::kColorBurn_Mode,    "ColorBurn"     },
            { SkXfermode::kHardLight_Mode,    "HardLight"     },
            { SkXfermode::kSoftLight_Mode,    "SoftLight"     },
            { SkXfermode::kDifference_Mode,   "Difference"    },
            { SkXfermode::kExclusion_Mode,    "Exclusion"     },*/
        };

        const SkScalar w = SkIntToScalar(W);
        const SkScalar h = SkIntToScalar(H);
        SkShader* s = SkShader::CreateBitmapShader(fBG,
                                                   SkShader::kRepeat_TileMode,
                                                   SkShader::kRepeat_TileMode);
        SkMatrix m;
        m.setScale(SkIntToScalar(6), SkIntToScalar(6));
        s->setLocalMatrix(m);

        SkPaint labelP;
        labelP.setAntiAlias(true);
        labelP.setLCDRenderText(true);
        labelP.setTextAlign(SkPaint::kCenter_Align);
        setNamedTypeface(&labelP, "Menlo Regular");

        const int W = 5;

        SkScalar x0 = 0;
        for (int twice = 0; twice < 2; twice++) {
            SkScalar x = x0, y = 0;
            for (size_t i = 0; i < SK_ARRAY_COUNT(gModes); i++) {
                SkXfermode* mode = SkXfermode::Create(gModes[i].fMode);
                SkAutoUnref aur(mode);
                SkRect r;
                r.set(x, y, x+w, y+h);

                SkPaint p;
                p.setStyle(SkPaint::kFill_Style);
                p.setShader(s);
                canvas->drawRect(r, p);

                canvas->saveLayer(&r, NULL, SkCanvas::kARGB_ClipLayer_SaveFlag);
                draw_mode(canvas, mode, twice ? 0x88 : 0xFF, r.fLeft, r.fTop);
                canvas->restore();

                r.inset(-SK_ScalarHalf, -SK_ScalarHalf);
                p.setStyle(SkPaint::kStroke_Style);
                p.setShader(NULL);
                canvas->drawRect(r, p);

                canvas->drawText(gModes[i].fLabel, strlen(gModes[i].fLabel),
                                 x + w/2, y - labelP.getTextSize()/2, labelP);
                x += w + SkIntToScalar(10);
                if ((i % W) == W - 1) {
                    x = x0;
                    y += h + SkIntToScalar(30);
                }
            }
            x0 += SkIntToScalar(400);
        }
        s->unref();
    }

private:
    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new XfermodesBlurView; }
static SkViewRegister reg(MyFactory);
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *       Albert Thuswaldner <albert.thuswaldner@gmail.com>
 * Portions created by the Initial Developer are Copyright (C) 2011 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#undef SC_DLLIMPLEMENTATION

#include "tpdefaults.hxx"
#include "optdlg.hrc"
#include "scresid.hxx"
#include "scmod.hxx"
#include "docoptio.hxx"
#include "document.hxx"
#include "global.hxx"
#include "globstr.hrc"

#define INIT_SHEETS_MIN 1
#define INIT_SHEETS_MAX 1024

using ::rtl::OUString;

ScTpDefaultsOptions::ScTpDefaultsOptions(Window *pParent, const SfxItemSet &rCoreAttrs) :
    SfxTabPage(pParent, ScResId(RID_SCPAGE_DEFAULTS), rCoreAttrs),
    aFLInitSpreadSheet ( this, ScResId( FL_INIT_SPREADSHEET ) ),
    aFtNSheets         ( this, ScResId( FT_NSHEETS ) ),
    aEdNSheets         ( this, ScResId( ED_NSHEETS ) ),
    aFtSheetPrefix     ( this, ScResId( FT_SHEETPREFIX ) ),
    aEdSheetPrefix     ( this, ScResId( ED_SHEETPREFIX ) )
{
    FreeResource();

    const ScTpCalcItem& rItem = static_cast<const ScTpCalcItem&>(
        rCoreAttrs.Get(GetWhich(SID_SCDOCOPTIONS)));
    mpOldOptions.reset(new ScDocOptions(rItem.GetDocOptions()));
    mpNewOptions.reset(new ScDocOptions(rItem.GetDocOptions()));

    long nTxtW = aFtNSheets.GetCtrlTextWidth( aFtNSheets.GetText() );
    long nCtrlW = aFtNSheets.GetSizePixel().Width();
    if ( nTxtW >= nCtrlW )
    {
        Size aNewSize = aFtNSheets.GetSizePixel();
        aNewSize.Width() += ( nTxtW - nCtrlW );
        aFtNSheets.SetSizePixel( aNewSize );
        Point aNewPoint = aEdNSheets.GetPosPixel();
        aNewPoint.X() += ( nTxtW - nCtrlW );
        aEdNSheets.SetPosPixel( aNewPoint );
   }
    aEdNSheets.SetModifyHdl( LINK(this, ScTpDefaultsOptions, NumModifiedHdl) );
    aEdSheetPrefix.SetModifyHdl( LINK(this, ScTpDefaultsOptions, PrefixModifiedHdl) );
    aEdSheetPrefix.SetGetFocusHdl( LINK(this, ScTpDefaultsOptions, PrefixEditOnFocusHdl) );
}

ScTpDefaultsOptions::~ScTpDefaultsOptions()
{
}

SfxTabPage* ScTpDefaultsOptions::Create(Window *pParent, const SfxItemSet &rCoreAttrs)
{
    return new ScTpDefaultsOptions(pParent, rCoreAttrs);
}

sal_Bool ScTpDefaultsOptions::FillItemSet(SfxItemSet &rCoreAttrs)
{
    SCTAB nTabCount = static_cast<SCTAB>(aEdNSheets.GetValue());
    OUString aSheetPrefix = aEdSheetPrefix.GetText();

    mpNewOptions->SetInitTabCount( nTabCount );
    mpNewOptions->SetInitTabPrefix( aSheetPrefix );

    if (*mpNewOptions != *mpOldOptions)
    {
        rCoreAttrs.Put(ScTpCalcItem(GetWhich(SID_SCDOCOPTIONS), *mpNewOptions));
        return sal_True;
    }
    else
        return sal_False;
}

void ScTpDefaultsOptions::Reset(const SfxItemSet& /*rCoreAttrs*/)
{
    aEdNSheets.SetValue( static_cast<sal_uInt16>(mpOldOptions->GetInitTabCount()) );
    aEdSheetPrefix.SetText( mpOldOptions->GetInitTabPrefix() );
}

int ScTpDefaultsOptions::DeactivatePage(SfxItemSet* /*pSet*/)
{
    return KEEP_PAGE;
}

void ScTpDefaultsOptions::CheckNumSheets()
{
    sal_Int64 nVal = aEdNSheets.GetValue();
    if (nVal > INIT_SHEETS_MAX)
        aEdNSheets.SetValue(INIT_SHEETS_MAX);
    if (nVal < INIT_SHEETS_MIN)
        aEdNSheets.SetValue(INIT_SHEETS_MIN);
}

void ScTpDefaultsOptions::CheckPrefix(Edit* pEdit)
{
    if (!pEdit)
        return;

    OUString aSheetPrefix = pEdit->GetText();

    if ( !ScDocument::ValidTabName( aSheetPrefix ) )
    {
        // Revert to last good Prefix
        pEdit->SetText( maOldPrefixValue );
    }
    else
    {
        OnFocusPrefixInput(pEdit);
    }
}

void ScTpDefaultsOptions::OnFocusPrefixInput(Edit* pEdit)
{
    if (!pEdit)
        return;

    // Store Prefix in case we need to revert
    maOldPrefixValue = pEdit->GetText();
}

IMPL_LINK( ScTpDefaultsOptions, NumModifiedHdl, NumericField*, EMPTYARG )
{
    CheckNumSheets();
    return 0;
}

IMPL_LINK( ScTpDefaultsOptions, PrefixModifiedHdl, Edit*, pEdit )
{
    CheckPrefix(pEdit);
    return 0;
}

IMPL_LINK( ScTpDefaultsOptions, PrefixEditOnFocusHdl, Edit*, pEdit )
{
    OnFocusPrefixInput(pEdit);
    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>some very minor tweak(s) to "Improvment-of-Custom-Sheet-Prefix-Option"<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *       Albert Thuswaldner <albert.thuswaldner@gmail.com>
 * Portions created by the Initial Developer are Copyright (C) 2011 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#undef SC_DLLIMPLEMENTATION

#include "tpdefaults.hxx"
#include "optdlg.hrc"
#include "scresid.hxx"
#include "scmod.hxx"
#include "docoptio.hxx"
#include "document.hxx"
#include "global.hxx"
#include "globstr.hrc"

#define INIT_SHEETS_MIN 1
#define INIT_SHEETS_MAX 1024

using ::rtl::OUString;

ScTpDefaultsOptions::ScTpDefaultsOptions(Window *pParent, const SfxItemSet &rCoreAttrs) :
    SfxTabPage(pParent, ScResId(RID_SCPAGE_DEFAULTS), rCoreAttrs),
    aFLInitSpreadSheet ( this, ScResId( FL_INIT_SPREADSHEET ) ),
    aFtNSheets         ( this, ScResId( FT_NSHEETS ) ),
    aEdNSheets         ( this, ScResId( ED_NSHEETS ) ),
    aFtSheetPrefix     ( this, ScResId( FT_SHEETPREFIX ) ),
    aEdSheetPrefix     ( this, ScResId( ED_SHEETPREFIX ) )
{
    FreeResource();

    const ScTpCalcItem& rItem = static_cast<const ScTpCalcItem&>(
        rCoreAttrs.Get(GetWhich(SID_SCDOCOPTIONS)));
    mpOldOptions.reset(new ScDocOptions(rItem.GetDocOptions()));
    mpNewOptions.reset(new ScDocOptions(rItem.GetDocOptions()));

    long nTxtW = aFtNSheets.GetCtrlTextWidth( aFtNSheets.GetText() );
    long nCtrlW = aFtNSheets.GetSizePixel().Width();
    if ( nTxtW >= nCtrlW )
    {
        Size aNewSize = aFtNSheets.GetSizePixel();
        aNewSize.Width() += ( nTxtW - nCtrlW );
        aFtNSheets.SetSizePixel( aNewSize );
        Point aNewPoint = aEdNSheets.GetPosPixel();
        aNewPoint.X() += ( nTxtW - nCtrlW );
        aEdNSheets.SetPosPixel( aNewPoint );
   }
    aEdNSheets.SetModifyHdl( LINK(this, ScTpDefaultsOptions, NumModifiedHdl) );
    aEdSheetPrefix.SetModifyHdl( LINK(this, ScTpDefaultsOptions, PrefixModifiedHdl) );
    aEdSheetPrefix.SetGetFocusHdl( LINK(this, ScTpDefaultsOptions, PrefixEditOnFocusHdl) );
}

ScTpDefaultsOptions::~ScTpDefaultsOptions()
{
}

SfxTabPage* ScTpDefaultsOptions::Create(Window *pParent, const SfxItemSet &rCoreAttrs)
{
    return new ScTpDefaultsOptions(pParent, rCoreAttrs);
}

sal_Bool ScTpDefaultsOptions::FillItemSet(SfxItemSet &rCoreAttrs)
{
    SCTAB nTabCount = static_cast<SCTAB>(aEdNSheets.GetValue());
    OUString aSheetPrefix = aEdSheetPrefix.GetText();

    mpNewOptions->SetInitTabCount( nTabCount );
    mpNewOptions->SetInitTabPrefix( aSheetPrefix );

    if (*mpNewOptions != *mpOldOptions)
    {
        rCoreAttrs.Put(ScTpCalcItem(GetWhich(SID_SCDOCOPTIONS), *mpNewOptions));
        return sal_True;
    }
    else
        return sal_False;
}

void ScTpDefaultsOptions::Reset(const SfxItemSet& /*rCoreAttrs*/)
{
    aEdNSheets.SetValue( static_cast<sal_uInt16>(mpOldOptions->GetInitTabCount()) );
    aEdSheetPrefix.SetText( mpOldOptions->GetInitTabPrefix() );
}

int ScTpDefaultsOptions::DeactivatePage(SfxItemSet* /*pSet*/)
{
    return KEEP_PAGE;
}

void ScTpDefaultsOptions::CheckNumSheets()
{
    sal_Int64 nVal = aEdNSheets.GetValue();
    if (nVal > INIT_SHEETS_MAX)
        aEdNSheets.SetValue(INIT_SHEETS_MAX);
    if (nVal < INIT_SHEETS_MIN)
        aEdNSheets.SetValue(INIT_SHEETS_MIN);
}

void ScTpDefaultsOptions::CheckPrefix(Edit* pEdit)
{
    if (!pEdit)
        return;

    OUString aSheetPrefix = pEdit->GetText();

    if ( !aSheetPrefix.isEmpty() && !ScDocument::ValidTabName( aSheetPrefix ) )
    {
        // Revert to last good Prefix and also select it to
        // indicate something illegal was typed
        Selection aSel( 0,  maOldPrefixValue.getLength() );
        pEdit->SetText( maOldPrefixValue, aSel );
    }
    else
    {
        OnFocusPrefixInput(pEdit);
    }
}

void ScTpDefaultsOptions::OnFocusPrefixInput(Edit* pEdit)
{
    if (!pEdit)
        return;

    // Store Prefix in case we need to revert
    maOldPrefixValue = pEdit->GetText();
}

IMPL_LINK( ScTpDefaultsOptions, NumModifiedHdl, NumericField*, EMPTYARG )
{
    CheckNumSheets();
    return 0;
}

IMPL_LINK( ScTpDefaultsOptions, PrefixModifiedHdl, Edit*, pEdit )
{
    CheckPrefix(pEdit);
    return 0;
}

IMPL_LINK( ScTpDefaultsOptions, PrefixEditOnFocusHdl, Edit*, pEdit )
{
    OnFocusPrefixInput(pEdit);
    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>