<commit_before>#include "CodeGen_Internal.h"
#include "IROperator.h"
#include "CSE.h"
#include "Debug.h"

namespace Halide {
namespace Internal {

using std::string;
using std::map;
using std::vector;
using std::pair;

using namespace llvm;

namespace {

vector<llvm::Type*> llvm_types(const Closure& closure, llvm::StructType *buffer_t, LLVMContext &context) {
    vector<llvm::Type *> res;
    for (const pair<string, Type> &i : closure.vars) {
        res.push_back(llvm_type_of(&context, i.second));
    }
    for (const pair<string, Closure::BufferRef> &i : closure.buffers) {
        res.push_back(llvm_type_of(&context, i.second.type)->getPointerTo());
        res.push_back(buffer_t->getPointerTo());
    }
    return res;
}

}  // namespace

StructType *build_closure_type(const Closure& closure, llvm::StructType *buffer_t, LLVMContext *context) {
    StructType *struct_t = StructType::create(*context, "closure_t");
    struct_t->setBody(llvm_types(closure, buffer_t, *context), false);
    return struct_t;
}

void pack_closure(llvm::Type *
#if LLVM_VERSION >= 37
                  type
#endif
                  ,
                  Value *dst,
                  const Closure& closure,
                  const Scope<Value *> &src,
                  llvm::StructType *buffer_t,
                  IRBuilder<> *builder) {
    // type, type of dst should be a pointer to a struct of the type returned by build_type
    int idx = 0;
    LLVMContext &context = builder->getContext();
    vector<string> nm = closure.names();
    vector<llvm::Type*> ty = llvm_types(closure, buffer_t, context);
    for (size_t i = 0; i < nm.size(); i++) {
#if LLVM_VERSION >= 37
        Value *ptr = builder->CreateConstInBoundsGEP2_32(type, dst, 0, idx);
#else
        Value *ptr = builder->CreateConstInBoundsGEP2_32(dst, 0, idx);
#endif
        Value *val;
        if (!ends_with(nm[i], ".buffer") || src.contains(nm[i])) {
            val = src.get(nm[i]);
            if (val->getType() != ty[i]) {
                val = builder->CreateBitCast(val, ty[i]);
            }
        } else {
            // Skip over buffers not in the symbol table. They must not be needed.
            val = ConstantPointerNull::get(buffer_t->getPointerTo());
        }
        builder->CreateStore(val, ptr);
        idx++;
    }
}

void unpack_closure(const Closure& closure,
                    Scope<Value *> &dst,
                    llvm::Type *
#if LLVM_VERSION >= 37
                    type
#endif
                    ,
                    Value *src,
                    IRBuilder<> *builder) {
    // type, type of src should be a pointer to a struct of the type returned by build_type
    int idx = 0;
    LLVMContext &context = builder->getContext();
    vector<string> nm = closure.names();
    for (size_t i = 0; i < nm.size(); i++) {
#if LLVM_VERSION >= 37
        Value *ptr = builder->CreateConstInBoundsGEP2_32(type, src, 0, idx++);
#else
        Value *ptr = builder->CreateConstInBoundsGEP2_32(src, 0, idx++);
#endif
        LoadInst *load = builder->CreateLoad(ptr);
        if (load->getType()->isPointerTy()) {
            // Give it a unique type so that tbaa tells llvm that this can't alias anything
            LLVMMDNodeArgumentType md_args[] = {MDString::get(context, nm[i])};
            load->setMetadata("tbaa", MDNode::get(context, md_args));
        }
        dst.push(nm[i], load);
        load->setName(nm[i]);
    }
}

llvm::Type *llvm_type_of(LLVMContext *c, Halide::Type t) {
    if (t.lanes() == 1) {
        if (t.is_float()) {
            switch (t.bits()) {
            case 16:
                return llvm::Type::getHalfTy(*c);
            case 32:
                return llvm::Type::getFloatTy(*c);
            case 64:
                return llvm::Type::getDoubleTy(*c);
            default:
                internal_error << "There is no llvm type matching this floating-point bit width: " << t << "\n";
                return nullptr;
            }
        } else if (t.is_handle()) {
            return llvm::Type::getInt8PtrTy(*c);
        } else {
            return llvm::Type::getIntNTy(*c, t.bits());
        }
    } else {
        llvm::Type *element_type = llvm_type_of(c, t.element_of());
        return VectorType::get(element_type, t.lanes());
    }
}

// Returns true if the given function name is one of the Halide runtime
// functions that takes a user_context pointer as its first parameter.
bool function_takes_user_context(const std::string &name) {
    static const char *user_context_runtime_funcs[] = {
        "halide_copy_to_host",
        "halide_copy_to_device",
        "halide_current_time_ns",
        "halide_debug_to_file",
        "halide_device_free",
        "halide_device_malloc",
        "halide_device_sync",
        "halide_do_par_for",
        "halide_do_task",
        "halide_error",
        "halide_free",
        "halide_malloc",
        "halide_print",
        "halide_profiler_memory_allocate",
        "halide_profiler_memory_free",
        "halide_profiler_pipeline_start",
        "halide_profiler_pipeline_end",
        "halide_profiler_stack_peak_update",
        "halide_spawn_thread",
        "halide_device_release",
        "halide_start_clock",
        "halide_trace",
        "halide_memoization_cache_lookup",
        "halide_memoization_cache_store",
        "halide_memoization_cache_release",
        "halide_cuda_run",
        "halide_opencl_run",
        "halide_opengl_run",
        "halide_openglcompute_run",
        "halide_renderscript_run",
        "halide_metal_run",
        "halide_cuda_initialize_kernels",
        "halide_opencl_initialize_kernels",
        "halide_opengl_initialize_kernels",
        "halide_openglcompute_initialize_kernels",
        "halide_renderscript_initialize_kernels",
        "halide_metal_initialize_kernels",
        "halide_get_gpu_device",
    };
    const int num_funcs = sizeof(user_context_runtime_funcs) /
        sizeof(user_context_runtime_funcs[0]);
    for (int i = 0; i < num_funcs; ++i) {
        if (name == user_context_runtime_funcs[i]) {
            return true;
        }
    }
    // The error functions all take a user context
    return starts_with(name, "halide_error_");
}

bool can_allocation_fit_on_stack(int32_t size) {
    user_assert(size > 0) << "Allocation size should be a positive number\n";
    return (size <= 1024 * 16);
}

Expr lower_euclidean_div(Expr a, Expr b) {
    internal_assert(a.type() == b.type());
    // IROperator's div_round_to_zero will replace this with a / b for
    // unsigned ops, so create the intrinsic directly.
    Expr q = Call::make(a.type(), Call::div_round_to_zero, {a, b}, Call::PureIntrinsic);
    if (a.type().is_int()) {
        // Signed integer division sucks. It should be defined such
        // that it satisifies (a/b)*b + a%b = a, where 0 <= a%b < |b|,
        // i.e. Euclidean division.

        // We get rounding to work by examining the implied remainder
        // and correcting the quotient.

        /* Here's the C code that we're trying to match:
           int q = a / b;
           int r = a - q * b;
           int bs = b >> (t.bits() - 1);
           int rs = r >> (t.bits() - 1);
           return q - (rs & bs) + (rs & ~bs);
        */

        Expr r = a - q*b;
        Expr bs = b >> (a.type().bits() - 1);
        Expr rs = r >> (a.type().bits() - 1);
        q = q - (rs & bs) + (rs & ~bs);
        return common_subexpression_elimination(q);
    } else {
        return q;
    }
}

Expr lower_euclidean_mod(Expr a, Expr b) {
    internal_assert(a.type() == b.type());
    // IROperator's mod_round_to_zero will replace this with a % b for
    // unsigned ops, so create the intrinsic directly.
    Expr r = Call::make(a.type(), Call::mod_round_to_zero, {a, b}, Call::PureIntrinsic);
    if (a.type().is_int()) {
        // Match this non-overflowing C code
        /*
          T r = a % b;
          r = r + (r < 0 ? abs(b) : 0);
        */

        r = select(r < 0, r + abs(b), r);
        return common_subexpression_elimination(r);
    } else {
        return r;
    }
}

bool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {
    #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)
    llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(value);
    #else
    llvm::ConstantAsMetadata *cam = llvm::cast<llvm::ConstantAsMetadata>(value);
    llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(cam->getValue());
    #endif
    if (c) {
        result = !c->isZero();
        return true;
    }
    return false;
}

bool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {
    #if LLVM_VERSION < 36
    if (llvm::dyn_cast<llvm::ConstantAggregateZero>(value)) {
        result = "";
        return true;
    }
    llvm::ConstantDataArray *c = llvm::cast<llvm::ConstantDataArray>(value);
    if (c) {
        result = c->getAsCString();
        return true;
    }
    #else
    llvm::MDString *c = llvm::dyn_cast<llvm::MDString>(value);
    if (c) {
        result = c->getString();
        return true;
    }
    #endif
    return false;
}

void get_target_options(const llvm::Module &module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {
    bool use_soft_float_abi = false;
    get_md_bool(module.getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi);
    get_md_string(module.getModuleFlag("halide_mcpu"), mcpu);
    get_md_string(module.getModuleFlag("halide_mattrs"), mattrs);

    options = llvm::TargetOptions();
    options.LessPreciseFPMADOption = true;
    options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
    options.UnsafeFPMath = true;
    options.NoInfsFPMath = true;
    options.NoNaNsFPMath = true;
    options.HonorSignDependentRoundingFPMathOption = false;
    #if LLVM_VERSION < 37
    options.NoFramePointerElim = false;
    options.UseSoftFloat = false;
    #endif
    options.NoZerosInBSS = false;
    options.GuaranteedTailCallOpt = false;
    #if LLVM_VERSION < 37
    options.DisableTailCalls = false;
    #endif
    options.StackAlignmentOverride = 0;
    #if LLVM_VERSION < 37
    options.TrapFuncName = "";
    #endif
    options.FunctionSections = true;
    #ifdef WITH_NATIVE_CLIENT
    options.UseInitArray = true;
    #else
    options.UseInitArray = false;
    #endif
    options.FloatABIType =
        use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;
}

void clone_target_options(const llvm::Module &from, llvm::Module &to) {
    to.setTargetTriple(from.getTargetTriple());

    llvm::LLVMContext &context = to.getContext();

    bool use_soft_float_abi = false;
    if (get_md_bool(from.getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi))
        to.addModuleFlag(llvm::Module::Warning, "halide_use_soft_float_abi", use_soft_float_abi ? 1 : 0);

    std::string mcpu;
    if (get_md_string(from.getModuleFlag("halide_mcpu"), mcpu)) {
        #if LLVM_VERSION < 36
        to.addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::ConstantDataArray::getString(context, mcpu));
        #else
        to.addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::MDString::get(context, mcpu));
        #endif
    }

    std::string mattrs;
    if (get_md_string(from.getModuleFlag("halide_mattrs"), mattrs)) {
        #if LLVM_VERSION < 36
        to.addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::ConstantDataArray::getString(context, mattrs));
        #else
        to.addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::MDString::get(context, mattrs));
        #endif
    }
}

