<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File GlobalLinSys.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: GlobalLinSys definition
//
///////////////////////////////////////////////////////////////////////////////

#include <MultiRegions/GlobalLinSysPETSc.h>

#include "petscis.h"
#include "petscversion.h"

namespace Nektar
{
    namespace MultiRegions
    {
        /**
         * @class GlobalLinSysPETSc
         *
         * Solves a linear system using direct methods.
         */

        /// Constructor for full direct matrix solve.
        GlobalLinSysPETSc::GlobalLinSysPETSc(
            const GlobalLinSysKey                &pKey,
            const boost::weak_ptr<ExpList>       &pExp,
            const boost::shared_ptr<AssemblyMap> &pLocToGloMap)
            : GlobalLinSys(pKey, pExp, pLocToGloMap)
        {
            // Initialise PETSc
            PetscInitialize(0, NULL, NULL, NULL);

            // Create matrix
            MatCreate(PETSC_COMM_WORLD, &m_matrix);
        }

        GlobalLinSysPETSc::~GlobalLinSysPETSc()
        {
        }

        void GlobalLinSysPETSc::v_SolveLinearSystem(
            const int                          pNumRows,
            const Array<OneD,const NekDouble> &pInput,
                  Array<OneD,      NekDouble> &pOutput,
            const AssemblyMapSharedPtr        &locToGloMap,
            const int                          pNumDir)
        {
            const int nHomDofs = pNumRows - pNumDir;

            // Populate RHS vector from input
            VecSetValues(m_b, nHomDofs, &m_reorderedMap[0], &pInput[pNumDir], INSERT_VALUES);

            // Assemble RHS vector
            VecAssemblyBegin(m_b);
            VecAssemblyEnd  (m_b);

            // Do system solve
            KSPSolve(m_ksp, m_b, m_x);

            // Grab number of iterations taken
            PetscInt its;
            KSPGetIterationNumber(m_ksp, &its);
            cout << "iterations = " << its << endl;

            // Scatter results to local vector
            VecScatterBegin(m_ctx, m_x, m_locVec, INSERT_VALUES, SCATTER_FORWARD);
            VecScatterEnd  (m_ctx, m_x, m_locVec, INSERT_VALUES, SCATTER_FORWARD);

            // Copy results into output vector
            PetscScalar *avec;
            VecGetArray    (m_locVec, &avec);
            Vmath::Vcopy   (nHomDofs, avec, 1, &pOutput[pNumDir], 1);
            VecRestoreArray(m_locVec, &avec);
        }

        void GlobalLinSysPETSc::SetUpScatter()
        {
            const int nHomDofs = m_reorderedMap.size();

            // Create local and global numbering systems for vector
            IS isGlobal, isLocal;
            ISCreateGeneral(PETSC_COMM_SELF, nHomDofs, &m_reorderedMap[0],
                            PETSC_COPY_VALUES, &isGlobal);
            ISCreateStride (PETSC_COMM_SELF, nHomDofs, 0, 1, &isLocal);

            // Create local vector for output
            VecCreate        (PETSC_COMM_SELF, &m_locVec);
            VecSetSizes      (m_locVec, m_reorderedMap.size(), PETSC_DECIDE);
            VecSetFromOptions(m_locVec);

            // Create scatter context
            VecScatterCreate (m_x, isGlobal, m_locVec, isLocal, &m_ctx);

            // Clean up
            ISDestroy(&isGlobal);
            ISDestroy(&isLocal);
        }

        void GlobalLinSysPETSc::CalculateReordering(
            const Array<OneD, const int> &glo2uniMap,
            const Array<OneD, const int> &glo2unique,
            const AssemblyMapSharedPtr   &pLocToGloMap)
        {
            LibUtilities::CommSharedPtr vComm
                = m_expList.lock()->GetSession()->GetComm();

            const int nDirDofs = pLocToGloMap->GetNumGlobalDirBndCoeffs();
            const int nHomDofs = glo2uniMap.num_elements() - nDirDofs;
            const int nProc    = vComm->GetSize();
            const int rank     = vComm->GetRank();

            int n, cnt;

            m_nLocal = Vmath::Vsum(nHomDofs, glo2unique + nDirDofs, 1);

            m_reorderedMap.resize(nHomDofs);

            Array<OneD, int> localCounts(nProc, 0), localOffset(nProc, 0);
            localCounts[rank] = nHomDofs;
            vComm->AllReduce(localCounts, LibUtilities::ReduceSum);

            for (n = 1; n < nProc; ++n)
            {
                localOffset[n] = localOffset[n-1] + localCounts[n-1];
            }

            int totHomDofs = Vmath::Vsum(nProc, localCounts, 1);
            vector<unsigned int> allUniIds(totHomDofs, 0);

            for (n = 0; n < nHomDofs; ++n)
            {
                int gid = n + nDirDofs;
                allUniIds[n + localOffset[rank]] = glo2uniMap[gid];
            }

            vComm->AllReduce(allUniIds, LibUtilities::ReduceSum);
            std::sort(allUniIds.begin(), allUniIds.end());
            map<int,int> uniIdReorder;

            for (cnt = n = 0; n < allUniIds.size(); ++n)
            {
                if (uniIdReorder.count(allUniIds[n]) > 0)
                {
                    continue;
                }

                uniIdReorder[allUniIds[n]] = cnt++;
            }

            for (n = 0; n < nHomDofs; ++n)
            {
                int gid = n + nDirDofs;
                int uniId = glo2uniMap[gid];
                ASSERTL0(uniIdReorder.count(uniId) > 0, "Error in ordering");
                m_reorderedMap[n] = uniIdReorder[uniId];
            }
        }

        void GlobalLinSysPETSc::SetUpMatVec()
        {
            // CREATE VECTORS
            VecCreate        (PETSC_COMM_WORLD, &m_x);
            VecSetSizes      (m_x, m_nLocal, PETSC_DECIDE);
            VecSetFromOptions(m_x);
            VecDuplicate     (m_x, &m_b);

            // CREATE MATRICES
            MatCreate        (PETSC_COMM_WORLD, &m_matrix);
            MatSetType       (m_matrix, MATAIJ);
            MatSetSizes      (m_matrix, m_nLocal, m_nLocal,
                              PETSC_DETERMINE, PETSC_DETERMINE);
            MatSetFromOptions(m_matrix);
            MatSetUp         (m_matrix);
        }

        void GlobalLinSysPETSc::SetUpSolver(NekDouble tolerance)
        {
            KSPCreate(PETSC_COMM_WORLD, &m_ksp);
            KSPSetTolerances(
                m_ksp, tolerance, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT);
            KSPSetFromOptions(m_ksp);
#if PETSC_VERSION_GE(3,5,0)
            KSPSetOperators(m_ksp, m_matrix, m_matrix);
#else
            KSPSetOperators(m_ksp, m_matrix, m_matrix, SAME_NONZERO_PATTERN);
#endif
        }
    }
}
<commit_msg>Fix bug with multi-level PETSc solver<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File GlobalLinSys.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: GlobalLinSys definition
//
///////////////////////////////////////////////////////////////////////////////

#include <MultiRegions/GlobalLinSysPETSc.h>

#include "petscis.h"
#include "petscversion.h"

namespace Nektar
{
    namespace MultiRegions
    {
        /**
         * @class GlobalLinSysPETSc
         *
         * Solves a linear system using direct methods.
         */

        /// Constructor for full direct matrix solve.
        GlobalLinSysPETSc::GlobalLinSysPETSc(
            const GlobalLinSysKey                &pKey,
            const boost::weak_ptr<ExpList>       &pExp,
            const boost::shared_ptr<AssemblyMap> &pLocToGloMap)
            : GlobalLinSys(pKey, pExp, pLocToGloMap)
        {
            // Initialise PETSc
            PetscInitialize(0, NULL, NULL, NULL);

            // Create matrix
            MatCreate(PETSC_COMM_WORLD, &m_matrix);
        }

        GlobalLinSysPETSc::~GlobalLinSysPETSc()
        {
        }

        void GlobalLinSysPETSc::v_SolveLinearSystem(
            const int                          pNumRows,
            const Array<OneD,const NekDouble> &pInput,
                  Array<OneD,      NekDouble> &pOutput,
            const AssemblyMapSharedPtr        &locToGloMap,
            const int                          pNumDir)
        {
            const int nHomDofs = pNumRows - pNumDir;

            // Populate RHS vector from input
            VecSetValues(m_b, nHomDofs, &m_reorderedMap[0], &pInput[pNumDir], INSERT_VALUES);

            // Assemble RHS vector
            VecAssemblyBegin(m_b);
            VecAssemblyEnd  (m_b);

            // Do system solve
            KSPSolve(m_ksp, m_b, m_x);

            // Grab number of iterations taken
            PetscInt its;
            KSPGetIterationNumber(m_ksp, &its);
            cout << "iterations = " << its << endl;

            // Scatter results to local vector
            VecScatterBegin(m_ctx, m_x, m_locVec, INSERT_VALUES, SCATTER_FORWARD);
            VecScatterEnd  (m_ctx, m_x, m_locVec, INSERT_VALUES, SCATTER_FORWARD);

            // Copy results into output vector
            PetscScalar *avec;
            VecGetArray    (m_locVec, &avec);
            Vmath::Vcopy   (nHomDofs, avec, 1, &pOutput[pNumDir], 1);
            VecRestoreArray(m_locVec, &avec);
        }

        void GlobalLinSysPETSc::SetUpScatter()
        {
            const int nHomDofs = m_reorderedMap.size();

            // Create local and global numbering systems for vector
            IS isGlobal, isLocal;
            ISCreateGeneral(PETSC_COMM_SELF, nHomDofs, &m_reorderedMap[0],
                            PETSC_COPY_VALUES, &isGlobal);
            ISCreateStride (PETSC_COMM_SELF, nHomDofs, 0, 1, &isLocal);

            // Create local vector for output
            VecCreate        (PETSC_COMM_SELF, &m_locVec);
            VecSetSizes      (m_locVec, m_reorderedMap.size(), PETSC_DECIDE);
            VecSetFromOptions(m_locVec);

            // Create scatter context
            VecScatterCreate (m_x, isGlobal, m_locVec, isLocal, &m_ctx);

            // Clean up
            ISDestroy(&isGlobal);
            ISDestroy(&isLocal);
        }

