<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "backend.h"
#include "mediaobject.h"
#include "soundcardcapture.h"
#include "bytestream.h"
#include "audiopath.h"
#include "audioeffect.h"
#include "audiooutput.h"
#include "audiodataoutput.h"
#include "audiofftoutput.h"
#include "videopath.h"
#include "videoeffect.h"

namespace Phonon
{
namespace Fake
{

Backend::Backend( QObject* parent )
	: Ifaces::Backend( parent )
{
}

Backend::~Backend()
{
}

Ifaces::MediaObject*      Backend::createMediaObject( QObject* parent )
{
	return new MediaObject( parent );
}

Ifaces::SoundcardCapture* Backend::createSoundcardCapture( QObject* parent )
{
	//return new SoundcardCapture( parent );
}

Ifaces::ByteStream*       Backend::createByteStream( QObject* parent )
{
	//return new ByteStream( parent );
}

Ifaces::AudioPath*        Backend::createAudioPath( QObject* parent )
{
	return new AudioPath( parent );
}

Ifaces::AudioEffect*      Backend::createAudioEffect( QObject* parent )
{
	//return new AudioEffect( parent );
}

Ifaces::AudioOutput*      Backend::createAudioOutput( QObject* parent )
{
	return new AudioOutput( parent );
}

Ifaces::AudioDataOutput*  Backend::createAudioDataOutput( QObject* parent )
{
	//return new AudioDataOutput( parent );
}

Ifaces::AudioFftOutput*   Backend::createAudioFftOutput( QObject* parent )
{
	//return new AudioFftOutput( parent );
}

Ifaces::VideoPath*        Backend::createVideoPath( QObject* parent )
{
	return new VideoPath( parent );
}

Ifaces::VideoEffect*      Backend::createVideoEffect( QObject* parent )
{
	//return new VideoEffect( parent );
}

bool Backend::supportsVideo() const
{
	return false;
}

bool Backend::supportsOSD() const
{
	return false;
}

bool Backend::supportsSubtitles() const
{
	return false;
}

const KMimeType::List& Backend::knownMimeTypes() const
{
	if( m_supportedMimeTypes.isEmpty() )
		const_cast<Backend*>( this )->m_supportedMimeTypes
			<< KMimeType::mimeType( "audio/vorbis" )
			<< KMimeType::mimeType( "audio/x-mp3" )
			<< KMimeType::mimeType( "audio/x-wav" )
			<< KMimeType::mimeType( "video/x-ogm" );
	return m_supportedMimeTypes;
}

int Backend::captureSourceCount() const
{
	return 2;
}

QString Backend::captureSourceNameForIndex( int index ) const
{
	switch( index )
	{
		case 1:
			return "fake1";
		case 2:
			return "fake2";
		default:
			return QString();
	}
}

QString Backend::captureSourceDescriptionForIndex( int index ) const
{
	switch( index )
	{
		case 1:
			return "first description";
		case 2:
			return "second description";
		default:
			return QString();
	}
}

const QStringList& Backend::availableAudioEffects() const
{
	if( m_audioEffects.isEmpty() )
		const_cast<Backend*>( this )->m_audioEffects << "audioEffect1" << "audioEffect2";
	return m_audioEffects;
}

const QStringList& Backend::availableVideoEffects() const
{
	if( m_videoEffects.isEmpty() )
		const_cast<Backend*>( this )->m_videoEffects << "videoEffect1" << "videoEffect2";
	return m_videoEffects;
}

const char* Backend::uiLibrary() const
{
	return "phonon_fakeui";
}

}}

#include "backend.moc"

// vim: sw=4 ts=4 noet
<commit_msg>SVN_SILENT: those classes are implemented (well fake) now, so let the backend return the instances<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "backend.h"
#include "mediaobject.h"
#include "soundcardcapture.h"
#include "bytestream.h"
#include "audiopath.h"
#include "audioeffect.h"
#include "audiooutput.h"
#include "audiodataoutput.h"
#include "audiofftoutput.h"
#include "videopath.h"
#include "videoeffect.h"

namespace Phonon
{
namespace Fake
{

Backend::Backend( QObject* parent )
	: Ifaces::Backend( parent )
{
}

Backend::~Backend()
{
}

Ifaces::MediaObject*      Backend::createMediaObject( QObject* parent )
{
	return new MediaObject( parent );
}

Ifaces::SoundcardCapture* Backend::createSoundcardCapture( QObject* parent )
{
	return new SoundcardCapture( parent );
}

Ifaces::ByteStream*       Backend::createByteStream( QObject* parent )
{
	return new ByteStream( parent );
}

Ifaces::AudioPath*        Backend::createAudioPath( QObject* parent )
{
	return new AudioPath( parent );
}

Ifaces::AudioEffect*      Backend::createAudioEffect( QObject* parent )
{
	return new AudioEffect( parent );
}

Ifaces::AudioOutput*      Backend::createAudioOutput( QObject* parent )
{
	return new AudioOutput( parent );
}

Ifaces::AudioDataOutput*  Backend::createAudioDataOutput( QObject* parent )
{
	return new AudioDataOutput( parent );
}

Ifaces::AudioFftOutput*   Backend::createAudioFftOutput( QObject* parent )
{
	return new AudioFftOutput( parent );
}

Ifaces::VideoPath*        Backend::createVideoPath( QObject* parent )
{
	return new VideoPath( parent );
}

Ifaces::VideoEffect*      Backend::createVideoEffect( QObject* parent )
{
	return new VideoEffect( parent );
}

bool Backend::supportsVideo() const
{
	return true;
}

bool Backend::supportsOSD() const
{
	return false;
}

bool Backend::supportsSubtitles() const
{
	return false;
}

const KMimeType::List& Backend::knownMimeTypes() const
{
	if( m_supportedMimeTypes.isEmpty() )
		const_cast<Backend*>( this )->m_supportedMimeTypes
			<< KMimeType::mimeType( "audio/vorbis" )
			<< KMimeType::mimeType( "audio/x-mp3" )
			<< KMimeType::mimeType( "audio/x-wav" )
			<< KMimeType::mimeType( "video/x-ogm" );
	return m_supportedMimeTypes;
}

int Backend::captureSourceCount() const
{
	return 2;
}

QString Backend::captureSourceNameForIndex( int index ) const
{
	switch( index )
	{
		case 1:
			return "fake1";
		case 2:
			return "fake2";
		default:
			return QString();
	}
}

QString Backend::captureSourceDescriptionForIndex( int index ) const
{
	switch( index )
	{
		case 1:
			return "first description";
		case 2:
			return "second description";
		default:
			return QString();
	}
}

const QStringList& Backend::availableAudioEffects() const
{
	if( m_audioEffects.isEmpty() )
		const_cast<Backend*>( this )->m_audioEffects << "audioEffect1" << "audioEffect2";
	return m_audioEffects;
}

const QStringList& Backend::availableVideoEffects() const
{
	if( m_videoEffects.isEmpty() )
		const_cast<Backend*>( this )->m_videoEffects << "videoEffect1" << "videoEffect2";
	return m_videoEffects;
}

const char* Backend::uiLibrary() const
{
	return "phonon_fakeui";
}

}}

#include "backend.moc"

// vim: sw=4 ts=4 noet
<|endoftext|>


<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2014, University of Toronto
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the University of Toronto nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Authors: Jonathan Gammell */

#include "ompl/geometric/planners/rrt/InformedRRTstar.h"

ompl::geometric::InformedRRTstar::InformedRRTstar(const base::SpaceInformationPtr &si)
    : RRTstar(si)
{
    //Set my name:
    setName("InformedRRTstar");

    //Configure RRTstar to be InformedRRT*:
    setInformedSampling(true);
    setTreePruning(true);
    setPrunedMeasure(true);

    //Remove those parameters:
    params_.remove("informed_sampling");
    params_.remove("pruned_measure");
    params_.remove("tree_pruning");

    //Remove conflicting parameters:
    params_.remove("sample_rejection");
    params_.remove("new_state_rejection");
    params_.remove("focus_search");
}
<commit_msg>Made Informed RRT* config a little more explicit.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2014, University of Toronto
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the University of Toronto nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Authors: Jonathan Gammell */

#include "ompl/geometric/planners/rrt/InformedRRTstar.h"