llvm::TargetMachine *get_target_machine(const llvm::Module &module) {
    std::string error_string;

    const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module.getTargetTriple(), error_string);
    if (!target) {
        std::cout << error_string << std::endl;
        llvm::TargetRegistry::printRegisteredTargetsForVersion();
    }
    internal_assert(target) << "Could not create target for " << module.getTargetTriple() << "\n";

    llvm::TargetOptions options;
    std::string mcpu = "";
    std::string mattrs = "";
    get_target_options(module, options, mcpu, mattrs);

    return target->createTargetMachine(module.getTargetTriple(),
                                       mcpu, mattrs,
                                       options,
                                       llvm::Reloc::PIC_,
                                       llvm::CodeModel::Default,
                                       llvm::CodeGenOpt::Aggressive);
}

}
}
<commit_msg>Turn off unsafe fp math :(<commit_after>#include "CodeGen_Internal.h"
#include "IROperator.h"
#include "CSE.h"
#include "Debug.h"

namespace Halide {
namespace Internal {

using std::string;
using std::map;
using std::vector;
using std::pair;

using namespace llvm;

namespace {

vector<llvm::Type*> llvm_types(const Closure& closure, llvm::StructType *buffer_t, LLVMContext &context) {
    vector<llvm::Type *> res;
    for (const pair<string, Type> &i : closure.vars) {
        res.push_back(llvm_type_of(&context, i.second));
    }
    for (const pair<string, Closure::BufferRef> &i : closure.buffers) {
        res.push_back(llvm_type_of(&context, i.second.type)->getPointerTo());
        res.push_back(buffer_t->getPointerTo());
    }
    return res;
}

}  // namespace

StructType *build_closure_type(const Closure& closure, llvm::StructType *buffer_t, LLVMContext *context) {
    StructType *struct_t = StructType::create(*context, "closure_t");
    struct_t->setBody(llvm_types(closure, buffer_t, *context), false);
    return struct_t;
}

void pack_closure(llvm::Type *
#if LLVM_VERSION >= 37
                  type
#endif
                  ,
                  Value *dst,
                  const Closure& closure,
                  const Scope<Value *> &src,
                  llvm::StructType *buffer_t,
                  IRBuilder<> *builder) {
    // type, type of dst should be a pointer to a struct of the type returned by build_type
    int idx = 0;
    LLVMContext &context = builder->getContext();
    vector<string> nm = closure.names();
    vector<llvm::Type*> ty = llvm_types(closure, buffer_t, context);
    for (size_t i = 0; i < nm.size(); i++) {
#if LLVM_VERSION >= 37
        Value *ptr = builder->CreateConstInBoundsGEP2_32(type, dst, 0, idx);
#else
        Value *ptr = builder->CreateConstInBoundsGEP2_32(dst, 0, idx);
#endif
        Value *val;
        if (!ends_with(nm[i], ".buffer") || src.contains(nm[i])) {
            val = src.get(nm[i]);
            if (val->getType() != ty[i]) {
                val = builder->CreateBitCast(val, ty[i]);
            }
        } else {
            // Skip over buffers not in the symbol table. They must not be needed.
            val = ConstantPointerNull::get(buffer_t->getPointerTo());
        }
        builder->CreateStore(val, ptr);
        idx++;
    }
}

void unpack_closure(const Closure& closure,
                    Scope<Value *> &dst,
                    llvm::Type *
#if LLVM_VERSION >= 37
                    type
#endif
                    ,
                    Value *src,
                    IRBuilder<> *builder) {
    // type, type of src should be a pointer to a struct of the type returned by build_type
    int idx = 0;
    LLVMContext &context = builder->getContext();
    vector<string> nm = closure.names();
    for (size_t i = 0; i < nm.size(); i++) {
#if LLVM_VERSION >= 37
        Value *ptr = builder->CreateConstInBoundsGEP2_32(type, src, 0, idx++);
#else
        Value *ptr = builder->CreateConstInBoundsGEP2_32(src, 0, idx++);
#endif
        LoadInst *load = builder->CreateLoad(ptr);
        if (load->getType()->isPointerTy()) {
            // Give it a unique type so that tbaa tells llvm that this can't alias anything
            LLVMMDNodeArgumentType md_args[] = {MDString::get(context, nm[i])};
            load->setMetadata("tbaa", MDNode::get(context, md_args));
        }
        dst.push(nm[i], load);
        load->setName(nm[i]);
    }
}

llvm::Type *llvm_type_of(LLVMContext *c, Halide::Type t) {
    if (t.lanes() == 1) {
        if (t.is_float()) {
            switch (t.bits()) {
            case 16:
                return llvm::Type::getHalfTy(*c);
            case 32:
                return llvm::Type::getFloatTy(*c);
            case 64:
                return llvm::Type::getDoubleTy(*c);
            default:
                internal_error << "There is no llvm type matching this floating-point bit width: " << t << "\n";
                return nullptr;
            }
        } else if (t.is_handle()) {
            return llvm::Type::getInt8PtrTy(*c);
        } else {
            return llvm::Type::getIntNTy(*c, t.bits());
        }
    } else {
        llvm::Type *element_type = llvm_type_of(c, t.element_of());
        return VectorType::get(element_type, t.lanes());
    }
}

// Returns true if the given function name is one of the Halide runtime
// functions that takes a user_context pointer as its first parameter.
bool function_takes_user_context(const std::string &name) {
    static const char *user_context_runtime_funcs[] = {
        "halide_copy_to_host",
        "halide_copy_to_device",
        "halide_current_time_ns",
        "halide_debug_to_file",
        "halide_device_free",
        "halide_device_malloc",
        "halide_device_sync",
        "halide_do_par_for",
        "halide_do_task",
        "halide_error",
        "halide_free",
        "halide_malloc",
        "halide_print",
        "halide_profiler_memory_allocate",
        "halide_profiler_memory_free",
        "halide_profiler_pipeline_start",
        "halide_profiler_pipeline_end",
        "halide_profiler_stack_peak_update",
        "halide_spawn_thread",
        "halide_device_release",
        "halide_start_clock",
        "halide_trace",
        "halide_memoization_cache_lookup",
        "halide_memoization_cache_store",
        "halide_memoization_cache_release",
        "halide_cuda_run",
        "halide_opencl_run",
        "halide_opengl_run",
        "halide_openglcompute_run",
        "halide_renderscript_run",
        "halide_metal_run",
        "halide_cuda_initialize_kernels",
        "halide_opencl_initialize_kernels",
        "halide_opengl_initialize_kernels",
        "halide_openglcompute_initialize_kernels",
        "halide_renderscript_initialize_kernels",
        "halide_metal_initialize_kernels",
        "halide_get_gpu_device",
    };
    const int num_funcs = sizeof(user_context_runtime_funcs) /
        sizeof(user_context_runtime_funcs[0]);
    for (int i = 0; i < num_funcs; ++i) {
        if (name == user_context_runtime_funcs[i]) {
            return true;
        }
    }
    // The error functions all take a user context
    return starts_with(name, "halide_error_");
}

bool can_allocation_fit_on_stack(int32_t size) {
    user_assert(size > 0) << "Allocation size should be a positive number\n";
    return (size <= 1024 * 16);
}

Expr lower_euclidean_div(Expr a, Expr b) {
    internal_assert(a.type() == b.type());
    // IROperator's div_round_to_zero will replace this with a / b for
    // unsigned ops, so create the intrinsic directly.
    Expr q = Call::make(a.type(), Call::div_round_to_zero, {a, b}, Call::PureIntrinsic);
    if (a.type().is_int()) {
        // Signed integer division sucks. It should be defined such
        // that it satisifies (a/b)*b + a%b = a, where 0 <= a%b < |b|,
        // i.e. Euclidean division.

        // We get rounding to work by examining the implied remainder
        // and correcting the quotient.

        /* Here's the C code that we're trying to match:
           int q = a / b;
           int r = a - q * b;
           int bs = b >> (t.bits() - 1);
           int rs = r >> (t.bits() - 1);
           return q - (rs & bs) + (rs & ~bs);
        */

        Expr r = a - q*b;
        Expr bs = b >> (a.type().bits() - 1);
        Expr rs = r >> (a.type().bits() - 1);
        q = q - (rs & bs) + (rs & ~bs);
        return common_subexpression_elimination(q);
    } else {
        return q;
    }
}

Expr lower_euclidean_mod(Expr a, Expr b) {
    internal_assert(a.type() == b.type());
    // IROperator's mod_round_to_zero will replace this with a % b for
    // unsigned ops, so create the intrinsic directly.
    Expr r = Call::make(a.type(), Call::mod_round_to_zero, {a, b}, Call::PureIntrinsic);
    if (a.type().is_int()) {
        // Match this non-overflowing C code
        /*
          T r = a % b;
          r = r + (r < 0 ? abs(b) : 0);
        */

        r = select(r < 0, r + abs(b), r);
        return common_subexpression_elimination(r);
    } else {
        return r;
    }
}

bool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {
    #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)
    llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(value);
    #else
    llvm::ConstantAsMetadata *cam = llvm::cast<llvm::ConstantAsMetadata>(value);
    llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(cam->getValue());
    #endif
    if (c) {
        result = !c->isZero();
        return true;
    }
    return false;
}

bool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {
    #if LLVM_VERSION < 36
    if (llvm::dyn_cast<llvm::ConstantAggregateZero>(value)) {
        result = "";
        return true;
    }
    llvm::ConstantDataArray *c = llvm::cast<llvm::ConstantDataArray>(value);
    if (c) {
        result = c->getAsCString();
        return true;
    }
    #else
    llvm::MDString *c = llvm::dyn_cast<llvm::MDString>(value);
    if (c) {
        result = c->getString();
        return true;
    }
    #endif
    return false;
}

void get_target_options(const llvm::Module &module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {
    bool use_soft_float_abi = false;
    get_md_bool(module.getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi);
    get_md_string(module.getModuleFlag("halide_mcpu"), mcpu);
    get_md_string(module.getModuleFlag("halide_mattrs"), mattrs);

    options = llvm::TargetOptions();
    options.LessPreciseFPMADOption = true;
    options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
    // Disabled because it makes LLVM compile vector division to
    // multiplication by approx reciprocal, which is too inaccurate
    // even for us.
    options.UnsafeFPMath = false;
    options.NoInfsFPMath = true;
    options.NoNaNsFPMath = true;
    options.HonorSignDependentRoundingFPMathOption = false;
    #if LLVM_VERSION < 37
    options.NoFramePointerElim = false;
    options.UseSoftFloat = false;
    #endif
    options.NoZerosInBSS = false;
    options.GuaranteedTailCallOpt = false;
    #if LLVM_VERSION < 37
    options.DisableTailCalls = false;
    #endif
    options.StackAlignmentOverride = 0;
    #if LLVM_VERSION < 37
    options.TrapFuncName = "";
    #endif
    options.FunctionSections = true;
    #ifdef WITH_NATIVE_CLIENT
    options.UseInitArray = true;
    #else
    options.UseInitArray = false;
    #endif
    options.FloatABIType =
        use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;
}

void clone_target_options(const llvm::Module &from, llvm::Module &to) {
    to.setTargetTriple(from.getTargetTriple());

    llvm::LLVMContext &context = to.getContext();

    bool use_soft_float_abi = false;
    if (get_md_bool(from.getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi))
        to.addModuleFlag(llvm::Module::Warning, "halide_use_soft_float_abi", use_soft_float_abi ? 1 : 0);

    std::string mcpu;
    if (get_md_string(from.getModuleFlag("halide_mcpu"), mcpu)) {
        #if LLVM_VERSION < 36
        to.addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::ConstantDataArray::getString(context, mcpu));
        #else
        to.addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::MDString::get(context, mcpu));
        #endif
    }

    std::string mattrs;
    if (get_md_string(from.getModuleFlag("halide_mattrs"), mattrs)) {
        #if LLVM_VERSION < 36
        to.addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::ConstantDataArray::getString(context, mattrs));
        #else
        to.addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::MDString::get(context, mattrs));
        #endif
    }
}

