<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9c_set_inband_addr.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9c_set_inband_addr.H
/// @brief configure Cumulus inband address
///
/// Set the inband base address in the MC
/// driven by attributes representing system memory map.
///

// *HWP HWP Owner: Yang Fan Liu shliuyf@cn.ibm.com
// *HWP FW Owner: Thi Tran thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: HB

//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <p9c_set_inband_addr.H>
#include <p9_fbc_utils.H>
#include <p9_mc_scom_addresses.H>

//-----------------------------------------------------------------------------------
// Function definitions
//-----------------------------------------------------------------------------------
///
/// @brief configure Cumulus inband address
///
/// @param[in] i_target => Processor chip target
///
/// @return FAPI_RC_SUCCESS if the setup completes successfully, else error
//
fapi2::ReturnCode p9c_set_inband_addr(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_DBG("Start");

    auto l_dmi_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_DMI>();
    fapi2::ATTR_DMI_INBAND_BAR_ENABLE_Type l_bar_enable;
    fapi2::ATTR_DMI_INBAND_BAR_BASE_ADDR_OFFSET_Type l_bar_offset;
    uint8_t l_dmi_pos;
    uint64_t l_base_addr_nm0, l_base_addr_nm1, l_base_addr_m, l_base_addr_mmio;
    uint64_t l_dmi_inband_addr;
    fapi2::buffer<uint64_t> l_scom_data;

    // determine base address of chip MMIO range
    FAPI_TRY(p9_fbc_utils_get_chip_base_address(i_target,
             EFF_FBC_GRP_CHIP_IDS,
             l_base_addr_nm0,
             l_base_addr_nm1,
             l_base_addr_m,
             l_base_addr_mmio),
             "Error from p9_fbc_utils_get_chip_base_address");

    for(auto l_dmi : l_dmi_chiplets)
    {
        // retrieve inband BAR enable
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DMI_INBAND_BAR_ENABLE, l_dmi, l_bar_enable),
                 "Error from FAPI_ATTR_GET (ATTR_DMI_INBAND_BAR_ENABLE)");

        if (l_bar_enable == fapi2::ENUM_ATTR_DMI_INBAND_BAR_ENABLE_ENABLE)
        {
            // retrieve inband BAR offset
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DMI_INBAND_BAR_BASE_ADDR_OFFSET, l_dmi, l_bar_offset),
                     "Error from FAPI_ATTR_GET (ATTR_DMI_INBAND_BAR_BASE_ADDR_OFFSET)");

            // form SCOM register format
            l_scom_data.flush<0>();
            // BAR address 8:38 into bits 4:34
            l_dmi_inband_addr = l_base_addr_mmio + l_bar_offset;
            l_scom_data.insert<4, 31, 8>(l_dmi_inband_addr);
            // Set valid(bit0 = 1), P9 mode(bit3 = 0)
            l_scom_data.setBit<0>();

            // get MI target to configure MCFGPR
            fapi2::Target<fapi2::TARGET_TYPE_MI> l_mi = l_dmi.getParent<fapi2::TARGET_TYPE_MI>();
            // retrieve DMI pos
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_dmi, l_dmi_pos),
                     "Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");

            // configure inband channel 0 MCFGPR0
            if(l_dmi_pos % 2 == 0)
            {
                FAPI_TRY(fapi2::putScom(l_mi, MCS_MCRSVDE, l_scom_data),
                         "Error from putScom MCFGPR0 for DMI id: %d", l_dmi_pos);
            }
            // configure inband channel 1 MCFGPR1
            else
            {
                FAPI_TRY(fapi2::putScom(l_mi, MCS_MCRSVDF, l_scom_data),
                         "Error from putScom MCFGPR1 for DMI id: %d", l_dmi_pos);
            }
        }
    }

fapi_try_exit:
    FAPI_DBG("End");
    return fapi2::current_err;
}
<commit_msg>p9_cen_framelock -- 2nd version<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9c_set_inband_addr.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9c_set_inband_addr.H
/// @brief configure Cumulus inband address
///
/// Set the inband base address in the MC
/// driven by attributes representing system memory map.
///

// *HWP HWP Owner: Yang Fan Liu shliuyf@cn.ibm.com
// *HWP FW Owner: Thi Tran thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: HB

//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <p9c_set_inband_addr.H>
#include <p9_fbc_utils.H>
#include <p9_mc_scom_addresses.H>

//-----------------------------------------------------------------------------------
// Function definitions
//-----------------------------------------------------------------------------------
///
/// @brief configure Cumulus inband address
///
/// @param[in] i_target => Processor chip target
///
/// @return FAPI_RC_SUCCESS if the setup completes successfully, else error
//
fapi2::ReturnCode p9c_set_inband_addr(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    uint64_t l_base_addr_nm0, l_base_addr_nm1, l_base_addr_m, l_base_addr_mmio;

    FAPI_DBG("Start");
    // determine base address of chip MMIO range
    FAPI_TRY(p9_fbc_utils_get_chip_base_address(i_target,
             EFF_FBC_GRP_CHIP_IDS,
             l_base_addr_nm0,
             l_base_addr_nm1,
             l_base_addr_m,
             l_base_addr_mmio),
             "Error from p9_fbc_utils_get_chip_base_address");

    for (auto l_dmi : i_target.getChildren<fapi2::TARGET_TYPE_DMI>())
    {
        fapi2::ATTR_DMI_INBAND_BAR_ENABLE_Type l_bar_enable;

        // retrieve inband BAR enable
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DMI_INBAND_BAR_ENABLE, l_dmi, l_bar_enable),
                 "Error from FAPI_ATTR_GET (ATTR_DMI_INBAND_BAR_ENABLE)");

        if (l_bar_enable == fapi2::ENUM_ATTR_DMI_INBAND_BAR_ENABLE_ENABLE)
        {
            fapi2::ATTR_DMI_INBAND_BAR_BASE_ADDR_OFFSET_Type l_bar_offset;
            uint64_t l_dmi_inband_addr;
            fapi2::buffer<uint64_t> l_scom_data;
            uint8_t l_dmi_pos;

            // retrieve inband BAR offset
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DMI_INBAND_BAR_BASE_ADDR_OFFSET, l_dmi, l_bar_offset),
                     "Error from FAPI_ATTR_GET (ATTR_DMI_INBAND_BAR_BASE_ADDR_OFFSET)");

            // form SCOM register format
            l_scom_data.flush<0>();
            // BAR address 8:38 into bits 4:34
            l_dmi_inband_addr = l_base_addr_mmio + l_bar_offset;
            l_scom_data.insert<4, 31, 8>(l_dmi_inband_addr);
            // Set valid(bit0 = 1), P9 mode(bit3 = 0)
            l_scom_data.setBit<0>();

            // get MI target to configure MCFGPR
            fapi2::Target<fapi2::TARGET_TYPE_MI> l_mi = l_dmi.getParent<fapi2::TARGET_TYPE_MI>();
            // retrieve DMI pos
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_dmi, l_dmi_pos),
                     "Error from FAPI_ATTR_GET (ATTR_CHIP_UNIT_POS)");

            // configure inband channel 0 MCFGPR0
            if(l_dmi_pos % 2 == 0)
            {
                FAPI_TRY(fapi2::putScom(l_mi, MCS_MCRSVDE, l_scom_data),
                         "Error from putScom MCFGPR0 for DMI id: %d", l_dmi_pos);
            }
            // configure inband channel 1 MCFGPR1
            else
            {
                FAPI_TRY(fapi2::putScom(l_mi, MCS_MCRSVDF, l_scom_data),
                         "Error from putScom MCFGPR1 for DMI id: %d", l_dmi_pos);
            }
        }
    }

    // configure host attention routing
    for (auto l_mc : i_target.getChildren<fapi2::TARGET_TYPE_MC>())
    {
        fapi2::buffer<uint64_t> l_mcbcfg_data = 0;
        fapi2::buffer<uint64_t> l_mcbcfg_mask = 0;
        // Set P9 MCB Configuration Register
        //   MCBCFGQ[62]=0 (disable special attention output)
        //   MCBCFGQ[63]=1 (enable host attention output)
        l_mcbcfg_mask.setBit<62>();
        l_mcbcfg_mask.setBit<63>();
        l_mcbcfg_data.setBit<63>();

        FAPI_TRY(fapi2::putScomUnderMask(l_mc,
                                         DMI_MCBCFG_0x070123E0,
                                         l_mcbcfg_data,
                                         l_mcbcfg_mask),
                 "Error from putScom DMI_MCBCFG");
    }

    for (auto l_mi : i_target.getChildren<fapi2::TARGET_TYPE_MI>())
    {
        fapi2::buffer<uint64_t> l_mcmode2_data = 0;
        fapi2::buffer<uint64_t> l_mcmode2_mask = 0;
        // Set P9 MC Mode2 Register
        //   MCMODE2Q[44]=0 (disable special attention output)
        //   MCMODE2Q[45]=1 (enable host attention output)
        l_mcmode2_mask.setBit<44>();
        l_mcmode2_mask.setBit<45>();
        l_mcmode2_data.setBit<45>();

        FAPI_TRY(fapi2::putScomUnderMask(l_mi,
                                         MI_MCMODE2_0x05010813,
                                         l_mcmode2_data,
                                         l_mcmode2_mask),
                 "Error from putScom MI_MCMODE2");
    }

fapi_try_exit:
    FAPI_DBG("End");
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>#include "codegen.h"
#include "node.h"
#include "parser.hpp"

void CodeGenContext::GenerateCode(NBlock & in_Root)
{
	std::cout << "Genrating code..." << std::endl;

	std::vector<const Type*> l_ArgTypes;
	FunctionType* l_FType = FunctionType::get(Type::getVoidTy(getGlobalContext()), l_ArgTypes, false);
	m_MainFunction = Function::Create(l_FType, GlobalValue::InternalLinkage, "main", Mod);
	BasicBlock* l_Block = BasicBlock::Create(getGlobalContext(), "entry", m_MainFunction);

	PushBlock(l_Block);
	in_Root.CodeGen(*this);
	ReturnInst::Create(getGlobalContext(), l_Block);
	PopBlock();

	std::cout << "Done" << std::endl;
	PassManager l_PassMgr;
	l_PassMgr.add(createPrintModulePass(&outs()));
	l_PassMgr.run();
}