ompl::geometric::InformedRRTstar::InformedRRTstar(const base::SpaceInformationPtr &si)
    : RRTstar(si)
{
    //Set my name:
    setName("InformedRRTstar");

    //Configure RRTstar to be InformedRRT*:
    setAdmissibleCostToCome(true);
    setInformedSampling(true);
    setTreePruning(true);
    setPrunedMeasure(true);

    //Disable conflicting options
    setSampleRejection(false);
    setNewStateRejection(false);

    //Remove those parameters:
    params_.remove("use_admissible_heuristic");
    params_.remove("informed_sampling");
    params_.remove("pruned_measure");
    params_.remove("tree_pruning");

    //Remove conflicting parameters:
    params_.remove("sample_rejection");
    params_.remove("new_state_rejection");
    params_.remove("focus_search");
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2016 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#define BOOST_TEST_MODULE path_extraction

#include <boost/test/included/unit_test.hpp>
#include <hpp/fcl/math/transform.h>

#include <hpp/core/path-vector.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/steering-method/straight.hh>

BOOST_AUTO_TEST_SUITE( test_hpp_core )

using hpp::pinocchio::ConfigurationOut_t;
using hpp::pinocchio::Configuration_t;
using hpp::pinocchio::Device;
using hpp::pinocchio::DevicePtr_t;
using hpp::pinocchio::JointPtr_t;
using hpp::pinocchio::JointConstPtr_t;

using namespace hpp::core;

HPP_PREDEF_CLASS (LocalPath);
typedef boost::shared_ptr <LocalPath> LocalPathPtr_t;

class LocalPath : public Path
{
public:
  virtual ~LocalPath () throw () {}
  virtual bool impl_compute
  (ConfigurationOut_t configuration, value_type t) const
  {
    value_type alpha (t-timeRange ().first/
		      (timeRange ().second - timeRange ().first));
    configuration = (1-alpha)*q1_ + alpha * q2_;
    return true;
  }

  static LocalPathPtr_t create (const interval_t& interval)
  {
    LocalPath* ptr (new LocalPath (interval));
    LocalPathPtr_t shPtr (ptr);
    ptr->init (shPtr);
    return shPtr;
  }

  static LocalPathPtr_t createCopy (const LocalPathPtr_t& other)
  {
    LocalPath* ptr (new LocalPath (*other));
    LocalPathPtr_t shPtr (ptr);
    ptr->init (shPtr);
    return shPtr;
  }

  virtual Configuration_t initial () const
  {
    return q1_;
  }

  virtual Configuration_t end () const
  {
    return q2_;
  }

  virtual PathPtr_t copy () const
  {
    return createCopy (weak_.lock ());
  }

  virtual PathPtr_t copy (const ConstraintSetPtr_t&) const
  {
    return createCopy (weak_.lock ());
  }

  virtual std::ostream& print (std::ostream &os) const
  {
    os << "LocalPath between " << q1_ [0] << " and " << q2_ [0];
    return os;
  }
protected:
  LocalPath (const interval_t& interval) : Path (interval, 1,1),
					   q1_ (1), q2_ (1)
  {
    q1_ [0] = interval.first;
    q2_ [0] = interval.second;
  }

  LocalPath (const LocalPath& other) :
    Path (other), q1_ (other.q1_), q2_ (other.q2_)
  {
  }

  void init (LocalPathWkPtr_t wkPtr)
  {
    Path::init (wkPtr.lock ());
    weak_ = wkPtr;
  }

private:
  Configuration_t q1_, q2_;
  LocalPathWkPtr_t weak_;
};

BOOST_AUTO_TEST_CASE (path_extraction_1)
{
  PathVectorPtr_t pv (PathVector::create (1, 1));
  // l0 = 0.52843097738664657
  interval_t inter0 (std::make_pair (0,0.52843097738664657));
  // L0 + l1 = 2.633158413063464
  interval_t inter1 (std::make_pair (0,2.1047274356768177));
  // l0 + l1 + l2 = 3.331454231080471
  interval_t inter2 (std::make_pair (0.6751734883957865,1.3734693064127934));
  // l0 + l1 + l2 + l3 = 4.079212904814735
  interval_t inter3 (std::make_pair (0.83075838111776035, 1.578517054852024));
  LocalPathPtr_t p0 (LocalPath::create (inter0));
  LocalPathPtr_t p1 (LocalPath::create (inter1));
  LocalPathPtr_t p2 (LocalPath::create (inter2));
  LocalPathPtr_t p3 (LocalPath::create (inter3));
  pv->appendPath (p0);
  pv->appendPath (p1);
  pv->appendPath (p2);
  pv->appendPath (p3);

  value_type tmin (3.7487655421722721), tmax (4.0792129048147352);
  PathPtr_t extracted (pv->extract (std::make_pair (tmin, tmax)));
  BOOST_CHECK_EQUAL (extracted->timeRange ().first, 0);
  BOOST_CHECK_CLOSE (extracted->timeRange ().second, tmax - tmin,
      std::numeric_limits <float>::epsilon ());
  BOOST_CHECK_CLOSE (extracted->length (), tmax - tmin,
	       std::numeric_limits <float>::epsilon ());

  extracted = pv->extract (std::make_pair (tmax, tmin));
  BOOST_CHECK_EQUAL (extracted->timeRange ().first, 0);
  BOOST_CHECK_CLOSE (extracted->timeRange ().second, tmax - tmin,
      std::numeric_limits <float>::epsilon ());
  BOOST_CHECK_CLOSE (extracted->length (), tmax - tmin,
	       std::numeric_limits <float>::epsilon ());
}
BOOST_AUTO_TEST_SUITE_END()

<commit_msg>Update test-path-extraction.cc<commit_after>//
// Copyright (c) 2016 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#define BOOST_TEST_MODULE path_extraction

#include <boost/test/included/unit_test.hpp>
#include <hpp/fcl/math/transform.h>

#include <hpp/core/path-vector.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/steering-method/straight.hh>
#include <hpp/core/time-parameterization/polynomial.hh>

BOOST_AUTO_TEST_SUITE( test_hpp_core )

using hpp::pinocchio::ConfigurationOut_t;
using hpp::pinocchio::Configuration_t;
using hpp::pinocchio::Device;
using hpp::pinocchio::DevicePtr_t;
using hpp::pinocchio::JointPtr_t;
using hpp::pinocchio::JointConstPtr_t;

using namespace hpp::core;

HPP_PREDEF_CLASS (LocalPath);
typedef boost::shared_ptr <LocalPath> LocalPathPtr_t;

class LocalPath : public Path
{
public:
  virtual ~LocalPath () throw () {}
  virtual bool impl_compute
  (ConfigurationOut_t configuration, value_type t) const
  {
    value_type alpha (t-timeRange ().first/
		      (timeRange ().second - timeRange ().first));
    configuration = (1-alpha)*q1_ + alpha * q2_;
    return true;
  }

  static LocalPathPtr_t create (const interval_t& interval)
  {
    LocalPath* ptr (new LocalPath (interval));
    LocalPathPtr_t shPtr (ptr);
    ptr->init (shPtr);
    return shPtr;
  }

  static LocalPathPtr_t createCopy (const LocalPathPtr_t& other)
  {
    LocalPath* ptr (new LocalPath (*other));
    LocalPathPtr_t shPtr (ptr);
    ptr->init (shPtr);
    return shPtr;
  }

  virtual Configuration_t initial () const
  {
    return q1_;
  }

  virtual Configuration_t end () const
  {
    return q2_;
  }

  virtual PathPtr_t copy () const
  {
    return createCopy (weak_.lock ());
  }

  virtual PathPtr_t copy (const ConstraintSetPtr_t&) const
  {
    return createCopy (weak_.lock ());
  }

  virtual std::ostream& print (std::ostream &os) const
  {
    os << "LocalPath between " << q1_ [0] << " and " << q2_ [0];
    return os;
  }
protected:
  LocalPath (const interval_t& interval) : Path (interval, 1,1),
					   q1_ (1), q2_ (1)
  {
    q1_ [0] = interval.first;
    q2_ [0] = interval.second;
  }

  LocalPath (const LocalPath& other) :
    Path (other), q1_ (other.q1_), q2_ (other.q2_)
  {
  }

  void init (LocalPathWkPtr_t wkPtr)
  {
    Path::init (wkPtr.lock ());
    weak_ = wkPtr;
  }

private:
  Configuration_t q1_, q2_;
  LocalPathWkPtr_t weak_;
};

BOOST_AUTO_TEST_CASE (path_extraction_1)
{
  PathVectorPtr_t pv (PathVector::create (1, 1));
  // l0 = 0.52843097738664657
  interval_t inter0 (std::make_pair (0,0.52843097738664657));
  // L0 + l1 = 2.633158413063464
  interval_t inter1 (std::make_pair (0,2.1047274356768177));
  // l0 + l1 + l2 = 3.331454231080471
  interval_t inter2 (std::make_pair (0.6751734883957865,1.3734693064127934));
  // l0 + l1 + l2 + l3 = 4.079212904814735
  interval_t inter3 (std::make_pair (0.83075838111776035, 1.578517054852024));
  LocalPathPtr_t p0 (LocalPath::create (inter0));
  LocalPathPtr_t p1 (LocalPath::create (inter1));
  LocalPathPtr_t p2 (LocalPath::create (inter2));
  LocalPathPtr_t p3 (LocalPath::create (inter3));
  pv->appendPath (p0);
  pv->appendPath (p1);
  pv->appendPath (p2);
  pv->appendPath (p3);

  value_type tmin (3.7487655421722721), tmax (4.0792129048147352);
  PathPtr_t extracted (pv->extract (std::make_pair (tmin, tmax)));
  BOOST_CHECK_EQUAL (extracted->timeRange ().first, 0);
  BOOST_CHECK_CLOSE (extracted->timeRange ().second, tmax - tmin,
      std::numeric_limits <float>::epsilon ());
  BOOST_CHECK_CLOSE (extracted->length (), tmax - tmin,
	       std::numeric_limits <float>::epsilon ());

  extracted = pv->extract (std::make_pair (tmax, tmin));
  BOOST_CHECK_EQUAL (extracted->timeRange ().first, 0);
  BOOST_CHECK_CLOSE (extracted->timeRange ().second, tmax - tmin,
      std::numeric_limits <float>::epsilon ());
  BOOST_CHECK_CLOSE (extracted->length (), tmax - tmin,
	       std::numeric_limits <float>::epsilon ());
}

BOOST_AUTO_TEST_CASE (path_extraction_2)
{
  PathVectorPtr_t pv (PathVector::create (1, 1));
  // l0 = 0.52843097738664657
  interval_t inter0 (std::make_pair (0,0.52843097738664657));
  // L0 + l1 = 2.633158413063464
  interval_t inter1 (std::make_pair (0,2.1047274356768177));
  // l0 + l1 + l2 = 3.331454231080471
  interval_t inter2 (std::make_pair (0.6751734883957865,1.3734693064127934));
  // l0 + l1 + l2 + l3 = 4.079212904814735
  interval_t inter3 (std::make_pair (0.83075838111776035, 1.578517054852024));
  LocalPathPtr_t p0 (LocalPath::create (inter0));
  LocalPathPtr_t p1 (LocalPath::create (inter1));
  LocalPathPtr_t p2 (LocalPath::create (inter2));
  vector_t a(2); a << 0, 0.5;
  p2->timeParameterization (
      TimeParameterizationPtr_t(new timeParameterization::Polynomial(a)),
      interval_t (0, 2 * p2->length())
      );
  LocalPathPtr_t p3 (LocalPath::create (inter3));
  pv->appendPath (p0);
  pv->appendPath (p1);
  pv->appendPath (p2);
  pv->appendPath (p3);

  value_type tmin (3.7487655421722721), tmax (4.0792129048147352);
  PathPtr_t extracted (pv->extract (std::make_pair (tmin, tmax)));
  BOOST_CHECK_EQUAL (extracted->timeRange ().first, 0);
  BOOST_CHECK_CLOSE (extracted->timeRange ().second, tmax - tmin,
      std::numeric_limits <float>::epsilon ());
  BOOST_CHECK_CLOSE (extracted->length (), tmax - tmin,
	       std::numeric_limits <float>::epsilon ());

  extracted = pv->extract (std::make_pair (tmax, tmin));
  BOOST_CHECK_EQUAL (extracted->timeRange ().first, 0);
  BOOST_CHECK_CLOSE (extracted->timeRange ().second, tmax - tmin,
      std::numeric_limits <float>::epsilon ());
  BOOST_CHECK_CLOSE (extracted->length (), tmax - tmin,
	       std::numeric_limits <float>::epsilon ());
}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"

using namespace mfem;

namespace ceed_test
{

double coeff_function(const Vector &x)
{
   return 1.0 + x[0]*x[0];
}

// Velocity coefficient
void velocity_function(const Vector &x, Vector &v)
{
   int dim = x.Size();
   switch (dim)
   {
      case 1: v(0) = 1.0; break;
      case 2: v(0) = 1.0; v(1) = 1.0; break;
      case 3: v(0) = 1.0; v(1) = 1.0; v(2) = 1.0; break;
   }
}

static std::string getString(AssemblyLevel assembly)
{
   switch (assembly)
   {
   case AssemblyLevel::NONE:
      return "NONE";
      break;
   case AssemblyLevel::PARTIAL:
      return "PARTIAL";
      break;
   case AssemblyLevel::ELEMENT:
      return "ELEMENT";
      break;
   case AssemblyLevel::FULL:
      return "FULL";
      break;
   case AssemblyLevel::LEGACYFULL:
      return "LEGACYFULL";
      break;
   }
}

static std::string getString(CeedCoeff coeff_type)
{
   switch (coeff_type)
   {
   case CeedCoeff::Const:
      return "Const";
      break;
   case CeedCoeff::Grid:
      return "Grid";
      break;
   case CeedCoeff::Quad:
      return "Quad";
      break;
   case CeedCoeff::VecConst:
      return "VecConst";
      break;
   case CeedCoeff::VecGrid:
      return "VecGrid";
      break;
   case CeedCoeff::VecQuad:
      return "VecQuad";
      break;
   }
}

enum class Problem {Mass, Convection, Diffusion, VectorMass, VectorDiffusion};

static std::string getString(Problem pb)
{
   switch (pb)
   {
   case Problem::Mass:
      return "Mass";
      break;
   case Problem::Convection:
      return "Convection";
      break;
   case Problem::Diffusion:
      return "Diffusion";
      break;
   case Problem::VectorMass:
      return "VectorMass";
      break;
   case Problem::VectorDiffusion:
      return "VectorDiffusion";
      break;
   }
}

enum class NLProblem {Convection};

static std::string getString(NLProblem pb)
{
   switch (pb)
   {
   case NLProblem::Convection:
      return "Convection";
      break;
   }
}

void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
                        const Problem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();

   H1_FECollection fec(order, dim);
   bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   BilinearForm k_test(&fes);
   BilinearForm k_ref(&fes);

   // Coefficient Initialization
   // Scalar coefficient
   FiniteElementSpace coeff_fes(&mesh, &fec);
   GridFunction gf(&coeff_fes);
   FunctionCoefficient f_coeff(coeff_function);
   Coefficient *coeff = nullptr;
   // Vector Coefficient
   FiniteElementSpace vcoeff_fes(&mesh, &fec, dim);
   GridFunction vgf(&vcoeff_fes);
   VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
   VectorCoefficient *vcoeff = nullptr;
   switch (coeff_type)
   {
      case CeedCoeff::Const:
         coeff = new ConstantCoefficient(1.0);
         break;
      case CeedCoeff::Grid:
         gf.ProjectCoefficient(f_coeff);
         coeff = new GridFunctionCoefficient(&gf);
         break;
      case CeedCoeff::Quad:
         coeff = &f_coeff;
         break;
      case CeedCoeff::VecConst:
      {
         Vector val(dim);
         for (size_t i = 0; i < dim; i++)
         {
            val(i) = 1.0;
         }
         vcoeff = new VectorConstantCoefficient(val);
      }
      break;
      case CeedCoeff::VecGrid:
      {
         vgf.ProjectCoefficient(f_vcoeff);
         vcoeff = new VectorGridFunctionCoefficient(&vgf);
      }
      break;
      case CeedCoeff::VecQuad:
         vcoeff = &f_vcoeff;
         break;
   }

   // Build the BilinearForm
   switch (pb)
   {
   case Problem::Mass:
      k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
      break;
   case Problem::Convection:
      k_ref.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
      k_test.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
   case Problem::Diffusion:
      k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      break;
   case Problem::VectorMass:
      k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      break;
   case Problem::VectorDiffusion:
      k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      break;
   }

   k_ref.Assemble();
   k_ref.Finalize();

   k_test.SetAssemblyLevel(assembly);
   k_test.Assemble();

   // Compare ceed with mfem.
   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
}

void test_ceed_nloperator(const char* input, int order, const CeedCoeff coeff_type,
                          const NLProblem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();

   H1_FECollection fec(order, dim);
   bool vecOp = pb == NLProblem::Convection;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   NonlinearForm k_test(&fes);
   NonlinearForm k_ref(&fes);

   // Coefficient Initialization
   // Scalar coefficient
   FiniteElementSpace coeff_fes(&mesh, &fec);
   GridFunction gf(&coeff_fes);
   FunctionCoefficient f_coeff(coeff_function);
   Coefficient *coeff = nullptr;
   // Vector Coefficient
   FiniteElementSpace vcoeff_fes(&mesh, &fec, dim);
   GridFunction vgf(&vcoeff_fes);
   VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
   VectorCoefficient *vcoeff = nullptr;
   switch (coeff_type)
   {
      case CeedCoeff::Const:
         coeff = new ConstantCoefficient(1.0);
         break;
      case CeedCoeff::Grid:
         gf.ProjectCoefficient(f_coeff);
         coeff = new GridFunctionCoefficient(&gf);
         break;
      case CeedCoeff::Quad:
         coeff = &f_coeff;
         break;
      case CeedCoeff::VecConst:
      {
         Vector val(dim);
         for (size_t i = 0; i < dim; i++)
         {
            val(i) = 1.0;
         }
         vcoeff = new VectorConstantCoefficient(val);
      }
      break;
      case CeedCoeff::VecGrid:
      {
         vgf.ProjectCoefficient(f_vcoeff);
         vcoeff = new VectorGridFunctionCoefficient(&vgf);
      }
      break;
      case CeedCoeff::VecQuad:
         vcoeff = &f_vcoeff;
         break;
   }

   // Build the BilinearForm
   switch (pb)
   {
   case NLProblem::Convection:
      k_ref.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
   }

   k_test.SetAssemblyLevel(assembly);
   k_test.Setup();
   k_ref.Setup();

   // Compare ceed with mfem.
   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
}

TEST_CASE("CEED mass & diffusion", "[CEED mass & diffusion]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
                      Problem::VectorMass,Problem::VectorDiffusion);
   auto order = GENERATE(1,2,4);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star-q3.mesh","../../data/fichera-q3.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

TEST_CASE("CEED convection", "[CEED convection]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::VecConst,CeedCoeff::VecGrid,
                              CeedCoeff::VecQuad);
   auto pb = GENERATE(Problem::Convection);
   auto order = GENERATE(1,2,4);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star-q3.mesh","../../data/fichera-q3.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

TEST_CASE("CEED non-linear convection", "[CEED nlconvection]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(NLProblem::Convection);
   auto order = GENERATE(1,2,4);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star-q3.mesh","../../data/fichera-q3.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_nloperator(mesh, order, coeff_type, pb, assembly);
} // test case

} // namespace ceed_test