llvm::TargetMachine *get_target_machine(const llvm::Module &module) {
    std::string error_string;

    const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module.getTargetTriple(), error_string);
    if (!target) {
        std::cout << error_string << std::endl;
        llvm::TargetRegistry::printRegisteredTargetsForVersion();
    }
    internal_assert(target) << "Could not create target for " << module.getTargetTriple() << "\n";

    llvm::TargetOptions options;
    std::string mcpu = "";
    std::string mattrs = "";
    get_target_options(module, options, mcpu, mattrs);

    return target->createTargetMachine(module.getTargetTriple(),
                                       mcpu, mattrs,
                                       options,
                                       llvm::Reloc::PIC_,
                                       llvm::CodeModel::Default,
                                       llvm::CodeGenOpt::Aggressive);
}

}
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 .
 */

#include "rtl/uuid.h"
#include "osl/thread.h"
#include "osl/mutex.hxx"

#include "uno/environment.hxx"
#include "uno/mapping.hxx"
#include "typelib/typedescription.h"

#include "current.hxx"

using namespace ::osl;
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;

namespace cppu
{

static typelib_InterfaceTypeDescription * get_type_XCurrentContext()
{
    static typelib_InterfaceTypeDescription * s_type_XCurrentContext = 0;
    if (0 == s_type_XCurrentContext)
    {
        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
        if (0 == s_type_XCurrentContext)
        {
            OUString sTypeName("com.sun.star.uno.XCurrentContext");
            typelib_InterfaceTypeDescription * pTD = 0;
            typelib_TypeDescriptionReference * pMembers[1] = { 0 };
            OUString sMethodName0("com.sun.star.uno.XCurrentContext::getValueByName");
            typelib_typedescriptionreference_new(
                &pMembers[0],
                typelib_TypeClass_INTERFACE_METHOD,
                sMethodName0.pData );
            typelib_typedescription_newInterface(
                &pTD,
                sTypeName.pData, 0, 0, 0, 0, 0,
                * typelib_static_type_getByTypeClass( typelib_TypeClass_INTERFACE ),
                1,
                pMembers );

            typelib_typedescription_register( (typelib_TypeDescription**)&pTD );
            typelib_typedescriptionreference_release( pMembers[0] );

            typelib_InterfaceMethodTypeDescription * pMethod = 0;
            typelib_Parameter_Init aParameters[1];
            OUString sParamName0("Name");
            OUString sParamType0("string");
            aParameters[0].pParamName = sParamName0.pData;
            aParameters[0].eTypeClass = typelib_TypeClass_STRING;
            aParameters[0].pTypeName = sParamType0.pData;
            aParameters[0].bIn = sal_True;
            aParameters[0].bOut = sal_False;
            rtl_uString * pExceptions[1];
            OUString sExceptionName0("com.sun.star.uno.RuntimeException");
            pExceptions[0] = sExceptionName0.pData;
            OUString sReturnType0("any");
            typelib_typedescription_newInterfaceMethod(
                &pMethod,
                3, sal_False,
                sMethodName0.pData,
                typelib_TypeClass_ANY, sReturnType0.pData,
                1, aParameters, 1, pExceptions );
            typelib_typedescription_register( (typelib_TypeDescription**)&pMethod );
            typelib_typedescription_release( (typelib_TypeDescription*)pMethod );
            // another static ref:
            ++reinterpret_cast< typelib_TypeDescription * >( pTD )->
                nStaticRefCount;
            s_type_XCurrentContext = pTD;
        }
    }
    return s_type_XCurrentContext;
}

class ThreadKey
{
    bool     _bInit;
    oslThreadKey _hThreadKey;
    oslThreadKeyCallbackFunction _pCallback;

public:
    inline oslThreadKey getThreadKey() SAL_THROW(());

    inline ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(());
    inline ~ThreadKey() SAL_THROW(());
};

inline ThreadKey::ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(())
    : _bInit( false )
    , _pCallback( pCallback )
{
}

inline ThreadKey::~ThreadKey() SAL_THROW(())
{
    if (_bInit)
    {
        ::osl_destroyThreadKey( _hThreadKey );
    }
}

inline oslThreadKey ThreadKey::getThreadKey() SAL_THROW(())
{
    if (! _bInit)
    {
        MutexGuard aGuard( Mutex::getGlobalMutex() );
        if (! _bInit)
        {
            _hThreadKey = ::osl_createThreadKey( _pCallback );
            _bInit = true;
        }
    }
    return _hThreadKey;
}

extern "C" void SAL_CALL delete_IdContainer( void * p )
{
    if (p)
    {
        IdContainer * pId = reinterpret_cast< IdContainer * >( p );
        if (pId->pCurrentContext)
        {
            (*pId->pCurrentContextEnv->releaseInterface)(
                pId->pCurrentContextEnv, pId->pCurrentContext );
            (*((uno_Environment *)pId->pCurrentContextEnv)->release)(
                (uno_Environment *)pId->pCurrentContextEnv );
        }
        if (pId->bInit)
        {
            ::rtl_byte_sequence_release( pId->pLocalThreadId );
            ::rtl_byte_sequence_release( pId->pCurrentId );
        }
        delete pId;
    }
}

IdContainer * getIdContainer() SAL_THROW(())
{
    static ThreadKey s_key( delete_IdContainer );
    oslThreadKey aKey = s_key.getThreadKey();

    IdContainer * pId = reinterpret_cast< IdContainer * >( ::osl_getThreadKeyData( aKey ) );
    if (! pId)
    {
        pId = new IdContainer();
        pId->pCurrentContext = 0;
        pId->pCurrentContextEnv = 0;
        pId->bInit = false;
        ::osl_setThreadKeyData( aKey, pId );
    }
    return pId;
}

}

extern "C" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_setCurrentContext(
    void * pCurrentContext,
    rtl_uString * pEnvTypeName, void * pEnvContext )
    SAL_THROW_EXTERN_C()
{
    IdContainer * pId = getIdContainer();
    OSL_ASSERT( pId );

    // free old one
    if (pId->pCurrentContext)
    {
        (*pId->pCurrentContextEnv->releaseInterface)(
            pId->pCurrentContextEnv, pId->pCurrentContext );
        (*((uno_Environment *)pId->pCurrentContextEnv)->release)(
            (uno_Environment *)pId->pCurrentContextEnv );
        pId->pCurrentContextEnv = 0;

        pId->pCurrentContext = 0;
    }

    if (pCurrentContext)
    {
        uno_Environment * pEnv = 0;
        ::uno_getEnvironment( &pEnv, pEnvTypeName, pEnvContext );
        OSL_ASSERT( pEnv && pEnv->pExtEnv );
        if (pEnv)
        {
            if (pEnv->pExtEnv)
            {
                pId->pCurrentContextEnv = pEnv->pExtEnv;
                (*pId->pCurrentContextEnv->acquireInterface)(
                    pId->pCurrentContextEnv, pCurrentContext );
                pId->pCurrentContext = pCurrentContext;
            }
            else
            {
                (*pEnv->release)( pEnv );
                return sal_False;
            }
        }
        else
        {
            return sal_False;
        }
    }
    return sal_True;
}

extern "C" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_getCurrentContext(
    void ** ppCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext )
    SAL_THROW_EXTERN_C()
{
    IdContainer * pId = getIdContainer();
    OSL_ASSERT( pId );

    Environment target_env;

    // release inout parameter
    if (*ppCurrentContext)
    {
        target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext);
        OSL_ASSERT( target_env.is() );
        if (! target_env.is())
            return sal_False;
        uno_ExtEnvironment * pEnv = target_env.get()->pExtEnv;
        OSL_ASSERT( 0 != pEnv );
        if (0 == pEnv)
            return sal_False;
        (*pEnv->releaseInterface)( pEnv, *ppCurrentContext );

        *ppCurrentContext = 0;
    }

    // case: null-ref
    if (0 == pId->pCurrentContext)
        return sal_True;

    if (! target_env.is())
    {
        target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext);
        OSL_ASSERT( target_env.is() );
        if (! target_env.is())
            return sal_False;
    }

    Mapping mapping((uno_Environment *) pId->pCurrentContextEnv, target_env.get());
    OSL_ASSERT( mapping.is() );
    if (! mapping.is())
        return sal_False;

    mapping.mapInterface(ppCurrentContext, pId->pCurrentContext, ::cppu::get_type_XCurrentContext() );

    return sal_True;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#707713 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 .
 */

#include "rtl/uuid.h"
#include "osl/thread.h"
#include "osl/mutex.hxx"

#include "uno/environment.hxx"
#include "uno/mapping.hxx"
#include "typelib/typedescription.h"

#include "current.hxx"

using namespace ::osl;
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star::uno;

namespace cppu
{

static typelib_InterfaceTypeDescription * get_type_XCurrentContext()
{
    static typelib_InterfaceTypeDescription * s_type_XCurrentContext = 0;
    if (0 == s_type_XCurrentContext)
    {
        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
        if (0 == s_type_XCurrentContext)
        {
            OUString sTypeName("com.sun.star.uno.XCurrentContext");
            typelib_InterfaceTypeDescription * pTD = 0;
            typelib_TypeDescriptionReference * pMembers[1] = { 0 };
            OUString sMethodName0("com.sun.star.uno.XCurrentContext::getValueByName");
            typelib_typedescriptionreference_new(
                &pMembers[0],
                typelib_TypeClass_INTERFACE_METHOD,
                sMethodName0.pData );
            typelib_typedescription_newInterface(
                &pTD,
                sTypeName.pData, 0, 0, 0, 0, 0,
                * typelib_static_type_getByTypeClass( typelib_TypeClass_INTERFACE ),
                1,
                pMembers );

            typelib_typedescription_register( (typelib_TypeDescription**)&pTD );
            typelib_typedescriptionreference_release( pMembers[0] );

            typelib_InterfaceMethodTypeDescription * pMethod = 0;
            typelib_Parameter_Init aParameters[1];
            OUString sParamName0("Name");
            OUString sParamType0("string");
            aParameters[0].pParamName = sParamName0.pData;
            aParameters[0].eTypeClass = typelib_TypeClass_STRING;
            aParameters[0].pTypeName = sParamType0.pData;
            aParameters[0].bIn = sal_True;
            aParameters[0].bOut = sal_False;
            rtl_uString * pExceptions[1];
            OUString sExceptionName0("com.sun.star.uno.RuntimeException");
            pExceptions[0] = sExceptionName0.pData;
            OUString sReturnType0("any");
            typelib_typedescription_newInterfaceMethod(
                &pMethod,
                3, sal_False,
                sMethodName0.pData,
                typelib_TypeClass_ANY, sReturnType0.pData,
                1, aParameters, 1, pExceptions );
            typelib_typedescription_register( (typelib_TypeDescription**)&pMethod );
            typelib_typedescription_release( (typelib_TypeDescription*)pMethod );
            // another static ref:
            ++reinterpret_cast< typelib_TypeDescription * >( pTD )->
                nStaticRefCount;
            s_type_XCurrentContext = pTD;
        }
    }
    return s_type_XCurrentContext;
}

class ThreadKey
{
    bool     _bInit;
    oslThreadKey _hThreadKey;
    oslThreadKeyCallbackFunction _pCallback;

public:
    inline oslThreadKey getThreadKey() SAL_THROW(());