        void GlobalLinSysPETSc::CalculateReordering(
            const Array<OneD, const int> &glo2uniMap,
            const Array<OneD, const int> &glo2unique,
            const AssemblyMapSharedPtr   &pLocToGloMap)
        {
            LibUtilities::CommSharedPtr vComm
                = m_expList.lock()->GetSession()->GetComm();

            const int nDirDofs = pLocToGloMap->GetNumGlobalDirBndCoeffs();
            const int nHomDofs = pLocToGloMap->GetNumGlobalBndCoeffs() - nDirDofs;
            const int nProc    = vComm->GetSize();
            const int rank     = vComm->GetRank();

            int n, cnt;

            m_nLocal = Vmath::Vsum(nHomDofs, glo2unique + nDirDofs, 1);

            m_reorderedMap.resize(nHomDofs);

            Array<OneD, int> localCounts(nProc, 0), localOffset(nProc, 0);
            localCounts[rank] = nHomDofs;
            vComm->AllReduce(localCounts, LibUtilities::ReduceSum);

            for (n = 1; n < nProc; ++n)
            {
                localOffset[n] = localOffset[n-1] + localCounts[n-1];
            }

            int totHomDofs = Vmath::Vsum(nProc, localCounts, 1);
            vector<unsigned int> allUniIds(totHomDofs, 0);

            for (n = 0; n < nHomDofs; ++n)
            {
                int gid = n + nDirDofs;
                allUniIds[n + localOffset[rank]] = glo2uniMap[gid];
            }

            vComm->AllReduce(allUniIds, LibUtilities::ReduceSum);
            std::sort(allUniIds.begin(), allUniIds.end());
            map<int,int> uniIdReorder;

            for (cnt = n = 0; n < allUniIds.size(); ++n)
            {
                if (uniIdReorder.count(allUniIds[n]) > 0)
                {
                    continue;
                }

                uniIdReorder[allUniIds[n]] = cnt++;
            }

            for (n = 0; n < nHomDofs; ++n)
            {
                int gid = n + nDirDofs;
                int uniId = glo2uniMap[gid];
                ASSERTL0(uniIdReorder.count(uniId) > 0, "Error in ordering");
                m_reorderedMap[n] = uniIdReorder[uniId];
            }
        }

        void GlobalLinSysPETSc::SetUpMatVec()
        {
            // CREATE VECTORS
            VecCreate        (PETSC_COMM_WORLD, &m_x);
            VecSetSizes      (m_x, m_nLocal, PETSC_DECIDE);
            VecSetFromOptions(m_x);
            VecDuplicate     (m_x, &m_b);

            // CREATE MATRICES
            MatCreate        (PETSC_COMM_WORLD, &m_matrix);
            MatSetType       (m_matrix, MATAIJ);
            MatSetSizes      (m_matrix, m_nLocal, m_nLocal,
                              PETSC_DETERMINE, PETSC_DETERMINE);
            MatSetFromOptions(m_matrix);
            MatSetUp         (m_matrix);
        }

        void GlobalLinSysPETSc::SetUpSolver(NekDouble tolerance)
        {
            KSPCreate(PETSC_COMM_WORLD, &m_ksp);
            KSPSetTolerances(
                m_ksp, tolerance, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT);
            KSPSetFromOptions(m_ksp);
#if PETSC_VERSION_GE(3,5,0)
            KSPSetOperators(m_ksp, m_matrix, m_matrix);
#else
            KSPSetOperators(m_ksp, m_matrix, m_matrix, SAME_NONZERO_PATTERN);
#endif
        }
    }
}
<|endoftext|>


<commit_before>#include "../include/ParticleEmitter.h"

namespace FGF
{
	ParticleEmitter::ParticleEmitter(SceneNode* parent, PEParameters* aParms, Texture* aTex)
		:SceneNode(parent)
	{
		parms = aParms;
		tex = aTex;

		srand((unsigned)time(NULL));

		bool active = false;
		T = parms->Emit_Period;
	}

	ParticleEmitter::~ParticleEmitter()
	{
		particles.clear();
	}

	void ParticleEmitter::Update(float dt)
	{
		if(active)
		{
			if(T <= 0)
			{
				EmitParticle();
				T = parms->Emit_Period;
			}
			else
			{
				T -= dt;
			}
		}

		UpdateParticles(dt);
		ClearDeadParticles();
		updateChildren(dt);//Не знаю, нахуй, но пусть будет, лол!
	}

	void ParticleEmitter::Render()
	{
		prepare();
		tex->Activate();
		float tex_x = tex->getXRes();
		float tex_y = tex->getYRes();
		glBegin(GL_QUADS);
		for(std::deque<particle>::iterator it = particles.begin(); it != particles.end(); it++)
		{
			float x = it->x;
			float y = it->y;
			glTexCoord2f(0,0);
			glVertex3f(x - tex_x/2, y - tex_y/2, 0);

			glTexCoord2f(1,0);
			glVertex3f(x + tex_x/2, y - tex_y/2, 0);

			glTexCoord2f(1,1);
			glVertex3f(x + tex_x/2, y + tex_y/2, 0);

			glTexCoord2f(0,1);
			glVertex3f(x - tex_x/2, y + tex_y/2, 0);
		}
		glEnd();

		renderChildren();
	}

	void ParticleEmitter::Fire()
	{
		active = true;
	}

	void ParticleEmitter::Stop()
	{
		active = false;
	}

	void ParticleEmitter::UpdateParticles(float dt)
	{
		for(std::deque<particle>::iterator it = particles.begin(); it != particles.end(); it++)
		{
			it->x = it->x + (it->spd_x)*dt;
			it->y = it->y + (it->spd_y)*dt;
			it->ttl -= dt;
		}
	}

	void ParticleEmitter::EmitParticle()
	{
			float speed_range = parms->MaxSpd - parms->MinSpd;
			float spd = (speed_range *((float)(rand()%101)) / 100) + parms->MinSpd;
			float angle = parms->Direction + (((float)(rand()%101 - 50)/100) * parms->DispAngle);
			particle new_part;
			new_part.x = 0;//Относительно
			new_part.y = 0;//эмиттера
			new_part.spd_x = spd* cos(angle);
			new_part.spd_y = spd* sin(angle);
			new_part.ttl = parms->Part_TTL;
			particles.push_back(new_part);
	}

	void ParticleEmitter::ClearDeadParticles()
	{
		/* TODO:
		 * Контейнерная магия!
		 * Заменить на что-то более разумное.
		 */
		if(!particles.empty()) while((particles.begin()->ttl) <= 0.0f) particles.pop_front();
	}
}
<commit_msg>Допилил работу со стеком матриц в рендер ParticleEmitter<commit_after>#include "../include/ParticleEmitter.h"

namespace FGF
{
	ParticleEmitter::ParticleEmitter(SceneNode* parent, PEParameters* aParms, Texture* aTex)
		:SceneNode(parent)
	{
		parms = aParms;
		tex = aTex;

		srand((unsigned)time(NULL));

		bool active = false;
		T = parms->Emit_Period;
	}

	ParticleEmitter::~ParticleEmitter()
	{
		particles.clear();
	}

	void ParticleEmitter::Update(float dt)
	{
		if(active)
		{
			if(T <= 0)
			{
				EmitParticle();
				T = parms->Emit_Period;
			}
			else
			{
				T -= dt;
			}
		}

		UpdateParticles(dt);
		ClearDeadParticles();
		updateChildren(dt);//Не знаю, нахуй, но пусть будет, лол!
	}

	void ParticleEmitter::Render()
	{
		glPushMatrix();
		prepare();
		tex->Activate();
		float tex_x = tex->getXRes();
		float tex_y = tex->getYRes();
		glBegin(GL_QUADS);
		for(std::deque<particle>::iterator it = particles.begin(); it != particles.end(); it++)
		{
			float x = it->x;
			float y = it->y;
			glTexCoord2f(0,0);
			glVertex3f(x - tex_x/2, y - tex_y/2, 0);

			glTexCoord2f(1,0);
			glVertex3f(x + tex_x/2, y - tex_y/2, 0);

			glTexCoord2f(1,1);
			glVertex3f(x + tex_x/2, y + tex_y/2, 0);

			glTexCoord2f(0,1);
			glVertex3f(x - tex_x/2, y + tex_y/2, 0);
		}
		glEnd();

		renderChildren();
		glPopMatrix();
	}

	void ParticleEmitter::Fire()
	{
		active = true;
	}

	void ParticleEmitter::Stop()
	{
		active = false;
	}

	void ParticleEmitter::UpdateParticles(float dt)
	{
		for(std::deque<particle>::iterator it = particles.begin(); it != particles.end(); it++)
		{
			it->x = it->x + (it->spd_x)*dt;
			it->y = it->y + (it->spd_y)*dt;
			it->ttl -= dt;
		}
	}

	void ParticleEmitter::EmitParticle()
	{
			float speed_range = parms->MaxSpd - parms->MinSpd;
			float spd = (speed_range *((float)(rand()%101)) / 100) + parms->MinSpd;
			float angle = parms->Direction + (((float)(rand()%101 - 50)/100) * parms->DispAngle);
			particle new_part;
			new_part.x = 0;//Относительно
			new_part.y = 0;//эмиттера
			new_part.spd_x = spd* cos(angle);
			new_part.spd_y = spd* sin(angle);
			new_part.ttl = parms->Part_TTL;
			particles.push_back(new_part);
	}

	void ParticleEmitter::ClearDeadParticles()
	{
		/* TODO:
		 * Контейнерная магия!
		 * Заменить на что-то более разумное.
		 */
		if(!particles.empty()) while((particles.begin()->ttl) <= 0.0f) particles.pop_front();
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: depapp.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: obo $ $Date: 2004-02-26 14:48:13 $
 *
 *  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 <svtools/solar.hrc>
#include <tools/solver.h>
#include <tools/resmgr.hxx>
#include <bootstrp/sstring.hxx>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/help.hxx>
#include "soldep.hxx"
// -----------------------------------------------------------------------
#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

class MyApp : public Application
{
    ResMgr*     pResMgr;
    SolDep*     pSolDep;
public:
    void        Main();
    ResMgr*     GetResMgr() const { return pResMgr; }
};

MyApp aMyApp;

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

class MyWin : public WorkWindow
{
public:
                MyWin( Window* pParent, WinBits nWinStyle );

    void        MouseMove( const MouseEvent& rMEvt );
    void        MouseButtonDown( const MouseEvent& rMEvt );
    void        MouseButtonUp( const MouseEvent& rMEvt );
    void        KeyInput( const KeyEvent& rKEvt );
    void        KeyUp( const KeyEvent& rKEvt );
    void        Paint( const Rectangle& rRect );
    void        Resize();
};

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

void MyApp::Main()
{
    ByteString aResMgrName( "dep" );
    aResMgrName += ByteString::CreateFromInt64( SOLARUPD );
    Application* pApp;
    pApp = GetpApp();
    International iNat;
    iNat = GetpApp()->GetAppInternational();
    LanguageType lt;
    lt = iNat.GetLanguage();
    pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(),
            GetpApp()->GetAppInternational().GetLanguage());
    DtSodResId::SetResMgr( pResMgr );

    MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
    aMainWin.SetText( String::CreateFromAscii( SOLDEPL_NAME ));
    aMainWin.Show();
    pSolDep = new SolDep( &aMainWin );
    pSolDep->Init();
    Help aHelp;
    SetHelp(&aHelp);
    aHelp.EnableContextHelp();
    aHelp.EnableQuickHelp();
    Execute();
    delete pResMgr;
    delete pSolDep;
}

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

MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle )
{
}

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

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

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

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonDown( rMEvt );
}

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

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

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

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

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

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

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

void MyWin::Paint( const Rectangle& rRect )
{
    WorkWindow::Paint( rRect );
}

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

void MyWin::Resize()
{
    WorkWindow::Resize();
    Window* pWin;
    USHORT  i, nChildCount = GetChildCount();

    for ( i = 0; i < nChildCount; i++ )
    {
        pWin = GetChild( i );
        pWin->SetPosSizePixel( GetPosPixel(), GetSizePixel() );
//      pWin->Resize();
//      ((GraphWin*) pWin)->EndScroll( 0, 0 );
    }
}