int main(int argc, char *argv[])
{
   // There must be exactly one instance.
   Catch::Session session;
   std::string device_str("ceed-cpu");
   using namespace Catch::clara;
   auto cli = session.cli()
      | Opt(device_str, "device_string")
        ["--device"]
        ("CEED device string (default: ceed-cpu)");
   session.cli(cli);
   int result = session.applyCommandLine( argc, argv );
   if (result != 0)
   {
      return result;
   }
   Device device(device_str.c_str());
   result = session.run();
   return result;
}
<commit_msg>Remove AMR meshes from NLConvection tests.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"

using namespace mfem;

namespace ceed_test
{

double coeff_function(const Vector &x)
{
   return 1.0 + x[0]*x[0];
}

// Velocity coefficient
void velocity_function(const Vector &x, Vector &v)
{
   int dim = x.Size();
   switch (dim)
   {
      case 1: v(0) = 1.0; break;
      case 2: v(0) = 1.0; v(1) = 1.0; break;
      case 3: v(0) = 1.0; v(1) = 1.0; v(2) = 1.0; break;
   }
}

static std::string getString(AssemblyLevel assembly)
{
   switch (assembly)
   {
   case AssemblyLevel::NONE:
      return "NONE";
      break;
   case AssemblyLevel::PARTIAL:
      return "PARTIAL";
      break;
   case AssemblyLevel::ELEMENT:
      return "ELEMENT";
      break;
   case AssemblyLevel::FULL:
      return "FULL";
      break;
   case AssemblyLevel::LEGACYFULL:
      return "LEGACYFULL";
      break;
   }
}

static std::string getString(CeedCoeff coeff_type)
{
   switch (coeff_type)
   {
   case CeedCoeff::Const:
      return "Const";
      break;
   case CeedCoeff::Grid:
      return "Grid";
      break;
   case CeedCoeff::Quad:
      return "Quad";
      break;
   case CeedCoeff::VecConst:
      return "VecConst";
      break;
   case CeedCoeff::VecGrid:
      return "VecGrid";
      break;
   case CeedCoeff::VecQuad:
      return "VecQuad";
      break;
   }
}

enum class Problem {Mass, Convection, Diffusion, VectorMass, VectorDiffusion};

static std::string getString(Problem pb)
{
   switch (pb)
   {
   case Problem::Mass:
      return "Mass";
      break;
   case Problem::Convection:
      return "Convection";
      break;
   case Problem::Diffusion:
      return "Diffusion";
      break;
   case Problem::VectorMass:
      return "VectorMass";
      break;
   case Problem::VectorDiffusion:
      return "VectorDiffusion";
      break;
   }
}

enum class NLProblem {Convection};

static std::string getString(NLProblem pb)
{
   switch (pb)
   {
   case NLProblem::Convection:
      return "Convection";
      break;
   }
}

void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
                        const Problem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();