    inline ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(());
    inline ~ThreadKey() SAL_THROW(());
};

inline ThreadKey::ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(())
    : _bInit( false )
    , _hThreadKey( 0 )
    , _pCallback( pCallback )
{
}

inline ThreadKey::~ThreadKey() SAL_THROW(())
{
    if (_bInit)
    {
        ::osl_destroyThreadKey( _hThreadKey );
    }
}

inline oslThreadKey ThreadKey::getThreadKey() SAL_THROW(())
{
    if (! _bInit)
    {
        MutexGuard aGuard( Mutex::getGlobalMutex() );
        if (! _bInit)
        {
            _hThreadKey = ::osl_createThreadKey( _pCallback );
            _bInit = true;
        }
    }
    return _hThreadKey;
}

extern "C" void SAL_CALL delete_IdContainer( void * p )
{
    if (p)
    {
        IdContainer * pId = reinterpret_cast< IdContainer * >( p );
        if (pId->pCurrentContext)
        {
            (*pId->pCurrentContextEnv->releaseInterface)(
                pId->pCurrentContextEnv, pId->pCurrentContext );
            (*((uno_Environment *)pId->pCurrentContextEnv)->release)(
                (uno_Environment *)pId->pCurrentContextEnv );
        }
        if (pId->bInit)
        {
            ::rtl_byte_sequence_release( pId->pLocalThreadId );
            ::rtl_byte_sequence_release( pId->pCurrentId );
        }
        delete pId;
    }
}

IdContainer * getIdContainer() SAL_THROW(())
{
    static ThreadKey s_key( delete_IdContainer );
    oslThreadKey aKey = s_key.getThreadKey();

    IdContainer * pId = reinterpret_cast< IdContainer * >( ::osl_getThreadKeyData( aKey ) );
    if (! pId)
    {
        pId = new IdContainer();
        pId->pCurrentContext = 0;
        pId->pCurrentContextEnv = 0;
        pId->bInit = false;
        ::osl_setThreadKeyData( aKey, pId );
    }
    return pId;
}

}

extern "C" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_setCurrentContext(
    void * pCurrentContext,
    rtl_uString * pEnvTypeName, void * pEnvContext )
    SAL_THROW_EXTERN_C()
{
    IdContainer * pId = getIdContainer();
    OSL_ASSERT( pId );

    // free old one
    if (pId->pCurrentContext)
    {
        (*pId->pCurrentContextEnv->releaseInterface)(
            pId->pCurrentContextEnv, pId->pCurrentContext );
        (*((uno_Environment *)pId->pCurrentContextEnv)->release)(
            (uno_Environment *)pId->pCurrentContextEnv );
        pId->pCurrentContextEnv = 0;

        pId->pCurrentContext = 0;
    }

    if (pCurrentContext)
    {
        uno_Environment * pEnv = 0;
        ::uno_getEnvironment( &pEnv, pEnvTypeName, pEnvContext );
        OSL_ASSERT( pEnv && pEnv->pExtEnv );
        if (pEnv)
        {
            if (pEnv->pExtEnv)
            {
                pId->pCurrentContextEnv = pEnv->pExtEnv;
                (*pId->pCurrentContextEnv->acquireInterface)(
                    pId->pCurrentContextEnv, pCurrentContext );
                pId->pCurrentContext = pCurrentContext;
            }
            else
            {
                (*pEnv->release)( pEnv );
                return sal_False;
            }
        }
        else
        {
            return sal_False;
        }
    }
    return sal_True;
}

extern "C" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_getCurrentContext(
    void ** ppCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext )
    SAL_THROW_EXTERN_C()
{
    IdContainer * pId = getIdContainer();
    OSL_ASSERT( pId );

    Environment target_env;

    // release inout parameter
    if (*ppCurrentContext)
    {
        target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext);
        OSL_ASSERT( target_env.is() );
        if (! target_env.is())
            return sal_False;
        uno_ExtEnvironment * pEnv = target_env.get()->pExtEnv;
        OSL_ASSERT( 0 != pEnv );
        if (0 == pEnv)
            return sal_False;
        (*pEnv->releaseInterface)( pEnv, *ppCurrentContext );

        *ppCurrentContext = 0;
    }

    // case: null-ref
    if (0 == pId->pCurrentContext)
        return sal_True;

    if (! target_env.is())
    {
        target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext);
        OSL_ASSERT( target_env.is() );
        if (! target_env.is())
            return sal_False;
    }

    Mapping mapping((uno_Environment *) pId->pCurrentContextEnv, target_env.get());
    OSL_ASSERT( mapping.is() );
    if (! mapping.is())
        return sal_False;

    mapping.mapInterface(ppCurrentContext, pId->pCurrentContext, ::cppu::get_type_XCurrentContext() );

    return sal_True;
}

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


<commit_before>/*
Part of Scallop Transcript Assembler
(c) 2017 by  Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/

#include <cstdio>
#include <cassert>
#include <sstream>
#include <algorithm>
#include <map>

#include "transcript.h"

transcript::transcript()
{
}

transcript::transcript(const item &e)
{
	assign(e);
	exons.clear();
}

transcript::~transcript()
{
}

int transcript::assign(const item &e)
{
	//assert(e.feature == "transcript");
	seqname = e.seqname;
	source = e.source;
	feature = e.feature;
	gene_id = e.gene_id;
	transcript_id = e.transcript_id;
	start = e.start;
	end = e.end;
	strand = e.strand;
	frame = e.frame;
	coverage = e.coverage;
	RPKM = e.RPKM;
	FPKM = e.FPKM;
	TPM = e.TPM;
	return 0;
}

bool transcript::operator< (const transcript &t) const
{
	int b = seqname.compare(t.seqname);
	if(b < 0) return true;
	if(b > 0) return false;
	if(exons.size() == 0) return true;
	if(t.exons.size() == 0) return false;
	if(exons[0].first < t.exons[0].first) return true;
	else return false;
}

int transcript::clear()
{
	exons.clear();
	seqname = "";
	source = "";
	feature = "";
	gene_id = "";
	transcript_id = "";
	start = 0;
	end = 0;
	strand = '.';
	frame = -1;
	coverage = 0;
	RPKM = 0;
	TPM = 0;
	return 0;
}

int transcript::add_exon(int s, int t)
{
	exons.push_back(PI32(s, t));
	return 0;
}

int transcript::add_exon(const item &e)
{
	assert(e.transcript_id == transcript_id);
	add_exon(e.start, e.end);
	return 0;
}

int transcript::sort()
{
	std::sort(exons.begin(), exons.end());
	return 0;
}

int transcript::shrink()
{
	if(exons.size() == 0) return 0;
	vector<PI32> v;
	PI32 p = exons[0];
	for(int i = 1; i < exons.size(); i++)
	{
		PI32 q = exons[i];
		if(p.second == q.first)
		{
			p.second = q.second;
		}
		else
		{
			//assert(p.second < q.first);
			v.push_back(p);
			p = q;
		}
	}
	v.push_back(p);
	exons = v;
	return 0;
}

int transcript::assign_RPKM(double factor)
{
	RPKM = coverage * factor;
	return 0;
}

int transcript::length() const
{
	int s = 0;
	for(int i = 0; i < exons.size(); i++)
	{
		assert(exons[i].second > exons[i].first);
		s += exons[i].second - exons[i].first;
	}
	return s;
}

PI32 transcript::get_bounds() const
{
	if(exons.size() == 0) return PI32(-1, -1);
	int32_t p = exons[0].first;
	int32_t q = exons[exons.size() - 1].second;
	return PI32(p, q);
}

PI32 transcript::get_first_intron() const
{
	if(exons.size() <= 1) return PI32(-1, -1);
	int32_t p = exons[0].second;
	int32_t q = exons[1].first;
	return PI32(p, q);
}

bool transcript::intron_chain_match(const transcript &t) const
{
	if(exons.size() != t.exons.size()) return false;
	if(exons.size() <= 1) return false;
	int n = exons.size() - 1;
	if(exons[0].second != t.exons[0].second) return false;
	if(exons[n].first != t.exons[n].first) return false;
	for(int k = 1; k < n - 1; k++)
	{
		if(exons[k].first != t.exons[k].first) return false;
		if(exons[k].second != t.exons[k].second) return false;
	}
	return true;
}

string transcript::label() const
{
	char buf[10240];
	PI32 p = get_bounds();
	sprintf(buf, "%s:%d-%d", seqname.c_str(), p.first, p.second);
	return string(buf);
}

int transcript::write(ostream &fout) const
{
	fout.precision(4);
	fout<<fixed;

	if(exons.size() == 0) return 0;

	PI32 p = get_bounds();

	fout<<seqname.c_str()<<"\t";				// chromosome name
	fout<<source.c_str()<<"\t";					// source
	fout<<"transcript\t";						// feature
	fout<<p.first + 1<<"\t";					// left position
	fout<<p.second<<"\t";						// right position
	fout<<1000<<"\t";							// score, now as expression
	fout<<strand<<"\t";							// strand
	fout<<".\t";								// frame
	fout<<"gene_id \""<<gene_id.c_str()<<"\"; ";
	fout<<"transcript_id \""<<transcript_id.c_str()<<"\"; ";
	fout<<"RPKM \""<<RPKM<<"\"; ";
	fout<<"FPKM \""<<FPKM<<"\"; ";
	fout<<"TPM \""<<TPM<<"\"; ";
	fout<<"cov \""<<coverage<<"\";"<<endl;

	for(int k = 0; k < exons.size(); k++)
	{
		fout<<seqname.c_str()<<"\t";		// chromosome name
		fout<<source.c_str()<<"\t";			// source
		fout<<"exon\t";						// feature
		fout<<exons[k].first + 1<<"\t";		// left position
		fout<<exons[k].second<<"\t";		// right position
		fout<<1000<<"\t";					// score, now as expression
		fout<<strand<<"\t";					// strand
		fout<<".\t";						// frame
		fout<<"gene_id \""<<gene_id.c_str()<<"\"; ";
		fout<<"transcript_id \""<<transcript_id.c_str()<<"\"; ";
		fout<<"exon \""<<k + 1<<"\"; ";
		fout<<"RPKM \""<<RPKM<<"\"; ";
		fout<<"FPKM \""<<FPKM<<"\"; ";
		fout<<"TPM \""<<TPM<<"\"; ";
		fout<<"cov \""<<coverage<<"\";"<<endl;
	}
	return 0;
}

<commit_msg>do not print TPM or FPKM<commit_after>/*
Part of Scallop Transcript Assembler
(c) 2017 by  Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/

#include <cstdio>
#include <cassert>
#include <sstream>
#include <algorithm>
#include <map>

#include "transcript.h"

transcript::transcript()
{
}

transcript::transcript(const item &e)
{
	assign(e);
	exons.clear();
}

transcript::~transcript()
{
}

int transcript::assign(const item &e)
{
	//assert(e.feature == "transcript");
	seqname = e.seqname;
	source = e.source;
	feature = e.feature;
	gene_id = e.gene_id;
	transcript_id = e.transcript_id;
	start = e.start;
	end = e.end;
	strand = e.strand;
	frame = e.frame;
	coverage = e.coverage;
	RPKM = e.RPKM;
	FPKM = e.FPKM;
	TPM = e.TPM;
	return 0;
}

bool transcript::operator< (const transcript &t) const
{
	int b = seqname.compare(t.seqname);
	if(b < 0) return true;
	if(b > 0) return false;
	if(exons.size() == 0) return true;
	if(t.exons.size() == 0) return false;
	if(exons[0].first < t.exons[0].first) return true;
	else return false;
}

int transcript::clear()
{
	exons.clear();
	seqname = "";
	source = "";
	feature = "";
	gene_id = "";
	transcript_id = "";
	start = 0;
	end = 0;
	strand = '.';
	frame = -1;
	coverage = 0;
	RPKM = 0;
	TPM = 0;
	return 0;
}

int transcript::add_exon(int s, int t)
{
	exons.push_back(PI32(s, t));
	return 0;
}

int transcript::add_exon(const item &e)
{
	assert(e.transcript_id == transcript_id);
	add_exon(e.start, e.end);
	return 0;
}

int transcript::sort()
{
	std::sort(exons.begin(), exons.end());
	return 0;
}

int transcript::shrink()
{
	if(exons.size() == 0) return 0;
	vector<PI32> v;
	PI32 p = exons[0];
	for(int i = 1; i < exons.size(); i++)
	{
		PI32 q = exons[i];
		if(p.second == q.first)
		{
			p.second = q.second;
		}
		else
		{
			//assert(p.second < q.first);
			v.push_back(p);
			p = q;
		}
	}
	v.push_back(p);
	exons = v;
	return 0;
}

int transcript::assign_RPKM(double factor)
{
	RPKM = coverage * factor;
	return 0;
}

int transcript::length() const
{
	int s = 0;
	for(int i = 0; i < exons.size(); i++)
	{
		assert(exons[i].second > exons[i].first);
		s += exons[i].second - exons[i].first;
	}
	return s;
}

PI32 transcript::get_bounds() const
{
	if(exons.size() == 0) return PI32(-1, -1);
	int32_t p = exons[0].first;
	int32_t q = exons[exons.size() - 1].second;
	return PI32(p, q);
}

PI32 transcript::get_first_intron() const
{
	if(exons.size() <= 1) return PI32(-1, -1);
	int32_t p = exons[0].second;
	int32_t q = exons[1].first;
	return PI32(p, q);
}

bool transcript::intron_chain_match(const transcript &t) const
{
	if(exons.size() != t.exons.size()) return false;
	if(exons.size() <= 1) return false;
	int n = exons.size() - 1;
	if(exons[0].second != t.exons[0].second) return false;
	if(exons[n].first != t.exons[n].first) return false;
	for(int k = 1; k < n - 1; k++)
	{
		if(exons[k].first != t.exons[k].first) return false;
		if(exons[k].second != t.exons[k].second) return false;
	}
	return true;
}

string transcript::label() const
{
	char buf[10240];
	PI32 p = get_bounds();
	sprintf(buf, "%s:%d-%d", seqname.c_str(), p.first, p.second);
	return string(buf);
}

int transcript::write(ostream &fout) const
{
	fout.precision(4);
	fout<<fixed;

	if(exons.size() == 0) return 0;

	PI32 p = get_bounds();

	fout<<seqname.c_str()<<"\t";				// chromosome name
	fout<<source.c_str()<<"\t";					// source
	fout<<"transcript\t";						// feature
	fout<<p.first + 1<<"\t";					// left position
	fout<<p.second<<"\t";						// right position
	fout<<1000<<"\t";							// score, now as expression
	fout<<strand<<"\t";							// strand
	fout<<".\t";								// frame
	fout<<"gene_id \""<<gene_id.c_str()<<"\"; ";
	fout<<"transcript_id \""<<transcript_id.c_str()<<"\"; ";
	fout<<"RPKM \""<<RPKM<<"\"; ";
	//fout<<"FPKM \""<<FPKM<<"\"; ";
	//fout<<"TPM \""<<TPM<<"\"; ";
	fout<<"cov \""<<coverage<<"\";"<<endl;

	for(int k = 0; k < exons.size(); k++)
	{
		fout<<seqname.c_str()<<"\t";		// chromosome name
		fout<<source.c_str()<<"\t";			// source
		fout<<"exon\t";						// feature
		fout<<exons[k].first + 1<<"\t";		// left position
		fout<<exons[k].second<<"\t";		// right position
		fout<<1000<<"\t";					// score, now as expression
		fout<<strand<<"\t";					// strand
		fout<<".\t";						// frame
		fout<<"gene_id \""<<gene_id.c_str()<<"\"; ";
		fout<<"transcript_id \""<<transcript_id.c_str()<<"\"; ";
		fout<<"exon \""<<k + 1<<"\"; "<<endl;
		//fout<<"RPKM \""<<RPKM<<"\"; ";
		//fout<<"FPKM \""<<FPKM<<"\"; ";
		//fout<<"TPM \""<<TPM<<"\"; ";
		//fout<<"cov \""<<coverage<<"\";"<<endl;
	}
	return 0;
}

<|endoftext|>


<commit_before>#pragma once

#include <ifaddrs.h>
#include <systemd/sd-event.h>

#include <chrono>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <sdeventplus/clock.hpp>
#include <sdeventplus/utility/timer.hpp>
#include <set>
#include <string>
#include <vector>

namespace phosphor
{
namespace network
{

using namespace std::chrono_literals;

// wait for three seconds before restarting the networkd
constexpr auto restartTimeout = 3s;

// refresh the objets after five seconds as network
// configuration takes 3-4 sec after systemd-networkd restart.
constexpr auto refreshTimeout = restartTimeout + 7s;

namespace systemd
{
namespace config
{

constexpr auto networkFilePrefix = "00-bmc-";
constexpr auto networkFileSuffix = ".network";
constexpr auto deviceFileSuffix = ".netdev";

} // namespace config
} // namespace systemd

using IntfName = std::string;

struct AddrInfo
{
    uint8_t addrType;
    std::string ipaddress;
    uint16_t prefix;
};

using Addr_t = ifaddrs*;

struct AddrDeleter
{
    void operator()(Addr_t ptr) const
    {
        freeifaddrs(ptr);
    }
};

using AddrPtr = std::unique_ptr<ifaddrs, AddrDeleter>;

/* Need a custom deleter for freeing up sd_event */
struct EventDeleter
{
    void operator()(sd_event* event) const
    {
        event = sd_event_unref(event);
    }
};
using EventPtr = std::unique_ptr<sd_event, EventDeleter>;