GenericValue CodeGenContext::RunCode()
{
	std::cout << "Running code..." << std::endl;
	ExistingModuleProvider* l_EMP = new ExistingModuleProvider(Mod);
	ExecutionEngine* l_EEngine = ExecutionEngine::create(l_EMP, false);
	std::vector<GenericValue> l_NoArgs;
	GenericValue l_GenValue = l_EEngine->runFunction(m_MainFunction, l_NoArgs);
	std::cout << "Code was run" << std::endl;
	return l_GenValue;
}

static const Type* TypeOf(const NIdentifier & in_Type)
{
	if(in_Type.Name.compare("int") == 0)
	{
		return Type::getInt64Ty(getGlobalContext());
	}
	else if(in_Type.Name.compare("double") == 0)
	{
		return Type::getDoubleTy(getGlobalContext());
	}
	return Type::getVoidTy(getGlobalContext());
}

/////////// Code Generation ///////////

Value* NInteger::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating integer" << std::endl;
	return ConstantInt::get(Type::getInt64Ty(getGlobalContext()), Value, true);
}

Value* NDouble::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating double" << std::endl;
	return ConstantFP::get(Type::getDoubleTy(getGlobalContext()), Value);
}

Value* NIdentifier::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating identifier reference: " << Name << std::endl;
	if(io_Context.Locals().find(Name) == io_Context.Locals().end())
	{
		std::cerr << "undeclared variable " << Name << std::endl;
		return nullptr;
	}
	return new LoadInst(io_Context.Locals()[Name], "", false, io_Context.CurrentBlock());
}

Value* NMethodCall::CodeGen(CodeGenContext & io_Context)
{
	Function* l_Function = io_Context.Mod->getFunction(ID.Name.c_str());
	if(l_Function == nullptr)
	{
		std::cerr << "no such function " << ID.Name << std::endl;
	}

	std::vector<Value*> l_Args;
	for(auto& in_Arg : Arguments)
	{
		l_Args.push_back(in_Arg->CodeGen(io_Context));
	}
	CallInst* l_Call = CallInst::Create(l_Function, l_Args.begin(), l_Args.end(), "", io_Context);
	std::cout << "Creating method call: " << ID.Name << std::endl;
	return l_Call;
}

Value* NBinaryOperator::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating binary operation " << Op << std::endl;
	Instruction::BinaryOps l_Instr;
	switch (Op)
	{
		case TPLUS: 	l_Instr = Instruction::Add; goto math;
		case TMINUS: 	l_Instr = Instruction::Sub; goto math;
		case TMUL: 		l_Instr = Instruction::Mul; goto math;
		case TDIV: 		l_Instr = Instruction::SDiv; goto math;

		/* TODO comparison */
	}

	return NULL;
math:
	return BinaryOperator::Create(l_Instr, LHS.CodeGen(io_Context),
		RHS.CodeGen(io_Context), "", io_Context.CurrentBlock());
}

Value* NAssignment::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating assignment for " << LHS.Name << std::endl;
	if (io_Context.Locals().find(LHS.Name) == io_Context.Locals().end())
	{
		std::cerr << "undeclared variable " << LHS.Name << std::endl;
		return nullptr;
	}
	return new StoreInst(RHS.CodeGen(io_Context), io_Context.Locals()[LHS.Name], false, io_Context.CurrentBlock());
}

Value* NBlock::CodeGen(CodeGenContext & io_Context)
{
	Value* l_Last = nullptr;

	for(auto& in_Stmt : Statements)
	{
		std::cout << "Generating code for " << typeid(in_Stmt).name() << std::endl;
		l_Last = in_Stmt->CodeGen(io_Context);
	}

	std::cout << "Creating block" << std::endl;
	return l_Last;
}

Value* NExpressionStatement::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Generating code for " << typeid(Expression).name() << std::endl;
	return Expression.CodeGen(io_Context);
}

Value* NVariableDeclaration::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating variable declaration " << Type.Name << " " << ID.Name << std::endl;
	AllocaInst* l_Alloc = new AllocaInst(TypeOf(Type), ID.Name.c_str(), io_Context.CurrentBlock());
	io_Context.Locals()[ID.Name] = l_Alloc;
	if (AssignmentExpr != nullptr)
	{
		NAssignment l_Assn(ID, *AssignmentExpr);
		l_Assn.CodeGen(io_Context);
	}
	return l_Alloc;
}

Value* NFunctionDeclaration::CodeGen(CodeGenContext & io_Context)
{
	std::vector<const Type*> l_ArgTypes;

	for(auto& in_Arg : Arguments)
	{
		l_ArgTypes.push_back(TypeOf(in_Arg).Type);
	}

	FunctionType* l_FType = FunctionType::get(TypeOf(Type), l_ArgTypes, false);
	Function* l_Function = Function::Create(l_FType, GlobalValue::InternalLinkage, ID.Name.c_str(), io_Context.Mod);
	BasicBlock* l_Block = BasicBlock::Create(getGlobalContext(), "entry", l_Function, 0);

	io_Context.PushBlock(l_Block);

	for(auto& in_Arg : Arguments)
	{
		in_Arg->CodeGen(io_Context);
	}

	Block.CodeGen(io_Context);
	ReturnInst::Create(getGlobalContext(), l_Block);

	io_Context.PopBlock();
	std::cout << "Creating function: " << ID.Name << std::endl;
	return l_Function;
}
<commit_msg>Updated the basic interpreter to LLVM 3.2<commit_after>#include "codegen.h"
#include "node.h"
#include "parser.hpp"

void CodeGenContext::GenerateCode(NBlock & in_Root)
{
	std::cout << "Genrating code..." << std::endl;

	FunctionType* l_FType = FunctionType::get(Type::getVoidTy(getGlobalContext()), std::vector<Type*>(), false);
	m_MainFunction = Function::Create(l_FType, GlobalValue::InternalLinkage, "main", Mod);
	BasicBlock* l_Block = BasicBlock::Create(getGlobalContext(), "entry", m_MainFunction);

	PushBlock(l_Block);
	in_Root.CodeGen(*this);
	ReturnInst::Create(getGlobalContext(), l_Block);
	PopBlock();

	std::cout << "Done" << std::endl;
	PassManager l_PassMgr;
	l_PassMgr.add(createPrintModulePass(&outs()));
	l_PassMgr.run(*Mod);
}

GenericValue CodeGenContext::RunCode()
{
	std::cout << "Running code..." << std::endl;
	ExecutionEngine* l_EEngine = ExecutionEngine::create(Mod);
	std::vector<GenericValue> l_NoArgs;
	GenericValue l_GenValue = l_EEngine->runFunction(m_MainFunction, l_NoArgs);
	std::cout << "Code was run" << std::endl;
	return l_GenValue;
}

static Type* TypeOf(const NIdentifier & in_Type)
{
	if(in_Type.Name.compare("int") == 0)
	{
		return Type::getInt64Ty(getGlobalContext());
	}
	else if(in_Type.Name.compare("double") == 0)
	{
		return Type::getDoubleTy(getGlobalContext());
	}
	return Type::getVoidTy(getGlobalContext());
}

/////////// Code Generation ///////////

Value* NInteger::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating integer" << std::endl;
	return ConstantInt::get(Type::getInt64Ty(getGlobalContext()), Value, true);
}

Value* NDouble::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating double" << std::endl;
	return ConstantFP::get(Type::getDoubleTy(getGlobalContext()), Value);
}

Value* NIdentifier::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating identifier reference: " << Name << std::endl;
	if(io_Context.Locals().find(Name) == io_Context.Locals().end())
	{
		std::cerr << "undeclared variable " << Name << std::endl;
		return nullptr;
	}
	return new LoadInst(io_Context.Locals()[Name], "", false, io_Context.CurrentBlock());
}

Value* NMethodCall::CodeGen(CodeGenContext & io_Context)
{
	Function* l_Function = io_Context.Mod->getFunction(ID.Name.c_str());
	if(l_Function == nullptr)
	{
		std::cerr << "no such function " << ID.Name << std::endl;
	}

	std::vector<Value*> l_Args;
	for(auto& in_Arg : Arguments)
	{
		l_Args.push_back(in_Arg->CodeGen(io_Context));
	}
	CallInst* l_Call = CallInst::Create(l_Function, l_Args, "", io_Context.CurrentBlock());
	std::cout << "Creating method call: " << ID.Name << std::endl;
	return l_Call;
}

Value* NBinaryOperator::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating binary operation " << Op << std::endl;
	Instruction::BinaryOps l_Instr;
	switch (Op)
	{
		case TPLUS: 	l_Instr = Instruction::Add; goto math;
		case TMINUS: 	l_Instr = Instruction::Sub; goto math;
		case TMUL: 		l_Instr = Instruction::Mul; goto math;
		case TDIV: 		l_Instr = Instruction::SDiv; goto math;

		/* TODO comparison */
	}

	return NULL;
math:
	return BinaryOperator::Create(l_Instr, LHS.CodeGen(io_Context),
		RHS.CodeGen(io_Context), "", io_Context.CurrentBlock());
}

Value* NAssignment::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating assignment for " << LHS.Name << std::endl;
	if (io_Context.Locals().find(LHS.Name) == io_Context.Locals().end())
	{
		std::cerr << "undeclared variable " << LHS.Name << std::endl;
		return nullptr;
	}
	return new StoreInst(RHS.CodeGen(io_Context), io_Context.Locals()[LHS.Name], false, io_Context.CurrentBlock());
}

Value* NBlock::CodeGen(CodeGenContext & io_Context)
{
	Value* l_Last = nullptr;

	for(auto& in_Stmt : Statements)
	{
		std::cout << "Generating code for " << typeid(in_Stmt).name() << std::endl;
		l_Last = in_Stmt->CodeGen(io_Context);
	}

	std::cout << "Creating block" << std::endl;
	return l_Last;
}

Value* NExpressionStatement::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Generating code for " << typeid(Expression).name() << std::endl;
	return Expression.CodeGen(io_Context);
}

Value* NVariableDeclaration::CodeGen(CodeGenContext & io_Context)
{
	std::cout << "Creating variable declaration " << Type.Name << " " << ID.Name << std::endl;
	AllocaInst* l_Alloc = new AllocaInst(TypeOf(Type), ID.Name.c_str(), io_Context.CurrentBlock());
	io_Context.Locals()[ID.Name] = l_Alloc;
	if (AssignmentExpr != nullptr)
	{
		NAssignment l_Assn(ID, *AssignmentExpr);
		l_Assn.CodeGen(io_Context);
	}
	return l_Alloc;
}