   H1_FECollection fec(order, dim);
   bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   BilinearForm k_test(&fes);
   BilinearForm k_ref(&fes);

   // Coefficient Initialization
   // Scalar coefficient
   FiniteElementSpace coeff_fes(&mesh, &fec);
   GridFunction gf(&coeff_fes);
   FunctionCoefficient f_coeff(coeff_function);
   Coefficient *coeff = nullptr;
   // Vector Coefficient
   FiniteElementSpace vcoeff_fes(&mesh, &fec, dim);
   GridFunction vgf(&vcoeff_fes);
   VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
   VectorCoefficient *vcoeff = nullptr;
   switch (coeff_type)
   {
      case CeedCoeff::Const:
         coeff = new ConstantCoefficient(1.0);
         break;
      case CeedCoeff::Grid:
         gf.ProjectCoefficient(f_coeff);
         coeff = new GridFunctionCoefficient(&gf);
         break;
      case CeedCoeff::Quad:
         coeff = &f_coeff;
         break;
      case CeedCoeff::VecConst:
      {
         Vector val(dim);
         for (size_t i = 0; i < dim; i++)
         {
            val(i) = 1.0;
         }
         vcoeff = new VectorConstantCoefficient(val);
      }
      break;
      case CeedCoeff::VecGrid:
      {
         vgf.ProjectCoefficient(f_vcoeff);
         vcoeff = new VectorGridFunctionCoefficient(&vgf);
      }
      break;
      case CeedCoeff::VecQuad:
         vcoeff = &f_vcoeff;
         break;
   }

   // Build the BilinearForm
   switch (pb)
   {
   case Problem::Mass:
      k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
      break;
   case Problem::Convection:
      k_ref.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
      k_test.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
   case Problem::Diffusion:
      k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      break;
   case Problem::VectorMass:
      k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      break;
   case Problem::VectorDiffusion:
      k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      break;
   }

   k_ref.Assemble();
   k_ref.Finalize();

   k_test.SetAssemblyLevel(assembly);
   k_test.Assemble();

   // Compare ceed with mfem.
   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
}

void test_ceed_nloperator(const char* input, int order, const CeedCoeff coeff_type,
                          const NLProblem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();

   H1_FECollection fec(order, dim);
   bool vecOp = pb == NLProblem::Convection;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   NonlinearForm k_test(&fes);
   NonlinearForm k_ref(&fes);

   // Coefficient Initialization
   // Scalar coefficient
   FiniteElementSpace coeff_fes(&mesh, &fec);
   GridFunction gf(&coeff_fes);
   FunctionCoefficient f_coeff(coeff_function);
   Coefficient *coeff = nullptr;
   // Vector Coefficient
   FiniteElementSpace vcoeff_fes(&mesh, &fec, dim);
   GridFunction vgf(&vcoeff_fes);
   VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
   VectorCoefficient *vcoeff = nullptr;
   switch (coeff_type)
   {
      case CeedCoeff::Const:
         coeff = new ConstantCoefficient(1.0);
         break;
      case CeedCoeff::Grid:
         gf.ProjectCoefficient(f_coeff);
         coeff = new GridFunctionCoefficient(&gf);
         break;
      case CeedCoeff::Quad:
         coeff = &f_coeff;
         break;
      case CeedCoeff::VecConst:
      {
         Vector val(dim);
         for (size_t i = 0; i < dim; i++)
         {
            val(i) = 1.0;
         }
         vcoeff = new VectorConstantCoefficient(val);
      }
      break;
      case CeedCoeff::VecGrid:
      {
         vgf.ProjectCoefficient(f_vcoeff);
         vcoeff = new VectorGridFunctionCoefficient(&vgf);
      }
      break;
      case CeedCoeff::VecQuad:
         vcoeff = &f_vcoeff;
         break;
   }

   // Build the BilinearForm
   switch (pb)
   {
   case NLProblem::Convection:
      k_ref.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
   }

   k_test.SetAssemblyLevel(assembly);
   k_test.Setup();
   k_ref.Setup();

   // Compare ceed with mfem.
   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
}

TEST_CASE("CEED mass & diffusion", "[CEED mass & diffusion]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
                      Problem::VectorMass,Problem::VectorDiffusion);
   auto order = GENERATE(1,2,4);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star-q3.mesh","../../data/fichera-q3.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

TEST_CASE("CEED convection", "[CEED convection]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::VecConst,CeedCoeff::VecGrid,
                              CeedCoeff::VecQuad);
   auto pb = GENERATE(Problem::Convection);
   auto order = GENERATE(1,2,4);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star-q3.mesh","../../data/fichera-q3.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

TEST_CASE("CEED non-linear convection", "[CEED nlconvection]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(NLProblem::Convection);
   auto order = GENERATE(1,2,4);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star-q3.mesh","../../data/fichera-q3.mesh");
   test_ceed_nloperator(mesh, order, coeff_type, pb, assembly);
} // test case

} // namespace ceed_test