template <typename T>
using UniquePtr = std::unique_ptr<T, std::function<void(T*)>>;

using AddrList = std::list<AddrInfo>;
using IntfAddrMap = std::map<IntfName, AddrList>;
using InterfaceList = std::set<IntfName>;

using Timer = sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>;

} // namespace network
} // namespace phosphor
<commit_msg>types: Add types for IPs and MACs in byte form<commit_after>#pragma once

#include <ifaddrs.h>
#include <netinet/in.h>
#include <systemd/sd-event.h>

#include <array>
#include <chrono>
#include <cstddef>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <sdeventplus/clock.hpp>
#include <sdeventplus/utility/timer.hpp>
#include <set>
#include <string>
#include <variant>
#include <vector>

namespace phosphor
{
namespace network
{

using namespace std::chrono_literals;

// wait for three seconds before restarting the networkd
constexpr auto restartTimeout = 3s;

// refresh the objets after five seconds as network
// configuration takes 3-4 sec after systemd-networkd restart.
constexpr auto refreshTimeout = restartTimeout + 7s;

namespace systemd
{
namespace config
{

constexpr auto networkFilePrefix = "00-bmc-";
constexpr auto networkFileSuffix = ".network";
constexpr auto deviceFileSuffix = ".netdev";

} // namespace config
} // namespace systemd

using IntfName = std::string;

struct AddrInfo
{
    uint8_t addrType;
    std::string ipaddress;
    uint16_t prefix;
};

using Addr_t = ifaddrs*;

struct AddrDeleter
{
    void operator()(Addr_t ptr) const
    {
        freeifaddrs(ptr);
    }
};

using AddrPtr = std::unique_ptr<ifaddrs, AddrDeleter>;

/* Need a custom deleter for freeing up sd_event */
struct EventDeleter
{
    void operator()(sd_event* event) const
    {
        event = sd_event_unref(event);
    }
};
using EventPtr = std::unique_ptr<sd_event, EventDeleter>;

template <typename T>
using UniquePtr = std::unique_ptr<T, std::function<void(T*)>>;

// Byte representations for common address types in network byte order
using InAddrAny = std::variant<struct in_addr, struct in6_addr>;
using MacAddr = std::array<std::byte, 6>;

using AddrList = std::list<AddrInfo>;
using IntfAddrMap = std::map<IntfName, AddrList>;
using InterfaceList = std::set<IntfName>;

using Timer = sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>;

} // namespace network
} // namespace phosphor
<|endoftext|>


<commit_before>#include "bloomierHash.h"

BloomierHash::BloomierHash(size_t pHashSeed, size_t pM, size_t pK, size_t pQ, size_t pByte) {

}

size_t BloomierHash::getHashValue(size_t pKey) {

}
size_t BloomierHash::getM(size_t pKey) {

}
vsize_t* BloomierHash::getNeighborhood(size_t pKey){

}
vsize_t* BloomierHash::getM(size_t pKey){

}<commit_msg>Implementation added<commit_after>#include "bloomierHash.h"

BloomierHash::BloomierHash(size_t pM, size_t pK, size_t pBitVectorSize) {
	mM = pM;
	mK = pK;
	// mQ = pQ;
	mHash = new Hash();
	mBitVectorSize = pBitVectorSize;
};
BloomierHash::~BloomierHash() {

};
bitVector* BloomierHash::getMask(size_t pKey) {
	bitVector* mask = new bitVector(mBitVectorSize);
	for (size_t i = 0; i < mBitVectorSize; ++i) {
		srand(pKey);
		(*mask)[i] =  static_cast<char>(rand() % 255);
	}
	return mask;
};
vsize_t* BloomierHash::getKNeighbors(size_t pElement, size_t pK, size_t pModulo) {

	vsize_t* kNeighbors = new vsize_t(pK);
	for (size_t i = 0; i < pK; ++i) {
		(*kNeighbors)[i] = mHash->hash(pElement+1, pModulo, i+1);
	}
	return kNeighbors;
};<|endoftext|>


<commit_before>/*
 * CoordinateSystem.hpp
 *
 *  Created on: Oct 15, 2014
 *      Author: Carsten Uphoff (uphoff@mytum.de)
 */
#ifndef HPLOTLIB_LEGEND_HPP
#define HPLOTLIB_LEGEND_HPP

#include "Plot.hpp"
#include "Statistics.hpp"

#include <GL/glld.h>

#include <queue>

namespace hpl
{
class Font;
class CoordinateSystem {
public:
	typedef IDBase<CoordinateSystem> ID;

	static constexpr float XOffset = 0.12f;
	static constexpr float YOffset = 0.08f;
	static constexpr int Ticks = 8;
	static constexpr float TickLength = 0.02f;

    CoordinateSystem(Font* font);
    ~CoordinateSystem();

    float* getLines() const;
    inline unsigned int getLinesCount() const {
        return 8 + 2*Ticks*4;
    }
    inline Registry<Plot>& getPlots() {
        return plots;
    }

    void setColor(const Color& c);
    void setGeometry(Geometry geom);

    template<typename T>
    T& addPlot(int n, double const* x, double const* y);

	virtual void init(GLuint lineprogram, GLuint textprogram);
	virtual void destroy();
	virtual void draw(float const* mvp);

	virtual void update();

    Delegate<> changed;

    inline ID id() const { return csId; }
    inline void setId(ID id) { csId = id; }

private:
    void updateLimits(double xmin, double xmax, double ymin, double ymax);

    Registry<Plot> plots;
	std::queue<Plot::ID> plotInit;
    ID csId;
	Geometry geometry;

	Font* font;
	Color drawColor;
	bool updateLabels = false;

	double xmin = std::numeric_limits<double>::min();
	double xmax = std::numeric_limits<double>::max();
	double ymin = std::numeric_limits<double>::min();
	double ymax = std::numeric_limits<double>::max();