Value* NFunctionDeclaration::CodeGen(CodeGenContext & io_Context)
{
	std::vector<llvm::Type*> l_ArgTypes;

	for(auto& in_Arg : Arguments)
	{
		l_ArgTypes.push_back(TypeOf((*in_Arg).Type));
	}

	FunctionType* l_FType = FunctionType::get(TypeOf(Type), l_ArgTypes, false);
	Function* l_Function = Function::Create(l_FType, GlobalValue::InternalLinkage, ID.Name.c_str(), io_Context.Mod);
	BasicBlock* l_Block = BasicBlock::Create(getGlobalContext(), "entry", l_Function, 0);

	io_Context.PushBlock(l_Block);

	for(auto& in_Arg : Arguments)
	{
		in_Arg->CodeGen(io_Context);
	}

	Block.CodeGen(io_Context);
	ReturnInst::Create(getGlobalContext(), l_Block);

	io_Context.PopBlock();
	std::cout << "Creating function: " << ID.Name << std::endl;
	return l_Function;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010-2011, Mathieu Labbe and IntRoLab - Universite de Sherbrooke
 *
 * This file is part of RTAB-Map.
 *
 * RTAB-Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * RTAB-Map 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with RTAB-Map.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "rtabmap/core/BayesFilter.h"
#include "rtabmap/core/Memory.h"
#include "rtabmap/core/Signature.h"
#include "rtabmap/core/Parameters.h"
#include <iostream>

#include "utilite/UtiLite.h"

namespace rtabmap {

BayesFilter::BayesFilter(const ParametersMap & parameters) :
	_virtualPlacePrior(Parameters::defaultBayesVirtualPlacePriorThr()),
	_predictionOnNonNullActionsOnly(Parameters::defaultBayesPredictionOnNonNullActionsOnly())
{
	this->setPredictionLC(Parameters::defaultBayesPredictionLC());
	this->parseParameters(parameters);
}

BayesFilter::~BayesFilter() {
}

void BayesFilter::parseParameters(const ParametersMap & parameters)
{
	ParametersMap::const_iterator iter;
	if((iter=parameters.find(Parameters::kBayesVirtualPlacePriorThr())) != parameters.end())
	{
		this->setVirtualPlacePrior(std::atof((*iter).second.c_str()));
	}
	if((iter=parameters.find(Parameters::kBayesPredictionLC())) != parameters.end())
	{
		this->setPredictionLC((*iter).second);
	}
	if((iter=parameters.find(Parameters::kBayesPredictionOnNonNullActionsOnly())) != parameters.end())
	{
		_predictionOnNonNullActionsOnly = uStr2Bool((*iter).second.c_str());
	}

}

void BayesFilter::setVirtualPlacePrior(float virtualPlacePrior)
{
	if(virtualPlacePrior < 0)
	{
		ULOGGER_WARN("virtualPlacePrior=%f, must be >=0 and <=1", virtualPlacePrior);
		_virtualPlacePrior = 0;
	}
	else if(virtualPlacePrior > 1)
	{
		ULOGGER_WARN("virtualPlacePrior=%f, must be >=0 and <=1", virtualPlacePrior);
		_virtualPlacePrior = 1;
	}
	else
	{
		_virtualPlacePrior = virtualPlacePrior;
	}
}

// format = {Virtual place, Loop closure, level1, level2, l3, l4...}
void BayesFilter::setPredictionLC(const std::string & prediction)
{
	std::list<std::string> strValues = uSplit(prediction, ' ');
	if(strValues.size() < 2)
	{
		UERROR("The number of values < 2 (prediction=\"%s\")", prediction.c_str());
	}
	else
	{
		std::vector<double> tmpValues(strValues.size());
		int i=0;
		bool valid = true;
		for(std::list<std::string>::iterator iter = strValues.begin(); iter!=strValues.end(); ++iter)
		{
			tmpValues[i] = std::atof((*iter).c_str());
			//UINFO("%d=%e", i, tmpValues[i]);
			if(tmpValues[i] < 0.0 || tmpValues[i]>1.0)
			{
				valid = false;
				break;
			}
			++i;
		}

		if(!valid)
		{
			UERROR("The prediction is not valid (values must be between >0 && <=1) prediction=\"%s\"", prediction.c_str());
		}
		else
		{
			_predictionLC = tmpValues;
		}
	}
}

const std::vector<double> & BayesFilter::getPredictionLC() const
{
	// {Vp, Lc, l1, l2, l3, l4...}
	return _predictionLC;
}

std::string BayesFilter::getPredictionLCStr() const
{
	std::string values;
	for(unsigned int i=0; i<_predictionLC.size(); ++i)
	{
		values.append(uNumber2Str(_predictionLC[i]));
		if(i+1 < _predictionLC.size())
		{
			values.append(" ");
		}
	}
	return values;
}

void BayesFilter::reset()
{
	_posterior.clear();
}

const std::map<int, float> & BayesFilter::computePosterior(const Memory * memory, const std::map<int, float> & likelihood)
{
	ULOGGER_DEBUG("");

	if(!memory)
	{
		ULOGGER_ERROR("Memory is Null!");
		return _posterior;
	}

	if(!likelihood.size())
	{
		ULOGGER_ERROR("likelihood is empty!");
		return _posterior;
	}

	if(_predictionLC.size() < 2)
	{
		ULOGGER_ERROR("Prediction is not valid!");
		return _posterior;
	}

	UTimer timer;
	timer.start();

	cv::Mat prediction;
	cv::Mat prior;
	cv::Mat posterior;

	float sum = 0;
	int j=0;
	// Recursive Bayes estimation...
	// STEP 1 - Prediction : Prior*lastPosterior
	prediction = cvCreateMat(likelihood.size(), likelihood.size(), CV_32FC1);
	if(this->generatePrediction(prediction, memory, uKeys(likelihood)))
	{
		ULOGGER_DEBUG("STEP1-generate prior=%fs, rows=%d, cols=%d", timer.ticks(), prediction.rows, prediction.cols);
		//std::cout << "Prediction=" << prediction << std::endl;

		// Adjust the last posterior if some images were
		// reactivated or removed from the working memory
		posterior = cv::Mat(likelihood.size(), 1, CV_32FC1);
		this->updatePosterior(memory, uKeys(likelihood));
		j=0;
		for(std::map<int, float>::const_iterator i=_posterior.begin(); i!= _posterior.end(); ++i)
		{
			((float*)posterior.data)[j++] = (*i).second;
		}
		ULOGGER_DEBUG("STEP1-update posterior=%fs, posterior=%d, _posterior size=%d", posterior.rows, _posterior.size());
		//std::cout << "LastPosterior=" << posterior << std::endl;

		// Multiply prediction matrix with the last posterior
		// (m,m) X (m,1) = (m,1)
		prior = prediction * posterior;
		ULOGGER_DEBUG("STEP1-matrix mult time=%fs", timer.ticks());
		//std::cout << "ResultingPrior=" << prior << std::endl;

		ULOGGER_DEBUG("STEP1-matrix mult time=%fs", timer.ticks());
		std::vector<float> likelihoodValues = uValues(likelihood);
		//std::cout << "Likelihood=" << cv::Mat(likelihoodValues) << std::endl;

		// STEP 2 - Update : Multiply with observations (likelihood)
		j=0;
		for(std::map<int, float>::const_iterator i=likelihood.begin(); i!= likelihood.end(); ++i)
		{
			std::map<int, float>::iterator p =_posterior.find((*i).first);
			if(p!= _posterior.end())
			{
				(*p).second = (*i).second * ((float*)prior.data)[j++];
				sum+=(*p).second;
			}
			else
			{
				ULOGGER_ERROR("Problem1! can't find id=%d", (*i).first);
			}
		}
		ULOGGER_DEBUG("STEP2-likelihood time=%fs", timer.ticks());

		// Normalize
		ULOGGER_DEBUG("sum=%f", sum);
		if(sum != 0)
		{
			for(std::map<int, float>::iterator i=_posterior.begin(); i!= _posterior.end(); ++i)
			{
				(*i).second /= sum;
			}
		}
		ULOGGER_DEBUG("normalize time=%fs", timer.ticks());
	}

	return _posterior;
}

bool BayesFilter::generatePrediction(cv::Mat & prediction, const Memory * memory, const std::vector<int> & ids) const
{
	ULOGGER_DEBUG("");
	UTimer timer;
	timer.start();
	UTimer timerGlobal;
	timerGlobal.start();

	if(!memory ||
	   prediction.empty() ||
	   prediction.rows != prediction.cols ||
	   (unsigned int)prediction.rows != ids.size() ||
	   _predictionLC.size() < 2 ||
	   !ids.size())
	{
		ULOGGER_ERROR( "fail");
		return false;
	}

	std::map<int, int> idToIndexMap;
	for(unsigned int i=0; i<ids.size(); ++i)
	{
		if(ids[i] == 0)
		{
			UFATAL("Signature id is null ?!?");
		}
		idToIndexMap.insert(idToIndexMap.end(), std::make_pair(ids[i], i));
	}

	//int rows = prediction.rows;
	prediction = cv::Mat::zeros(prediction.rows, prediction.cols, prediction.type());
	int cols = prediction.cols;

	// Each prior is a column vector
	ULOGGER_DEBUG("_predictionLC.size()=%d",_predictionLC.size());
	for(unsigned int i=0; i<ids.size(); ++i)
	{
		int loopSignId = ids[i];
		if(loopSignId > 0)
		{
			// Set high values (gaussians curves) to loop closure neighbors

			float sum = 0.0f; // sum values added

			float totalModelValues = 0.0f;
			for(unsigned int j=0; j<_predictionLC.size(); ++j)
			{
				totalModelValues += _predictionLC[j];
			}

			// ADD prob for each neighbors
			double dbAccessTime = 0.0;
			std::map<int, int> neighbors = memory->getNeighborsId(dbAccessTime, loopSignId, _predictionLC.size()-1, 0, _predictionOnNonNullActionsOnly);
			sum += this->addNeighborProb(prediction, i, neighbors, idToIndexMap);
			// ADD values of not found neighbors to loop closure
			if(sum < totalModelValues-_predictionLC[0])
			{
				float delta = totalModelValues-_predictionLC[0]-sum;
				((float*)prediction.data)[i + i*cols] += delta;
				sum+=delta;
			}

			float allOtherPlacesValue = 0;
			if(totalModelValues < 1)
			{
				allOtherPlacesValue = 1.0f - totalModelValues;
			}

			// Set all loop events to small values according to the model
			if(allOtherPlacesValue > 0 && cols>1)
			{
				float value = allOtherPlacesValue / float(cols - 1);
				for(int j=ids[0] < 0?1:0; j<cols; ++j)
				{
					if(((float*)prediction.data)[i + j*cols] == 0)
					{
						((float*)prediction.data)[i + j*cols] = value;
						sum += ((float*)prediction.data)[i + j*cols];
					}
				}
			}

			//normalize this row
			float maxNorm = 1 - (ids[0]<0?_predictionLC[0]:0); // 1 - virtual place probability
			if(sum<maxNorm-0.0001 || sum>maxNorm+0.0001)
			{
				for(int j=ids[0] < 0?1:0; j<cols; ++j)
				{
					((float*)prediction.data)[i + j*cols] *= maxNorm / sum;
				}
				sum = maxNorm;
			}

			// ADD virtual place prob
			if(ids[0] < 0)
			{
				((float*)prediction.data)[i] = _predictionLC[0];
				sum += ((float*)prediction.data)[i];
			}

			//debug
			//for(int j=0; j<cols; ++j)
			//{
			//	ULOGGER_DEBUG("test col=%d = %f", i, prediction.data.fl[i + j*cols]);
			//}

			if(sum<0.99 || sum > 1.01)
			{
				UWARN("Prediction is not normalized sum=%f", sum);
			}
		}
		else
		{
			// Set the virtual place prior
			if(_virtualPlacePrior > 0)
			{
				if(cols>1) // The first must be the virtual place
				{
					((float*)prediction.data)[i] = _virtualPlacePrior;
					float val = (1.0-_virtualPlacePrior)/(cols-1);
					for(int j=1; j<cols; j++)
					{
						((float*)prediction.data)[i + j*cols] = val;
					}
				}
				else if(cols>0)
				{
					((float*)prediction.data)[i] = 1;
				}
			}
			else
			{
				// Only for some tests...
				// when _virtualPlacePrior=0, set all priors to the same value
				if(cols>1)
				{
					float val = 1.0/cols;
					for(int j=0; j<cols; j++)
					{
						((float*)prediction.data)[i + j*cols] = val;
					}
				}
				else if(cols>0)
				{
					((float*)prediction.data)[i] = 1;
				}
			}
		}
	}

	ULOGGER_DEBUG("time = %fs", timerGlobal.ticks());

	return true;
}

void BayesFilter::updatePosterior(const Memory * memory, const std::vector<int> & likelihoodIds)
{
	ULOGGER_DEBUG("");
	std::map<int, float> newPosterior;
	for(std::vector<int>::const_iterator i=likelihoodIds.begin(); i != likelihoodIds.end(); ++i)
	{
		std::map<int, float>::iterator post = _posterior.find(*i);
		if(post == _posterior.end())
		{
			if(_posterior.size() == 0)
			{
				newPosterior.insert(std::pair<int, float>(*i, 1));
			}
			else
			{
				newPosterior.insert(std::pair<int, float>(*i, 0));
			}
		}
		else
		{
			newPosterior.insert(std::pair<int, float>((*post).first, (*post).second));
		}
	}
	_posterior = newPosterior;
}

float BayesFilter::addNeighborProb(cv::Mat & prediction, unsigned int col, const std::map<int, int> & neighbors, const std::map<int, int> & idToIndexMap) const
{
	if((unsigned int)prediction.cols != idToIndexMap.size() ||
	   (unsigned int)prediction.rows != idToIndexMap.size())
	{
		UFATAL("Requirements no met");
	}

	float sum=0;
	for(std::map<int, int>::const_iterator iter=neighbors.begin(); iter!=neighbors.end(); ++iter)
	{
		int index = uValue(idToIndexMap, iter->first, -1);
		if(index >= 0)
		{
			sum += ((float*)prediction.data)[col + index*prediction.cols] = _predictionLC[iter->second+1];
		}
	}
	return sum;
}

} // namespace rtabmap
<commit_msg>fixed Bayes filter memory leak<commit_after>/*
 * Copyright (C) 2010-2011, Mathieu Labbe and IntRoLab - Universite de Sherbrooke
 *
 * This file is part of RTAB-Map.
 *
 * RTAB-Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * RTAB-Map 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with RTAB-Map.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "rtabmap/core/BayesFilter.h"
#include "rtabmap/core/Memory.h"
#include "rtabmap/core/Signature.h"
#include "rtabmap/core/Parameters.h"
#include <iostream>

#include "utilite/UtiLite.h"

namespace rtabmap {

BayesFilter::BayesFilter(const ParametersMap & parameters) :
	_virtualPlacePrior(Parameters::defaultBayesVirtualPlacePriorThr()),
	_predictionOnNonNullActionsOnly(Parameters::defaultBayesPredictionOnNonNullActionsOnly())
{
	this->setPredictionLC(Parameters::defaultBayesPredictionLC());
	this->parseParameters(parameters);
}

BayesFilter::~BayesFilter() {
}

void BayesFilter::parseParameters(const ParametersMap & parameters)
{
	ParametersMap::const_iterator iter;
	if((iter=parameters.find(Parameters::kBayesVirtualPlacePriorThr())) != parameters.end())
	{
		this->setVirtualPlacePrior(std::atof((*iter).second.c_str()));
	}
	if((iter=parameters.find(Parameters::kBayesPredictionLC())) != parameters.end())
	{
		this->setPredictionLC((*iter).second);
	}
	if((iter=parameters.find(Parameters::kBayesPredictionOnNonNullActionsOnly())) != parameters.end())
	{
		_predictionOnNonNullActionsOnly = uStr2Bool((*iter).second.c_str());
	}

}

void BayesFilter::setVirtualPlacePrior(float virtualPlacePrior)
{
	if(virtualPlacePrior < 0)
	{
		ULOGGER_WARN("virtualPlacePrior=%f, must be >=0 and <=1", virtualPlacePrior);
		_virtualPlacePrior = 0;
	}
	else if(virtualPlacePrior > 1)
	{
		ULOGGER_WARN("virtualPlacePrior=%f, must be >=0 and <=1", virtualPlacePrior);
		_virtualPlacePrior = 1;
	}
	else
	{
		_virtualPlacePrior = virtualPlacePrior;
	}
}

// format = {Virtual place, Loop closure, level1, level2, l3, l4...}
void BayesFilter::setPredictionLC(const std::string & prediction)
{
	std::list<std::string> strValues = uSplit(prediction, ' ');
	if(strValues.size() < 2)
	{
		UERROR("The number of values < 2 (prediction=\"%s\")", prediction.c_str());
	}
	else
	{
		std::vector<double> tmpValues(strValues.size());
		int i=0;
		bool valid = true;
		for(std::list<std::string>::iterator iter = strValues.begin(); iter!=strValues.end(); ++iter)
		{
			tmpValues[i] = std::atof((*iter).c_str());
			//UINFO("%d=%e", i, tmpValues[i]);
			if(tmpValues[i] < 0.0 || tmpValues[i]>1.0)
			{
				valid = false;
				break;
			}
			++i;
		}

		if(!valid)
		{
			UERROR("The prediction is not valid (values must be between >0 && <=1) prediction=\"%s\"", prediction.c_str());
		}
		else
		{
			_predictionLC = tmpValues;
		}
	}
}

const std::vector<double> & BayesFilter::getPredictionLC() const
{
	// {Vp, Lc, l1, l2, l3, l4...}
	return _predictionLC;
}

std::string BayesFilter::getPredictionLCStr() const
{
	std::string values;
	for(unsigned int i=0; i<_predictionLC.size(); ++i)
	{
		values.append(uNumber2Str(_predictionLC[i]));
		if(i+1 < _predictionLC.size())
		{
			values.append(" ");
		}
	}
	return values;
}

void BayesFilter::reset()
{
	_posterior.clear();
}

const std::map<int, float> & BayesFilter::computePosterior(const Memory * memory, const std::map<int, float> & likelihood)
{
	ULOGGER_DEBUG("");

	if(!memory)
	{
		ULOGGER_ERROR("Memory is Null!");
		return _posterior;
	}

	if(!likelihood.size())
	{
		ULOGGER_ERROR("likelihood is empty!");
		return _posterior;
	}

	if(_predictionLC.size() < 2)
	{
		ULOGGER_ERROR("Prediction is not valid!");
		return _posterior;
	}

	UTimer timer;
	timer.start();

	cv::Mat prediction;
	cv::Mat prior;
	cv::Mat posterior;

	float sum = 0;
	int j=0;
	// Recursive Bayes estimation...
	// STEP 1 - Prediction : Prior*lastPosterior
	prediction = cv::Mat(likelihood.size(), likelihood.size(), CV_32FC1);
	if(this->generatePrediction(prediction, memory, uKeys(likelihood)))
	{
		ULOGGER_DEBUG("STEP1-generate prior=%fs, rows=%d, cols=%d", timer.ticks(), prediction.rows, prediction.cols);
		//std::cout << "Prediction=" << prediction << std::endl;

		// Adjust the last posterior if some images were
		// reactivated or removed from the working memory
		posterior = cv::Mat(likelihood.size(), 1, CV_32FC1);
		this->updatePosterior(memory, uKeys(likelihood));
		j=0;
		for(std::map<int, float>::const_iterator i=_posterior.begin(); i!= _posterior.end(); ++i)
		{
			((float*)posterior.data)[j++] = (*i).second;
		}
		ULOGGER_DEBUG("STEP1-update posterior=%fs, posterior=%d, _posterior size=%d", posterior.rows, _posterior.size());
		//std::cout << "LastPosterior=" << posterior << std::endl;

		// Multiply prediction matrix with the last posterior
		// (m,m) X (m,1) = (m,1)
		prior = prediction * posterior;
		ULOGGER_DEBUG("STEP1-matrix mult time=%fs", timer.ticks());
		//std::cout << "ResultingPrior=" << prior << std::endl;

		ULOGGER_DEBUG("STEP1-matrix mult time=%fs", timer.ticks());
		std::vector<float> likelihoodValues = uValues(likelihood);
		//std::cout << "Likelihood=" << cv::Mat(likelihoodValues) << std::endl;

		// STEP 2 - Update : Multiply with observations (likelihood)
		j=0;
		for(std::map<int, float>::const_iterator i=likelihood.begin(); i!= likelihood.end(); ++i)
		{
			std::map<int, float>::iterator p =_posterior.find((*i).first);
			if(p!= _posterior.end())
			{
				(*p).second = (*i).second * ((float*)prior.data)[j++];
				sum+=(*p).second;
			}
			else
			{
				ULOGGER_ERROR("Problem1! can't find id=%d", (*i).first);
			}
		}
		ULOGGER_DEBUG("STEP2-likelihood time=%fs", timer.ticks());

		// Normalize
		ULOGGER_DEBUG("sum=%f", sum);
		if(sum != 0)
		{
			for(std::map<int, float>::iterator i=_posterior.begin(); i!= _posterior.end(); ++i)
			{
				(*i).second /= sum;
			}
		}
		ULOGGER_DEBUG("normalize time=%fs", timer.ticks());
	}

	return _posterior;
}

bool BayesFilter::generatePrediction(cv::Mat & prediction, const Memory * memory, const std::vector<int> & ids) const
{
	ULOGGER_DEBUG("");
	UTimer timer;
	timer.start();
	UTimer timerGlobal;
	timerGlobal.start();

	if(!memory ||
	   prediction.empty() ||
	   prediction.rows != prediction.cols ||
	   (unsigned int)prediction.rows != ids.size() ||
	   _predictionLC.size() < 2 ||
	   !ids.size())
	{
		ULOGGER_ERROR( "fail");
		return false;
	}

	std::map<int, int> idToIndexMap;
	for(unsigned int i=0; i<ids.size(); ++i)
	{
		if(ids[i] == 0)
		{
			UFATAL("Signature id is null ?!?");
		}
		idToIndexMap.insert(idToIndexMap.end(), std::make_pair(ids[i], i));
	}

	//int rows = prediction.rows;
	prediction = cv::Mat::zeros(prediction.rows, prediction.cols, prediction.type());
	int cols = prediction.cols;

	// Each prior is a column vector
	ULOGGER_DEBUG("_predictionLC.size()=%d",_predictionLC.size());
	for(unsigned int i=0; i<ids.size(); ++i)
	{
		int loopSignId = ids[i];
		if(loopSignId > 0)
		{
			// Set high values (gaussians curves) to loop closure neighbors

			float sum = 0.0f; // sum values added

			float totalModelValues = 0.0f;
			for(unsigned int j=0; j<_predictionLC.size(); ++j)
			{
				totalModelValues += _predictionLC[j];
			}

			// ADD prob for each neighbors
			double dbAccessTime = 0.0;
			std::map<int, int> neighbors = memory->getNeighborsId(dbAccessTime, loopSignId, _predictionLC.size()-1, 0, _predictionOnNonNullActionsOnly);
			sum += this->addNeighborProb(prediction, i, neighbors, idToIndexMap);
			// ADD values of not found neighbors to loop closure
			if(sum < totalModelValues-_predictionLC[0])
			{
				float delta = totalModelValues-_predictionLC[0]-sum;
				((float*)prediction.data)[i + i*cols] += delta;
				sum+=delta;
			}

			float allOtherPlacesValue = 0;
			if(totalModelValues < 1)
			{
				allOtherPlacesValue = 1.0f - totalModelValues;
			}

			// Set all loop events to small values according to the model
			if(allOtherPlacesValue > 0 && cols>1)
			{
				float value = allOtherPlacesValue / float(cols - 1);
				for(int j=ids[0] < 0?1:0; j<cols; ++j)
				{
					if(((float*)prediction.data)[i + j*cols] == 0)
					{
						((float*)prediction.data)[i + j*cols] = value;
						sum += ((float*)prediction.data)[i + j*cols];
					}
				}
			}

			//normalize this row
			float maxNorm = 1 - (ids[0]<0?_predictionLC[0]:0); // 1 - virtual place probability
			if(sum<maxNorm-0.0001 || sum>maxNorm+0.0001)
			{
				for(int j=ids[0] < 0?1:0; j<cols; ++j)
				{
					((float*)prediction.data)[i + j*cols] *= maxNorm / sum;
				}
				sum = maxNorm;
			}

			// ADD virtual place prob
			if(ids[0] < 0)
			{
				((float*)prediction.data)[i] = _predictionLC[0];
				sum += ((float*)prediction.data)[i];
			}

			//debug
			//for(int j=0; j<cols; ++j)
			//{
			//	ULOGGER_DEBUG("test col=%d = %f", i, prediction.data.fl[i + j*cols]);
			//}

			if(sum<0.99 || sum > 1.01)
			{
				UWARN("Prediction is not normalized sum=%f", sum);
			}
		}
		else
		{
			// Set the virtual place prior
			if(_virtualPlacePrior > 0)
			{
				if(cols>1) // The first must be the virtual place
				{
					((float*)prediction.data)[i] = _virtualPlacePrior;
					float val = (1.0-_virtualPlacePrior)/(cols-1);
					for(int j=1; j<cols; j++)
					{
						((float*)prediction.data)[i + j*cols] = val;
					}
				}
				else if(cols>0)
				{
					((float*)prediction.data)[i] = 1;
				}
			}
			else
			{
				// Only for some tests...
				// when _virtualPlacePrior=0, set all priors to the same value
				if(cols>1)
				{
					float val = 1.0/cols;
					for(int j=0; j<cols; j++)
					{
						((float*)prediction.data)[i + j*cols] = val;
					}
				}
				else if(cols>0)
				{
					((float*)prediction.data)[i] = 1;
				}
			}
		}
	}

	ULOGGER_DEBUG("time = %fs", timerGlobal.ticks());

	return true;
}

void BayesFilter::updatePosterior(const Memory * memory, const std::vector<int> & likelihoodIds)
{
	ULOGGER_DEBUG("");
	std::map<int, float> newPosterior;
	for(std::vector<int>::const_iterator i=likelihoodIds.begin(); i != likelihoodIds.end(); ++i)
	{
		std::map<int, float>::iterator post = _posterior.find(*i);
		if(post == _posterior.end())
		{
			if(_posterior.size() == 0)
			{
				newPosterior.insert(std::pair<int, float>(*i, 1));
			}
			else
			{
				newPosterior.insert(std::pair<int, float>(*i, 0));
			}
		}
		else
		{
			newPosterior.insert(std::pair<int, float>((*post).first, (*post).second));
		}
	}
	_posterior = newPosterior;
}

float BayesFilter::addNeighborProb(cv::Mat & prediction, unsigned int col, const std::map<int, int> & neighbors, const std::map<int, int> & idToIndexMap) const
{
	if((unsigned int)prediction.cols != idToIndexMap.size() ||
	   (unsigned int)prediction.rows != idToIndexMap.size())
	{
		UFATAL("Requirements no met");
	}

	float sum=0;
	for(std::map<int, int>::const_iterator iter=neighbors.begin(); iter!=neighbors.end(); ++iter)
	{
		int index = uValue(idToIndexMap, iter->first, -1);
		if(index >= 0)
		{
			sum += ((float*)prediction.data)[col + index*prediction.cols] = _predictionLC[iter->second+1];
		}
	}
	return sum;
}

} // namespace rtabmap
<|endoftext|>


<commit_before>#pragma once

#include <iostream>

#include "binary.hxx"
#include "bitnode.hxx"

namespace despairagus {
	namespace bitwisetrie {
		using std::cout;
		using std::ostream;
		using namespace bitnodeNS;
		using namespace binaryNS;

		template <typename A, typename B>
		class bitwisetrie final {
			template<typename C>
			using conref = const C&;

			using bitA = std::bitset<sizeof(A) << 3>;
			using byte = unsigned char;
			using bit = bool;

			constexpr static const size_t limit{sizeof(A) << 3};

			static inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data) {
				return bitwisetrie<A,B>::navigate(currNode, data, 0);
			}

			static inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data, conref<size_t> idx) {
				binary<A> bitHolder{data};

				return bitwisetrie<A,B>::navigate(currNode, bitHolder, idx);
			}

			static bitnode<B>* navigate(bitnode<B>* currNode, conref<binary<A>> bits, conref<size_t> idx) {
				if (idx < limit) {
					if (bits.getBit(idx)) {
						if (currNode->getOne() == nullptr) {
							currNode->setOne(new bitnode<B>);
						}

						return bitwisetrie<A,B>::navigate(currNode->getOne(), bits, idx + 1);
					} else {
						if (currNode->getZero() == nullptr) {
							currNode->setZero(new bitnode<B>);
						}

						return bitwisetrie<A,B>::navigate(currNode->getZero(), bits, idx + 1);
					}
				}

				return currNode;
			}

		public:
			explicit bitwisetrie(void) : root{new bitnode<B>} {}

			inline bool insertOnEmpty(conref<B> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				if (leafNode->isEmpty()) {
					leafNode->setData(a);

					return true;
				}

				return false;
			}

			inline bool insertOnNotEmpty(conref<B> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				if (leafNode->isNotEmpty()) {
					leafNode->setData(a);

					return true;
				}

				return false;
			}

			inline void insert(conref<B> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				leafNode->setData(a);
			}

			inline bool remove(conref<B> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				if (leafNode->isNotEmpty()) {
					leafNode->dump();

					return true;
				}

				return false;
			}

			inline bool contains(conref<B> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				return leafNode->isNotEmpty();
			}

			inline bool notContains(conref<B> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				return leafNode->isEmpty();
			}

		private:
			bitnode<B>* root;
		};

		template <typename A>
		bitwisetrie<A,A>;
	}
}
<commit_msg>fixed proper parameters<commit_after>#pragma once

#include <iostream>

#include "binary.hxx"
#include "bitnode.hxx"

namespace despairagus {
	namespace bitwisetrie {
		using std::cout;
		using std::ostream;
		using namespace bitnodeNS;
		using namespace binaryNS;

		template <typename A, typename B>
		class bitwisetrie final {
			template<typename C>
			using conref = const C&;

			using bitA = std::bitset<sizeof(A) << 3>;
			using byte = unsigned char;
			using bit = bool;

			constexpr static const size_t limit{sizeof(A) << 3};

			static inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data) {
				return bitwisetrie<A,B>::navigate(currNode, data, 0);
			}

			static inline bitnode<B>* navigate(bitnode<B>* currNode, conref<A> data, conref<size_t> idx) {
				binary<A> bitHolder{data};

				return bitwisetrie<A,B>::navigate(currNode, bitHolder, idx);
			}

			static bitnode<B>* navigate(bitnode<B>* currNode, conref<binary<A>> bits, conref<size_t> idx) {
				if (idx < limit) {
					if (bits.getBit(idx)) {
						if (currNode->getOne() == nullptr) {
							currNode->setOne(new bitnode<B>);
						}

						return bitwisetrie<A,B>::navigate(currNode->getOne(), bits, idx + 1);
					} else {
						if (currNode->getZero() == nullptr) {
							currNode->setZero(new bitnode<B>);
						}

						return bitwisetrie<A,B>::navigate(currNode->getZero(), bits, idx + 1);
					}
				}

				return currNode;
			}

		public:
			explicit bitwisetrie(void) : root{new bitnode<B>} {}

			inline bool insertOnEmpty(conref<A> a, conref<B> b) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				if (leafNode->isEmpty()) {
					leafNode->setData(b);

					return true;
				}

				return false;
			}

			inline bool insertOnNotEmpty(conref<A> a, conref<B> b) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				if (leafNode->isNotEmpty()) {
					leafNode->setData(b);

					return true;
				}

				return false;
			}

			inline void insert(conref<A> a, conref<B> b) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				leafNode->setData(a);
			}

			inline bool remove(conref<A> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				if (leafNode->isNotEmpty()) {
					leafNode->dump();

					return true;
				}

				return false;
			}

			inline bool contains(conref<A> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				return leafNode->isNotEmpty();
			}

			inline bool notContains(conref<A> a) noexcept {
				bitnode<B>* leafNode = bitwisetrie<A,B>::navigate(root, a);

				return leafNode->isEmpty();
			}

		private:
			bitnode<B>* root;
		};
	}
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_ppe_state.H $       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file  p9_ppe_state.H
/// @brief Dump a PPE engine's state.
///
/// *HWP HW Owner        : Ashish More <ashish.more.@in.ibm.com>
/// *HWP HW Backup Owner : Brian Vanderpool <vanderp@us.ibm.com>
/// *HWP FW Owner        : Sangeetha T S <sangeet2@in.ibm.com>
/// *HWP Team            : PM
/// *HWP Level           : 2
/// *HWP Consumed by     : SBE, Cronus
#include <p9_ppe_utils.H>

#ifndef __P9_PPE_STATE_H__
#define __P9_PPE_STATE_H__

/// @typedef p9_ppe_state_FP_t
/// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_ppe_state_FP_t) (
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
    const uint64_t, const PPE_DUMP_MODE,
    std::vector<PPERegValue_t>& v_ppe_sprs_value,
    std::vector<PPERegValue_t>& v_ppe_xirs_value,
    std::vector<PPERegValue_t>& v_ppe_gprs_value
);

extern "C"
{

/// @brief Dump the PPE state based on the based base address
/// @param [in] i_target TARGET_TYPE_PROC_CHIP
/// @param [in] i_base_address Base offset to be used for all accesses
/// @return FAPI2_RC_SUCCESS
    fapi2::ReturnCode
    p9_ppe_state(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
                 const uint64_t i_base_address, const PPE_DUMP_MODE i_mode,
                 std::vector<PPERegValue_t>& v_ppe_sprs_value,
                 std::vector<PPERegValue_t>& v_ppe_xirs_value,
                 std::vector<PPERegValue_t>& v_ppe_gprs_value

                );

} // extern C

#endif  // __P9_PPE_DUMP_H__
<commit_msg>PM: deprecate p9_ppe_dump in favor of p9_ppe_state<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_ppe_state.H $       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed 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                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file  p9_ppe_state.H
/// @brief Dump a PPE engine's state.
///
/// *HWP HW Owner        : Ashish More <ashish.more.@in.ibm.com>
/// *HWP HW Backup Owner : Brian Vanderpool <vanderp@us.ibm.com>
/// *HWP FW Owner        : Sangeetha T S <sangeet2@in.ibm.com>
/// *HWP Team            : PM
/// *HWP Level           : 2
/// *HWP Consumed by     : SBE, Cronus
#include <p9_ppe_utils.H>

#ifndef __P9_PPE_STATE_H__
#define __P9_PPE_STATE_H__

/// @typedef p9_ppe_state_FP_t
/// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_ppe_state_FP_t) (
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
    const uint64_t, const PPE_DUMP_MODE,
    std::vector<PPERegValue_t>& v_ppe_sprs_value,
    std::vector<PPERegValue_t>& v_ppe_xirs_value,
    std::vector<PPERegValue_t>& v_ppe_gprs_value
);

extern "C"
{

/// @brief Dump the PPE state based on the based base address
/// @param [in] i_target TARGET_TYPE_PROC_CHIP
/// @param [in] i_base_address Base offset to be used for all accesses
/// @return FAPI2_RC_SUCCESS
    fapi2::ReturnCode
    p9_ppe_state(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
                 const uint64_t i_base_address, const PPE_DUMP_MODE i_mode,
                 std::vector<PPERegValue_t>& v_ppe_sprs_value,
                 std::vector<PPERegValue_t>& v_ppe_xirs_value,
                 std::vector<PPERegValue_t>& v_ppe_gprs_value

                );

} // extern C

#endif  // __P9_PPE_STATE_H__
<|endoftext|>


<commit_before>/**
 * \file
 * \brief Thread class implementation
 *
 * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * 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/.
 *
 * \date 2015-11-13
 */

#include "distortos/Thread.hpp"

#include "distortos/architecture/InterruptMaskingLock.hpp"

#include "distortos/scheduler/getScheduler.hpp"
#include "distortos/scheduler/Scheduler.hpp"

#include "distortos/synchronization/SignalsReceiverControlBlock.hpp"

#include <cerrno>

namespace distortos
{

/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/

Thread::Thread(architecture::Stack&& stack, const uint8_t priority, const SchedulingPolicy schedulingPolicy,
		scheduler::ThreadGroupControlBlock* const threadGroupControlBlock, SignalsReceiver* const signalsReceiver) :
		threadControlBlock_{std::move(stack), priority, schedulingPolicy, threadGroupControlBlock, signalsReceiver,
				*this},
		joinSemaphore_{0}
{

}

Thread::~Thread()
{

}

int Thread::generateSignal(const uint8_t signalNumber)
{
	const auto signalsReceiverControlBlock = threadControlBlock_.getSignalsReceiverControlBlock();
	if (signalsReceiverControlBlock == nullptr)
		return ENOTSUP;

	return signalsReceiverControlBlock->generateSignal(signalNumber, threadControlBlock_);
}

uint8_t Thread::getEffectivePriority() const
{
	return threadControlBlock_.getEffectivePriority();
}

SignalSet Thread::getPendingSignalSet() const
{
	const auto signalsReceiverControlBlock = threadControlBlock_.getSignalsReceiverControlBlock();
	if (signalsReceiverControlBlock == nullptr)
		return SignalSet{SignalSet::empty};

	architecture::InterruptMaskingLock interruptMaskingLock;
	return signalsReceiverControlBlock->getPendingSignalSet();
}

uint8_t Thread::getPriority() const
{
	return threadControlBlock_.getPriority();
}

SchedulingPolicy Thread::getSchedulingPolicy() const
{
	return threadControlBlock_.getSchedulingPolicy();
}

scheduler::ThreadControlBlock::State Thread::getState() const
{
	return threadControlBlock_.getState();
}

int Thread::join()
{
	if (&threadControlBlock_ == &scheduler::getScheduler().getCurrentThreadControlBlock())
		return EDEADLK;

	int ret;
	while ((ret = joinSemaphore_.wait()) == EINTR);
	return ret;
}

int Thread::queueSignal(const uint8_t signalNumber, const sigval value)
{
	const auto signalsReceiverControlBlock = threadControlBlock_.getSignalsReceiverControlBlock();
	if (signalsReceiverControlBlock == nullptr)
		return ENOTSUP;

	return signalsReceiverControlBlock->queueSignal(signalNumber, value, threadControlBlock_);
}

void Thread::setPriority(const uint8_t priority, const bool alwaysBehind)
{
	threadControlBlock_.setPriority(priority, alwaysBehind);
}

void Thread::setSchedulingPolicy(const SchedulingPolicy schedulingPolicy)
{
	threadControlBlock_.setSchedulingPolicy(schedulingPolicy);
}

int Thread::start()
{
	if (getState() != scheduler::ThreadControlBlock::State::New)
		return EINVAL;

	return scheduler::getScheduler().add(threadControlBlock_);
}

/*---------------------------------------------------------------------------------------------------------------------+
| protected functions
+---------------------------------------------------------------------------------------------------------------------*/

scheduler::ThreadControlBlock& Thread::getThreadControlBlock()
{
	return threadControlBlock_;
}

const scheduler::ThreadControlBlock& Thread::getThreadControlBlock() const
{
	return threadControlBlock_;
}

/*---------------------------------------------------------------------------------------------------------------------+
| protected static functions
+---------------------------------------------------------------------------------------------------------------------*/

void Thread::threadRunner(Thread& thread)
{
	thread.run();
	scheduler::getScheduler().remove(&Thread::terminationHook);

	while (1);
}

/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/

void Thread::terminationHook()
{
	joinSemaphore_.post();
	threadControlBlock_.setList(nullptr);
}

}	// namespace distortos
<commit_msg>Thread: access internal ThreadControlBlock object only through accessor<commit_after>/**
 * \file
 * \brief Thread class implementation
 *
 * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * 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/.
 *
 * \date 2015-11-13
 */

#include "distortos/Thread.hpp"

#include "distortos/architecture/InterruptMaskingLock.hpp"

#include "distortos/scheduler/getScheduler.hpp"
#include "distortos/scheduler/Scheduler.hpp"

#include "distortos/synchronization/SignalsReceiverControlBlock.hpp"

#include <cerrno>

namespace distortos
{

/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/

Thread::Thread(architecture::Stack&& stack, const uint8_t priority, const SchedulingPolicy schedulingPolicy,
		scheduler::ThreadGroupControlBlock* const threadGroupControlBlock, SignalsReceiver* const signalsReceiver) :
		threadControlBlock_{std::move(stack), priority, schedulingPolicy, threadGroupControlBlock, signalsReceiver,
				*this},
		joinSemaphore_{0}
{

}

Thread::~Thread()
{

}

int Thread::generateSignal(const uint8_t signalNumber)
{
	auto& threadControlBlock = getThreadControlBlock();
	const auto signalsReceiverControlBlock = threadControlBlock.getSignalsReceiverControlBlock();
	if (signalsReceiverControlBlock == nullptr)
		return ENOTSUP;

	return signalsReceiverControlBlock->generateSignal(signalNumber, threadControlBlock);
}

uint8_t Thread::getEffectivePriority() const
{
	return getThreadControlBlock().getEffectivePriority();
}

SignalSet Thread::getPendingSignalSet() const
{
	const auto signalsReceiverControlBlock = getThreadControlBlock().getSignalsReceiverControlBlock();
	if (signalsReceiverControlBlock == nullptr)
		return SignalSet{SignalSet::empty};

	architecture::InterruptMaskingLock interruptMaskingLock;
	return signalsReceiverControlBlock->getPendingSignalSet();
}

uint8_t Thread::getPriority() const
{
	return getThreadControlBlock().getPriority();
}

SchedulingPolicy Thread::getSchedulingPolicy() const
{
	return getThreadControlBlock().getSchedulingPolicy();
}

scheduler::ThreadControlBlock::State Thread::getState() const
{
	return getThreadControlBlock().getState();
}

int Thread::join()
{
	if (&getThreadControlBlock() == &scheduler::getScheduler().getCurrentThreadControlBlock())
		return EDEADLK;

	int ret;
	while ((ret = joinSemaphore_.wait()) == EINTR);
	return ret;
}

int Thread::queueSignal(const uint8_t signalNumber, const sigval value)
{
	auto& threadControlBlock = getThreadControlBlock();
	const auto signalsReceiverControlBlock = threadControlBlock.getSignalsReceiverControlBlock();
	if (signalsReceiverControlBlock == nullptr)
		return ENOTSUP;

	return signalsReceiverControlBlock->queueSignal(signalNumber, value, threadControlBlock);
}

void Thread::setPriority(const uint8_t priority, const bool alwaysBehind)
{
	getThreadControlBlock().setPriority(priority, alwaysBehind);
}

void Thread::setSchedulingPolicy(const SchedulingPolicy schedulingPolicy)
{
	getThreadControlBlock().setSchedulingPolicy(schedulingPolicy);
}

int Thread::start()
{
	if (getState() != scheduler::ThreadControlBlock::State::New)
		return EINVAL;

	return scheduler::getScheduler().add(getThreadControlBlock());
}

/*---------------------------------------------------------------------------------------------------------------------+
| protected functions
+---------------------------------------------------------------------------------------------------------------------*/

scheduler::ThreadControlBlock& Thread::getThreadControlBlock()
{
	return threadControlBlock_;
}

const scheduler::ThreadControlBlock& Thread::getThreadControlBlock() const
{
	return threadControlBlock_;
}

/*---------------------------------------------------------------------------------------------------------------------+
| protected static functions
+---------------------------------------------------------------------------------------------------------------------*/

void Thread::threadRunner(Thread& thread)
{
	thread.run();
	scheduler::getScheduler().remove(&Thread::terminationHook);

	while (1);
}

/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/

void Thread::terminationHook()
{
	joinSemaphore_.post();
	getThreadControlBlock().setList(nullptr);
}

}	// namespace distortos
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SlsQueueProcessor.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-17 09:43:47 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "SlsQueueProcessor.hxx"

namespace sd { namespace slidesorter { namespace cache {

//===== QueueProcessorBase  ===================================================

QueueProcessorBase::QueueProcessorBase (void)
    : mnTimeBetweenHighPriorityRequests (50/*ms*/),
      mnTimeBetweenLowPriorityRequests (250/*ms*/),
      mnTimeBetweenRequestsWhenNotIdle (1000/*ms*/)
{
    maTimer.SetTimeoutHdl (LINK(this,QueueProcessorBase,ProcessRequest));
    maTimer.SetTimeout (mnTimeBetweenHighPriorityRequests);
}

void QueueProcessorBase::Start (int nPriorityClass)
{
    if ( ! maTimer.IsActive())
    {
        if (nPriorityClass == 0)
            maTimer.SetTimeout (mnTimeBetweenHighPriorityRequests);
        else
            maTimer.SetTimeout (mnTimeBetweenLowPriorityRequests);
        maTimer.Start();
    }
}

void QueueProcessorBase::Stop (void)
{
    if (maTimer.IsActive())
        maTimer.Stop();
}

IMPL_LINK(QueueProcessorBase, ProcessRequest, Timer*, pTimer)
{
    ProcessRequest();
    return 1;
}

} } } // end of namespace ::sd::slidesorter::cache
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.198); FILE MERGED 2005/09/05 13:24:17 rt 1.4.198.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsQueueProcessor.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:11:52 $
 *
 *  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 "SlsQueueProcessor.hxx"