int main(int argc, char *argv[])
{
   // There must be exactly one instance.
   Catch::Session session;
   std::string device_str("ceed-cpu");
   using namespace Catch::clara;
   auto cli = session.cli()
      | Opt(device_str, "device_string")
        ["--device"]
        ("CEED device string (default: ceed-cpu)");
   session.cli(cli);
   int result = session.applyCommandLine( argc, argv );
   if (result != 0)
   {
      return result;
   }
   Device device(device_str.c_str());
   result = session.run();
   return result;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * thrill/core/stage_builder.hpp
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Sebastian Lamm <seba.lamm@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef THRILL_CORE_STAGE_BUILDER_HEADER
#define THRILL_CORE_STAGE_BUILDER_HEADER

#include <thrill/api/collapse.hpp>
#include <thrill/api/dia_base.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/stat_logger.hpp>
#include <thrill/common/stats_timer.hpp>

#include <algorithm>
#include <chrono>
#include <ctime>
#include <functional>
#include <iomanip>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>

namespace thrill {
namespace core {

using api::DIABase;

class Stage
{
public:
    explicit Stage(DIABase* node) : node_(node) { }

    void Execute() {
        // time_t tt;
        // timer.Start();
        node_->Execute();
        // timer.Stop();
        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        STAT(node_->context())
           << "FINISH (EXECUTING) stage" << node_->label() << node_->id();
        //    << "took (ms)" << timer.Milliseconds()
        //    << "time:" << std::put_time(std::localtime(&tt), "%T");

        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        // timer.Start();
        node_->DoPushData(node_->consume_on_push_data());
        node_->set_state(api::DIAState::EXECUTED);
        // timer.Stop();
        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        STAT(node_->context())
           << "FINISH (PUSHING) stage" << node_->label() << node_->id();
        //    << "took (ms)" << timer.Milliseconds()
        //    << "time:" << std::put_time(std::localtime(&tt), "%T");
    }

    void PushData() {
        // time_t tt;
        if (node_->consume_on_push_data()) {
            sLOG1 << "StageBuilder: Attempt to PushData on"
                  << "stage" << node_->label()
                  << "failed, it was already consumed. Add .Keep()";
            abort();
        }
        die_unless(!node_->consume_on_push_data());
        // timer.Start();
        node_->DoPushData(node_->consume_on_push_data());
        node_->set_state(api::DIAState::EXECUTED);
        // timer.Stop();
        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        STAT(node_->context())
           << "FINISH (PUSHING) stage" << node_->label() << node_->id();
        //    << "took (ms)" << timer.Milliseconds()
        //    << "time: " << std::put_time(std::localtime(&tt), "%T");
    }

    void Dispose() {
        // time_t tt;
        // timer.Start();
        node_->Dispose();
        // timer.Stop();
        node_->set_state(api::DIAState::DISPOSED);
        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        // STAT(node_->context())
        //    << "FINISH (DISPOSING) stage" << node_->label()
        //    << "took (ms)" << timer.Milliseconds()
        //    << "time:" << std::put_time(std::localtime(&tt), "%T");
    }

    DIABase * node() {
        return node_;
    }

private:
    static const bool debug = false;
    common::StatsTimer<true> timer;
    DIABase* node_;
};

class StageBuilder
{
public:
    template <typename T>
    using mm_set = std::set<T, std::less<T>, mem::Allocator<T> >;

    void FindStages(DIABase* action, mem::mm_vector<Stage>& stages_result) {
        LOG << "FINDING stages:";
        mm_set<const DIABase*> stages_found(
            mem::Allocator<const DIABase*>(action->mem_manager()));

        // Do a reverse DFS and find all stages
        mem::mm_deque<DIABase*> dia_stack(
            mem::Allocator<DIABase*>(action->mem_manager()));

        dia_stack.push_back(action);
        stages_found.insert(action);
        stages_result.push_back(Stage(action));
        while (!dia_stack.empty()) {
            DIABase* curr = dia_stack.front();
            dia_stack.pop_front();
            const auto parents = curr->parents();
            for (size_t i = 0; i < parents.size(); ++i) {
                // Check if parent was already added
                auto p = parents[i].get();
                if (p) {
                    // If not add parent to stages found and result stages
                    stages_found.insert(p);
                    stages_result.push_back(Stage(p));
                    LOG1 << "FOUND: " << p->label() << " " << p->id();
                    // If parent was not executed push it to the DFS
                    if (p->state() != api::DIAState::EXECUTED ||
                        p->type() == api::DIANodeType::COLLAPSE) {
                        dia_stack.push_back(p);
                    }
                }
            }
        }
        // Reverse the execution order
        std::reverse(stages_result.begin(), stages_result.end());
    }

    void RunScope(DIABase* action) {
        mem::mm_vector<Stage> result(
            mem::Allocator<Stage>(action->mem_manager()));

        FindStages(action, result);
        for (auto s : result)
        {
            if (s.node()->state() == api::DIAState::EXECUTED) {
                bool skip = true;
                for (DIABase* child : s.node()->children())
                    if(child->state() != api::DIAState::EXECUTED) skip = false;
                if (skip) continue;
                else s.PushData();
            }
            if (s.node()->state() == api::DIAState::NEW) s.Execute();
            s.node()->UnregisterChilds();
        }
    }

    static const bool debug = false;
};

} // namespace core
} // namespace thrill

#endif // !THRILL_CORE_STAGE_BUILDER_HEADER

/******************************************************************************/
<commit_msg>Improved fix. Removed Stat because of errors.<commit_after>/*******************************************************************************
 * thrill/core/stage_builder.hpp
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Sebastian Lamm <seba.lamm@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef THRILL_CORE_STAGE_BUILDER_HEADER
#define THRILL_CORE_STAGE_BUILDER_HEADER

#include <thrill/api/collapse.hpp>
#include <thrill/api/dia_base.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/stat_logger.hpp>
#include <thrill/common/stats_timer.hpp>

#include <algorithm>
#include <chrono>
#include <ctime>
#include <functional>
#include <iomanip>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>

namespace thrill {
namespace core {

using api::DIABase;

class Stage
{
public:
    explicit Stage(DIABase* node) : node_(node) { }

    void Execute() {
        // time_t tt;
        // timer.Start();
        node_->Execute();
        // timer.Stop();
        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        // STAT(node_->context())
        //    << "FINISH (EXECUTING) stage" << node_->label() << node_->id();
        //    << "took (ms)" << timer.Milliseconds()
        //    << "time:" << std::put_time(std::localtime(&tt), "%T");

        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        // timer.Start();
        node_->DoPushData(node_->consume_on_push_data());
        node_->set_state(api::DIAState::EXECUTED);
        // timer.Stop();
        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        // STAT(node_->context())
        //    << "FINISH (PUSHING) stage" << node_->label() << node_->id();
        //    << "took (ms)" << timer.Milliseconds()
        //    << "time:" << std::put_time(std::localtime(&tt), "%T");
    }

    void PushData() {
        // time_t tt;
        if (node_->consume_on_push_data()) {
            sLOG1 << "StageBuilder: Attempt to PushData on"
                  << "stage" << node_->label()
                  << "failed, it was already consumed. Add .Keep()";
            abort();
        }
        die_unless(!node_->consume_on_push_data());
        // timer.Start();
        node_->DoPushData(node_->consume_on_push_data());
        node_->set_state(api::DIAState::EXECUTED);
        // timer.Stop();
        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        // STAT(node_->context())
        //    << "FINISH (PUSHING) stage" << node_->label() << node_->id();
        //    << "took (ms)" << timer.Milliseconds()
        //    << "time: " << std::put_time(std::localtime(&tt), "%T");
    }

    void Dispose() {
        // time_t tt;
        // timer.Start();
        node_->Dispose();
        // timer.Stop();
        node_->set_state(api::DIAState::DISPOSED);
        // tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
        // STAT(node_->context())
        //    << "FINISH (DISPOSING) stage" << node_->label()
        //    << "took (ms)" << timer.Milliseconds()
        //    << "time:" << std::put_time(std::localtime(&tt), "%T");
    }

    DIABase * node() {
        return node_;
    }

private:
    static const bool debug = false;
    common::StatsTimer<true> timer;
    DIABase* node_;
};

class StageBuilder
{
public:
    template <typename T>
    using mm_set = std::set<T, std::less<T>, mem::Allocator<T> >;

    void FindStages(DIABase* action, mem::mm_vector<Stage>& stages_result) {
        LOG << "FINDING stages:";
        mm_set<const DIABase*> stages_found(
            mem::Allocator<const DIABase*>(action->mem_manager()));

        // Do a reverse DFS and find all stages
        mem::mm_deque<DIABase*> dia_stack(
            mem::Allocator<DIABase*>(action->mem_manager()));

        dia_stack.push_back(action);
        stages_found.insert(action);
        stages_result.push_back(Stage(action));
        while (!dia_stack.empty()) {
            DIABase* curr = dia_stack.front();
            dia_stack.pop_front();
            const auto parents = curr->parents();
            for (size_t i = 0; i < parents.size(); ++i) {
                // Check if parent was already added
                auto p = parents[i].get();
                if (p) {
                    // If not add parent to stages found and result stages
                    stages_found.insert(p);
                    stages_result.push_back(Stage(p));
                    LOG1 << "FOUND: " << p->label() << " " << p->id();
                    // If parent was not executed push it to the DFS
                    if (p->state() != api::DIAState::EXECUTED ||
                        p->type() == api::DIANodeType::COLLAPSE) {
                        dia_stack.push_back(p);
                    }
                }
            }
        }
        // Reverse the execution order
        std::reverse(stages_result.begin(), stages_result.end());
    }

    void RunScope(DIABase* action) {
        mem::mm_vector<Stage> result(
            mem::Allocator<Stage>(action->mem_manager()));

        FindStages(action, result);
        for (auto s : result)
        {
            if (s.node()->state() == api::DIAState::EXECUTED) {
                bool skip = true;
                for (DIABase* child : s.node()->children())
                    if(child->state() != api::DIAState::EXECUTED
                            || child->type() == api::DIANodeType::COLLAPSE)
                        skip = false;
                if (skip) continue;
                else s.PushData();
            }
            if (s.node()->state() == api::DIAState::NEW) s.Execute();
            s.node()->UnregisterChilds();
        }
    }

    static const bool debug = false;
};

} // namespace core
} // namespace thrill

#endif // !THRILL_CORE_STAGE_BUILDER_HEADER

/******************************************************************************/
<|endoftext|>


<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

// See docs in ../ops/data_flow_ops.cc.

#include <limits.h>
#include <vector>

#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

class GetSessionHandleOp : public OpKernel {
 public:
  explicit GetSessionHandleOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* ctx) override {
    Tensor val = ctx->input(0);
    int64 id = ctx->session_state()->GetNewId();
    TensorStore::TensorAndKey tk{val, id, def().device()};
    OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(def().name(), tk));

    Tensor* handle = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));
    if (ctx->expected_output_dtype(0) == DT_RESOURCE) {
      ResourceHandle resource_handle = MakeResourceHandle<Tensor>(
          ctx, SessionState::kTensorHandleResourceTypeName,
          tk.GetHandle(def().name()));
      resource_handle.set_maybe_type_name(
          SessionState::kTensorHandleResourceTypeName);
      handle->scalar<ResourceHandle>()() = resource_handle;
    } else {
      // Legacy behavior in V1.
      handle->flat<string>().setConstant(tk.GetHandle(def().name()));
    }
  }

  TF_DISALLOW_COPY_AND_ASSIGN(GetSessionHandleOp);
};

REGISTER_KERNEL_BUILDER(Name("GetSessionHandle").Device(DEVICE_CPU),
                        GetSessionHandleOp);
REGISTER_KERNEL_BUILDER(Name("GetSessionHandleV2").Device(DEVICE_CPU),
                        GetSessionHandleOp);