SAL_IMPLEMENT_MAIN()
{
    Reference< XMultiServiceFactory > xMS;

    // for this to work make sure an <appname>.ini file is available, you can just copy soffice.ini
    Reference< XComponentContext > xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext();
    xMS = cppu::createRegistryServiceFactory(
                  rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );

    InitVCL( xMS );
    //GetpApp()->WaitForClientConnect();  // is a no-op in local case
    //::Main();
    aMyApp.Main();
    DeInitVCL();
    return 0;
}

<commit_msg>iso code change<commit_after>/*************************************************************************
 *
 *  $RCSfile: depapp.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-07-27 15:52:26 $
 *
 *  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 <svtools/solar.hrc>
#include <tools/solver.h>
#include <tools/resmgr.hxx>
#include <bootstrp/sstring.hxx>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/help.hxx>
#include "soldep.hxx"
// -----------------------------------------------------------------------
#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

class MyApp : public Application
{
    ResMgr*     pResMgr;
    SolDep*     pSolDep;
public:
    void        Main();
    ResMgr*     GetResMgr() const { return pResMgr; }
};

MyApp aMyApp;

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

class MyWin : public WorkWindow
{
public:
                MyWin( Window* pParent, WinBits nWinStyle );

    void        MouseMove( const MouseEvent& rMEvt );
    void        MouseButtonDown( const MouseEvent& rMEvt );
    void        MouseButtonUp( const MouseEvent& rMEvt );
    void        KeyInput( const KeyEvent& rKEvt );
    void        KeyUp( const KeyEvent& rKEvt );
    void        Paint( const Rectangle& rRect );
    void        Resize();
};

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

void MyApp::Main()
{
    ByteString aResMgrName( "dep" );
    aResMgrName += ByteString::CreateFromInt64( SOLARUPD );
    International iNat;
    iNat = GetAppInternational();
    ::com::sun::star::lang::Locale aLocale;
    pResMgr = ResMgr::SearchCreateResMgr( aResMgrName.GetBuffer(), aLocale );
        AllSettings as = GetSettings();
        as.SetUILocale(aLocale);
        SetSettings(as);

    Resource::SetResManager( pResMgr ); // from vcl
    DtSodResId::SetResMgr( pResMgr );

    MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
    aMainWin.SetText( String::CreateFromAscii( SOLDEPL_NAME ));
    aMainWin.Show();
    pSolDep = new SolDep( &aMainWin );
    pSolDep->Init();
    Help aHelp;
    SetHelp(&aHelp);
    aHelp.EnableContextHelp();
    aHelp.EnableQuickHelp();
    Execute();
    delete pResMgr;
    delete pSolDep;
}

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

MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle )
{
}

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

void MyWin::MouseMove( const MouseEvent& rMEvt )
{
    WorkWindow::MouseMove( rMEvt );
}

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

void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonDown( rMEvt );
}

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

void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
    WorkWindow::MouseButtonUp( rMEvt );
}

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

void MyWin::KeyInput( const KeyEvent& rKEvt )
{
    WorkWindow::KeyInput( rKEvt );
}

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

void MyWin::KeyUp( const KeyEvent& rKEvt )
{
    WorkWindow::KeyUp( rKEvt );
}

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

void MyWin::Paint( const Rectangle& rRect )
{
    WorkWindow::Paint( rRect );
}

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

void MyWin::Resize()
{
    WorkWindow::Resize();
    Window* pWin;
    USHORT  i, nChildCount = GetChildCount();

    for ( i = 0; i < nChildCount; i++ )
    {
        pWin = GetChild( i );
        pWin->SetPosSizePixel( GetPosPixel(), GetSizePixel() );
//      pWin->Resize();
//      ((GraphWin*) pWin)->EndScroll( 0, 0 );
    }
}

SAL_IMPLEMENT_MAIN()
{
    Reference< XMultiServiceFactory > xMS;

    // for this to work make sure an <appname>.ini file is available, you can just copy soffice.ini
    Reference< XComponentContext > xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext();
    xMS = cppu::createRegistryServiceFactory(
                  rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );

    InitVCL( xMS );
    //GetpApp()->WaitForClientConnect();  // is a no-op in local case
    //::Main();
    aMyApp.Main();
    DeInitVCL();
    return 0;
}

<|endoftext|>


<commit_before>#include "hip_global.hpp"

#include "hip/hip_runtime.h"
#include "hip_internal.hpp"
#include "hip_code_object.hpp"
#include "platform/program.hpp"

namespace hip {

//Device Vars
DeviceVar::DeviceVar(std::string name, hipModule_t hmod) : shadowVptr(nullptr), name_(name),
                                                           amd_mem_obj_(nullptr), device_ptr_(nullptr),
                                                           size_(0) {
  amd::Program* program = as_amd(reinterpret_cast<cl_program>(hmod));
  device::Program* dev_program = program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0]);
  if (dev_program == nullptr) {
    DevLogPrintfError("Cannot get Device Function for module: 0x%x \n", hmod);
    guarantee(false);
  }

  if(!dev_program->createGlobalVarObj(&amd_mem_obj_, &device_ptr_, &size_, name.c_str())) {
    DevLogPrintfError("Cannot create Global Var obj for symbol: %s \n", name.c_str());
    guarantee(false);
  }

  if (amd_mem_obj_ == nullptr || device_ptr_ == nullptr) {
    DevLogPrintfError("Cannot get memory for creating device Var: %s", name.c_str());
    guarantee(false);
  }

  amd::MemObjMap::AddMemObj(device_ptr_, amd_mem_obj_);
}

DeviceVar::~DeviceVar() {
  if (device_ptr_ != nullptr) {
    amd::MemObjMap::RemoveMemObj(device_ptr_);
    amd_mem_obj_->release();
  }

  if (shadowVptr != nullptr) {
    textureReference* texRef = reinterpret_cast<textureReference*>(shadowVptr);
    delete texRef;
    shadowVptr = nullptr;
  }

  device_ptr_ = nullptr;
  size_ = 0;
}

//Device Functions
DeviceFunc::DeviceFunc(std::string name, hipModule_t hmod) : dflock_("function lock"),
                       name_(name), kernel_(nullptr) {
  amd::Program* program = as_amd(reinterpret_cast<cl_program>(hmod));

  const amd::Symbol *symbol = program->findSymbol(name.c_str());
  if (symbol == nullptr) {
    DevLogPrintfError("Cannot find Symbol with name: %s \n", name.c_str());
    guarantee(false);
  }

  kernel_ = new amd::Kernel(*program, *symbol, name);
  if (kernel_ == nullptr) {
    DevLogPrintfError("Cannot create kernel with name: %s \n", name.c_str());
    guarantee(false);
  }
}

DeviceFunc::~DeviceFunc() {
  if (kernel_ != nullptr) {
    kernel_->release();
  }
}

//Abstract functions
Function::Function(std::string name, FatBinaryInfoType* modules)
                   : name_(name), modules_(modules) {
  dFunc_.resize(g_devices.size());
}

Function::~Function() {
  for (auto& elem : dFunc_) {
    delete elem;
  }
  name_ = "";
  modules_ = nullptr;
}

hipError_t Function::getDynFunc(hipFunction_t* hfunc, hipModule_t hmod) {
  guarantee(dFunc_.size() == g_devices.size());
  if (dFunc_[ihipGetDevice()] == nullptr) {
    dFunc_[ihipGetDevice()] = new DeviceFunc(name_, hmod);
  }
  *hfunc = dFunc_[ihipGetDevice()]->asHipFunction();

  return hipSuccess;
}

hipError_t Function::getStatFunc(hipFunction_t* hfunc, int deviceId) {
  guarantee(modules_ != nullptr);
  guarantee(deviceId >= 0);
  guarantee(static_cast<size_t>(deviceId) < modules_->size());

  hipModule_t module = (*modules_)[deviceId].first;
  FatBinaryMetaInfo* fb_meta = (*modules_)[deviceId].second;

  if (!fb_meta->built()) {
    IHIP_RETURN_ONFAIL(CodeObject::add_program(deviceId, module, fb_meta->binary_ptr(),
                                               fb_meta->binary_size()));
    IHIP_RETURN_ONFAIL(CodeObject::build_module(module, g_devices[deviceId]->devices()));
    fb_meta->set_built();
  }

  if (dFunc_[deviceId] == nullptr) {
    dFunc_[deviceId] = new DeviceFunc(name_, (*modules_)[deviceId].first);
  }
  *hfunc = dFunc_[deviceId]->asHipFunction();

  return hipSuccess;
}

hipError_t Function::getStatFuncAttr(hipFuncAttributes* func_attr, int deviceId) {
  guarantee(modules_ != nullptr);
  guarantee(deviceId >= 0);
  guarantee(static_cast<size_t>(deviceId) < modules_->size());

  hipModule_t module = (*modules_)[deviceId].first;
  FatBinaryMetaInfo* fb_meta = (*modules_)[deviceId].second;

  if (!fb_meta->built()) {
    IHIP_RETURN_ONFAIL(CodeObject::add_program(deviceId, module, fb_meta->binary_ptr(),
                                               fb_meta->binary_size()));
    IHIP_RETURN_ONFAIL(CodeObject::build_module(module, g_devices[deviceId]->devices()));
    fb_meta->set_built();
  }

  if (dFunc_[deviceId] == nullptr) {
    dFunc_[deviceId] = new DeviceFunc(name_, (*modules_)[deviceId].first);
  }

  const std::vector<amd::Device*>& devices = amd::Device::getDevices(CL_DEVICE_TYPE_GPU, false);

  amd::Kernel* kernel = dFunc_[deviceId]->kernel();
  const device::Kernel::WorkGroupInfo* wginfo = kernel->getDeviceKernel(*devices[deviceId])->workGroupInfo();
  func_attr->sharedSizeBytes = static_cast<int>(wginfo->localMemSize_);
  func_attr->binaryVersion = static_cast<int>(kernel->signature().version());
  func_attr->cacheModeCA = 0;
  func_attr->constSizeBytes = 0;
  func_attr->localSizeBytes = wginfo->privateMemSize_;
  func_attr->maxDynamicSharedSizeBytes = static_cast<int>(wginfo->availableLDSSize_
                                                          - wginfo->localMemSize_);

  func_attr->maxThreadsPerBlock = static_cast<int>(wginfo->size_);
  func_attr->numRegs = static_cast<int>(wginfo->usedVGPRs_);
  func_attr->preferredShmemCarveout = 0;
  func_attr->ptxVersion = 30;

  return hipSuccess;
}

//Abstract Vars
Var::Var(std::string name, DeviceVarKind dVarKind, size_t size, int type, int norm,
         FatBinaryInfoType* modules) : name_(name), dVarKind_(dVarKind), size_(size),
         type_(type), norm_(norm), modules_(modules) {
  dVar_.resize(g_devices.size());
}

Var::~Var() {
  for (auto& elem : dVar_) {
    delete elem;
  }
  modules_ = nullptr;
}

hipError_t Var::getDeviceVar(DeviceVar** dvar, int deviceId, hipModule_t hmod) {
  guarantee(deviceId >= 0);
  guarantee(static_cast<size_t>(deviceId) < g_devices.size());
  guarantee(dVar_.size() == g_devices.size());

  if (dVar_[deviceId] == nullptr) {
    dVar_[deviceId] = new DeviceVar(name_, hmod);
  }

  *dvar = dVar_[deviceId];
  return hipSuccess;
}

hipError_t Var::getStatDeviceVar(DeviceVar** dvar, int deviceId) {
  guarantee(deviceId >= 0);
  guarantee(static_cast<size_t>(deviceId) < g_devices.size());

  hipModule_t module = (*modules_)[deviceId].first;
  FatBinaryMetaInfo* fb_meta = (*modules_)[deviceId].second;

  if (!fb_meta->built()) {
    IHIP_RETURN_ONFAIL(CodeObject::add_program(deviceId, module, fb_meta->binary_ptr(),
                                               fb_meta->binary_size()));
    IHIP_RETURN_ONFAIL(CodeObject::build_module(module, g_devices[deviceId]->devices()));
    fb_meta->set_built();
  }

  if (dVar_[deviceId] == nullptr) {
    dVar_[deviceId] = new DeviceVar(name_, (*modules_)[deviceId].first);
  }

  *dvar = dVar_[deviceId];
  return hipSuccess;
}

}; //namespace: hip
<commit_msg>Handle size 0 symbols<commit_after>#include "hip_global.hpp"

#include "hip/hip_runtime.h"
#include "hip_internal.hpp"
#include "hip_code_object.hpp"
#include "platform/program.hpp"

namespace hip {

//Device Vars
DeviceVar::DeviceVar(std::string name, hipModule_t hmod) : shadowVptr(nullptr), name_(name),
                                                           amd_mem_obj_(nullptr), device_ptr_(nullptr),
                                                           size_(0) {
  amd::Program* program = as_amd(reinterpret_cast<cl_program>(hmod));
  device::Program* dev_program = program->getDeviceProgram(*hip::getCurrentDevice()->devices()[0]);
  if (dev_program == nullptr) {
    DevLogPrintfError("Cannot get Device Function for module: 0x%x \n", hmod);
    guarantee(false);
  }

  if(!dev_program->createGlobalVarObj(&amd_mem_obj_, &device_ptr_, &size_, name.c_str())) {
    DevLogPrintfError("Cannot create Global Var obj for symbol: %s \n", name.c_str());
    guarantee(false);
  }

  // Handle size 0 symbols
  if (size_ != 0) {
    if (amd_mem_obj_ == nullptr || device_ptr_ == nullptr) {
      DevLogPrintfError("Cannot get memory for creating device Var: %s", name.c_str());
      guarantee(false);
    }
    amd::MemObjMap::AddMemObj(device_ptr_, amd_mem_obj_);
  }
}

DeviceVar::~DeviceVar() {
  if (amd_mem_obj_ != nullptr) {
    amd::MemObjMap::RemoveMemObj(device_ptr_);
    amd_mem_obj_->release();
  }

  if (shadowVptr != nullptr) {
    textureReference* texRef = reinterpret_cast<textureReference*>(shadowVptr);
    delete texRef;
    shadowVptr = nullptr;
  }

  device_ptr_ = nullptr;
  size_ = 0;
}

//Device Functions
DeviceFunc::DeviceFunc(std::string name, hipModule_t hmod) : dflock_("function lock"),
                       name_(name), kernel_(nullptr) {
  amd::Program* program = as_amd(reinterpret_cast<cl_program>(hmod));

  const amd::Symbol *symbol = program->findSymbol(name.c_str());
  if (symbol == nullptr) {
    DevLogPrintfError("Cannot find Symbol with name: %s \n", name.c_str());
    guarantee(false);
  }

  kernel_ = new amd::Kernel(*program, *symbol, name);
  if (kernel_ == nullptr) {
    DevLogPrintfError("Cannot create kernel with name: %s \n", name.c_str());
    guarantee(false);
  }
}

DeviceFunc::~DeviceFunc() {
  if (kernel_ != nullptr) {
    kernel_->release();
  }
}

//Abstract functions
Function::Function(std::string name, FatBinaryInfoType* modules)
                   : name_(name), modules_(modules) {
  dFunc_.resize(g_devices.size());
}

Function::~Function() {
  for (auto& elem : dFunc_) {
    delete elem;
  }
  name_ = "";
  modules_ = nullptr;
}

hipError_t Function::getDynFunc(hipFunction_t* hfunc, hipModule_t hmod) {
  guarantee(dFunc_.size() == g_devices.size());
  if (dFunc_[ihipGetDevice()] == nullptr) {
    dFunc_[ihipGetDevice()] = new DeviceFunc(name_, hmod);
  }
  *hfunc = dFunc_[ihipGetDevice()]->asHipFunction();

  return hipSuccess;
}

hipError_t Function::getStatFunc(hipFunction_t* hfunc, int deviceId) {
  guarantee(modules_ != nullptr);
  guarantee(deviceId >= 0);
  guarantee(static_cast<size_t>(deviceId) < modules_->size());

  hipModule_t module = (*modules_)[deviceId].first;
  FatBinaryMetaInfo* fb_meta = (*modules_)[deviceId].second;

  if (!fb_meta->built()) {
    IHIP_RETURN_ONFAIL(CodeObject::add_program(deviceId, module, fb_meta->binary_ptr(),
                                               fb_meta->binary_size()));
    IHIP_RETURN_ONFAIL(CodeObject::build_module(module, g_devices[deviceId]->devices()));
    fb_meta->set_built();
  }

  if (dFunc_[deviceId] == nullptr) {
    dFunc_[deviceId] = new DeviceFunc(name_, (*modules_)[deviceId].first);
  }
  *hfunc = dFunc_[deviceId]->asHipFunction();

  return hipSuccess;
}

hipError_t Function::getStatFuncAttr(hipFuncAttributes* func_attr, int deviceId) {
  guarantee(modules_ != nullptr);
  guarantee(deviceId >= 0);
  guarantee(static_cast<size_t>(deviceId) < modules_->size());

  hipModule_t module = (*modules_)[deviceId].first;
  FatBinaryMetaInfo* fb_meta = (*modules_)[deviceId].second;

  if (!fb_meta->built()) {
    IHIP_RETURN_ONFAIL(CodeObject::add_program(deviceId, module, fb_meta->binary_ptr(),
                                               fb_meta->binary_size()));
    IHIP_RETURN_ONFAIL(CodeObject::build_module(module, g_devices[deviceId]->devices()));
    fb_meta->set_built();
  }

  if (dFunc_[deviceId] == nullptr) {
    dFunc_[deviceId] = new DeviceFunc(name_, (*modules_)[deviceId].first);
  }

  const std::vector<amd::Device*>& devices = amd::Device::getDevices(CL_DEVICE_TYPE_GPU, false);

  amd::Kernel* kernel = dFunc_[deviceId]->kernel();
  const device::Kernel::WorkGroupInfo* wginfo = kernel->getDeviceKernel(*devices[deviceId])->workGroupInfo();
  func_attr->sharedSizeBytes = static_cast<int>(wginfo->localMemSize_);
  func_attr->binaryVersion = static_cast<int>(kernel->signature().version());
  func_attr->cacheModeCA = 0;
  func_attr->constSizeBytes = 0;
  func_attr->localSizeBytes = wginfo->privateMemSize_;
  func_attr->maxDynamicSharedSizeBytes = static_cast<int>(wginfo->availableLDSSize_
                                                          - wginfo->localMemSize_);

  func_attr->maxThreadsPerBlock = static_cast<int>(wginfo->size_);
  func_attr->numRegs = static_cast<int>(wginfo->usedVGPRs_);
  func_attr->preferredShmemCarveout = 0;
  func_attr->ptxVersion = 30;

  return hipSuccess;
}

//Abstract Vars
Var::Var(std::string name, DeviceVarKind dVarKind, size_t size, int type, int norm,
         FatBinaryInfoType* modules) : name_(name), dVarKind_(dVarKind), size_(size),
         type_(type), norm_(norm), modules_(modules) {
  dVar_.resize(g_devices.size());
}

Var::~Var() {
  for (auto& elem : dVar_) {
    delete elem;
  }
  modules_ = nullptr;
}

hipError_t Var::getDeviceVar(DeviceVar** dvar, int deviceId, hipModule_t hmod) {
  guarantee(deviceId >= 0);
  guarantee(static_cast<size_t>(deviceId) < g_devices.size());
  guarantee(dVar_.size() == g_devices.size());

  if (dVar_[deviceId] == nullptr) {
    dVar_[deviceId] = new DeviceVar(name_, hmod);
  }

  *dvar = dVar_[deviceId];
  return hipSuccess;
}

hipError_t Var::getStatDeviceVar(DeviceVar** dvar, int deviceId) {
  guarantee(deviceId >= 0);
  guarantee(static_cast<size_t>(deviceId) < g_devices.size());

  hipModule_t module = (*modules_)[deviceId].first;
  FatBinaryMetaInfo* fb_meta = (*modules_)[deviceId].second;

  if (!fb_meta->built()) {
    IHIP_RETURN_ONFAIL(CodeObject::add_program(deviceId, module, fb_meta->binary_ptr(),
                                               fb_meta->binary_size()));
    IHIP_RETURN_ONFAIL(CodeObject::build_module(module, g_devices[deviceId]->devices()));
    fb_meta->set_built();
  }

  if (dVar_[deviceId] == nullptr) {
    dVar_[deviceId] = new DeviceVar(name_, (*modules_)[deviceId].first);
  }

  *dvar = dVar_[deviceId];
  return hipSuccess;
}

}; //namespace: hip
<|endoftext|>


<commit_before>// =================================================================== //
// Copyright (C) 2014-2018 Kimura Ryo                                  //
//                                                                     //
// 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/.            //
// =================================================================== //

#include "RenderingWidget.h"

#include <QtWidgets>
#include <QtCore/QMimeData>
#include <QtCore/QUrl>

#include <osg/ShapeDrawable>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgUtil/Optimizer>

#include "SceneUtil.h"

RenderingWidget::RenderingWidget(const QGLFormat&   format,
                                 QWidget*           parent,
                                 const QGLWidget*   shareWidget,
                                 Qt::WindowFlags    f,
                                 bool               forwardKeyEvents)
                                 : osgQt::GLWidget(format, parent, shareWidget, f, forwardKeyEvents),
                                   renderingScene_(0),
                                   mouseMoved_(false),
                                   pickedInDir_(0.0, 0.0, 0.0)
{
    //setAcceptDrops(true);
    setMinimumSize(1, 1);

    actionResetCamera_ = new QAction(this);
    actionResetCamera_->setText(QApplication::translate("RenderingWidget", "Reset camera position", 0));
    connect(actionResetCamera_, SIGNAL(triggered()), this, SLOT(resetCameraPosition()));

    actionShapeSphere_ = new QAction(this);
    actionShapeSphere_->setText(QApplication::translate("RenderingWidget", "Sphere", 0));
    connect(actionShapeSphere_, SIGNAL(triggered()), this, SLOT(showSphere()));

    actionShapeCylinder_ = new QAction(this);
    actionShapeCylinder_->setText(QApplication::translate("RenderingWidget", "Cylinder", 0));
    connect(actionShapeCylinder_, SIGNAL(triggered()), this, SLOT(showCylinder()));

    actionShapeBox_ = new QAction(this);
    actionShapeBox_->setText(QApplication::translate("RenderingWidget", "Box", 0));
    connect(actionShapeBox_, SIGNAL(triggered()), this, SLOT(showBox()));

    actionShapeOpen_ = new QAction(this);
    actionShapeOpen_->setText(QApplication::translate("RenderingWidget", "Open...", 0));
    connect(actionShapeOpen_, SIGNAL(triggered()), this, SLOT(showLoadedModel()));
}

void RenderingWidget::resetCameraPosition()
{
    if (!renderingScene_) return;

    osgGA::CameraManipulator* cm = renderingScene_->getCameraManipulator();

    RenderingScene::fitCameraPosition(renderingScene_->getCamera(),
                                      osg::Vec3(0.0, -1.0, 0.0),
                                      osg::Vec3(0.0, 0.0, 1.0),
                                      renderingScene_->getScene());

    osg::Vec3d eye, center, up;
    renderingScene_->getCamera()->getViewMatrixAsLookAt(eye, center, up);
    center = scene_util::computeCenter(renderingScene_->getScene());
    cm->setHomePosition(eye, center, up);
    cm->home(0.0);
}

void RenderingWidget::showSphere()
{
    renderingScene_->getScene()->removeChildren(0, renderingScene_->getScene()->getNumChildren());

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(), 1.0f)));
    renderingScene_->getScene()->addChild(geode);
}

void RenderingWidget::showCylinder()
{
    renderingScene_->getScene()->removeChildren(0, renderingScene_->getScene()->getNumChildren());

    osg::Geode* geode = new osg::Geode;
    osg::Cylinder* cylinder = new osg::Cylinder(osg::Vec3(), 1.0f, 2.0f);
    osg::Quat rotQuat(M_PI / 2.0, osg::Vec3(0.0, 1.0, 0.0));
    cylinder->setRotation(rotQuat);
    geode->addDrawable(new osg::ShapeDrawable(cylinder));
    renderingScene_->getScene()->addChild(geode);
}

void RenderingWidget::showBox()
{
    renderingScene_->getScene()->removeChildren(0, renderingScene_->getScene()->getNumChildren());

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(), 1.5f)));
    renderingScene_->getScene()->addChild(geode);
}

void RenderingWidget::showLoadedModel()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Model File"), QString(),
                                                    tr("Obj Files (*.obj)"));

    if (fileName.isEmpty()) return;

    openModel(fileName);
    resetCameraPosition();
}

void RenderingWidget::resizeEvent(QResizeEvent* event)
{
    osgQt::GLWidget::resizeEvent(event);

    if (renderingScene_) {
        renderingScene_->updateView(event->size().width(), event->size().height());
    }
}

void RenderingWidget::keyPressEvent(QKeyEvent* event)
{
    osgQt::GLWidget::keyPressEvent(event);

    if (!renderingScene_) return;

    osgGA::CameraManipulator* cm = renderingScene_->getCameraManipulator();
    osgGA::TrackballManipulator* tm = dynamic_cast<osgGA::TrackballManipulator*>(cm);

    osg::Vec3 camPos, camCenter, camUp;
    renderingScene_->getCamera()->getViewMatrixAsLookAt(camPos, camCenter, camUp);
    osg::Vec3 camDir = camPos - camCenter;
    camDir.normalize();

    switch (event->key()) {
        case Qt::Key_Up: {
            if (!tm) break;

            osg::Vec3 rotAxis = camDir ^ camUp;
            osg::Quat rotQuat(M_PI / 180.0, rotAxis);
            tm->setRotation(tm->getRotation() * rotQuat);

            break;
        }
        case Qt::Key_Down: {
            if (!tm) break;

            osg::Vec3 rotAxis = camDir ^ camUp;
            osg::Quat rotQuat(-M_PI / 180.0, rotAxis);
            tm->setRotation(tm->getRotation() * rotQuat);

            break;
        }
        case Qt::Key_Left: {
            if (!tm) break;

            osg::Vec3 rotAxis(0.0, 0.0, 1.0);
            osg::Quat rotQuat(-M_PI / 180.0, rotAxis);
            tm->setRotation(tm->getRotation() * rotQuat);

            break;
        }
        case Qt::Key_Right: {
            if (!tm) break;

            osg::Vec3 rotAxis(0.0, 0.0, 1.0);
            osg::Quat rotQuat(M_PI / 180.0, rotAxis);
            tm->setRotation(tm->getRotation() * rotQuat);

            break;
        }
        case Qt::Key_Plus: {
            if (!tm) break;

            tm->setDistance(tm->getDistance() * 0.9);

            break;
        }
        case Qt::Key_Minus: {
            if (!tm) break;

            tm->setDistance(tm->getDistance() * 1.0 / 0.9);

            break;
        }
        default: {
            break;
        }
    }
}

void RenderingWidget::mouseMoveEvent(QMouseEvent* event)
{
    osgQt::GLWidget::mouseMoveEvent(event);
    mouseMoved_ = true;
}

void RenderingWidget::mousePressEvent(QMouseEvent* event)
{
    osgQt::GLWidget::mousePressEvent(event);
    mouseMoved_ = false;
}

void RenderingWidget::mouseReleaseEvent(QMouseEvent* event)
{
    osgQt::GLWidget::mouseReleaseEvent(event);

    if (event->button() == Qt::LeftButton && !mouseMoved_) {
        if (!renderingScene_) return;

        int x = event->pos().x();
        int y = event->pos().y();

        lb::Vec3 inDir = renderingScene_->getInDir(x, y);
        lb::Vec3 outDir = renderingScene_->getOutDir(x, y);
        if (inDir.isZero() || outDir.isZero()) {
            pickedInDir_ = lb::Vec3::Zero();
            emit inOutDirPicked(lb::Vec3::Zero(), lb::Vec3::Zero());
            return;
        }

        const lb::Brdf* brdf = renderingScene_->getBrdf();
        const lb::SampleSet2D* ss2 = renderingScene_->getReflectance();

        if (brdf) {
            if (brdf->getSampleSet()->isIsotropic()) {
                float inTheta, outTheta, outPhi;
                lb::SphericalCoordinateSystem::fromXyz(inDir, outDir, &inTheta, &outTheta, &outPhi);
                lb::SphericalCoordinateSystem::toXyz(inTheta, 0.0f, outTheta, outPhi, &inDir, &outDir);
            }
        }
        else if (ss2) {
            if (ss2->isIsotropic()) {
                float theta, phi;
                lb::SphericalCoordinateSystem::fromXyz(outDir, &theta, &phi);
                outDir = lb::SphericalCoordinateSystem::toXyz(theta, lb::PI_F);
            }

            inDir = lb::reflect(outDir, lb::Vec3(0.0, 0.0, 1.0));
        }

        pickedInDir_ = inDir;
        emit inOutDirPicked(inDir, outDir);
    }
#ifdef __APPLE__
    else if (event->button() == Qt::RightButton && !mouseMoved_) {
        showContextMenu(event->globalPos());
    }
#endif
}

void RenderingWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
    osgQt::GLWidget::mouseDoubleClickEvent(event);

    if (!pickedInDir_.isZero()) {
        emit inDirPicked(pickedInDir_);
    }
}

void RenderingWidget::dragEnterEvent(QDragEnterEvent* event)
{
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

void RenderingWidget::dropEvent(QDropEvent* event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    QString fileName = urls.front().toLocalFile();
    openModel(fileName);
}

void RenderingWidget::wheelEvent(QWheelEvent* event)
{
    osgQt::GLWidget::wheelEvent(event);
    mouseMoved_ = true;
}

void RenderingWidget::contextMenuEvent(QContextMenuEvent* event)
{
    osgQt::GLWidget::contextMenuEvent(event);

#ifndef __APPLE__
    if (mouseMoved_) return;

    showContextMenu(event->globalPos());
#endif
}

void RenderingWidget::showContextMenu(const QPoint& pos)
{
    QMenu menu(this);
    menu.addAction(actionResetCamera_);

    QMenu* shapeMenu = menu.addMenu(tr("Shape"));
    shapeMenu->addAction(actionShapeSphere_);
    shapeMenu->addAction(actionShapeCylinder_);
    shapeMenu->addAction(actionShapeBox_);
    shapeMenu->addAction(actionShapeOpen_);

    menu.exec(pos);
}

void RenderingWidget::openModel(const QString& fileName)
{
    osg::Node* loadedModel = osgDB::readNodeFile(fileName.toLocal8Bit().data());
    if (!loadedModel) {
        QMessageBox::warning(this, tr("BSDF Processor"),
                             tr("Failed to load \"") + fileName + "\"",
                             QMessageBox::Ok);
        return;
    }

    renderingScene_->getScene()->removeChildren(0, renderingScene_->getScene()->getNumChildren());

    osgUtil::Optimizer optimzer;
    optimzer.optimize(loadedModel, osgUtil::Optimizer::ALL_OPTIMIZATIONS);
    renderingScene_->getScene()->addChild(loadedModel);
}
<commit_msg>Added a debug output<commit_after>// =================================================================== //
// Copyright (C) 2014-2019 Kimura Ryo                                  //
//                                                                     //
// 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/.            //
// =================================================================== //

#include "RenderingWidget.h"

#include <QtWidgets>
#include <QtCore/QMimeData>
#include <QtCore/QUrl>

#include <osg/ShapeDrawable>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgUtil/Optimizer>

#include "SceneUtil.h"

RenderingWidget::RenderingWidget(const QGLFormat&   format,
                                 QWidget*           parent,
                                 const QGLWidget*   shareWidget,
                                 Qt::WindowFlags    f,
                                 bool               forwardKeyEvents)
                                 : osgQt::GLWidget(format, parent, shareWidget, f, forwardKeyEvents),
                                   renderingScene_(0),
                                   mouseMoved_(false),
                                   pickedInDir_(0.0, 0.0, 0.0)
{
    //setAcceptDrops(true);
    setMinimumSize(1, 1);

    actionResetCamera_ = new QAction(this);
    actionResetCamera_->setText(QApplication::translate("RenderingWidget", "Reset camera position", 0));
    connect(actionResetCamera_, SIGNAL(triggered()), this, SLOT(resetCameraPosition()));

    actionShapeSphere_ = new QAction(this);
    actionShapeSphere_->setText(QApplication::translate("RenderingWidget", "Sphere", 0));
    connect(actionShapeSphere_, SIGNAL(triggered()), this, SLOT(showSphere()));

    actionShapeCylinder_ = new QAction(this);
    actionShapeCylinder_->setText(QApplication::translate("RenderingWidget", "Cylinder", 0));
    connect(actionShapeCylinder_, SIGNAL(triggered()), this, SLOT(showCylinder()));

    actionShapeBox_ = new QAction(this);
    actionShapeBox_->setText(QApplication::translate("RenderingWidget", "Box", 0));
    connect(actionShapeBox_, SIGNAL(triggered()), this, SLOT(showBox()));

    actionShapeOpen_ = new QAction(this);
    actionShapeOpen_->setText(QApplication::translate("RenderingWidget", "Open...", 0));
    connect(actionShapeOpen_, SIGNAL(triggered()), this, SLOT(showLoadedModel()));
}

void RenderingWidget::resetCameraPosition()
{
    if (!renderingScene_) return;

    osgGA::CameraManipulator* cm = renderingScene_->getCameraManipulator();

    RenderingScene::fitCameraPosition(renderingScene_->getCamera(),
                                      osg::Vec3(0.0, -1.0, 0.0),
                                      osg::Vec3(0.0, 0.0, 1.0),
                                      renderingScene_->getScene());

    osg::Vec3d eye, center, up;
    renderingScene_->getCamera()->getViewMatrixAsLookAt(eye, center, up);
    center = scene_util::computeCenter(renderingScene_->getScene());
    cm->setHomePosition(eye, center, up);
    cm->home(0.0);
}

void RenderingWidget::showSphere()
{
    renderingScene_->getScene()->removeChildren(0, renderingScene_->getScene()->getNumChildren());

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(), 1.0f)));
    renderingScene_->getScene()->addChild(geode);
}

void RenderingWidget::showCylinder()
{
    renderingScene_->getScene()->removeChildren(0, renderingScene_->getScene()->getNumChildren());

    osg::Geode* geode = new osg::Geode;
    osg::Cylinder* cylinder = new osg::Cylinder(osg::Vec3(), 1.0f, 2.0f);
    osg::Quat rotQuat(M_PI / 2.0, osg::Vec3(0.0, 1.0, 0.0));
    cylinder->setRotation(rotQuat);
    geode->addDrawable(new osg::ShapeDrawable(cylinder));
    renderingScene_->getScene()->addChild(geode);
}

void RenderingWidget::showBox()
{
    renderingScene_->getScene()->removeChildren(0, renderingScene_->getScene()->getNumChildren());

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(), 1.5f)));
    renderingScene_->getScene()->addChild(geode);
}

void RenderingWidget::showLoadedModel()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Model File"), QString(),
                                                    tr("Obj Files (*.obj)"));

    if (fileName.isEmpty()) return;

    openModel(fileName);
    resetCameraPosition();
}

void RenderingWidget::resizeEvent(QResizeEvent* event)
{
    osgQt::GLWidget::resizeEvent(event);

    if (renderingScene_) {
        renderingScene_->updateView(event->size().width(), event->size().height());
    }
}

void RenderingWidget::keyPressEvent(QKeyEvent* event)
{
    osgQt::GLWidget::keyPressEvent(event);

    if (!renderingScene_) return;

    osgGA::CameraManipulator* cm = renderingScene_->getCameraManipulator();
    osgGA::TrackballManipulator* tm = dynamic_cast<osgGA::TrackballManipulator*>(cm);

    osg::Vec3 camPos, camCenter, camUp;
    renderingScene_->getCamera()->getViewMatrixAsLookAt(camPos, camCenter, camUp);
    osg::Vec3 camDir = camPos - camCenter;
    camDir.normalize();

    switch (event->key()) {
        case Qt::Key_Up: {
            if (!tm) break;

            osg::Vec3 rotAxis = camDir ^ camUp;
            osg::Quat rotQuat(M_PI / 180.0, rotAxis);
            tm->setRotation(tm->getRotation() * rotQuat);

            break;
        }
        case Qt::Key_Down: {
            if (!tm) break;

            osg::Vec3 rotAxis = camDir ^ camUp;
            osg::Quat rotQuat(-M_PI / 180.0, rotAxis);
            tm->setRotation(tm->getRotation() * rotQuat);

            break;
        }
        case Qt::Key_Left: {
            if (!tm) break;

            osg::Vec3 rotAxis(0.0, 0.0, 1.0);
            osg::Quat rotQuat(-M_PI / 180.0, rotAxis);
            tm->setRotation(tm->getRotation() * rotQuat);

            break;
        }
        case Qt::Key_Right: {
            if (!tm) break;

            osg::Vec3 rotAxis(0.0, 0.0, 1.0);
            osg::Quat rotQuat(M_PI / 180.0, rotAxis);
            tm->setRotation(tm->getRotation() * rotQuat);

            break;
        }
        case Qt::Key_Plus: {
            if (!tm) break;

            tm->setDistance(tm->getDistance() * 0.9);

            break;
        }
        case Qt::Key_Minus: {
            if (!tm) break;

            tm->setDistance(tm->getDistance() * 1.0 / 0.9);

            break;
        }
        default: {
            break;
        }
    }
}

void RenderingWidget::mouseMoveEvent(QMouseEvent* event)
{
    osgQt::GLWidget::mouseMoveEvent(event);
    mouseMoved_ = true;
}

void RenderingWidget::mousePressEvent(QMouseEvent* event)
{
    osgQt::GLWidget::mousePressEvent(event);
    mouseMoved_ = false;
}

void RenderingWidget::mouseReleaseEvent(QMouseEvent* event)
{
    osgQt::GLWidget::mouseReleaseEvent(event);

    if (event->button() == Qt::LeftButton && !mouseMoved_) {
        if (!renderingScene_) return;

        int x = event->pos().x();
        int y = event->pos().y();

        lb::Vec3 inDir = renderingScene_->getInDir(x, y);
        lb::Vec3 outDir = renderingScene_->getOutDir(x, y);
        if (inDir.isZero() || outDir.isZero()) {
            pickedInDir_ = lb::Vec3::Zero();
            emit inOutDirPicked(lb::Vec3::Zero(), lb::Vec3::Zero());
            return;
        }

        const lb::Brdf* brdf = renderingScene_->getBrdf();
        const lb::SampleSet2D* ss2 = renderingScene_->getReflectance();

        if (brdf) {
            if (brdf->getSampleSet()->isIsotropic()) {
                float inTheta, outTheta, outPhi;
                lb::SphericalCoordinateSystem::fromXyz(inDir, outDir, &inTheta, &outTheta, &outPhi);
                lb::SphericalCoordinateSystem::toXyz(inTheta, 0.0f, outTheta, outPhi, &inDir, &outDir);
            }

            lb::Spectrum sp = brdf->getSpectrum(inDir, outDir);
            lbDebug << "[RenderingWidget::mouseReleaseEvent] Spectrum: " << sp.format(lb::EIGEN_IO_FMT);
        }
        else if (ss2) {
            if (ss2->isIsotropic()) {
                float theta, phi;
                lb::SphericalCoordinateSystem::fromXyz(outDir, &theta, &phi);
                outDir = lb::SphericalCoordinateSystem::toXyz(theta, lb::PI_F);
            }

            inDir = lb::reflect(outDir, lb::Vec3(0.0, 0.0, 1.0));
        }

        pickedInDir_ = inDir;
        emit inOutDirPicked(inDir, outDir);
    }
#ifdef __APPLE__
    else if (event->button() == Qt::RightButton && !mouseMoved_) {
        showContextMenu(event->globalPos());
    }
#endif
}

void RenderingWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
    osgQt::GLWidget::mouseDoubleClickEvent(event);

    if (!pickedInDir_.isZero()) {
        emit inDirPicked(pickedInDir_);
    }
}

void RenderingWidget::dragEnterEvent(QDragEnterEvent* event)
{
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

void RenderingWidget::dropEvent(QDropEvent* event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    QString fileName = urls.front().toLocalFile();
    openModel(fileName);
}

void RenderingWidget::wheelEvent(QWheelEvent* event)
{
    osgQt::GLWidget::wheelEvent(event);
    mouseMoved_ = true;
}

void RenderingWidget::contextMenuEvent(QContextMenuEvent* event)
{
    osgQt::GLWidget::contextMenuEvent(event);

#ifndef __APPLE__
    if (mouseMoved_) return;

    showContextMenu(event->globalPos());
#endif
}

void RenderingWidget::showContextMenu(const QPoint& pos)
{
    QMenu menu(this);
    menu.addAction(actionResetCamera_);

    QMenu* shapeMenu = menu.addMenu(tr("Shape"));
    shapeMenu->addAction(actionShapeSphere_);
    shapeMenu->addAction(actionShapeCylinder_);
    shapeMenu->addAction(actionShapeBox_);
    shapeMenu->addAction(actionShapeOpen_);

    menu.exec(pos);
}

void RenderingWidget::openModel(const QString& fileName)
{
    osg::Node* loadedModel = osgDB::readNodeFile(fileName.toLocal8Bit().data());
    if (!loadedModel) {
        QMessageBox::warning(this, tr("BSDF Processor"),
                             tr("Failed to load \"") + fileName + "\"",
                             QMessageBox::Ok);
        return;
    }

    renderingScene_->getScene()->removeChildren(0, renderingScene_->getScene()->getNumChildren());

    osgUtil::Optimizer optimzer;
    optimzer.optimize(loadedModel, osgUtil::Optimizer::ALL_OPTIMIZATIONS);
    renderingScene_->getScene()->addChild(loadedModel);
}
<|endoftext|>


<commit_before>#include <UnitTest/stdafx.h>
#include <UnitTest/UnitTest.h>
#include <core/utility/file.h>

namespace filetest
{
	TEST_CLASS(filetest)
	{
	public:
		// Without this, clang gets weird
		static const bool dummy_var = true;

		TEST_CLASS_INITIALIZE(initialize) { unittest::init(); }

		TEST_METHOD(Test_GetSystemDirectory)
		{
			// This test is likely not portable
			unittest::AreEqualEx(L"c:\\windows\\system32", strings::wstringToLower(file::GetSystemDirectory()));
		}

		TEST_METHOD(Test_ShortenPath)
		{
			unittest::AreEqualEx(L"", file::ShortenPath(L""));
			unittest::AreEqualEx(
				L"c:\\thisisafakepath\\thisisanotherfakepath",
				strings::wstringToLower(file::ShortenPath(L"C:\\thisIsAFakePath\\thisIsAnotherFakePath")));
			// This test is likely not portable
			unittest::AreEqualEx(
				L"c:\\progra~1\\common~1\\",
				strings::wstringToLower(file::ShortenPath(L"C:\\Program Files\\Common Files")));
			// This test is likely not portable
			unittest::AreEqualEx(
				L"c:\\progra~2\\common~1\\",
				strings::wstringToLower(file::ShortenPath(L"C:\\Program Files (x86)\\Common Files")));
		}

		TEST_METHOD(Test_BuildFileNameAndPath)
		{
			unittest::AreEqualEx(
				L"c:\\testpath\\subject.xml", file::BuildFileNameAndPath(L".xml", L"subject", L"c:\\testpath\\", NULL));
			unittest::AreEqualEx(
				L"c:\\testpath\\UnknownSubject.xml", file::BuildFileNameAndPath(L".xml", L"", L"c:\\testpath\\", NULL));
			unittest::AreEqualEx(
				L"c:\\testpath\\Now is the time for all good men to come to the aid of the party. This is the way the "
				L"world ends. Not with a bang but with a whimper. So long and thanks for all the fish. That's great it "
				L"starts with an earthquake_ birds and snakes an.xml",
				file::BuildFileNameAndPath(
					L".xml",
					L"Now is the time for all good men to come to the aid of the party. This is the way the world "
					L"ends. Not with a bang but with a whimper. So long and thanks for all the fish. That's great it "
					L"starts with an earthquake, birds and snakes and aeroplanes. Lenny Bruce is not afraid.",
					L"c:\\testpath\\",
					NULL));
			unittest::AreEqualEx(
				L"",
				file::BuildFileNameAndPath(
					L".xml",
					L"subject",
					L"c:\\Now is the time for all good men to come to the aid of the party. This is the way the world "
					L"ends. Not with a bang but with a whimper. So long and thanks for all the fish. That's great it "
					L"starts with an earthquake, birds and snakes and aeroplanes. Lenny Bruce is not afraid.",
					NULL));
		}

		TEST_METHOD(Test_GetModuleFileName)
		{
			unittest::AreEqualEx(
				L"c:\\windows\\system32\\ntdll.dll",
				strings::wstringToLower(file::GetModuleFileName(::GetModuleHandleW(L"ntdll.dll"))));
			unittest::AreEqualEx(L"", file::GetModuleFileName(HMODULE(0x1234)));
		}

		TEST_METHOD(Test_GetFileVersionInfo)
		{
			auto fi1 = file::GetFileVersionInfo(::GetModuleHandleW(NULL));
			unittest::AreEqualEx(L"Microsoft Corporation", fi1[L"CompanyName"]);
			unittest::AreEqualEx(L"© Microsoft Corporation. All rights reserved.", fi1[L"LegalCopyright"]);

			auto fi2 = file::GetFileVersionInfo(::GetModuleHandleW(L"ntdll.dll"));
			unittest::AreEqualEx(L"Microsoft Corporation", fi2[L"CompanyName"]);
			unittest::AreEqualEx(L"NT Layer DLL", fi2[L"FileDescription"]);
			unittest::AreEqualEx(L"Microsoft® Windows® Operating System", fi2[L"ProductName"]);
		}
	};
} // namespace filetest<commit_msg>more coverage<commit_after>#include <UnitTest/stdafx.h>
#include <UnitTest/UnitTest.h>
#include <core/utility/file.h>

namespace filetest
{
	TEST_CLASS(filetest)
	{
	public:
		// Without this, clang gets weird
		static const bool dummy_var = true;

		TEST_CLASS_INITIALIZE(initialize) { unittest::init(); }

		TEST_METHOD(Test_GetSystemDirectory)
		{
			// This test is likely not portable
			unittest::AreEqualEx(L"c:\\windows\\system32", strings::wstringToLower(file::GetSystemDirectory()));
		}

		TEST_METHOD(Test_ShortenPath)
		{
			unittest::AreEqualEx(L"", file::ShortenPath(L""));
			unittest::AreEqualEx(
				L"c:\\thisisafakepath\\thisisanotherfakepath",
				strings::wstringToLower(file::ShortenPath(L"C:\\thisIsAFakePath\\thisIsAnotherFakePath")));
			// This test is likely not portable
			unittest::AreEqualEx(
				L"c:\\progra~1\\common~1\\",
				strings::wstringToLower(file::ShortenPath(L"C:\\Program Files\\Common Files")));
			// This test is likely not portable
			unittest::AreEqualEx(
				L"c:\\progra~2\\common~1\\",
				strings::wstringToLower(file::ShortenPath(L"C:\\Program Files (x86)\\Common Files")));
		}

		TEST_METHOD(Test_BuildFileNameAndPath)
		{
			unittest::AreEqualEx(
				L"c:\\testpath\\subject.xml", file::BuildFileNameAndPath(L".xml", L"subject", L"c:\\testpath\\", NULL));
			unittest::AreEqualEx(
				L"c:\\testpath\\UnknownSubject.xml", file::BuildFileNameAndPath(L".xml", L"", L"c:\\testpath\\", NULL));
			std::wstring binStr = L"binstr";
			auto bin = SBinary{
				static_cast<ULONG>(binStr.length() * sizeof(WCHAR)),
				reinterpret_cast<LPBYTE>(const_cast<WCHAR*>(binStr.c_str()))};

			unittest::AreEqualEx(
				L"c:\\testpath\\subject_620069006E00730074007200.xml", file::BuildFileNameAndPath(L".xml", L"subject", L"c:\\testpath\\", &bin));
			unittest::AreEqualEx(
				L"c:\\testpath\\Now is the time for all good men to come to the aid of the party. This is the way the "
				L"world ends. Not with a bang but with a whimper. So long and thanks for all the fish. That's great it "
				L"starts with an earthquake_ birds and snakes an.xml",
				file::BuildFileNameAndPath(
					L".xml",
					L"Now is the time for all good men to come to the aid of the party. This is the way the world "
					L"ends. Not with a bang but with a whimper. So long and thanks for all the fish. That's great it "
					L"starts with an earthquake, birds and snakes and aeroplanes. Lenny Bruce is not afraid.",
					L"c:\\testpath\\",
					NULL));
			unittest::AreEqualEx(
				L"",
				file::BuildFileNameAndPath(
					L".xml",
					L"subject",
					L"c:\\Now is the time for all good men to come to the aid of the party. This is the way the world "
					L"ends. Not with a bang but with a whimper. So long and thanks for all the fish. That's great it "
					L"starts with an earthquake, birds and snakes and aeroplanes. Lenny Bruce is not afraid.",
					NULL));
		}

		TEST_METHOD(Test_GetModuleFileName)
		{
			unittest::AreEqualEx(
				L"c:\\windows\\system32\\ntdll.dll",
				strings::wstringToLower(file::GetModuleFileName(::GetModuleHandleW(L"ntdll.dll"))));
			unittest::AreEqualEx(L"", file::GetModuleFileName(HMODULE(0x1234)));
		}

		TEST_METHOD(Test_GetFileVersionInfo)
		{
			auto fi1 = file::GetFileVersionInfo(::GetModuleHandleW(NULL));
			unittest::AreEqualEx(L"Microsoft Corporation", fi1[L"CompanyName"]);
			unittest::AreEqualEx(L"© Microsoft Corporation. All rights reserved.", fi1[L"LegalCopyright"]);

			auto fi2 = file::GetFileVersionInfo(::GetModuleHandleW(L"ntdll.dll"));
			unittest::AreEqualEx(L"Microsoft Corporation", fi2[L"CompanyName"]);
			unittest::AreEqualEx(L"NT Layer DLL", fi2[L"FileDescription"]);
			unittest::AreEqualEx(L"Microsoft® Windows® Operating System", fi2[L"ProductName"]);
		}
	};
} // namespace filetest<|endoftext|>


<commit_before>#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define SV_NAME "slp-vectorizer"
static cl::opt<int>
    SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
                     cl::desc("Only vectorize if you gain more than this "
                              "number "));
static cl::opt<bool>
ShouldVectorizeHor("slp-vectorize-hor", cl::init(false), cl::Hidden,
    cl::desc(
        "Attempt to vectorize horizontal reductions feeding into a store"));
namespace {
static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
                                    TargetLibraryInfo *TLI) {
  unsigned Opcode = UserInst->getOpcode();
  switch (Opcode) {
  case Instruction::Load: {
  }
  }
}
class BoUpSLP {
public:
  typedef SmallVector<Value *, 8> ValueList;
  BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
          TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
          DominatorTree *Dt, AssumptionCache *AC)
      : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
        Builder(Se->getContext()) {
  }
  int getTreeCost();
  void buildTree(ArrayRef<Value *> Roots,
                 ArrayRef<Value *> UserIgnoreLst = None);
  void deleteTree() {
    for (auto &Iter : BlocksSchedules) {
    }
  }
  bool shouldReorder() const {
  }
  struct TreeEntry {
    ValueList Scalars;
  };
  TreeEntry *newTreeEntry(ArrayRef<Value *> VL, bool Vectorized) {
    if (Vectorized) {
    }
  }
  std::vector<TreeEntry> VectorizableTree;
  SmallDenseMap<Value*, int> ScalarToTreeEntry;
  struct ExternalUser {
    Value *Scalar;
    int Lane;
  };
  typedef SmallVector<ExternalUser, 16> UserList;
  bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
                 Instruction *Inst2) {
    AliasCacheKey key = std::make_pair(Inst1, Inst2);
    Optional<bool> &result = AliasCache[key];
    if (result.hasValue()) {
    }
  }
  typedef std::pair<Instruction *, Instruction *> AliasCacheKey;
  DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
  UserList ExternalUses;
  SetVector<Instruction *> GatherSeq;
  SetVector<BasicBlock *> CSEBlocks;
  struct ScheduleData {
  };
  struct BlockScheduling {
    ScheduleData *getScheduleData(Value *V) {
    }
    template <typename ReadyListType>
    void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
      ScheduleData *BundleMember = SD;
      while (BundleMember) {
      }
    }
    void initScheduleData(Instruction *FromI, Instruction *ToI,
                          ScheduleData *NextLoadStore);
    struct ReadyList : SmallVector<ScheduleData *, 8> {
    };
  };
  MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
  int NumLoadsWantToKeepOrder;
  int NumLoadsWantToChangeOrder;
  Function *F;
  TargetTransformInfo *TTI;
  TargetLibraryInfo *TLI;
  DominatorTree *DT;
  IRBuilder<> Builder;
};
void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
                        ArrayRef<Value *> UserIgnoreLst) {
  for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
    TreeEntry *Entry = &VectorizableTree[EIdx];
    for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
      Value *Scalar = Entry->Scalars[Lane];
      for (User *U : Scalar->users()) {
        Instruction *UserInst = dyn_cast<Instruction>(U);
        if (ScalarToTreeEntry.count(U)) {
          int Idx = ScalarToTreeEntry[U];
          TreeEntry *UseEntry = &VectorizableTree[Idx];
          Value *UseScalar = UseEntry->Scalars[0];
          if (UseScalar != U ||
              !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
          }
        }
      }
    }
  }
}
int BoUpSLP::getTreeCost() {
  unsigned BundleWidth = VectorizableTree[0].Scalars.size();
  for (unsigned i = 0, e = VectorizableTree.size(); i != e; ++i) {
  }
  int ExtractCost = 0;
  for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
       I != E; ++I) {
    VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
    ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
                                           I->Lane);
  }
}
struct SLPVectorizer : public FunctionPass {
  static char ID;
  explicit SLPVectorizer() : FunctionPass(ID) {
  }
  ScalarEvolution *SE;
  TargetTransformInfo *TTI;
  TargetLibraryInfo *TLI;
  AliasAnalysis *AA;
  LoopInfo *LI;
  DominatorTree *DT;
  AssumptionCache *AC;
  bool runOnFunction(Function &F) override {
    SE = &getAnalysis<ScalarEvolution>();
    TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
    bool Changed = false;
    if (!TTI->getNumberOfRegisters(true))
      return false;
    BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC);
    for (auto BB : post_order(&F.getEntryBlock())) {
      Changed |= vectorizeChainsInBlock(BB, R);
    }
  }
  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.addRequired<ScalarEvolution>();
    AU.addRequired<TargetTransformInfoWrapperPass>();
  }
  bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
  bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
                          ArrayRef<Value *> BuildVector = None,
                          bool allowReorder = false);
  bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
  bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
};
bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
  Value *VL[] = { A, B };
  return tryToVectorizeList(VL, R, None, true);
}
bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
                                       ArrayRef<Value *> BuildVector,
                                       bool allowReorder) {
  Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  if (!I0)
    return false;
  for (unsigned i = 0, e = VL.size(); i < e; ++i) {
    unsigned OpsWidth = 0;
    DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
                 << "\n");
    ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
    if (allowReorder && R.shouldReorder()) {
      Value *ReorderedOps[] = { Ops[1], Ops[0] };
      R.buildTree(ReorderedOps, None);
    }
    int Cost = R.getTreeCost();
    if (Cost < -SLPCostThreshold) {
    }
  }
}
bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
  BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
  BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
  if (B && B->hasOneUse()) {
    BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
    if (tryToVectorizePair(A0, B, R)) {
    }
  }
}
static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
                                   bool IsPairwise, bool IsLeft,
                                   IRBuilder<> &Builder) {
}
class HorizontalReduction {
  SmallVector<Value *, 32> ReducedVals;
  BinaryOperator *ReductionRoot;
  unsigned ReductionOpcode;
  unsigned ReduxWidth;
  bool IsPairwiseReduction;
public:
  bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
    assert((!Phi ||
            std::find(Phi->op_begin(), Phi->op_end(), B) != Phi->op_end()) &&
           "Thi phi needs to use the binary operator");
    SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
    while (!Stack.empty()) {
    }
  }
  bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
    unsigned NumReducedVals = ReducedVals.size();
    unsigned i = 0;
    for (; i < NumReducedVals - ReduxWidth + 1; i += ReduxWidth) {
    }
  }
  Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder) {
    Value *TmpVec = VectorizedValue;
    for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
      if (IsPairwiseReduction) {
        Value *RightMask =
          createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
        Value *RightShuf = Builder.CreateShuffleVector(
          TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
                             "bin.rdx");
        Value *UpperHalf =
          createRdxShuffleMask(ReduxWidth, i, false, false, Builder);
        Value *Shuf = Builder.CreateShuffleVector(
          TmpVec, UndefValue::get(TmpVec->getType()), UpperHalf, "rdx.shuf");
      }
    }
  }
};
bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
  bool HaveVectorizedPhiNodes = true;
  while (HaveVectorizedPhiNodes) {
    HaveVectorizedPhiNodes = false;
    for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
         ++instr) {
    }
  }
  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
    if (PHINode *P = dyn_cast<PHINode>(it)) {
      Value *Rdx =
          (P->getIncomingBlock(0) == BB
               ? (P->getIncomingValue(0))
               : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
                                               : nullptr));
      BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
     Value *Inst = BI->getOperand(0);
      if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
      }
    }
      if (StoreInst *SI = dyn_cast<StoreInst>(it))
        if (BinaryOperator *BinOp =
                dyn_cast<BinaryOperator>(SI->getValueOperand())) {
          HorizontalReduction HorRdx;
          if (((HorRdx.matchAssociativeReduction(nullptr, BinOp) &&
                HorRdx.tryToReduce(R, TTI)) ||
               tryToVectorize(BinOp, R))) {
          }
        }
    if (ReturnInst *RI = dyn_cast<ReturnInst>(it))
        if (BinaryOperator *BinOp =
                dyn_cast<BinaryOperator>(RI->getOperand(0))) {
        }
    if (CmpInst *CI = dyn_cast<CmpInst>(it)) {
      for (int i = 0; i < 2; ++i) {
        if (BinaryOperator *BI = dyn_cast<BinaryOperator>(CI->getOperand(i))) {
        }
      }
      SmallVector<Value *, 16> BuildVector;
      SmallVector<Value *, 16> BuildVectorOpds;
      if (tryToVectorizeList(BuildVectorOpds, R, BuildVector)) {
      }
    }
  }
}
} // end anonymous namespace
char SLPVectorizer::ID = 0;
static const char lv_name[] = "SLP Vectorizer";
INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
namespace llvm {
Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
}
<commit_msg>Another round of reductions<commit_after>#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
namespace {
class BoUpSLP {
public:
  typedef SmallVector<Value *, 8> ValueList;
  BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
          TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
          DominatorTree *Dt, AssumptionCache *AC)
      : NumLoadsWantToKeepOrder(0), NumLoadsWantToChangeOrder(0), F(Func),
        Builder(Se->getContext()) {
  }
  void getTreeCost();
  void buildTree(ArrayRef<Value *> Roots,
                 ArrayRef<Value *> UserIgnoreLst = None);
  bool shouldReorder() const {
  }
  struct TreeEntry {
    ValueList Scalars;
  };
  std::vector<TreeEntry> VectorizableTree;
  SmallDenseMap<Value*, int> ScalarToTreeEntry;
  struct ExternalUser {
    Value *Scalar;
    int Lane;
  };
  typedef SmallVector<ExternalUser, 16> UserList;
  UserList ExternalUses;
  SetVector<Instruction *> GatherSeq;
  struct ScheduleData {
  };
  struct BlockScheduling {
    ScheduleData *getScheduleData(Value *V) {
    }
    template <typename ReadyListType>
    void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
    }
  };
  int NumLoadsWantToKeepOrder;
  int NumLoadsWantToChangeOrder;
  Function *F;
  TargetTransformInfo *TTI;
  TargetLibraryInfo *TLI;
  DominatorTree *DT;
  IRBuilder<> Builder;
};
void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
                        ArrayRef<Value *> UserIgnoreLst) {
  for (int EIdx = 0, EE = VectorizableTree.size(); EIdx < EE; ++EIdx) {
    TreeEntry *Entry = &VectorizableTree[EIdx];
    for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
      Value *Scalar = Entry->Scalars[Lane];
      for (User *U : Scalar->users()) {
        if (ScalarToTreeEntry.count(U)) {
        }
      }
    }
  }
}
void BoUpSLP::getTreeCost() {
  unsigned BundleWidth = VectorizableTree[0].Scalars.size();
  int ExtractCost = 0;
  for (UserList::iterator I = ExternalUses.begin(), E = ExternalUses.end();
       I != E; ++I) {
    VectorType *VecTy = VectorType::get(I->Scalar->getType(), BundleWidth);
    ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
                                           I->Lane);
  }
}
struct SLPVectorizer : public FunctionPass {
  static char ID;
  explicit SLPVectorizer() : FunctionPass(ID) {
  }
  ScalarEvolution *SE;
  TargetTransformInfo *TTI;
  TargetLibraryInfo *TLI;
  AliasAnalysis *AA;
  LoopInfo *LI;
  DominatorTree *DT;
  AssumptionCache *AC;
  bool runOnFunction(Function &F) override {
    SE = &getAnalysis<ScalarEvolution>();
    TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
    bool Changed = false;
    if (!TTI->getNumberOfRegisters(true))
      return false;
    BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC);
    for (auto BB : post_order(&F.getEntryBlock())) {
      Changed |= vectorizeChainsInBlock(BB, R);
    }
  }
  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.addRequired<ScalarEvolution>();
    AU.addRequired<TargetTransformInfoWrapperPass>();
  }
  bool tryToVectorizePair(Value *A, Value *B, BoUpSLP &R);
  bool tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
                          ArrayRef<Value *> BuildVector = None,
                          bool allowReorder = false);
  bool tryToVectorize(BinaryOperator *V, BoUpSLP &R);
  bool vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R);
};
bool SLPVectorizer::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
  Value *VL[] = { A, B };
  return tryToVectorizeList(VL, R, None, true);
}
bool SLPVectorizer::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
                                       ArrayRef<Value *> BuildVector,
                                       bool allowReorder) {
  Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  if (!I0)
    return false;
  for (unsigned i = 0, e = VL.size(); i < e; ++i) {
    unsigned OpsWidth = 0;
    DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
                 << "\n");
    ArrayRef<Value *> Ops = VL.slice(i, OpsWidth);
    if (allowReorder && R.shouldReorder()) {
      Value *ReorderedOps[] = { Ops[1], Ops[0] };
      R.buildTree(ReorderedOps, None);
    }
    R.getTreeCost();
  }
}
bool SLPVectorizer::tryToVectorize(BinaryOperator *V, BoUpSLP &R) {
  BinaryOperator *A = dyn_cast<BinaryOperator>(V->getOperand(0));
  BinaryOperator *B = dyn_cast<BinaryOperator>(V->getOperand(1));
  if (B && B->hasOneUse()) {
    BinaryOperator *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
    if (tryToVectorizePair(A0, B, R)) {
    }
  }
}
class HorizontalReduction {
public:
  bool matchAssociativeReduction(PHINode *Phi, BinaryOperator *B) {
    SmallVector<std::pair<BinaryOperator *, unsigned>, 32> Stack;
    while (!Stack.empty()) {
    }
  }
  bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
  }
};
bool SLPVectorizer::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
  bool HaveVectorizedPhiNodes = true;
  while (HaveVectorizedPhiNodes) {
    HaveVectorizedPhiNodes = false;
    for (BasicBlock::iterator instr = BB->begin(), ie = BB->end(); instr != ie;
         ++instr) {
    }
  }
  for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
    if (PHINode *P = dyn_cast<PHINode>(it)) {
      Value *Rdx =
          (P->getIncomingBlock(0) == BB
               ? (P->getIncomingValue(0))
               : (P->getIncomingBlock(1) == BB ? P->getIncomingValue(1)
                                               : nullptr));
      BinaryOperator *BI = dyn_cast_or_null<BinaryOperator>(Rdx);
     Value *Inst = BI->getOperand(0);
      if (tryToVectorize(dyn_cast<BinaryOperator>(Inst), R)) {
      }
    }
      if (StoreInst *SI = dyn_cast<StoreInst>(it))
        if (BinaryOperator *BinOp =
                dyn_cast<BinaryOperator>(SI->getValueOperand())) {
          HorizontalReduction HorRdx;
          if (((HorRdx.matchAssociativeReduction(nullptr, BinOp) &&
                HorRdx.tryToReduce(R, TTI)) ||
               tryToVectorize(BinOp, R))) {
          }
        }
    if (dyn_cast<CmpInst>(it)) {
      SmallVector<Value *, 16> BuildVector;
      SmallVector<Value *, 16> BuildVectorOpds;
      tryToVectorizeList(BuildVectorOpds, R, BuildVector);
    }
  }
}
} // end anonymous namespace
char SLPVectorizer::ID = 0;
static const char lv_name[] = "SLP Vectorizer";
INITIALIZE_PASS_BEGIN(SLPVectorizer, "slp-vectorizer", lv_name, false, false)
INITIALIZE_PASS_END(SLPVectorizer, "slp-vectorizer", lv_name, false, false)
namespace llvm {
Pass *createSLPVectorizerPass() { return new SLPVectorizer(); }
}
<|endoftext|>


<commit_before>//
// FormulaEngine Project
// By Mike Lewis - 2015
//
// Project entry point routine
//

#include "Pch.h"

#include "Tests.h"
#include "Simulation.h"

// This is Microsoft-specific for _TCHAR and _tmain.
// The entry point can be trivially rewritten for other
// compilers/platforms, so I'm not putting much effort
// into abstracting away those dependencies for now.
#include <tchar.h>

//
// Entry point for the program
//
int _tmain() {

	// TODO - memory leak checking

	//
	// Optionally run the test suite
	//
	Tests::RunAll();

	//
	// Run the simulation
	//
	Simulation::RunKingdomWar();

	return 0;
}

<commit_msg>Add stubbed out code for leak checking on MSVC<commit_after>//
// FormulaEngine Project
// By Mike Lewis - 2015
//
// Project entry point routine
//

#include "Pch.h"

#include "Tests.h"
#include "Simulation.h"

// This is Microsoft-specific for _TCHAR and _tmain.
// The entry point can be trivially rewritten for other
// compilers/platforms, so I'm not putting much effort
// into abstracting away those dependencies for now.
#include <tchar.h>

//
// Entry point for the program
//
int _tmain() {

	// Optional memory leak checking
	/*
	{
		int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
		flag |= _CRTDBG_LEAK_CHECK_DF;
		_CrtSetDbgFlag(flag);

		_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
		_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
		_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
		_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
		_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
		_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);

		//_CrtSetBreakAlloc(207737);
	}
	*/

	//
	// Optionally run the test suite
	//
	Tests::RunAll();

	//
	// Run the simulation
	//
	Simulation::RunKingdomWar();

	return 0;
}

<|endoftext|>