namespace sd { namespace slidesorter { namespace cache {

//===== QueueProcessorBase  ===================================================

QueueProcessorBase::QueueProcessorBase (void)
    : mnTimeBetweenHighPriorityRequests (50/*ms*/),
      mnTimeBetweenLowPriorityRequests (250/*ms*/),
      mnTimeBetweenRequestsWhenNotIdle (1000/*ms*/)
{
    maTimer.SetTimeoutHdl (LINK(this,QueueProcessorBase,ProcessRequest));
    maTimer.SetTimeout (mnTimeBetweenHighPriorityRequests);
}

void QueueProcessorBase::Start (int nPriorityClass)
{
    if ( ! maTimer.IsActive())
    {
        if (nPriorityClass == 0)
            maTimer.SetTimeout (mnTimeBetweenHighPriorityRequests);
        else
            maTimer.SetTimeout (mnTimeBetweenLowPriorityRequests);
        maTimer.Start();
    }
}

void QueueProcessorBase::Stop (void)
{
    if (maTimer.IsActive())
        maTimer.Stop();
}

IMPL_LINK(QueueProcessorBase, ProcessRequest, Timer*, pTimer)
{
    ProcessRequest();
    return 1;
}

} } } // end of namespace ::sd::slidesorter::cache
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "ICUBridgeCollationCompareFunctor.hpp"
#include "ICUBridge.hpp"