#define REGISTER_GPU_KERNEL(type)                         \
  REGISTER_KERNEL_BUILDER(Name("GetSessionHandle")        \
                              .Device(DEVICE_GPU)         \
                              .HostMemory("handle")       \
                              .TypeConstraint<type>("T"), \
                          GetSessionHandleOp)             \
  REGISTER_KERNEL_BUILDER(Name("GetSessionHandleV2")      \
                              .Device(DEVICE_GPU)         \
                              .HostMemory("handle")       \
                              .TypeConstraint<type>("T"), \
                          GetSessionHandleOp)

TF_CALL_NUMBER_TYPES(REGISTER_GPU_KERNEL);
REGISTER_GPU_KERNEL(bool);
#undef REGISTER_GPU_KERNEL

#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNEL(type)                        \
  REGISTER_KERNEL_BUILDER(Name("GetSessionHandle")        \
                              .Device(DEVICE_SYCL)        \
                              .HostMemory("handle")       \
                              .TypeConstraint<type>("T"), \
                          GetSessionHandleOp)             \
  REGISTER_KERNEL_BUILDER(Name("GetSessionHandleV2")      \
                              .Device(DEVICE_SYCL)        \
                              .HostMemory("handle")       \
                              .TypeConstraint<type>("T"), \
                          GetSessionHandleOp)

TF_CALL_NUMBER_TYPES(REGISTER_SYCL_KERNEL);
REGISTER_SYCL_KERNEL(bool);
#undef REGISTER_SYCL_KERNEL
#endif  // TENSORFLOW_USE_SYCL

class GetSessionTensorOp : public OpKernel {
 public:
  explicit GetSessionTensorOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* ctx) override {
    const Tensor& handle = ctx->input(0);
    const string& name = handle.scalar<string>()();
    Tensor val;
    OP_REQUIRES_OK(ctx, ctx->session_state()->GetTensor(name, &val));
    ctx->set_output(0, val);
  }

  TF_DISALLOW_COPY_AND_ASSIGN(GetSessionTensorOp);
};

REGISTER_KERNEL_BUILDER(Name("GetSessionTensor").Device(DEVICE_CPU),
                        GetSessionTensorOp);

#define REGISTER_GPU_KERNEL(type)                             \
  REGISTER_KERNEL_BUILDER(Name("GetSessionTensor")            \
                              .Device(DEVICE_GPU)             \
                              .HostMemory("handle")           \
                              .TypeConstraint<type>("dtype"), \
                          GetSessionTensorOp)

TF_CALL_NUMBER_TYPES(REGISTER_GPU_KERNEL);
REGISTER_GPU_KERNEL(bool);
#undef REGISTER_GPU_KERNEL

#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNEL(type)                            \
  REGISTER_KERNEL_BUILDER(Name("GetSessionTensor")            \
                              .Device(DEVICE_SYCL)            \
                              .HostMemory("handle")           \
                              .TypeConstraint<type>("dtype"), \
                          GetSessionTensorOp)

TF_CALL_NUMBER_TYPES(REGISTER_SYCL_KERNEL);
REGISTER_SYCL_KERNEL(bool);
#undef REGISTER_SYCL_KERNEL
#endif // TENSORFLOW_USE_SYCL

class DeleteSessionTensorOp : public OpKernel {
 public:
  explicit DeleteSessionTensorOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* ctx) override {
    const Tensor& handle = ctx->input(0);
    const string& name = handle.scalar<string>()();
    OP_REQUIRES_OK(ctx, ctx->session_state()->DeleteTensor(name));
  }

  TF_DISALLOW_COPY_AND_ASSIGN(DeleteSessionTensorOp);
};

REGISTER_KERNEL_BUILDER(Name("DeleteSessionTensor").Device(DEVICE_CPU),
                        DeleteSessionTensorOp);
REGISTER_KERNEL_BUILDER(
    Name("DeleteSessionTensor").Device(DEVICE_GPU).HostMemory("handle"),
    DeleteSessionTensorOp);

#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(
    Name("DeleteSessionTensor").Device(DEVICE_SYCL).HostMemory("handle"),
    DeleteSessionTensorOp);
#endif  // TENSORFLOW_USE_SYCL
}  // namespace tensorflow
<commit_msg>Remove unnecessary copy-assignment in GetSessionHandleOp::Compute() Change: 152949451<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

// See docs in ../ops/data_flow_ops.cc.

#include <limits.h>
#include <vector>

#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

class GetSessionHandleOp : public OpKernel {
 public:
  explicit GetSessionHandleOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* ctx) override {
    const Tensor& val = ctx->input(0);
    int64 id = ctx->session_state()->GetNewId();
    TensorStore::TensorAndKey tk{val, id, def().device()};
    OP_REQUIRES_OK(ctx, ctx->tensor_store()->AddTensor(def().name(), tk));

    Tensor* handle = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle));
    if (ctx->expected_output_dtype(0) == DT_RESOURCE) {
      ResourceHandle resource_handle = MakeResourceHandle<Tensor>(
          ctx, SessionState::kTensorHandleResourceTypeName,
          tk.GetHandle(def().name()));
      resource_handle.set_maybe_type_name(
          SessionState::kTensorHandleResourceTypeName);
      handle->scalar<ResourceHandle>()() = resource_handle;
    } else {
      // Legacy behavior in V1.
      handle->flat<string>().setConstant(tk.GetHandle(def().name()));
    }
  }

  TF_DISALLOW_COPY_AND_ASSIGN(GetSessionHandleOp);
};

REGISTER_KERNEL_BUILDER(Name("GetSessionHandle").Device(DEVICE_CPU),
                        GetSessionHandleOp);
REGISTER_KERNEL_BUILDER(Name("GetSessionHandleV2").Device(DEVICE_CPU),
                        GetSessionHandleOp);

#define REGISTER_GPU_KERNEL(type)                         \
  REGISTER_KERNEL_BUILDER(Name("GetSessionHandle")        \
                              .Device(DEVICE_GPU)         \
                              .HostMemory("handle")       \
                              .TypeConstraint<type>("T"), \
                          GetSessionHandleOp)             \
  REGISTER_KERNEL_BUILDER(Name("GetSessionHandleV2")      \
                              .Device(DEVICE_GPU)         \
                              .HostMemory("handle")       \
                              .TypeConstraint<type>("T"), \
                          GetSessionHandleOp)

TF_CALL_NUMBER_TYPES(REGISTER_GPU_KERNEL);
REGISTER_GPU_KERNEL(bool);
#undef REGISTER_GPU_KERNEL

#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNEL(type)                        \
  REGISTER_KERNEL_BUILDER(Name("GetSessionHandle")        \
                              .Device(DEVICE_SYCL)        \
                              .HostMemory("handle")       \
                              .TypeConstraint<type>("T"), \
                          GetSessionHandleOp)             \
  REGISTER_KERNEL_BUILDER(Name("GetSessionHandleV2")      \
                              .Device(DEVICE_SYCL)        \
                              .HostMemory("handle")       \
                              .TypeConstraint<type>("T"), \
                          GetSessionHandleOp)

TF_CALL_NUMBER_TYPES(REGISTER_SYCL_KERNEL);
REGISTER_SYCL_KERNEL(bool);
#undef REGISTER_SYCL_KERNEL
#endif  // TENSORFLOW_USE_SYCL

class GetSessionTensorOp : public OpKernel {
 public:
  explicit GetSessionTensorOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* ctx) override {
    const Tensor& handle = ctx->input(0);
    const string& name = handle.scalar<string>()();
    Tensor val;
    OP_REQUIRES_OK(ctx, ctx->session_state()->GetTensor(name, &val));
    ctx->set_output(0, val);
  }

  TF_DISALLOW_COPY_AND_ASSIGN(GetSessionTensorOp);
};

REGISTER_KERNEL_BUILDER(Name("GetSessionTensor").Device(DEVICE_CPU),
                        GetSessionTensorOp);

#define REGISTER_GPU_KERNEL(type)                             \
  REGISTER_KERNEL_BUILDER(Name("GetSessionTensor")            \
                              .Device(DEVICE_GPU)             \
                              .HostMemory("handle")           \
                              .TypeConstraint<type>("dtype"), \
                          GetSessionTensorOp)

TF_CALL_NUMBER_TYPES(REGISTER_GPU_KERNEL);
REGISTER_GPU_KERNEL(bool);
#undef REGISTER_GPU_KERNEL

#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNEL(type)                            \
  REGISTER_KERNEL_BUILDER(Name("GetSessionTensor")            \
                              .Device(DEVICE_SYCL)            \
                              .HostMemory("handle")           \
                              .TypeConstraint<type>("dtype"), \
                          GetSessionTensorOp)

TF_CALL_NUMBER_TYPES(REGISTER_SYCL_KERNEL);
REGISTER_SYCL_KERNEL(bool);
#undef REGISTER_SYCL_KERNEL
#endif // TENSORFLOW_USE_SYCL

class DeleteSessionTensorOp : public OpKernel {
 public:
  explicit DeleteSessionTensorOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* ctx) override {
    const Tensor& handle = ctx->input(0);
    const string& name = handle.scalar<string>()();
    OP_REQUIRES_OK(ctx, ctx->session_state()->DeleteTensor(name));
  }

  TF_DISALLOW_COPY_AND_ASSIGN(DeleteSessionTensorOp);
};

REGISTER_KERNEL_BUILDER(Name("DeleteSessionTensor").Device(DEVICE_CPU),
                        DeleteSessionTensorOp);
REGISTER_KERNEL_BUILDER(
    Name("DeleteSessionTensor").Device(DEVICE_GPU).HostMemory("handle"),
    DeleteSessionTensorOp);

#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(
    Name("DeleteSessionTensor").Device(DEVICE_SYCL).HostMemory("handle"),
    DeleteSessionTensorOp);