    GLuint lineBuffer;
    GLuint textBuffer;
    GLuint lineprogram;
    GLuint textprogram;

	GLint linepos, linerect, linecolor, linemvp, textpos, textuv, textrect, textglyphs, textmvp, textcolor;
	int numLines = 0;
	int numChars = 0;

    float* lines = nullptr;
};

template<typename T>
T& CoordinateSystem::addPlot(int n, double const* x, double const* y)
{
	updateLimits(hpl::min(n, x), hpl::max(n, x), hpl::min(n, y), hpl::max(n, y));

    T* plot = new T(n, x, y);
    plot->changed.template bind<Delegate<>, &Delegate<>::invoke>(&changed);
    Plot::ID id = plots.add(plot);
    plotInit.push(id);
    setGeometry(geometry);
    changed.invoke();
    return *plot;
}
}

#endif

<commit_msg>Fixed header guard<commit_after>/*
 * CoordinateSystem.hpp
 *
 *  Created on: Oct 15, 2014
 *      Author: Carsten Uphoff (uphoff@mytum.de)
 */
#ifndef HPLOTLIB_COORDINATESYSTEM_HPP
#define HPLOTLIB_COORDINATESYSTEM_HPP

#include "Plot.hpp"
#include "Statistics.hpp"

#include <GL/glld.h>

#include <queue>

namespace hpl
{
class Font;
class CoordinateSystem {
public:
	typedef IDBase<CoordinateSystem> ID;

	static constexpr float XOffset = 0.12f;
	static constexpr float YOffset = 0.08f;
	static constexpr int Ticks = 8;
	static constexpr float TickLength = 0.02f;

    CoordinateSystem(Font* font);
    ~CoordinateSystem();

    float* getLines() const;
    inline unsigned int getLinesCount() const {
        return 8 + 2*Ticks*4;
    }
    inline Registry<Plot>& getPlots() {
        return plots;
    }

    void setColor(const Color& c);
    void setGeometry(Geometry geom);

    template<typename T>
    T& addPlot(int n, double const* x, double const* y);

	virtual void init(GLuint lineprogram, GLuint textprogram);
	virtual void destroy();
	virtual void draw(float const* mvp);

	virtual void update();

    Delegate<> changed;

    inline ID id() const { return csId; }
    inline void setId(ID id) { csId = id; }

private:
    void updateLimits(double xmin, double xmax, double ymin, double ymax);

    Registry<Plot> plots;
	std::queue<Plot::ID> plotInit;
    ID csId;
	Geometry geometry;

	Font* font;
	Color drawColor;
	bool updateLabels = false;

	double xmin = std::numeric_limits<double>::min();
	double xmax = std::numeric_limits<double>::max();
	double ymin = std::numeric_limits<double>::min();
	double ymax = std::numeric_limits<double>::max();

    GLuint lineBuffer;
    GLuint textBuffer;
    GLuint lineprogram;
    GLuint textprogram;

	GLint linepos, linerect, linecolor, linemvp, textpos, textuv, textrect, textglyphs, textmvp, textcolor;
	int numLines = 0;
	int numChars = 0;

    float* lines = nullptr;
};

template<typename T>
T& CoordinateSystem::addPlot(int n, double const* x, double const* y)
{
	updateLimits(hpl::min(n, x), hpl::max(n, x), hpl::min(n, y), hpl::max(n, y));

    T* plot = new T(n, x, y);
    plot->changed.template bind<Delegate<>, &Delegate<>::invoke>(&changed);
    Plot::ID id = plots.add(plot);
    plotInit.push(id);
    setGeometry(geometry);
    changed.invoke();
    return *plot;
}
}

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VAxisProperties.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 01:37:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "VAxisProperties.hxx"
#include "macros.hxx"
#include "ViewDefines.hxx"
#include "CommonConverters.hxx"

#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART_CHARTAXISARRANGEORDERTYPE_HPP_
#include <com/sun/star/chart/ChartAxisArrangeOrderType.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_WRITINGMODE2_HPP_
#include <com/sun/star/text/WritingMode2.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

sal_Int32 lcl_calcTickLengthForDepth(sal_Int32 nDepth,sal_Int32 nTickmarkStyle)
{
    sal_Int32 nWidth = AXIS2D_TICKLENGTH; //@maybefuturetodo this length could be offered by the model
    double fPercent = 1.0;
    switch(nDepth)
    {
        case 0:
            fPercent = 1.0;
            break;
        case 1:
            fPercent = 0.75;//percentage like in the old chart
            break;
        case 2:
            fPercent = 0.5;
            break;
        default:
            fPercent = 0.3;
            break;
    }
    if(nTickmarkStyle==3)//inner and outer tickmarks
        fPercent*=2.0;
    return static_cast<sal_Int32>(nWidth*fPercent);
}

double lcl_getTickOffset(sal_Int32 nLength,sal_Int32 nTickmarkStyle)
{
    double fPercent = 0.0; //0<=fPercent<=1
    //0.0: completly inner
    //1.0: completly outer
    //0.5: half and half

    /*
    nTickmarkStyle:
    1: inner tickmarks
    2: outer tickmarks
    3: inner and outer tickmarks
    */
    switch(nTickmarkStyle)
    {
        case 1:
            fPercent = 0.0;
            break;
        case 2:
            fPercent = 1.0;
            break;
        default:
            fPercent = 0.5;
            break;
    }
    return fPercent*nLength;
}

VLineProperties AxisProperties::makeLinePropertiesForDepth( sal_Int32 nDepth ) const
{
    //@todo get this from somewhere; maybe for each subincrement
    //so far the model does not offer different settings for each tick depth
    return m_aLineProperties;
}

TickmarkProperties AxisProperties::makeTickmarkProperties(
                        sal_Int32 nDepth ) const
{
    /*
    nTickmarkStyle:
    1: inner tickmarks
    2: outer tickmarks
    3: inner and outer tickmarks
    */
    sal_Int32 nTickmarkStyle = 1;
    if(nDepth==0)
    {
        nTickmarkStyle = m_nMajorTickmarks;
        if(!nTickmarkStyle)
        {
            //create major tickmarks as if they were minor tickmarks
            nDepth = 1;
            nTickmarkStyle = m_nMinorTickmarks;
        }
    }
    else if( nDepth==1)
    {
        nTickmarkStyle = m_nMinorTickmarks;
    }

    if( m_fInnerDirectionSign == 0.0 )
    {
        if( nTickmarkStyle != 0 )
            nTickmarkStyle = 3; //inner and outer tickmarks
    }

    TickmarkProperties aTickmarkProperties;
    aTickmarkProperties.Length = lcl_calcTickLengthForDepth(nDepth,nTickmarkStyle);
    aTickmarkProperties.RelativePos = static_cast<sal_Int32>(lcl_getTickOffset(aTickmarkProperties.Length,nTickmarkStyle));
    aTickmarkProperties.aLineProperties = this->makeLinePropertiesForDepth( nDepth );
    return aTickmarkProperties;
}

//--------------------------------------------------------------------------

AxisProperties::AxisProperties( const uno::Reference< XAxis >& xAxisModel
                              , const ::com::sun::star::awt::Size& rReferenceSize )
    : m_xAxisModel(xAxisModel)
    , m_aReferenceSize(rReferenceSize)
    , m_bIsMainAxis(true)
    , m_pfMainLinePositionAtOtherAxis(NULL)
    , m_pfExrtaLinePositionAtOtherAxis(NULL)
    , m_fInnerDirectionSign(1.0)
    , m_bLabelsOutside(true)
    , m_aLabelAlignment(LABEL_ALIGN_RIGHT_TOP)
    , m_bDisplayLabels( true )
//    , m_eRelativeLabelPosition(LEFTORBOTTOM_OF_AXIS)
    , m_nMajorTickmarks(1)
    , m_nMinorTickmarks(1)
    , m_aTickmarkPropertiesList()
    , m_aLineProperties()
{
}

AxisProperties::AxisProperties( const AxisProperties& rAxisProperties )
    : m_xAxisModel( rAxisProperties.m_xAxisModel )
    , m_aReferenceSize( rAxisProperties.m_aReferenceSize )
    , m_bIsMainAxis( rAxisProperties.m_bIsMainAxis )
    , m_pfMainLinePositionAtOtherAxis( NULL )
    , m_pfExrtaLinePositionAtOtherAxis( NULL )
    , m_fInnerDirectionSign( rAxisProperties.m_fInnerDirectionSign )
    , m_bLabelsOutside( rAxisProperties.m_bLabelsOutside )
    , m_aLabelAlignment( rAxisProperties.m_aLabelAlignment )
    , m_bDisplayLabels( rAxisProperties.m_bDisplayLabels )
//    , m_eRelativeLabelPosition( rAxisProperties.m_eRelativeLabelPosition )
    , m_nMajorTickmarks( rAxisProperties.m_nMajorTickmarks )
    , m_nMinorTickmarks( rAxisProperties.m_nMinorTickmarks )
    , m_aTickmarkPropertiesList( rAxisProperties.m_aTickmarkPropertiesList )
    , m_aLineProperties( rAxisProperties.m_aLineProperties )
{
    if( rAxisProperties.m_pfMainLinePositionAtOtherAxis )
        m_pfMainLinePositionAtOtherAxis = new double(*rAxisProperties.m_pfMainLinePositionAtOtherAxis);
    if( rAxisProperties.m_pfExrtaLinePositionAtOtherAxis )
        m_pfExrtaLinePositionAtOtherAxis = new double (*rAxisProperties.m_pfExrtaLinePositionAtOtherAxis);
}

AxisProperties::~AxisProperties()
{
    delete m_pfMainLinePositionAtOtherAxis;
    delete m_pfExrtaLinePositionAtOtherAxis;
}

LabelAlignment lcl_getLabelAlignment( const AxisProperties& rAxisProperties, bool bIsYAxis )
{
    LabelAlignment aRet( LABEL_ALIGN_LEFT );
    if(bIsYAxis)
    {
        if(rAxisProperties.m_bIsMainAxis)
        {
            if( rAxisProperties.m_bLabelsOutside )
                aRet = LABEL_ALIGN_LEFT;
            else
                aRet = LABEL_ALIGN_RIGHT;
        }
        else
        {
            if( !rAxisProperties.m_bLabelsOutside )
                aRet = LABEL_ALIGN_LEFT;
            else
                aRet = LABEL_ALIGN_RIGHT;
        }
    }
    else
    {
        if(rAxisProperties.m_bIsMainAxis )
        {
            if(rAxisProperties.m_bLabelsOutside)
                aRet = LABEL_ALIGN_BOTTOM;
            else
                aRet = LABEL_ALIGN_TOP;
        }
        else
        {
            if(!rAxisProperties.m_bLabelsOutside)
                aRet = LABEL_ALIGN_BOTTOM;
            else
                aRet = LABEL_ALIGN_TOP;
        }
    }
    return aRet;
}