#include <Include/XalanAutoPtr.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <unicode/coll.h>

const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor		ICUBridgeCollationCompareFunctor::s_defaultFunctor;

ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() :
	m_isValid(false),
	m_defaultCollator(0)
{
	UErrorCode	theStatus = U_ZERO_ERROR;

#if defined(XALAN_ICU_DEFAULT_LOCALE_PROBLEM)
	m_defaultCollator = Collator::createInstance(Locale::US, theStatus);
#else
	m_defaultCollator = Collator::createInstance(theStatus);
#endif

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		m_isValid = true;
	}
}

ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor()
{
	delete m_defaultCollator;
}

int
ICUBridgeCollationCompareFunctor::doDefaultCompare(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const
{
	if (isValid() == false)
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
	else
	{
		assert(m_defaultCollator != 0);

#if defined(XALAN_USE_WCHAR_CAST_HACK)
		return m_defaultCollator->compare(
					(const wchar_t*)theLHS,
					length(theLHS),
					(const wchar_t*)theRHS,
					length(theRHS));
#else
		return m_defaultCollator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const
{
	return doDefaultCompare(theLHS, theRHS);
}

inline Collator*
getCollator(
			const XalanDOMChar*		theLocale,
			UErrorCode&				theStatus)
{
	const unsigned int	theLength = length(theLocale);

	if (theLength >= ULOC_FULLNAME_CAPACITY)
	{
		theStatus = U_ILLEGAL_ARGUMENT_ERROR;

		return 0;
	}
	else
	{
#if defined(XALAN_NON_ASCII_PLATFORM)
		CharVectorType	theVector;

		TranscodeToLocalCodePage(theLocale, theVector, true);

		const char* const	theBuffer = c_str(theVector);
#else
		char	theBuffer[ULOC_FULLNAME_CAPACITY];

		// Since language names must be ASCII, this
		// is the cheapest way to "transcode"...
		for (unsigned int i = 0; i <= theLength; ++i)
		{
			theBuffer[i] = char(theLocale[i]);
		}
#endif
		return Collator::createInstance(
					Locale::createFromName(theBuffer),
					theStatus);
	}
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale) const
{
	UErrorCode	theStatus = U_ZERO_ERROR;

	XalanAutoPtr<Collator>	theCollator(getCollator(theLocale, theStatus));

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		assert(theCollator.get() != 0);

#if defined(XALAN_USE_WCHAR_CAST_HACK)
		return theCollator->compare(
					(const wchar_t*)theLHS,
					length(theLHS),
					(const wchar_t*)theRHS,
					length(theRHS));
#else
		return theCollator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
	else
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
}
<commit_msg>32/64-bit fixes.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "ICUBridgeCollationCompareFunctor.hpp"
#include "ICUBridge.hpp"

#include <Include/XalanAutoPtr.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <unicode/coll.h>

const StylesheetExecutionContextDefault::DefaultCollationCompareFunctor		ICUBridgeCollationCompareFunctor::s_defaultFunctor;

ICUBridgeCollationCompareFunctor::ICUBridgeCollationCompareFunctor() :
	m_isValid(false),
	m_defaultCollator(0)
{
	UErrorCode	theStatus = U_ZERO_ERROR;

#if defined(XALAN_ICU_DEFAULT_LOCALE_PROBLEM)
	m_defaultCollator = Collator::createInstance(Locale::US, theStatus);
#else
	m_defaultCollator = Collator::createInstance(theStatus);
#endif

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		m_isValid = true;
	}
}

ICUBridgeCollationCompareFunctor::~ICUBridgeCollationCompareFunctor()
{
	delete m_defaultCollator;
}

int
ICUBridgeCollationCompareFunctor::doDefaultCompare(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const
{
	if (isValid() == false)
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
	else
	{
		assert(m_defaultCollator != 0);

#if defined(XALAN_USE_WCHAR_CAST_HACK)
		return m_defaultCollator->compare(
					(const wchar_t*)theLHS,
					length(theLHS),
					(const wchar_t*)theRHS,
					length(theRHS));
#else
		return m_defaultCollator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const
{
	return doDefaultCompare(theLHS, theRHS);
}

inline Collator*
getCollator(
			const XalanDOMChar*		theLocale,
			UErrorCode&				theStatus)
{
	const XalanDOMString::size_type		theLength = length(theLocale);

	if (theLength >= ULOC_FULLNAME_CAPACITY)
	{
		theStatus = U_ILLEGAL_ARGUMENT_ERROR;

		return 0;
	}
	else
	{
#if defined(XALAN_NON_ASCII_PLATFORM)
		CharVectorType	theVector;

		TranscodeToLocalCodePage(theLocale, theVector, true);

		const char* const	theBuffer = c_str(theVector);
#else
		char	theBuffer[ULOC_FULLNAME_CAPACITY];

		// Since language names must be ASCII, this
		// is the cheapest way to "transcode"...
		for (unsigned int i = 0; i <= theLength; ++i)
		{
			theBuffer[i] = char(theLocale[i]);
		}
#endif
		return Collator::createInstance(
					Locale::createFromName(theBuffer),
					theStatus);
	}
}

int
ICUBridgeCollationCompareFunctor::operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale) const
{
	UErrorCode	theStatus = U_ZERO_ERROR;

	XalanAutoPtr<Collator>	theCollator(getCollator(theLocale, theStatus));

	if (theStatus == U_ZERO_ERROR ||
	    (theStatus >= U_ERROR_INFO_START && theStatus < U_ERROR_INFO_LIMIT))
	{
		assert(theCollator.get() != 0);

#if defined(XALAN_USE_WCHAR_CAST_HACK)
		return theCollator->compare(
					(const wchar_t*)theLHS,
					length(theLHS),
					(const wchar_t*)theRHS,
					length(theRHS));
#else
		return theCollator->compare(
					theLHS,
					length(theLHS),
					theRHS,
					length(theRHS));
#endif
	}
	else
	{
		return s_defaultFunctor(theLHS, theRHS);
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dispatcher.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2003-10-06 13:01:32 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#if ! defined INCLUDED_UNO_DISPATCHER_HXX
#define INCLUDED_UNO_DISPATCHER_HXX

#include "uno/dispatcher.h"

namespace com
{
namespace sun
{
namespace star
{
namespace uno
{

/** C++ holder reference for binary C uno_Interface.  Not for public use, may be
    subject to changes.

    @see uno_Interface
    @internal
              not for public use!
*/
class UnoInterfaceReference
{
public:
    uno_Interface * m_pUnoI;

    inline bool is() const
        { return m_pUnoI != 0; }

    inline ~UnoInterfaceReference();
    inline UnoInterfaceReference();
    inline UnoInterfaceReference( uno_Interface * pUnoI, __sal_NoAcquire );
    inline UnoInterfaceReference( uno_Interface * pUnoI );
    inline UnoInterfaceReference( UnoInterfaceReference const & ref );

    inline uno_Interface * get() const
        { return m_pUnoI; }

    inline UnoInterfaceReference & set(
        uno_Interface * pUnoI );
    inline UnoInterfaceReference & set(
        uno_Interface * pUnoI, __sal_NoAcquire );
    inline void clear();

    inline UnoInterfaceReference & operator = (
        UnoInterfaceReference const & ref )
        { return set( ref.m_pUnoI ); }
    inline UnoInterfaceReference & operator = (
        uno_Interface * pUnoI )
        { return set( pUnoI ); }

    inline void dispatch(
        struct _typelib_TypeDescription const * pMemberType,
        void * pReturn, void * pArgs [], uno_Any ** ppException ) const;

private:
    inline bool operator == ( UnoInterfaceReference const & ); // not impl
    inline bool operator != ( UnoInterfaceReference const & ); // not impl
    inline bool operator == ( uno_Interface * ); // not impl
    inline bool operator != ( uno_Interface * ); // not impl
};

//______________________________________________________________________________
inline UnoInterfaceReference::~UnoInterfaceReference()
{
    if (m_pUnoI != 0)
        (*m_pUnoI->release)( m_pUnoI );
}

//______________________________________________________________________________
inline UnoInterfaceReference::UnoInterfaceReference()
    : m_pUnoI( 0 )
{
}

//______________________________________________________________________________
inline UnoInterfaceReference::UnoInterfaceReference(
    uno_Interface * pUnoI, __sal_NoAcquire )
    : m_pUnoI( pUnoI )
{
}

//______________________________________________________________________________
inline UnoInterfaceReference::UnoInterfaceReference( uno_Interface * pUnoI )
    : m_pUnoI( pUnoI )
{
    if (m_pUnoI != 0)
        (*m_pUnoI->acquire)( m_pUnoI );
}

//______________________________________________________________________________
inline UnoInterfaceReference::UnoInterfaceReference(
    UnoInterfaceReference const & ref )
    : m_pUnoI( ref.m_pUnoI )
{
    if (m_pUnoI != 0)
        (*m_pUnoI->acquire)( m_pUnoI );
}

//______________________________________________________________________________
inline UnoInterfaceReference & UnoInterfaceReference::set(
    uno_Interface * pUnoI )
{
    if (pUnoI != 0)
        (*pUnoI->acquire)( pUnoI );
    if (m_pUnoI != 0)
        (*m_pUnoI->release)( m_pUnoI );
    m_pUnoI = pUnoI;
    return *this;
}

//______________________________________________________________________________
inline UnoInterfaceReference & UnoInterfaceReference::set(
    uno_Interface * pUnoI, __sal_NoAcquire )
{
    if (m_pUnoI != 0)
        (*m_pUnoI->release)( m_pUnoI );
    m_pUnoI = pUnoI;
    return *this;
}

//______________________________________________________________________________
inline void UnoInterfaceReference::clear()
{
    if (m_pUnoI != 0)
    {
        (*m_pUnoI->release)( m_pUnoI );
        m_pUnoI = 0;
    }
}

//______________________________________________________________________________
inline void UnoInterfaceReference::dispatch(
    struct _typelib_TypeDescription const * pMemberType,
    void * pReturn, void * pArgs [], uno_Any ** ppException ) const
{
    (*m_pUnoI->pDispatcher)(
        m_pUnoI, pMemberType, pReturn, pArgs, ppException );
}

}
}
}
}

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.78); FILE MERGED 2005/09/05 13:54:17 rt 1.2.78.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dispatcher.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:40:02 $
 *
 *  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
 *
 ************************************************************************/

#if ! defined INCLUDED_UNO_DISPATCHER_HXX
#define INCLUDED_UNO_DISPATCHER_HXX

#include "uno/dispatcher.h"

namespace com
{
namespace sun
{
namespace star
{
namespace uno
{

/** C++ holder reference for binary C uno_Interface.  Not for public use, may be
    subject to changes.

    @see uno_Interface
    @internal
              not for public use!
*/
class UnoInterfaceReference
{
public:
    uno_Interface * m_pUnoI;

    inline bool is() const
        { return m_pUnoI != 0; }

    inline ~UnoInterfaceReference();
    inline UnoInterfaceReference();
    inline UnoInterfaceReference( uno_Interface * pUnoI, __sal_NoAcquire );
    inline UnoInterfaceReference( uno_Interface * pUnoI );
    inline UnoInterfaceReference( UnoInterfaceReference const & ref );

    inline uno_Interface * get() const
        { return m_pUnoI; }

    inline UnoInterfaceReference & set(
        uno_Interface * pUnoI );
    inline UnoInterfaceReference & set(
        uno_Interface * pUnoI, __sal_NoAcquire );
    inline void clear();

    inline UnoInterfaceReference & operator = (
        UnoInterfaceReference const & ref )
        { return set( ref.m_pUnoI ); }
    inline UnoInterfaceReference & operator = (
        uno_Interface * pUnoI )
        { return set( pUnoI ); }

    inline void dispatch(
        struct _typelib_TypeDescription const * pMemberType,
        void * pReturn, void * pArgs [], uno_Any ** ppException ) const;

private:
    inline bool operator == ( UnoInterfaceReference const & ); // not impl
    inline bool operator != ( UnoInterfaceReference const & ); // not impl
    inline bool operator == ( uno_Interface * ); // not impl
    inline bool operator != ( uno_Interface * ); // not impl
};

//______________________________________________________________________________
inline UnoInterfaceReference::~UnoInterfaceReference()
{
    if (m_pUnoI != 0)
        (*m_pUnoI->release)( m_pUnoI );
}

//______________________________________________________________________________
inline UnoInterfaceReference::UnoInterfaceReference()
    : m_pUnoI( 0 )
{
}

//______________________________________________________________________________
inline UnoInterfaceReference::UnoInterfaceReference(
    uno_Interface * pUnoI, __sal_NoAcquire )
    : m_pUnoI( pUnoI )
{
}

//______________________________________________________________________________
inline UnoInterfaceReference::UnoInterfaceReference( uno_Interface * pUnoI )
    : m_pUnoI( pUnoI )
{
    if (m_pUnoI != 0)
        (*m_pUnoI->acquire)( m_pUnoI );
}

//______________________________________________________________________________
inline UnoInterfaceReference::UnoInterfaceReference(
    UnoInterfaceReference const & ref )
    : m_pUnoI( ref.m_pUnoI )
{
    if (m_pUnoI != 0)
        (*m_pUnoI->acquire)( m_pUnoI );
}

//______________________________________________________________________________
inline UnoInterfaceReference & UnoInterfaceReference::set(
    uno_Interface * pUnoI )
{
    if (pUnoI != 0)
        (*pUnoI->acquire)( pUnoI );
    if (m_pUnoI != 0)
        (*m_pUnoI->release)( m_pUnoI );
    m_pUnoI = pUnoI;
    return *this;
}

//______________________________________________________________________________
inline UnoInterfaceReference & UnoInterfaceReference::set(
    uno_Interface * pUnoI, __sal_NoAcquire )
{
    if (m_pUnoI != 0)
        (*m_pUnoI->release)( m_pUnoI );
    m_pUnoI = pUnoI;
    return *this;
}

//______________________________________________________________________________
inline void UnoInterfaceReference::clear()
{
    if (m_pUnoI != 0)
    {
        (*m_pUnoI->release)( m_pUnoI );
        m_pUnoI = 0;
    }
}

//______________________________________________________________________________
inline void UnoInterfaceReference::dispatch(
    struct _typelib_TypeDescription const * pMemberType,
    void * pReturn, void * pArgs [], uno_Any ** ppException ) const
{
    (*m_pUnoI->pDispatcher)(
        m_pUnoI, pMemberType, pReturn, pArgs, ppException );
}

}
}
}
}

#endif

<|endoftext|>


<commit_before><commit_msg>Add comphelp and stocservices UNO component mapping<commit_after><|endoftext|>