#endif  // TENSORFLOW_USE_SYCL
}  // namespace tensorflow
<|endoftext|>


<commit_before><commit_msg>fix linux build<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Erik Hallnor
 *          Dave Greene
 */

/**
 * @file
 * Miss Status and Handling Register (MSHR) definitions.
 */

#include <assert.h>
#include <string>
#include <vector>
#include <algorithm>

#include "mem/cache/miss/mshr.hh"
#include "sim/core.hh" // for curTick
#include "sim/host.hh"
#include "base/misc.hh"
#include "mem/cache/cache.hh"

using namespace std;

MSHR::MSHR()
{
    inService = false;
    ntargets = 0;
    threadNum = -1;
    targets = new TargetList();
    deferredTargets = new TargetList();
}

MSHR::TargetList::TargetList()
    : needsExclusive(false), hasUpgrade(false)
{}

inline void
MSHR::TargetList::add(PacketPtr pkt, Tick readyTime,
                      Counter order, bool cpuSide)
{
    if (cpuSide) {
        if (pkt->needsExclusive()) {
            needsExclusive = true;
        }

        if (pkt->cmd == MemCmd::UpgradeReq) {
            hasUpgrade = true;
        }

        MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
        if (mshr != NULL) {
            assert(!mshr->downstreamPending);
            mshr->downstreamPending = true;
        }
    }

    push_back(Target(pkt, readyTime, order, cpuSide));
}

void
MSHR::TargetList::replaceUpgrades()
{
    if (!hasUpgrade)
        return;

    Iterator end_i = end();
    for (Iterator i = begin(); i != end_i; ++i) {
        if (i->pkt->cmd == MemCmd::UpgradeReq) {
            i->pkt->cmd = MemCmd::ReadExReq;
            DPRINTF(Cache, "Replacing UpgradeReq with ReadExReq\n");
        }
    }

    hasUpgrade = false;
}

void
MSHR::TargetList::clearDownstreamPending()
{
    Iterator end_i = end();
    for (Iterator i = begin(); i != end_i; ++i) {
        MSHR *mshr = dynamic_cast<MSHR*>(i->pkt->senderState);
        if (mshr != NULL) {
            assert(mshr->downstreamPending);
            mshr->downstreamPending = false;
        }
    }
}

bool
MSHR::TargetList::checkFunctional(PacketPtr pkt)
{
    Iterator end_i = end();
    for (Iterator i = begin(); i != end_i; ++i) {
        if (pkt->checkFunctional(i->pkt)) {
            return true;
        }
    }

    return false;
}

void
MSHR::allocate(Addr _addr, int _size, PacketPtr target,
               Tick whenReady, Counter _order)
{
    addr = _addr;
    size = _size;
    readyTime = whenReady;
    order = _order;
    assert(target);
    isCacheFill = false;
    _isUncacheable = target->req->isUncacheable();
    inService = false;
    downstreamPending = false;
    threadNum = 0;
    ntargets = 1;
    // Don't know of a case where we would allocate a new MSHR for a
    // snoop (mem-side request), so set cpuSide to true here.
    assert(targets->isReset());
    targets->add(target, whenReady, _order, true);
    assert(deferredTargets->isReset());
    pendingInvalidate = false;
    pendingShared = false;
    data = NULL;
}

bool
MSHR::markInService()
{
    assert(!inService);
    if (isSimpleForward()) {
        // we just forwarded the request packet & don't expect a
        // response, so get rid of it
        assert(getNumTargets() == 1);
        popTarget();
        return true;
    }
    inService = true;
    if (!downstreamPending) {
        // let upstream caches know that the request has made it to a
        // level where it's going to get a response
        targets->clearDownstreamPending();
    }
    return false;
}

void
MSHR::deallocate()
{
    assert(targets->empty());
    targets->resetFlags();
    assert(deferredTargets->isReset());
    assert(ntargets == 0);
    inService = false;
    //allocIter = NULL;
    //readyIter = NULL;
}

/*
 * Adds a target to an MSHR
 */
void
MSHR::allocateTarget(PacketPtr pkt, Tick whenReady, Counter _order)
{
    // if there's a request already in service for this MSHR, we will
    // have to defer the new target until after the response if any of
    // the following are true:
    // - there are other targets already deferred
    // - there's a pending invalidate to be applied after the response
    //   comes back (but before this target is processed)
    // - the outstanding request is for a non-exclusive block and this
    //   target requires an exclusive block
    if (inService &&
        (!deferredTargets->empty() || pendingInvalidate ||
         (!targets->needsExclusive && pkt->needsExclusive()))) {
        // need to put on deferred list
        deferredTargets->add(pkt, whenReady, _order, true);
    } else {
        // no request outstanding, or still OK to append to
        // outstanding request
        targets->add(pkt, whenReady, _order, true);
    }

    ++ntargets;
}

bool
MSHR::handleSnoop(PacketPtr pkt, Counter _order)
{
    if (!inService || (pkt->isExpressSnoop() && downstreamPending)) {
        // Request has not been issued yet, or it's been issued
        // locally but is buffered unissued at some downstream cache
        // which is forwarding us this snoop.  Either way, the packet
        // we're snooping logically precedes this MSHR's request, so
        // the snoop has no impact on the MSHR, but must be processed
        // in the standard way by the cache.  The only exception is
        // that if we're an L2+ cache buffering an UpgradeReq from a
        // higher-level cache, and the snoop is invalidating, then our
        // buffered upgrades must be converted to read exclusives,
        // since the upper-level cache no longer has a valid copy.
        // That is, even though the upper-level cache got out on its
        // local bus first, some other invalidating transaction
        // reached the global bus before the upgrade did.
        if (pkt->needsExclusive()) {
            targets->replaceUpgrades();
            deferredTargets->replaceUpgrades();
        }

        return false;
    }

    // From here on down, the request issued by this MSHR logically
    // precedes the request we're snooping.

    if (pkt->needsExclusive()) {
        // snooped request still precedes the re-request we'll have to
        // issue for deferred targets, if any...
        deferredTargets->replaceUpgrades();
    }

    if (pendingInvalidate) {
        // a prior snoop has already appended an invalidation, so
        // logically we don't have the block anymore; no need for
        // further snooping.
        return true;
    }

    if (targets->needsExclusive || pkt->needsExclusive()) {
        // actual target device (typ. PhysicalMemory) will delete the
        // packet on reception, so we need to save a copy here
        PacketPtr cp_pkt = new Packet(pkt, true);
        targets->add(cp_pkt, curTick, _order, false);
        ++ntargets;

        if (targets->needsExclusive) {
            // We're awaiting an exclusive copy, so ownership is pending.
            // It's up to us to respond once the data arrives.
            pkt->assertMemInhibit();
            pkt->setSupplyExclusive();
        } else {
            // Someone else may respond before we get around to
            // processing this snoop, which means the copied request
            // pointer will no longer be valid
            cp_pkt->req = NULL;
        }

        if (pkt->needsExclusive()) {
            // This transaction will take away our pending copy
            pendingInvalidate = true;
        }
    } else {
        // Read to a read: no conflict, so no need to record as
        // target, but make sure neither reader thinks he's getting an
        // exclusive copy
        pendingShared = true;
        pkt->assertShared();
    }

    return true;
}

bool
MSHR::promoteDeferredTargets()
{
    assert(targets->empty());
    if (deferredTargets->empty()) {
        return false;
    }

    // swap targets & deferredTargets lists
    TargetList *tmp = targets;
    targets = deferredTargets;
    deferredTargets = tmp;

    assert(targets->size() == ntargets);

    // clear deferredTargets flags
    deferredTargets->resetFlags();

    pendingInvalidate = false;
    pendingShared = false;
    order = targets->front().order;
    readyTime = std::max(curTick, targets->front().readyTime);

    return true;
}

void
MSHR::handleFill(Packet *pkt, CacheBlk *blk)
{
    if (pendingShared) {
        // we snooped another read while this read was in
        // service... assert shared line on its behalf
        pkt->assertShared();
    }
}

void
MSHR::dump()
{
    ccprintf(cerr,
             "inService: %d thread: %d\n"
             "Addr: %x ntargets %d\n"
             "Targets:\n",
             inService, threadNum, addr, ntargets);
#if 0
    TargetListIterator tar_it = targets->begin();
    for (int i = 0; i < ntargets; i++) {
        assert(tar_it != targets->end());

        ccprintf(cerr, "\t%d: Addr: %x cmd: %s\n",
                 i, tar_it->pkt->getAddr(), tar_it->pkt->cmdString());

        tar_it++;
    }
#endif
    ccprintf(cerr, "\n");
}

MSHR::~MSHR()
{
}
<commit_msg>Fix bug on exclusive response to ReadReq with pending WriteReq.<commit_after>/*
 * Copyright (c) 2002-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Erik Hallnor
 *          Dave Greene
 */

/**
 * @file
 * Miss Status and Handling Register (MSHR) definitions.
 */

#include <assert.h>
#include <string>
#include <vector>
#include <algorithm>

#include "mem/cache/miss/mshr.hh"
#include "sim/core.hh" // for curTick
#include "sim/host.hh"
#include "base/misc.hh"
#include "mem/cache/cache.hh"

using namespace std;

MSHR::MSHR()
{
    inService = false;
    ntargets = 0;
    threadNum = -1;
    targets = new TargetList();
    deferredTargets = new TargetList();
}

MSHR::TargetList::TargetList()
    : needsExclusive(false), hasUpgrade(false)
{}