void AxisProperties::init( bool bCartesian )
{
    if( bCartesian )
    {
        sal_Int32 nDimensionIndex = m_xAxisModel->getRepresentedDimension();
        m_fInnerDirectionSign = m_bIsMainAxis ? 1 : -1;
        if(nDimensionIndex==1)
            m_fInnerDirectionSign*=-1;
        m_aLabelAlignment = lcl_getLabelAlignment(*this,nDimensionIndex==1);
    }

    uno::Reference< beans::XPropertySet > xProp =
        uno::Reference<beans::XPropertySet>::query( this->m_xAxisModel );
    if( !xProp.is() )
        return;

    try
    {
        //init LineProperties
        m_aLineProperties.initFromPropertySet( xProp );

        //init display labels
        xProp->getPropertyValue( C2U( "DisplayLabels" ) ) >>= m_bDisplayLabels;

        //init TickmarkProperties
        xProp->getPropertyValue( C2U( "MajorTickmarks" ) ) >>= m_nMajorTickmarks;
        xProp->getPropertyValue( C2U( "MinorTickmarks" ) ) >>= m_nMinorTickmarks;

        sal_Int32 nMaxDepth = 0;
        if(m_nMinorTickmarks!=0)
            nMaxDepth=2;
        else if(m_nMajorTickmarks!=0)
            nMaxDepth=1;

        this->m_aTickmarkPropertiesList.clear();
        for( sal_Int32 nDepth=0; nDepth<nMaxDepth; nDepth++ )
        {
            TickmarkProperties aTickmarkProperties = this->makeTickmarkProperties( nDepth );
            this->m_aTickmarkPropertiesList.push_back( aTickmarkProperties );
        }
    }
    catch( uno::Exception& e )
    {
            e;
    }
}

//-----------------------------------------------------------------------------

AxisLabelProperties::AxisLabelProperties()
                        : aNumberFormat()
                        , eStaggering( SIDE_BY_SIDE )
                        , bLineBreakAllowed( true )
                        , bOverlapAllowed( false )
                        , bStackCharacters( false )
                        , fRotationAngleDegree( 0.0 )
                        , nRhythm( 1 )
                        , bRhythmIsFix(false)
{
    /*
    aLocale.Language = C2U( "en" );
    aLocale.Country  = C2U( "US" );

    //aLocale.Language = C2U( "ar" );
    //aLocale.Country  = C2U( "IR" );

    //aLocale.Language = C2U( "ja" );
    //aLocale.Country  = C2U( "JP" );
    */
}

void AxisLabelProperties::init( const uno::Reference< XAxis >& xAxisModel )
{
    uno::Reference< beans::XPropertySet > xProp =
        uno::Reference<beans::XPropertySet>::query( xAxisModel );
    if(xProp.is())
    {
        try
        {
            if( !( xProp->getPropertyValue( C2U( "NumberFormat" ) ) >>= this->aNumberFormat ) )
            {
                //@todo get number format from calc
            }

            xProp->getPropertyValue( C2U( "TextBreak" ) ) >>= this->bLineBreakAllowed;
            xProp->getPropertyValue( C2U( "TextOverlap" ) ) >>= this->bOverlapAllowed;
            xProp->getPropertyValue( C2U( "StackCharacters" ) ) >>= this->bStackCharacters;
            xProp->getPropertyValue( C2U( "TextRotation" ) ) >>= this->fRotationAngleDegree;

            ::com::sun::star::chart::ChartAxisArrangeOrderType eArrangeOrder;
            xProp->getPropertyValue( C2U( "ArrangeOrder" ) ) >>= eArrangeOrder;
            switch(eArrangeOrder)
            {
                case ::com::sun::star::chart::ChartAxisArrangeOrderType_SIDE_BY_SIDE:
                    this->eStaggering = SIDE_BY_SIDE;
                    break;
                case ::com::sun::star::chart::ChartAxisArrangeOrderType_STAGGER_EVEN:
                    this->eStaggering = STAGGER_EVEN;
                    break;
                case ::com::sun::star::chart::ChartAxisArrangeOrderType_STAGGER_ODD:
                    this->eStaggering = STAGGER_ODD;
                    break;
                default:
                    this->eStaggering = STAGGER_AUTO;
                    break;
            }
        }
        catch( uno::Exception& e )
        {
             e;
        }
    }
}

/*
sal_Int16 getSwappedWritingMode( sal_Int16 nWritingMode )
{
    //LR_TB == LT
    //RL_TB == RT (Arabic, Hebrew)
    //TB_RL == TR (Japanese, Chinese, Korean)
    // ?? TL (Mongolian) see also text::WritingMode2

    switch(nWritingMode)
    {
        case text::WritingMode2::RL_TB:
            return  text::WritingMode2::TB_RL;
        case text::WritingMode2::TB_RL:
            return  text::WritingMode2::RL_TB;
        case text::WritingMode2::LR_TB:
            return  text::WritingMode2::TB_LR;
        default:
            return  text::WritingMode2::LR_TB;
    }
}
*/

sal_Bool AxisLabelProperties::getIsStaggered() const
{
    if( STAGGER_ODD == eStaggering || STAGGER_EVEN == eStaggering )
        return sal_True;
    return sal_False;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.80); FILE MERGED 2006/09/01 17:18:56 kaib 1.9.80.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VAxisProperties.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:31:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "VAxisProperties.hxx"
#include "macros.hxx"
#include "ViewDefines.hxx"
#include "CommonConverters.hxx"

#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART_CHARTAXISARRANGEORDERTYPE_HPP_
#include <com/sun/star/chart/ChartAxisArrangeOrderType.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_WRITINGMODE2_HPP_
#include <com/sun/star/text/WritingMode2.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

sal_Int32 lcl_calcTickLengthForDepth(sal_Int32 nDepth,sal_Int32 nTickmarkStyle)
{
    sal_Int32 nWidth = AXIS2D_TICKLENGTH; //@maybefuturetodo this length could be offered by the model
    double fPercent = 1.0;
    switch(nDepth)
    {
        case 0:
            fPercent = 1.0;
            break;
        case 1:
            fPercent = 0.75;//percentage like in the old chart
            break;
        case 2:
            fPercent = 0.5;
            break;
        default:
            fPercent = 0.3;
            break;
    }
    if(nTickmarkStyle==3)//inner and outer tickmarks
        fPercent*=2.0;
    return static_cast<sal_Int32>(nWidth*fPercent);
}

double lcl_getTickOffset(sal_Int32 nLength,sal_Int32 nTickmarkStyle)
{
    double fPercent = 0.0; //0<=fPercent<=1
    //0.0: completly inner
    //1.0: completly outer
    //0.5: half and half

    /*
    nTickmarkStyle:
    1: inner tickmarks
    2: outer tickmarks
    3: inner and outer tickmarks
    */
    switch(nTickmarkStyle)
    {
        case 1:
            fPercent = 0.0;
            break;
        case 2:
            fPercent = 1.0;
            break;
        default:
            fPercent = 0.5;
            break;
    }
    return fPercent*nLength;
}

VLineProperties AxisProperties::makeLinePropertiesForDepth( sal_Int32 nDepth ) const
{
    //@todo get this from somewhere; maybe for each subincrement
    //so far the model does not offer different settings for each tick depth
    return m_aLineProperties;
}

TickmarkProperties AxisProperties::makeTickmarkProperties(
                        sal_Int32 nDepth ) const
{
    /*
    nTickmarkStyle:
    1: inner tickmarks
    2: outer tickmarks
    3: inner and outer tickmarks
    */
    sal_Int32 nTickmarkStyle = 1;
    if(nDepth==0)
    {
        nTickmarkStyle = m_nMajorTickmarks;
        if(!nTickmarkStyle)
        {
            //create major tickmarks as if they were minor tickmarks
            nDepth = 1;
            nTickmarkStyle = m_nMinorTickmarks;
        }
    }
    else if( nDepth==1)
    {
        nTickmarkStyle = m_nMinorTickmarks;
    }

    if( m_fInnerDirectionSign == 0.0 )
    {
        if( nTickmarkStyle != 0 )
            nTickmarkStyle = 3; //inner and outer tickmarks
    }

    TickmarkProperties aTickmarkProperties;
    aTickmarkProperties.Length = lcl_calcTickLengthForDepth(nDepth,nTickmarkStyle);
    aTickmarkProperties.RelativePos = static_cast<sal_Int32>(lcl_getTickOffset(aTickmarkProperties.Length,nTickmarkStyle));
    aTickmarkProperties.aLineProperties = this->makeLinePropertiesForDepth( nDepth );
    return aTickmarkProperties;
}

//--------------------------------------------------------------------------

AxisProperties::AxisProperties( const uno::Reference< XAxis >& xAxisModel
                              , const ::com::sun::star::awt::Size& rReferenceSize )
    : m_xAxisModel(xAxisModel)
    , m_aReferenceSize(rReferenceSize)
    , m_bIsMainAxis(true)
    , m_pfMainLinePositionAtOtherAxis(NULL)
    , m_pfExrtaLinePositionAtOtherAxis(NULL)
    , m_fInnerDirectionSign(1.0)
    , m_bLabelsOutside(true)
    , m_aLabelAlignment(LABEL_ALIGN_RIGHT_TOP)
    , m_bDisplayLabels( true )
//    , m_eRelativeLabelPosition(LEFTORBOTTOM_OF_AXIS)
    , m_nMajorTickmarks(1)
    , m_nMinorTickmarks(1)
    , m_aTickmarkPropertiesList()
    , m_aLineProperties()
{
}

AxisProperties::AxisProperties( const AxisProperties& rAxisProperties )
    : m_xAxisModel( rAxisProperties.m_xAxisModel )
    , m_aReferenceSize( rAxisProperties.m_aReferenceSize )
    , m_bIsMainAxis( rAxisProperties.m_bIsMainAxis )
    , m_pfMainLinePositionAtOtherAxis( NULL )
    , m_pfExrtaLinePositionAtOtherAxis( NULL )
    , m_fInnerDirectionSign( rAxisProperties.m_fInnerDirectionSign )
    , m_bLabelsOutside( rAxisProperties.m_bLabelsOutside )
    , m_aLabelAlignment( rAxisProperties.m_aLabelAlignment )
    , m_bDisplayLabels( rAxisProperties.m_bDisplayLabels )
//    , m_eRelativeLabelPosition( rAxisProperties.m_eRelativeLabelPosition )
    , m_nMajorTickmarks( rAxisProperties.m_nMajorTickmarks )
    , m_nMinorTickmarks( rAxisProperties.m_nMinorTickmarks )
    , m_aTickmarkPropertiesList( rAxisProperties.m_aTickmarkPropertiesList )
    , m_aLineProperties( rAxisProperties.m_aLineProperties )
{
    if( rAxisProperties.m_pfMainLinePositionAtOtherAxis )
        m_pfMainLinePositionAtOtherAxis = new double(*rAxisProperties.m_pfMainLinePositionAtOtherAxis);
    if( rAxisProperties.m_pfExrtaLinePositionAtOtherAxis )
        m_pfExrtaLinePositionAtOtherAxis = new double (*rAxisProperties.m_pfExrtaLinePositionAtOtherAxis);
}

AxisProperties::~AxisProperties()
{
    delete m_pfMainLinePositionAtOtherAxis;
    delete m_pfExrtaLinePositionAtOtherAxis;
}

LabelAlignment lcl_getLabelAlignment( const AxisProperties& rAxisProperties, bool bIsYAxis )
{
    LabelAlignment aRet( LABEL_ALIGN_LEFT );
    if(bIsYAxis)
    {
        if(rAxisProperties.m_bIsMainAxis)
        {
            if( rAxisProperties.m_bLabelsOutside )
                aRet = LABEL_ALIGN_LEFT;
            else
                aRet = LABEL_ALIGN_RIGHT;
        }
        else
        {
            if( !rAxisProperties.m_bLabelsOutside )
                aRet = LABEL_ALIGN_LEFT;
            else
                aRet = LABEL_ALIGN_RIGHT;
        }
    }
    else
    {
        if(rAxisProperties.m_bIsMainAxis )
        {
            if(rAxisProperties.m_bLabelsOutside)
                aRet = LABEL_ALIGN_BOTTOM;
            else
                aRet = LABEL_ALIGN_TOP;
        }
        else
        {
            if(!rAxisProperties.m_bLabelsOutside)
                aRet = LABEL_ALIGN_BOTTOM;
            else
                aRet = LABEL_ALIGN_TOP;
        }
    }
    return aRet;
}