inline void
MSHR::TargetList::add(PacketPtr pkt, Tick readyTime,
                      Counter order, bool cpuSide)
{
    if (cpuSide) {
        if (pkt->needsExclusive()) {
            needsExclusive = true;
        }

        if (pkt->cmd == MemCmd::UpgradeReq) {
            hasUpgrade = true;
        }

        MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
        if (mshr != NULL) {
            assert(!mshr->downstreamPending);
            mshr->downstreamPending = true;
        }
    }

    push_back(Target(pkt, readyTime, order, cpuSide));
}

void
MSHR::TargetList::replaceUpgrades()
{
    if (!hasUpgrade)
        return;

    Iterator end_i = end();
    for (Iterator i = begin(); i != end_i; ++i) {
        if (i->pkt->cmd == MemCmd::UpgradeReq) {
            i->pkt->cmd = MemCmd::ReadExReq;
            DPRINTF(Cache, "Replacing UpgradeReq with ReadExReq\n");
        }
    }

    hasUpgrade = false;
}

void
MSHR::TargetList::clearDownstreamPending()
{
    Iterator end_i = end();
    for (Iterator i = begin(); i != end_i; ++i) {
        MSHR *mshr = dynamic_cast<MSHR*>(i->pkt->senderState);
        if (mshr != NULL) {
            assert(mshr->downstreamPending);
            mshr->downstreamPending = false;
        }
    }
}

bool
MSHR::TargetList::checkFunctional(PacketPtr pkt)
{
    Iterator end_i = end();
    for (Iterator i = begin(); i != end_i; ++i) {
        if (pkt->checkFunctional(i->pkt)) {
            return true;
        }
    }

    return false;
}

void
MSHR::allocate(Addr _addr, int _size, PacketPtr target,
               Tick whenReady, Counter _order)
{
    addr = _addr;
    size = _size;
    readyTime = whenReady;
    order = _order;
    assert(target);
    isCacheFill = false;
    _isUncacheable = target->req->isUncacheable();
    inService = false;
    downstreamPending = false;
    threadNum = 0;
    ntargets = 1;
    // Don't know of a case where we would allocate a new MSHR for a
    // snoop (mem-side request), so set cpuSide to true here.
    assert(targets->isReset());
    targets->add(target, whenReady, _order, true);
    assert(deferredTargets->isReset());
    pendingInvalidate = false;
    pendingShared = false;
    data = NULL;
}

bool
MSHR::markInService()
{
    assert(!inService);
    if (isSimpleForward()) {
        // we just forwarded the request packet & don't expect a
        // response, so get rid of it
        assert(getNumTargets() == 1);
        popTarget();
        return true;
    }
    inService = true;
    if (!downstreamPending) {
        // let upstream caches know that the request has made it to a
        // level where it's going to get a response
        targets->clearDownstreamPending();
    }
    return false;
}

void
MSHR::deallocate()
{
    assert(targets->empty());
    targets->resetFlags();
    assert(deferredTargets->isReset());
    assert(ntargets == 0);
    inService = false;
    //allocIter = NULL;
    //readyIter = NULL;
}

/*
 * Adds a target to an MSHR
 */
void
MSHR::allocateTarget(PacketPtr pkt, Tick whenReady, Counter _order)
{
    // if there's a request already in service for this MSHR, we will
    // have to defer the new target until after the response if any of
    // the following are true:
    // - there are other targets already deferred
    // - there's a pending invalidate to be applied after the response
    //   comes back (but before this target is processed)
    // - the outstanding request is for a non-exclusive block and this
    //   target requires an exclusive block
    if (inService &&
        (!deferredTargets->empty() || pendingInvalidate ||
         (!targets->needsExclusive && pkt->needsExclusive()))) {
        // need to put on deferred list
        deferredTargets->add(pkt, whenReady, _order, true);
    } else {
        // no request outstanding, or still OK to append to
        // outstanding request
        targets->add(pkt, whenReady, _order, true);
    }

    ++ntargets;
}

bool
MSHR::handleSnoop(PacketPtr pkt, Counter _order)
{
    if (!inService || (pkt->isExpressSnoop() && downstreamPending)) {
        // Request has not been issued yet, or it's been issued
        // locally but is buffered unissued at some downstream cache
        // which is forwarding us this snoop.  Either way, the packet
        // we're snooping logically precedes this MSHR's request, so
        // the snoop has no impact on the MSHR, but must be processed
        // in the standard way by the cache.  The only exception is
        // that if we're an L2+ cache buffering an UpgradeReq from a
        // higher-level cache, and the snoop is invalidating, then our
        // buffered upgrades must be converted to read exclusives,
        // since the upper-level cache no longer has a valid copy.
        // That is, even though the upper-level cache got out on its
        // local bus first, some other invalidating transaction
        // reached the global bus before the upgrade did.
        if (pkt->needsExclusive()) {
            targets->replaceUpgrades();
            deferredTargets->replaceUpgrades();
        }

        return false;
    }

    // From here on down, the request issued by this MSHR logically
    // precedes the request we're snooping.

    if (pkt->needsExclusive()) {
        // snooped request still precedes the re-request we'll have to
        // issue for deferred targets, if any...
        deferredTargets->replaceUpgrades();
    }

    if (pendingInvalidate) {
        // a prior snoop has already appended an invalidation, so
        // logically we don't have the block anymore; no need for
        // further snooping.
        return true;
    }

    if (targets->needsExclusive || pkt->needsExclusive()) {
        // actual target device (typ. PhysicalMemory) will delete the
        // packet on reception, so we need to save a copy here
        PacketPtr cp_pkt = new Packet(pkt, true);
        targets->add(cp_pkt, curTick, _order, false);
        ++ntargets;

        if (targets->needsExclusive) {
            // We're awaiting an exclusive copy, so ownership is pending.
            // It's up to us to respond once the data arrives.
            pkt->assertMemInhibit();
            pkt->setSupplyExclusive();
        } else {
            // Someone else may respond before we get around to
            // processing this snoop, which means the copied request
            // pointer will no longer be valid
            cp_pkt->req = NULL;
        }

        if (pkt->needsExclusive()) {
            // This transaction will take away our pending copy
            pendingInvalidate = true;
        }
    } else {
        // Read to a read: no conflict, so no need to record as
        // target, but make sure neither reader thinks he's getting an
        // exclusive copy
        pendingShared = true;
        pkt->assertShared();
    }

    return true;
}

bool
MSHR::promoteDeferredTargets()
{
    assert(targets->empty());
    if (deferredTargets->empty()) {
        return false;
    }

    // swap targets & deferredTargets lists
    TargetList *tmp = targets;
    targets = deferredTargets;
    deferredTargets = tmp;

    assert(targets->size() == ntargets);

    // clear deferredTargets flags
    deferredTargets->resetFlags();

    pendingInvalidate = false;
    pendingShared = false;
    order = targets->front().order;
    readyTime = std::max(curTick, targets->front().readyTime);

    return true;
}

void
MSHR::handleFill(Packet *pkt, CacheBlk *blk)
{
    if (pendingShared) {
        // we snooped another read while this read was in
        // service... assert shared line on its behalf
        pkt->assertShared();
    }

    if (!pkt->sharedAsserted() && !pendingInvalidate
        && deferredTargets->needsExclusive) {
        // We got an exclusive response, but we have deferred targets
        // which are waiting to request an exclusive copy (not because
        // of a pending invalidate).  This can happen if the original
        // request was for a read-only (non-exclusive) block, but we
        // got an exclusive copy anyway because of the E part of the
        // MOESI/MESI protocol.  Since we got the exclusive copy
        // there's no need to defer the targets, so move them up to
        // the regular target list.
        assert(!targets->needsExclusive);
        targets->needsExclusive = true;
        // this clears out deferredTargets too
        targets->splice(targets->end(), *deferredTargets);
        deferredTargets->resetFlags();
    }
}

void
MSHR::dump()
{
    ccprintf(cerr,
             "inService: %d thread: %d\n"
             "Addr: %x ntargets %d\n"
             "Targets:\n",
             inService, threadNum, addr, ntargets);
#if 0
    TargetListIterator tar_it = targets->begin();
    for (int i = 0; i < ntargets; i++) {
        assert(tar_it != targets->end());

        ccprintf(cerr, "\t%d: Addr: %x cmd: %s\n",
                 i, tar_it->pkt->getAddr(), tar_it->pkt->cmdString());

        tar_it++;
    }
#endif
    ccprintf(cerr, "\n");
}

MSHR::~MSHR()
{
}
<|endoftext|>


<commit_before>// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s

// REQUIRES: compiler-rt-optimized

#include <string.h>
int main(int argc, char **argv) {
  char a1[] = {static_cast<char>(argc), 2, 3, 4};
  char a2[] = {1, static_cast<char>(2 * argc), 3, 4};
  int res = bcmp(a1, a2, 4 + argc); // BOOM
  // CHECK: AddressSanitizer: stack-buffer-overflow
  // CHECK: {{#1.*bcmp}}
  // CHECK: {{#2.*main}}
  return res;
}
<commit_msg>[compiler-rt] disable asan bcmp tests on android.<commit_after>// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s

// REQUIRES: compiler-rt-optimized
// UNSUPPORTED: android

#include <string.h>
int main(int argc, char **argv) {
  char a1[] = {static_cast<char>(argc), 2, 3, 4};
  char a2[] = {1, static_cast<char>(2 * argc), 3, 4};
  int res = bcmp(a1, a2, 4 + argc); // BOOM
  // CHECK: AddressSanitizer: stack-buffer-overflow
  // CHECK: {{#1.*bcmp}}
  // CHECK: {{#2.*main}}
  return res;
}
<|endoftext|>