void AxisProperties::init( bool bCartesian )
{
    if( bCartesian )
    {
        sal_Int32 nDimensionIndex = m_xAxisModel->getRepresentedDimension();
        m_fInnerDirectionSign = m_bIsMainAxis ? 1 : -1;
        if(nDimensionIndex==1)
            m_fInnerDirectionSign*=-1;
        m_aLabelAlignment = lcl_getLabelAlignment(*this,nDimensionIndex==1);
    }

    uno::Reference< beans::XPropertySet > xProp =
        uno::Reference<beans::XPropertySet>::query( this->m_xAxisModel );
    if( !xProp.is() )
        return;

    try
    {
        //init LineProperties
        m_aLineProperties.initFromPropertySet( xProp );

        //init display labels
        xProp->getPropertyValue( C2U( "DisplayLabels" ) ) >>= m_bDisplayLabels;

        //init TickmarkProperties
        xProp->getPropertyValue( C2U( "MajorTickmarks" ) ) >>= m_nMajorTickmarks;
        xProp->getPropertyValue( C2U( "MinorTickmarks" ) ) >>= m_nMinorTickmarks;

        sal_Int32 nMaxDepth = 0;
        if(m_nMinorTickmarks!=0)
            nMaxDepth=2;
        else if(m_nMajorTickmarks!=0)
            nMaxDepth=1;

        this->m_aTickmarkPropertiesList.clear();
        for( sal_Int32 nDepth=0; nDepth<nMaxDepth; nDepth++ )
        {
            TickmarkProperties aTickmarkProperties = this->makeTickmarkProperties( nDepth );
            this->m_aTickmarkPropertiesList.push_back( aTickmarkProperties );
        }
    }
    catch( uno::Exception& e )
    {
            e;
    }
}

//-----------------------------------------------------------------------------

AxisLabelProperties::AxisLabelProperties()
                        : aNumberFormat()
                        , eStaggering( SIDE_BY_SIDE )
                        , bLineBreakAllowed( true )
                        , bOverlapAllowed( false )
                        , bStackCharacters( false )
                        , fRotationAngleDegree( 0.0 )
                        , nRhythm( 1 )
                        , bRhythmIsFix(false)
{
    /*
    aLocale.Language = C2U( "en" );
    aLocale.Country  = C2U( "US" );

    //aLocale.Language = C2U( "ar" );
    //aLocale.Country  = C2U( "IR" );

    //aLocale.Language = C2U( "ja" );
    //aLocale.Country  = C2U( "JP" );
    */
}

void AxisLabelProperties::init( const uno::Reference< XAxis >& xAxisModel )
{
    uno::Reference< beans::XPropertySet > xProp =
        uno::Reference<beans::XPropertySet>::query( xAxisModel );
    if(xProp.is())
    {
        try
        {
            if( !( xProp->getPropertyValue( C2U( "NumberFormat" ) ) >>= this->aNumberFormat ) )
            {
                //@todo get number format from calc
            }

            xProp->getPropertyValue( C2U( "TextBreak" ) ) >>= this->bLineBreakAllowed;
            xProp->getPropertyValue( C2U( "TextOverlap" ) ) >>= this->bOverlapAllowed;
            xProp->getPropertyValue( C2U( "StackCharacters" ) ) >>= this->bStackCharacters;
            xProp->getPropertyValue( C2U( "TextRotation" ) ) >>= this->fRotationAngleDegree;

            ::com::sun::star::chart::ChartAxisArrangeOrderType eArrangeOrder;
            xProp->getPropertyValue( C2U( "ArrangeOrder" ) ) >>= eArrangeOrder;
            switch(eArrangeOrder)
            {
                case ::com::sun::star::chart::ChartAxisArrangeOrderType_SIDE_BY_SIDE:
                    this->eStaggering = SIDE_BY_SIDE;
                    break;
                case ::com::sun::star::chart::ChartAxisArrangeOrderType_STAGGER_EVEN:
                    this->eStaggering = STAGGER_EVEN;
                    break;
                case ::com::sun::star::chart::ChartAxisArrangeOrderType_STAGGER_ODD:
                    this->eStaggering = STAGGER_ODD;
                    break;
                default:
                    this->eStaggering = STAGGER_AUTO;
                    break;
            }
        }
        catch( uno::Exception& e )
        {
             e;
        }
    }
}

/*
sal_Int16 getSwappedWritingMode( sal_Int16 nWritingMode )
{
    //LR_TB == LT
    //RL_TB == RT (Arabic, Hebrew)
    //TB_RL == TR (Japanese, Chinese, Korean)
    // ?? TL (Mongolian) see also text::WritingMode2

    switch(nWritingMode)
    {
        case text::WritingMode2::RL_TB:
            return  text::WritingMode2::TB_RL;
        case text::WritingMode2::TB_RL:
            return  text::WritingMode2::RL_TB;
        case text::WritingMode2::LR_TB:
            return  text::WritingMode2::TB_LR;
        default:
            return  text::WritingMode2::LR_TB;
    }
}
*/

sal_Bool AxisLabelProperties::getIsStaggered() const
{
    if( STAGGER_ODD == eStaggering || STAGGER_EVEN == eStaggering )
        return sal_True;
    return sal_False;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Fangfang Bai, fangfang@multicorewareinc.com
//    Jin Ma,       jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "../perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"

#ifdef HAVE_OPENCL

namespace cvtest {
namespace ocl {

///////////// dft ////////////////////////

enum OCL_FFT_TYPE
{
    R2R = 0,
    C2R = 1,
    R2C = 2,
    C2C = 3
};

typedef tuple<OCL_FFT_TYPE, Size, int> DftParams;
typedef TestBaseWithParam<DftParams> DftFixture;

OCL_PERF_TEST_P(DftFixture, Dft, ::testing::Combine(Values(C2C, R2R, C2R, R2C),
                                                    Values(OCL_SIZE_1, OCL_SIZE_2, OCL_SIZE_3, Size(512, 512), Size(1024, 1024), Size(2048, 2048)),
                                                    Values((int) 0, (int)DFT_ROWS, (int)DFT_SCALE, (int)DFT_INVERSE,
                                                           (int)DFT_INVERSE | DFT_SCALE, (int)DFT_ROWS | DFT_INVERSE)))
{
    const DftParams params = GetParam();
    const int dft_type = get<0>(params);
    const Size srcSize = get<1>(params);
    int flags = get<2>(params);

    int in_cn, out_cn;
    switch (dft_type)
    {
    case R2R: flags |= cv::DFT_REAL_OUTPUT; in_cn = 1; out_cn = 1; break;
    case C2R: flags |= cv::DFT_REAL_OUTPUT; in_cn = 2; out_cn = 2; break;
    case R2C: flags |= cv::DFT_COMPLEX_OUTPUT; in_cn = 1; out_cn = 2; break;
    case C2C: flags |= cv::DFT_COMPLEX_OUTPUT; in_cn = 2; out_cn = 2; break;
    }

    UMat src(srcSize, CV_MAKE_TYPE(CV_32F, in_cn)), dst(srcSize, CV_MAKE_TYPE(CV_32F, out_cn));
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::dft(src, dst, flags);

    SANITY_CHECK(dst, 1e-5, ERROR_RELATIVE);
}

///////////// MulSpectrums ////////////////////////

typedef tuple<Size, bool> MulSpectrumsParams;
typedef TestBaseWithParam<MulSpectrumsParams> MulSpectrumsFixture;

OCL_PERF_TEST_P(MulSpectrumsFixture, MulSpectrums,
                ::testing::Combine(Values(OCL_SIZE_1, OCL_SIZE_2, OCL_SIZE_3),
                                   Bool()))
{
    const MulSpectrumsParams params = GetParam();
    const Size srcSize = get<0>(params);
    const bool conj = get<1>(params);

    UMat src1(srcSize, CV_32FC2), src2(srcSize, CV_32FC2), dst(srcSize, CV_32FC2);
    declare.in(src1, src2, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::mulSpectrums(src1, src2, dst, 0, conj);

    SANITY_CHECK(dst, 1e-3);
}

} } // namespace cvtest::ocl

#endif // HAVE_OPENCL
<commit_msg>Fixed warning with "uninitialized local variable"<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Fangfang Bai, fangfang@multicorewareinc.com
//    Jin Ma,       jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "../perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"

#ifdef HAVE_OPENCL

namespace cvtest {
namespace ocl {

///////////// dft ////////////////////////

enum OCL_FFT_TYPE
{
    R2R = 0,
    C2R = 1,
    R2C = 2,
    C2C = 3
};

typedef tuple<OCL_FFT_TYPE, Size, int> DftParams;
typedef TestBaseWithParam<DftParams> DftFixture;

OCL_PERF_TEST_P(DftFixture, Dft, ::testing::Combine(Values(C2C, R2R, C2R, R2C),
                                                    Values(OCL_SIZE_1, OCL_SIZE_2, OCL_SIZE_3, Size(512, 512), Size(1024, 1024), Size(2048, 2048)),
                                                    Values((int) 0, (int)DFT_ROWS, (int)DFT_SCALE, (int)DFT_INVERSE,
                                                           (int)DFT_INVERSE | DFT_SCALE, (int)DFT_ROWS | DFT_INVERSE)))
{
    const DftParams params = GetParam();
    const int dft_type = get<0>(params);
    const Size srcSize = get<1>(params);
    int flags = get<2>(params);

    int in_cn = 0, out_cn = 0;
    switch (dft_type)
    {
    case R2R: flags |= cv::DFT_REAL_OUTPUT; in_cn = 1; out_cn = 1; break;
    case C2R: flags |= cv::DFT_REAL_OUTPUT; in_cn = 2; out_cn = 2; break;
    case R2C: flags |= cv::DFT_COMPLEX_OUTPUT; in_cn = 1; out_cn = 2; break;
    case C2C: flags |= cv::DFT_COMPLEX_OUTPUT; in_cn = 2; out_cn = 2; break;
    }

    UMat src(srcSize, CV_MAKE_TYPE(CV_32F, in_cn)), dst(srcSize, CV_MAKE_TYPE(CV_32F, out_cn));
    declare.in(src, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::dft(src, dst, flags);

    SANITY_CHECK(dst, 1e-5, ERROR_RELATIVE);
}

///////////// MulSpectrums ////////////////////////

typedef tuple<Size, bool> MulSpectrumsParams;
typedef TestBaseWithParam<MulSpectrumsParams> MulSpectrumsFixture;

OCL_PERF_TEST_P(MulSpectrumsFixture, MulSpectrums,
                ::testing::Combine(Values(OCL_SIZE_1, OCL_SIZE_2, OCL_SIZE_3),
                                   Bool()))
{
    const MulSpectrumsParams params = GetParam();
    const Size srcSize = get<0>(params);
    const bool conj = get<1>(params);

    UMat src1(srcSize, CV_32FC2), src2(srcSize, CV_32FC2), dst(srcSize, CV_32FC2);
    declare.in(src1, src2, WARMUP_RNG).out(dst);

    OCL_TEST_CYCLE() cv::mulSpectrums(src1, src2, dst, 0, conj);

    SANITY_CHECK(dst, 1e-3);
}

} } // namespace cvtest::ocl

#endif // HAVE_OPENCL
<|endoftext|>