<commit_before>#include "rtpsession.h"
#include "rtpipv4address.h"
#include "rtpsessionparams.h"
#include "rtpudpv4transmitter.h"
#include "rtperrors.h"
#include "rtcpcompoundpacket.h"
#include "rtcpsrpacket.h"
#include "rtcprrpacket.h"
#include "rtcpbyepacket.h"
#include "rtprawpacket.h"
#include <stdio.h>
#include <iostream>

using namespace jrtplib;

void checkError(int status)
{
	if (status >= 0)
		return;

	std::cerr << "An error occured in the RTP component: " << std::endl;
	std::cerr << "Error description: " << RTPGetErrorString(status) << std::endl;

	exit(-1);
}

class MyRTPSession : public RTPSession
{
private:
	FILE *pLogFile;
public:
	MyRTPSession()
	{
		SetChangeIncomingData(true);

		pLogFile = fopen("logfile.dat", "wb");
	}

	~MyRTPSession()
	{
		if (pLogFile)
			fclose(pLogFile);
	}
protected:
	bool OnChangeIncomingData(RTPRawPacket *pPack)
	{
		if (pLogFile)
		{
			double t = pPack->GetReceiveTime().GetDouble();
			bool isRTP = pPack->IsRTP();
			uint32_t dataLength = (uint32_t)pPack->GetDataLength();

			if (isRTP)
				fwrite("RTP ", 1, 4, pLogFile);
			else
				fwrite("RTCP", 1, 4, pLogFile);

			fwrite(&t, 1, sizeof(double), pLogFile);
			fwrite(&dataLength, 1, sizeof(uint32_t),pLogFile);
			fwrite(pPack->GetData(), 1, dataLength, pLogFile);
		}
		return true;
	}

	void OnRTCPCompoundPacket(RTCPCompoundPacket *p, const RTPTime &receivetime, const RTPAddress *senderaddress)
	{
		printf("%u.%06u RECEIVED\n",receivetime.GetSeconds(),receivetime.GetMicroSeconds());

		DumpCompoundPacket(stdout,p);
	}

	void OnSendRTCPCompoundPacket(RTCPCompoundPacket *p)
	{
		RTPTime t = RTPTime::CurrentTime();

		printf("%u.%06u SENDING\n",t.GetSeconds(),t.GetMicroSeconds());

		DumpCompoundPacket(stdout,p);
	}

	void DumpCompoundPacket(FILE *f, RTCPCompoundPacket *p)
	{
		RTCPPacket *pack;

		p->GotoFirstPacket();
		while ((pack = p->GetNextPacket()) != 0)
		{
			if (pack->GetPacketType() == RTCPPacket::SR)
			{
				RTCPSRPacket *p = (RTCPSRPacket *)pack;

				RTPTime t(p->GetNTPTimestamp());

				fprintf(f,"  SR packet\n    SSRC %27u\n",p->GetSenderSSRC());
				fprintf(f,"    NTP timestamp: %10u.%06u\n    RTP timestamp: %17u\n    Packets sent: %18u\n    Octets sent: %19u\n",t.GetSeconds(),t.GetMicroSeconds(),p->GetRTPTimestamp(),p->GetSenderPacketCount(),p->GetSenderOctetCount());

				for (int i = 0 ; i < p->GetReceptionReportCount() ; i++)
					fprintf(f,"    RR block %d\n      SSRC %25u\n      Fraction lost: %15d\n      Packets lost: %16d\n      Ext. high. seq. nr: %10u\n      Jitter: %22u\n      LSR: %25u\n      DLSR: %24u\n",(i+1),
							p->GetSSRC(i),(int)p->GetFractionLost(i),p->GetLostPacketCount(i),p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),
							p->GetDLSR(i));
			}
			else if (pack->GetPacketType() == RTCPPacket::RR)
			{
				RTCPRRPacket *p = (RTCPRRPacket *)pack;

				fprintf(f,"  RR packet\n    SSRC %27u\n",p->GetSenderSSRC());

				for (int i = 0 ; i < p->GetReceptionReportCount() ; i++)
					fprintf(f,"    RR block %d\n      SSRC %25u\n      Fraction lost: %15d\n      Packets lost: %16d\n      Ext. high. seq. nr: %10u\n      Jitter: %22u\n      LSR: %25u\n      DLSR: %24u\n",(i+1),
							p->GetSSRC(i),(int)p->GetFractionLost(i),p->GetLostPacketCount(i),p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),
							p->GetDLSR(i));
			}
			else if (pack->GetPacketType() == RTCPPacket::SDES)
			{
				RTCPSDESPacket *p = (RTCPSDESPacket *)pack;
				char str[1024];

				if (!p->GotoFirstChunk())
					return;

				do
				{
					fprintf(f,"  SDES Chunk:\n");
					fprintf(f,"    SSRC: %26u\n",p->GetChunkSSRC());
					if (p->GotoFirstItem())
					{
						do
						{
							switch (p->GetItemType())
							{
							case RTCPSDESPacket::None:
								strcpy(str,"None    ");
								break;
							case RTCPSDESPacket::CNAME:
								strcpy(str,"CNAME:  ");
								break;
							case RTCPSDESPacket::NAME:
								strcpy(str,"NAME:   ");
								break;
							case RTCPSDESPacket::EMAIL:
								strcpy(str,"EMAIL:  ");
								break;
							case RTCPSDESPacket::PHONE:
								strcpy(str,"PHONE:  ");
								break;
							case RTCPSDESPacket::LOC:
								strcpy(str,"LOC:    ");
								break;
							case RTCPSDESPacket::TOOL:
								strcpy(str,"TOOL:   ");
								break;
							case RTCPSDESPacket::NOTE:
								strcpy(str,"NOTE:   ");
								break;
							case RTCPSDESPacket::PRIV:
								strcpy(str,"PRIV:   ");
								break;
							case RTCPSDESPacket::Unknown:
							default:
								strcpy(str,"Unknown ");
							}
							fprintf(f,"    %s",str);

							if (p->GetItemType() != RTCPSDESPacket::PRIV)
							{
								char str[1024];
								memcpy(str,p->GetItemData(),p->GetItemLength());
								str[p->GetItemLength()] = 0;
								fprintf(f,"%24s\n",str);
							}
						} while (p->GotoNextItem());
					}
				} while (p->GotoNextChunk());
			}
			else if (pack->GetPacketType() == RTCPPacket::BYE)
			{
				fprintf(f,"  BYE packet:\n");

				RTCPBYEPacket *p = (RTCPBYEPacket *)pack;

				int num = p->GetSSRCCount();
				int i;

				for (i = 0 ; i < num ; i++)
					fprintf(f,"    SSRC: %26u\n",p->GetSSRC(i));
				if (p->HasReasonForLeaving())
				{
					char str[1024];
					memcpy(str,p->GetReasonData(),p->GetReasonLength());
					str[p->GetReasonLength()] = 0;
					fprintf(f,"    Reason: %24s\n",str);
				}
			}
		}
		fprintf(f,"\n");
	}
};

int main(int argc, char *argv[])
{
	if (argc != 4)
	{
		fprintf(stderr, "Usage: rtcpdump portbase destIP destport\n");
		return -1;
	}

	int portBase = atoi(argv[1]);
	int destPort = atoi(argv[3]);
	std::string destIP(argv[2]);

	RTPIPv4Address dest;
	RTPUDPv4TransmissionParams transParams;
	RTPSessionParams sessParams;
	MyRTPSession session;

	dest.SetIP(ntohl(inet_addr(destIP.c_str())));
	dest.SetPort((uint16_t)destPort);

	transParams.SetPortbase((uint16_t)portBase);
	transParams.SetRTPReceiveBuffer(1024*1024);
	transParams.SetRTCPReceiveBuffer(1024*1024);
	sessParams.SetOwnTimestampUnit(1.0/5.0);
	sessParams.SetProbationType(RTPSources::NoProbation);

	int status;

	status = session.Create(sessParams, &transParams);
	checkError(status);

	status = session.AddDestination(dest);
	checkError(status);

	int i = 0;

	getchar();

	return 0;
}
<commit_msg>Added OnValidatedRTPPacket to discard (the unused) incoming RTP data<commit_after>#include "rtpsession.h"
#include "rtpipv4address.h"
#include "rtpsessionparams.h"
#include "rtpudpv4transmitter.h"
#include "rtperrors.h"
#include "rtcpcompoundpacket.h"
#include "rtcpsrpacket.h"
#include "rtcprrpacket.h"
#include "rtcpbyepacket.h"
#include "rtprawpacket.h"
#include <stdio.h>
#include <iostream>

using namespace jrtplib;

void checkError(int status)
{
	if (status >= 0)
		return;

	std::cerr << "An error occured in the RTP component: " << std::endl;
	std::cerr << "Error description: " << RTPGetErrorString(status) << std::endl;

	exit(-1);
}

class MyRTPSession : public RTPSession
{
private:
	FILE *pLogFile;
public:
	MyRTPSession()
	{
		SetChangeIncomingData(true);

		pLogFile = fopen("logfile.dat", "wb");
	}

	~MyRTPSession()
	{
		if (pLogFile)
			fclose(pLogFile);
	}
protected:
	void OnValidatedRTPPacket(RTPSourceData *srcdat, RTPPacket *rtppack, bool isonprobation, bool *ispackethandled)
	{
		// Make sure no RTP packets are stored internally, we'd just be wasting memory
		DeletePacket(rtppack);
		*ispackethandled = true;
	}

	bool OnChangeIncomingData(RTPRawPacket *pPack)
	{
		if (pLogFile)
		{
			double t = pPack->GetReceiveTime().GetDouble();
			bool isRTP = pPack->IsRTP();
			uint32_t dataLength = (uint32_t)pPack->GetDataLength();

			if (isRTP)
				fwrite("RTP ", 1, 4, pLogFile);
			else
				fwrite("RTCP", 1, 4, pLogFile);

			fwrite(&t, 1, sizeof(double), pLogFile);
			fwrite(&dataLength, 1, sizeof(uint32_t),pLogFile);
			fwrite(pPack->GetData(), 1, dataLength, pLogFile);
		}
		return true;
	}

	void OnRTCPCompoundPacket(RTCPCompoundPacket *p, const RTPTime &receivetime, const RTPAddress *senderaddress)
	{
		printf("%u.%06u RECEIVED\n",receivetime.GetSeconds(),receivetime.GetMicroSeconds());

		DumpCompoundPacket(stdout,p);
	}

	void OnSendRTCPCompoundPacket(RTCPCompoundPacket *p)
	{
		RTPTime t = RTPTime::CurrentTime();

		printf("%u.%06u SENDING\n",t.GetSeconds(),t.GetMicroSeconds());

		DumpCompoundPacket(stdout,p);
	}

	void DumpCompoundPacket(FILE *f, RTCPCompoundPacket *p)
	{
		RTCPPacket *pack;

		p->GotoFirstPacket();
		while ((pack = p->GetNextPacket()) != 0)
		{
			if (pack->GetPacketType() == RTCPPacket::SR)
			{
				RTCPSRPacket *p = (RTCPSRPacket *)pack;

				RTPTime t(p->GetNTPTimestamp());

				fprintf(f,"  SR packet\n    SSRC %27u\n",p->GetSenderSSRC());
				fprintf(f,"    NTP timestamp: %10u.%06u\n    RTP timestamp: %17u\n    Packets sent: %18u\n    Octets sent: %19u\n",t.GetSeconds(),t.GetMicroSeconds(),p->GetRTPTimestamp(),p->GetSenderPacketCount(),p->GetSenderOctetCount());

				for (int i = 0 ; i < p->GetReceptionReportCount() ; i++)
					fprintf(f,"    RR block %d\n      SSRC %25u\n      Fraction lost: %15d\n      Packets lost: %16d\n      Ext. high. seq. nr: %10u\n      Jitter: %22u\n      LSR: %25u\n      DLSR: %24u\n",(i+1),
							p->GetSSRC(i),(int)p->GetFractionLost(i),p->GetLostPacketCount(i),p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),
							p->GetDLSR(i));
			}
			else if (pack->GetPacketType() == RTCPPacket::RR)
			{
				RTCPRRPacket *p = (RTCPRRPacket *)pack;

				fprintf(f,"  RR packet\n    SSRC %27u\n",p->GetSenderSSRC());

				for (int i = 0 ; i < p->GetReceptionReportCount() ; i++)
					fprintf(f,"    RR block %d\n      SSRC %25u\n      Fraction lost: %15d\n      Packets lost: %16d\n      Ext. high. seq. nr: %10u\n      Jitter: %22u\n      LSR: %25u\n      DLSR: %24u\n",(i+1),
							p->GetSSRC(i),(int)p->GetFractionLost(i),p->GetLostPacketCount(i),p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),
							p->GetDLSR(i));
			}
			else if (pack->GetPacketType() == RTCPPacket::SDES)
			{
				RTCPSDESPacket *p = (RTCPSDESPacket *)pack;
				char str[1024];

				if (!p->GotoFirstChunk())
					return;

				do
				{
					fprintf(f,"  SDES Chunk:\n");
					fprintf(f,"    SSRC: %26u\n",p->GetChunkSSRC());
					if (p->GotoFirstItem())
					{
						do
						{
							switch (p->GetItemType())
							{
							case RTCPSDESPacket::None:
								strcpy(str,"None    ");
								break;
							case RTCPSDESPacket::CNAME:
								strcpy(str,"CNAME:  ");
								break;
							case RTCPSDESPacket::NAME:
								strcpy(str,"NAME:   ");
								break;
							case RTCPSDESPacket::EMAIL:
								strcpy(str,"EMAIL:  ");
								break;
							case RTCPSDESPacket::PHONE:
								strcpy(str,"PHONE:  ");
								break;
							case RTCPSDESPacket::LOC:
								strcpy(str,"LOC:    ");
								break;
							case RTCPSDESPacket::TOOL:
								strcpy(str,"TOOL:   ");
								break;
							case RTCPSDESPacket::NOTE:
								strcpy(str,"NOTE:   ");
								break;
							case RTCPSDESPacket::PRIV:
								strcpy(str,"PRIV:   ");
								break;
							case RTCPSDESPacket::Unknown:
							default:
								strcpy(str,"Unknown ");
							}
							fprintf(f,"    %s",str);

							if (p->GetItemType() != RTCPSDESPacket::PRIV)
							{
								char str[1024];
								memcpy(str,p->GetItemData(),p->GetItemLength());
								str[p->GetItemLength()] = 0;
								fprintf(f,"%24s\n",str);
							}
						} while (p->GotoNextItem());
					}
				} while (p->GotoNextChunk());
			}
			else if (pack->GetPacketType() == RTCPPacket::BYE)
			{
				fprintf(f,"  BYE packet:\n");

				RTCPBYEPacket *p = (RTCPBYEPacket *)pack;

				int num = p->GetSSRCCount();
				int i;

				for (i = 0 ; i < num ; i++)
					fprintf(f,"    SSRC: %26u\n",p->GetSSRC(i));
				if (p->HasReasonForLeaving())
				{
					char str[1024];
					memcpy(str,p->GetReasonData(),p->GetReasonLength());
					str[p->GetReasonLength()] = 0;
					fprintf(f,"    Reason: %24s\n",str);
				}
			}
		}
		fprintf(f,"\n");
	}
};

int main(int argc, char *argv[])
{
	if (argc != 4)
	{
		fprintf(stderr, "Usage: rtcpdump portbase destIP destport\n");
		return -1;
	}

	int portBase = atoi(argv[1]);
	int destPort = atoi(argv[3]);
	std::string destIP(argv[2]);

	RTPIPv4Address dest;
	RTPUDPv4TransmissionParams transParams;
	RTPSessionParams sessParams;
	MyRTPSession session;

	dest.SetIP(ntohl(inet_addr(destIP.c_str())));
	dest.SetPort((uint16_t)destPort);

	transParams.SetPortbase((uint16_t)portBase);
	transParams.SetRTPReceiveBuffer(1024*1024);
	transParams.SetRTCPReceiveBuffer(1024*1024);
	sessParams.SetOwnTimestampUnit(1.0/5.0);
	sessParams.SetProbationType(RTPSources::NoProbation);

	int status;

	status = session.Create(sessParams, &transParams);
	checkError(status);

	status = session.AddDestination(dest);
	checkError(status);

	int i = 0;

	getchar();

	return 0;
}
<|endoftext|>


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

/*
  definition of the current version of OpenCV
  Usefull to test in user programs
*/

#ifndef __OPENCV_VERSION_HPP__
#define __OPENCV_VERSION_HPP__

#define CV_VERSION_EPOCH    2
#define CV_VERSION_MAJOR    4
#define CV_VERSION_MINOR    9
#define CV_VERSION_REVISION 0

#define CVAUX_STR_EXP(__A)  #__A
#define CVAUX_STR(__A)      CVAUX_STR_EXP(__A)

#if CV_VERSION_REVISION
#  define CV_VERSION        CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION)
#else
#  define CV_VERSION        CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR)
#endif

/* old  style version constants*/
#define CV_MAJOR_VERSION    CV_VERSION_EPOCH
#define CV_MINOR_VERSION    CV_VERSION_MAJOR
#define CV_SUBMINOR_VERSION CV_VERSION_MINOR

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

/*
  definition of the current version of OpenCV
  Usefull to test in user programs
*/

#ifndef __OPENCV_VERSION_HPP__
#define __OPENCV_VERSION_HPP__

#define CV_VERSION_EPOCH    2
#define CV_VERSION_MAJOR    9
#define CV_VERSION_MINOR    0
#define CV_VERSION_REVISION 0

#define CVAUX_STR_EXP(__A)  #__A
#define CVAUX_STR(__A)      CVAUX_STR_EXP(__A)

#if CV_VERSION_REVISION
#  define CV_VERSION        CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION)
#else
#  define CV_VERSION        CVAUX_STR(CV_VERSION_EPOCH) "." CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR)
#endif

/* old  style version constants*/
#define CV_MAJOR_VERSION    CV_VERSION_EPOCH
#define CV_MINOR_VERSION    CV_VERSION_MAJOR
#define CV_SUBMINOR_VERSION CV_VERSION_MINOR

#endif
<|endoftext|>


<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>

#include <node-manager/DistributedSynchroFactory.h>
#include <node-manager/ScdSharding.h>
#include <node-manager/ShardingStrategy.h>
#include <node-manager/ScdDispatcher.h>

using namespace std;
using namespace sf1r;
using namespace boost;
using namespace boost::lambda;

void callback_on_consumed(bool isSuccess)
{
    cout <<"--> callback on consume finished: "<<isSuccess<<endl;
}

bool callback_on_produced(const std::string& datapath)
{
    cout<<"--> callback on produced: "<<datapath<<endl;

    cout<<"Consuming ..." <<endl;
    sleep(5);

    return true;
}

void thread_consumer_run()
{
    SynchroConsumerPtr scp =
            DistributedSynchroFactory::makeConsumer(DistributedSynchroFactory::SYNCHRO_TYPE_PRODUCT_MANAGER);

    scp->watchProducer(callback_on_produced, true);
}

BOOST_AUTO_TEST_SUITE( t_zookeeper )

BOOST_AUTO_TEST_CASE( node_manager_synchro )
{
    return;
    // set default config
    DistributedTopologyConfig dsTopologyConfig;
    dsTopologyConfig.clusterId_ = "zhongxia";
    dsTopologyConfig.nodeNum_ = 2;
    dsTopologyConfig.curSF1Node_.host_ = "172.16.0.36";
    dsTopologyConfig.curSF1Node_.nodeId_ = 1;
    dsTopologyConfig.curSF1Node_.replicaId_ = 1;
    DistributedUtilConfig dsUtilConfig;
    dsUtilConfig.zkConfig_.zkHosts_ = "172.16.0.161:2181,172.16.0.162:2181,172.16.0.163:2181";
    dsUtilConfig.zkConfig_.zkRecvTimeout_ = 2000;

    NodeManagerSingleton::get()->initWithConfig(dsTopologyConfig, dsUtilConfig);

    // Consumer
    boost::thread consumer_thread(thread_consumer_run);

    // Producer
    {
    SynchroProducerPtr spd =
        DistributedSynchroFactory::makeProcuder(DistributedSynchroFactory::SYNCHRO_TYPE_PRODUCT_MANAGER);
    spd->produce("/data/scd", callback_on_consumed);
    bool ret;
    spd->waitConsumers(ret);
    cout << "Producer: wait consumers ended " <<ret<<endl;

    spd->produce("/data/scd2", callback_on_consumed);

    //while (true)
        sleep(6);
    }
}

BOOST_AUTO_TEST_SUITE_END()

<commit_msg>adjust unitest<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>

#include <node-manager/DistributedSynchroFactory.h>
#include <node-manager/ScdSharding.h>
#include <node-manager/ShardingStrategy.h>
#include <node-manager/ScdDispatcher.h>

using namespace std;
using namespace sf1r;
using namespace boost;
using namespace boost::lambda;

void callback_on_consumed(bool isSuccess)
{
    cout <<"--> callback on consume finished: "<<isSuccess<<endl;
}

bool callback_on_produced(const std::string& datapath)
{
    cout<<"--> callback on produced: "<<datapath<<endl;

    cout<<"Consuming ..." <<endl;
    sleep(5);

    return true;
}

void thread_consumer_run()
{
    SynchroConsumerPtr scp =
            DistributedSynchroFactory::makeConsumer(DistributedSynchroFactory::SYNCHRO_TYPE_PRODUCT_MANAGER);

    scp->watchProducer(callback_on_produced, true);
}

BOOST_AUTO_TEST_SUITE( t_zookeeper )

BOOST_AUTO_TEST_CASE( node_manager_synchro )
{
    // set default config
    DistributedTopologyConfig dsTopologyConfig;
    dsTopologyConfig.clusterId_ = "zhongxia";
    dsTopologyConfig.nodeNum_ = 2;
    dsTopologyConfig.curSF1Node_.host_ = "172.16.0.36";
    dsTopologyConfig.curSF1Node_.nodeId_ = 1;
    dsTopologyConfig.curSF1Node_.replicaId_ = 1;
    DistributedUtilConfig dsUtilConfig;
    dsUtilConfig.zkConfig_.zkHosts_ = "172.16.0.161:2181,172.16.0.162:2181,172.16.0.163:2181";
    dsUtilConfig.zkConfig_.zkRecvTimeout_ = 2000;

    NodeManagerSingleton::get()->initWithConfig(dsTopologyConfig, dsUtilConfig);

    // Consumer
    boost::thread consumer_thread(thread_consumer_run);

    // Producer
    {
    SynchroProducerPtr spd =
        DistributedSynchroFactory::makeProcuder(DistributedSynchroFactory::SYNCHRO_TYPE_PRODUCT_MANAGER);
    spd->produce("/data/scd", callback_on_consumed);
    bool ret;
    spd->waitConsumers(ret);
    cout << "Producer: wait consumers ended " <<ret<<endl;

    //spd->produce("/data/scd2", callback_on_consumed);

    //while (true)
    //    sleep(4);
    }
}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>


<commit_before>#include "support.h"

#include <fstream>
#include <iso646.h>
#include <sstream>

#include <sha256.h>

#include "lexer.h"
#include "parser.h"
#include "compiler.h"

bool CompilerSupport::loadBytecode(const std::string &name, Bytecode &object)
{
    std::pair<std::string, std::string> names = findModule(name);
    if (names.first.empty() && names.second.empty()) {
        return false;
    }

    std::ifstream obj(names.second, std::ios::binary);
    std::ifstream src(names.first);

    std::string source;
    if (src.good()) {
        std::stringstream buf;
        buf << src.rdbuf();
        source = buf.str();
    }

    if (obj.good() && not source.empty()) {
        SHA256 sha256;
        sha256(source);
        unsigned char h[SHA256::HashBytes];
        sha256.getHash(h);
        std::string hash = std::string(h, h+sizeof(h));

        std::stringstream buf;
        buf << obj.rdbuf();
        std::vector<unsigned char> bytecode;
        std::string s = buf.str();
        std::copy(s.begin(), s.end(), std::back_inserter(bytecode));
        object = Bytecode(bytecode);

        if (object.source_hash == hash) {
            return true;
        }
    }

    if (not source.empty()) {
        {
            std::ofstream outf(names.first+"x", std::ios::binary);
            auto tokens = tokenize(source);
            auto parsetree = parse(tokens);
            auto ast = analyze(this, parsetree);
            auto bytecode = compile(ast, nullptr);
            outf.write(reinterpret_cast<const std::ofstream::char_type *>(bytecode.data()), bytecode.size());
        }
        obj.open(names.first+"x", std::ios::binary);
        if (not obj.good()) {
            return false;
        }
    }

    std::stringstream buf;
    buf << obj.rdbuf();
    std::vector<unsigned char> bytecode;
    std::string s = buf.str();
    std::copy(s.begin(), s.end(), std::back_inserter(bytecode));
    object = Bytecode(bytecode);
    return true;
}
<commit_msg>Fix another compile problem on import<commit_after>#include "support.h"

#include <fstream>
#include <iso646.h>
#include <sstream>

#include <sha256.h>

#include "lexer.h"
#include "parser.h"
#include "compiler.h"

bool CompilerSupport::loadBytecode(const std::string &name, Bytecode &object)
{
    std::pair<std::string, std::string> names = findModule(name);
    if (names.first.empty() && names.second.empty()) {
        return false;
    }

    std::ifstream obj(names.second, std::ios::binary);
    std::ifstream src(names.first);

    std::string source;
    if (src.good()) {
        std::stringstream buf;
        buf << src.rdbuf();
        source = buf.str();
    }

    if (obj.good() && not source.empty()) {
        SHA256 sha256;
        sha256(source);
        unsigned char h[SHA256::HashBytes];
        sha256.getHash(h);
        std::string hash = std::string(h, h+sizeof(h));

        std::stringstream buf;
        buf << obj.rdbuf();
        std::vector<unsigned char> bytecode;
        std::string s = buf.str();
        std::copy(s.begin(), s.end(), std::back_inserter(bytecode));
        object = Bytecode(bytecode);

        if (object.source_hash == hash) {
            return true;
        }
    }

    if (not source.empty()) {
        {
            std::ofstream outf(names.first+"x", std::ios::binary);
            auto tokens = tokenize(source);
            auto parsetree = parse(tokens);
            auto ast = analyze(this, parsetree);
            auto bytecode = compile(ast, nullptr);
            outf.write(reinterpret_cast<const std::ofstream::char_type *>(bytecode.data()), bytecode.size());
        }
        obj.close();
        obj.open(names.first+"x", std::ios::binary);
        if (not obj.good()) {
            return false;
        }
    }

    std::stringstream buf;
    buf << obj.rdbuf();
    std::vector<unsigned char> bytecode;
    std::string s = buf.str();
    std::copy(s.begin(), s.end(), std::back_inserter(bytecode));
    object = Bytecode(bytecode);
    return true;
}
<|endoftext|>


<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/*
 * Copyright (C) FFLAS-FFPACK
 * Written by Hongguang ZHU <zhuhongguang2014@gmail.com>
 * This file is Free Software and part of FFLAS-FFPACK.
 *
 * ========LICENCE========
 * This file is part of the library FFLAS-FFPACK.
 *
 * FFLAS-FFPACK 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 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 *.
 */
#define  __FFLASFFPACK_SEQUENTIAL

//#define ENABLE_ALL_CHECKINGS 1

//#include "fflas-ffpack/fflas-ffpack-config.h"
#include <givaro/modular-integer.h>

#include <iomanip>
#include <iostream>

#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "fflas-ffpack/utils/test-utils.h"
#include <givaro/modular.h>
#include <givaro/modular-balanced.h>

using namespace std;
using namespace FFPACK;
using Givaro::Modular;
using Givaro::ModularBalanced;

template<typename Field, class RandIter>
bool check_solve(const Field &F, size_t m, RandIter& Rand){

typedef typename Field::Element_ptr A, A2, B, B2, x;

	size_t lda,incb,incx;
	lda=m;
	incb=1;
	incx=1;
	A  = FFLAS::fflas_new(F,m,lda);
	A2 = FFLAS::fflas_new(F,m,lda);
	B  = FFLAS::fflas_new(F,m,incb);
	B2 = FFLAS::fflas_new(F,m,incb);
	x  = FFLAS::fflas_new(F,m,incx);

	RandomMatrixWithRank (F,  m,  m, m, A, lda, Rand);

	RandomMatrix (F, m, 1, B, incb, Rand);

	FFLAS::fassign (F, m, B, incb, B2, incb);
	FFLAS::fassign (F, m, m, A, lda, A2, lda);
	#ifdef DEBUG
	FFLAS::WriteMatrix(std::cout<<"b:="<<std::endl,F,m,1,B,incb)<<std::endl;
	#endif
	FFLAS::Timer t; t.clear();
	double time=0.0;
	t.clear();
	t.start();

	FFPACK::Solve(F, m, A, lda, x, incx, B, incb);
	t.stop();
	time+=t.usertime();

	FFLAS::fgemv(F, FFLAS::FflasNoTrans, m, m, F.one, A2, lda, x, incx, F.zero, B, incb);

	bool ok = true;
	if (FFLAS::fequal (F, m, 1, B2, incb, B, incb)){

		cout << "PASSED ("<<time<<")"<<endl;

	} else{
		#ifdef DEBUG
		FFLAS::WriteMatrix(std::cout<<"A*x:="<<std::endl,F,m,1,B2,incb)<<std::endl;
		FFLAS::WriteMatrix(std::cout<<"b:="<<std::endl,F,m,1,B,incb)<<std::endl;
		#endif
		cout << "FAILED ("<<time<<")"<<endl;
		ok=false;

	}

	FFLAS::fflas_delete(A);
	FFLAS::fflas_delete(A2);
	FFLAS::fflas_delete(B);
	FFLAS::fflas_delete(B2);
	FFLAS::fflas_delete(x);
	return ok;
}
template <class Field>
bool run_with_field (Givaro::Integer q, size_t b, size_t m, size_t iters, uint64_t seed){
	bool ok = true ;
	int nbit=(int)iters;

	while (ok &&  nbit){
		//typedef typename Field::Element Element ;
		// choose Field
		Field* F= chooseField<Field>(q,b);
		typename Field::RandIter G(*F,0,seed);
		if (F==nullptr)
			return true;

		cout<<"Checking with ";F->write(cout)<<endl;
		ok = ok && check_solve(*F,m,G);

		nbit--;
		delete F;

	}

	return ok;
}

int main(int argc, char** argv)
{
	cerr<<setprecision(10);
	Givaro::Integer q=-1;
	size_t b=0;
	size_t m=300;

	size_t iters=30;
	bool loop=false;
	uint64_t seed = time(NULL);
	Argument as[] = {
		{ 'q', "-q Q", "Set the field characteristic (-1 for random).",         TYPE_INTEGER , &q },
		{ 'b', "-b B", "Set the bitsize of the field characteristic.",  TYPE_INT , &b },
		{ 'm', "-m M", "Set the dimension of unknown square matrix.",      TYPE_INT , &m },

		{ 'i', "-i R", "Set number of repetitions.",            TYPE_INT , &iters },
		{ 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop },
		{ 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed },
                END_OF_ARGUMENTS
        };

	FFLAS::parseArguments(argc,argv,as);

	bool ok = true;

	do{
		ok = ok && run_with_field<Modular<double> >(q,b,m,iters,seed);
		ok = ok && run_with_field<ModularBalanced<double> >(q,b,m,iters,seed);
		ok = ok && run_with_field<Modular<float> >(q,b,m,iters,seed);
		ok = ok && run_with_field<ModularBalanced<float> >(q,b,m,iters,seed);
		ok = ok && run_with_field<Modular<int32_t> >(q,b,m,iters,seed);
		ok = ok && run_with_field<ModularBalanced<int32_t> >(q,b,m,iters,seed);
		ok = ok && run_with_field<Modular<int64_t> >(q,b,m,iters,seed);
		ok = ok && run_with_field<ModularBalanced<int64_t> >(q,b,m,iters,seed);
		ok = ok &&run_with_field<Givaro::Modular<Givaro::Integer> > (q,5,m/6,iters,seed);
		ok = ok &&run_with_field<Givaro::Modular<Givaro::Integer> > (q,(b?b:512),m/6,iters,seed);

	} while (loop && ok);

	return !ok ;
}
<commit_msg>fix typo<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/*
 * Copyright (C) FFLAS-FFPACK
 * Written by Hongguang ZHU <zhuhongguang2014@gmail.com>
 * This file is Free Software and part of FFLAS-FFPACK.
 *
 * ========LICENCE========
 * This file is part of the library FFLAS-FFPACK.
 *
 * FFLAS-FFPACK 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 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 *.
 */
#define  __FFLASFFPACK_SEQUENTIAL

//#define ENABLE_ALL_CHECKINGS 1

//#include "fflas-ffpack/fflas-ffpack-config.h"
#include <givaro/modular-integer.h>

#include <iomanip>
#include <iostream>

#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "fflas-ffpack/utils/test-utils.h"
#include <givaro/modular.h>
#include <givaro/modular-balanced.h>

using namespace std;
using namespace FFPACK;
using Givaro::Modular;
using Givaro::ModularBalanced;

template<typename Field, class RandIter>
bool check_solve(const Field &F, size_t m, RandIter& Rand){

	typename Field::Element_ptr A, A2, B, B2, x;

	size_t lda,incb,incx;
	lda=m;
	incb=1;
	incx=1;
	A  = FFLAS::fflas_new(F,m,lda);
	A2 = FFLAS::fflas_new(F,m,lda);
	B  = FFLAS::fflas_new(F,m,incb);
	B2 = FFLAS::fflas_new(F,m,incb);
	x  = FFLAS::fflas_new(F,m,incx);

	RandomMatrixWithRank (F,  m,  m, m, A, lda, Rand);

	RandomMatrix (F, m, 1, B, incb, Rand);

	FFLAS::fassign (F, m, B, incb, B2, incb);
	FFLAS::fassign (F, m, m, A, lda, A2, lda);
	#ifdef DEBUG
	FFLAS::WriteMatrix(std::cout<<"b:="<<std::endl,F,m,1,B,incb)<<std::endl;
	#endif
	FFLAS::Timer t; t.clear();
	double time=0.0;
	t.clear();
	t.start();

	FFPACK::Solve(F, m, A, lda, x, incx, B, incb);
	t.stop();
	time+=t.usertime();

	FFLAS::fgemv(F, FFLAS::FflasNoTrans, m, m, F.one, A2, lda, x, incx, F.zero, B, incb);

	bool ok = true;
	if (FFLAS::fequal (F, m, 1, B2, incb, B, incb)){

		cout << "PASSED ("<<time<<")"<<endl;

	} else{
		#ifdef DEBUG
		FFLAS::WriteMatrix(std::cout<<"A*x:="<<std::endl,F,m,1,B2,incb)<<std::endl;
		FFLAS::WriteMatrix(std::cout<<"b:="<<std::endl,F,m,1,B,incb)<<std::endl;
		#endif
		cout << "FAILED ("<<time<<")"<<endl;
		ok=false;

	}

	FFLAS::fflas_delete(A);
	FFLAS::fflas_delete(A2);
	FFLAS::fflas_delete(B);
	FFLAS::fflas_delete(B2);
	FFLAS::fflas_delete(x);
	return ok;
}
template <class Field>
bool run_with_field (Givaro::Integer q, size_t b, size_t m, size_t iters, uint64_t seed){
	bool ok = true ;
	int nbit=(int)iters;

	while (ok &&  nbit){
		//typedef typename Field::Element Element ;
		// choose Field
		Field* F= chooseField<Field>(q,b);
		typename Field::RandIter G(*F,0,seed);
		if (F==nullptr)
			return true;

		cout<<"Checking with ";F->write(cout)<<endl;
		ok = ok && check_solve(*F,m,G);

		nbit--;
		delete F;

	}

	return ok;
}

int main(int argc, char** argv)
{
	cerr<<setprecision(10);
	Givaro::Integer q=-1;
	size_t b=0;
	size_t m=300;

	size_t iters=30;
	bool loop=false;
	uint64_t seed = time(NULL);
	Argument as[] = {
		{ 'q', "-q Q", "Set the field characteristic (-1 for random).",         TYPE_INTEGER , &q },
		{ 'b', "-b B", "Set the bitsize of the field characteristic.",  TYPE_INT , &b },
		{ 'm', "-m M", "Set the dimension of unknown square matrix.",      TYPE_INT , &m },

		{ 'i', "-i R", "Set number of repetitions.",            TYPE_INT , &iters },
		{ 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop },
		{ 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed },
                END_OF_ARGUMENTS
        };

	FFLAS::parseArguments(argc,argv,as);

	bool ok = true;

	do{
		ok = ok && run_with_field<Modular<double> >(q,b,m,iters,seed);
		ok = ok && run_with_field<ModularBalanced<double> >(q,b,m,iters,seed);
		ok = ok && run_with_field<Modular<float> >(q,b,m,iters,seed);
		ok = ok && run_with_field<ModularBalanced<float> >(q,b,m,iters,seed);
		ok = ok && run_with_field<Modular<int32_t> >(q,b,m,iters,seed);
		ok = ok && run_with_field<ModularBalanced<int32_t> >(q,b,m,iters,seed);
		ok = ok && run_with_field<Modular<int64_t> >(q,b,m,iters,seed);
		ok = ok && run_with_field<ModularBalanced<int64_t> >(q,b,m,iters,seed);
		ok = ok &&run_with_field<Givaro::Modular<Givaro::Integer> > (q,5,m/6,iters,seed);
		ok = ok &&run_with_field<Givaro::Modular<Givaro::Integer> > (q,(b?b:512),m/6,iters,seed);

	} while (loop && ok);

	return !ok ;
}
<|endoftext|>


<commit_before><commit_msg>Newton and AMR in a loop<commit_after><|endoftext|>


<commit_before>#include <tiramisu/tiramisu.h>

using namespace tiramisu;

void gen(std::string name, int size, int val0, int val1)
{
    tiramisu::init(name);

    tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0);

    tiramisu::var i("i", 0, N), j("j", 0, N);
    tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1");

    tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j);

    S0.tile(i, j, 2, 2, i0, j0, i1, j1);
    S0.tag_parallel_level(i0);

    tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output);
    S0.store_in(&buf0, {i ,j});

    tiramisu::codegen({&buf0}, "build/generated_fct_test_119.o");
}

int main(int argc, char **argv)
{
    gen("func", 10, 3, 4);

    return 0;
}
<commit_msg>Fix test<commit_after>#include <tiramisu/tiramisu.h>

using namespace tiramisu;

void gen(std::string name, int size, int val0, int val1)
{
    tiramisu::init(name);

    tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0);

    tiramisu::var i("i", 0, N), j("j", 0, N);
    tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1");

    tiramisu::computation S0({i, j}, tiramisu::expr((uint8_t) (val0 + val1)));

    S0.tile(i, j, 2, 2, i0, j0, i1, j1);
    S0.tag_parallel_level(i0);

    tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output);
    S0.store_in(&buf0, {i ,j});

    tiramisu::codegen({&buf0}, "build/generated_fct_test_119.o");
}

int main(int argc, char **argv)
{
    gen("func", 10, 3, 4);

    return 0;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>

#include <yaml-cpp/yaml.h>

#include <vector>
#include <fstream>
#include <string>

#include <visualization_msgs/MarkerArray.h>

class WaypointsNavigation{
public:
    WaypointsNavigation() :
        has_activate_(false),
        move_base_action_("move_base", true),
        rate_(10)
    {
        while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))
        {
            ROS_INFO("Waiting...");
        }

        ros::NodeHandle private_nh("~");
        private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
        private_nh.param("world_frame", world_frame_, std::string("/map"));

        double max_update_rate;
        private_nh.param("max_update_rate", max_update_rate, 10.0);
        rate_ = ros::Rate(max_update_rate);
        std::string filename = "";
        private_nh.param("filename", filename, filename);
        if(filename != ""){
            ROS_INFO_STREAM("Read waypoints data from " << filename);
            readFile(filename);
        }

        ros::NodeHandle nh;
        syscommand_sub_ = nh.subscribe("syscommand", 1, &WaypointsNavigation::syscommandCallback, this);
        marker_pub_ = nh.advertise<visualization_msgs::MarkerArray>("visualization_marker", 10);
    }

    void syscommandCallback(const std_msgs::String &msg){
        if(msg.data == "start"){
            has_activate_ = true;
        }
    }

    bool readFile(const std::string &filename){
        waypoints_.clear();
        try{
            std::ifstream ifs(filename.c_str(), std::ifstream::in);
            if(ifs.good() == false){
                return false;
            }

            YAML::Node node;
            node = YAML::Load(ifs);
            const YAML::Node &wp_node_tmp = node["waypoints"];
            const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;
            if(wp_node != NULL){
                for(int i=0; i < wp_node->size(); i++){
                    geometry_msgs::PointStamped point;

                    point.point.x = (*wp_node)[i]["point"]["x"].as<double>();
                    point.point.y = (*wp_node)[i]["point"]["y"].as<double>();
                    point.point.z = (*wp_node)[i]["point"]["z"].as<double>();

                    waypoints_.push_back(point);

                }
            }else{
                return false;
            }

            const YAML::Node &fp_node_tmp = node["finish_pose"];
            const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;

            if(fp_node != NULL){
                finish_pose_.position.x = (*fp_node)["pose"]["position"]["x"].as<double>();
                finish_pose_.position.y = (*fp_node)["pose"]["position"]["y"].as<double>();
                finish_pose_.position.z = (*fp_node)["pose"]["position"]["z"].as<double>();

                finish_pose_.orientation.x = (*fp_node)["pose"]["orientation"]["x"].as<double>();
                finish_pose_.orientation.y = (*fp_node)["pose"]["orientation"]["y"].as<double>();
                finish_pose_.orientation.z = (*fp_node)["pose"]["orientation"]["z"].as<double>();
                finish_pose_.orientation.w = (*fp_node)["pose"]["orientation"]["w"].as<double>();
            }else{
                return false;
            }

        }catch(YAML::ParserException &e){
            return false;

        }catch(YAML::RepresentationException &e){
            return false;
        }

        return true;
    }

    bool shouldSendGoal(){
        bool ret = true;
        actionlib::SimpleClientGoalState state = move_base_action_.getState();
        if((state != actionlib::SimpleClientGoalState::ACTIVE) &&
           (state != actionlib::SimpleClientGoalState::PENDING) &&
           (state != actionlib::SimpleClientGoalState::RECALLED) &&
           (state != actionlib::SimpleClientGoalState::PREEMPTED))
        {
            ret = false;
        }

        if(waypoints_.empty()){
            ret = false;
        }

        return ret;
    }

    bool navigationFinished(){
        return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;
    }

    bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){
        tf::StampedTransform robot_gl;
        try{
            tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
        }catch(tf::TransformException &e){
            ROS_WARN_STREAM("tf::TransformException: " << e.what());
        }
        const double wx = dest.x;
        const double wy = dest.y;
        const double rx = robot_gl.getOrigin().x();
        const double ry = robot_gl.getOrigin().y();
        const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));

        return dist < dist_err;
    }

    void sleep(){
        rate_.sleep();
        ros::spinOnce();
        publishMarkers();
    }

    void startNavigationGL(const geometry_msgs::Point &dest){
        geometry_msgs::Pose pose;
        pose.position = dest;
        pose.orientation = tf::createQuaternionMsgFromYaw(0.0);
        startNavigationGL(pose);
    }

    void startNavigationGL(const geometry_msgs::Pose &dest){
        move_base_msgs::MoveBaseGoal move_base_goal;
        move_base_goal.target_pose.header.stamp = ros::Time::now();
        move_base_goal.target_pose.header.frame_id = world_frame_;
        move_base_goal.target_pose.pose.position = dest.position;
        move_base_goal.target_pose.pose.orientation = dest.orientation;

        move_base_action_.sendGoal(move_base_goal);
    }

    void publishMarkers(){
        visualization_msgs::MarkerArray markers_array;
        for(int i=0; i < waypoints_.size(); i++){
            visualization_msgs::Marker marker, label;
            marker.header.frame_id = world_frame_;
            marker.header.stamp = ros::Time::now();
            marker.scale.x = 0.2;
            marker.scale.y = 0.2;
            marker.scale.z = 0.2;
            marker.pose.position.z = marker.scale.z / 2.0;
            marker.color.r = 0.8f;
            marker.color.g = 0.2f;
            marker.color.b = 0.2f;

            std::stringstream name;
            name << "waypoint " << i;
            marker.ns = name.str();
            marker.id = i;
            marker.pose.position.x = waypoints_[i].point.x;
            marker.pose.position.y = waypoints_[i].point.y;
            marker.type = visualization_msgs::Marker::SPHERE;
            marker.action = visualization_msgs::Marker::ADD;
            marker.color.a = 1.0f;
            markers_array.markers.push_back(marker);

            //ROS_INFO_STREAM("waypoints \n" << waypoints_[i]);
        }
        marker_pub_.publish(markers_array);
    }

    void run(){
        while(ros::ok()){
            if(has_activate_){
                for(int i=0; i < waypoints_.size(); i++){
                    ROS_INFO_STREAM("waypoint = " << waypoints_[i]);
                    if(!ros::ok()) break;

                    startNavigationGL(waypoints_[i].point);
                    double start_nav_time = ros::Time::now().toSec();
                    while(!onNavigationPoint(waypoints_[i].point)){
                        if(ros::Time::now().toSec() - start_nav_time > 10.0){
                            ROS_INFO("Resend the navigation goal.");
                            startNavigationGL(waypoints_[i].point);
                            start_nav_time = ros::Time::now().toSec();
                        }
                        actionlib::SimpleClientGoalState state = move_base_action_.getState();
                        sleep();
                    }
                    ROS_INFO("waypoint goal");
                }
                ROS_INFO("waypoints clear");
                waypoints_.clear();
                startNavigationGL(finish_pose_);
                while(!navigationFinished() && ros::ok()) sleep();
                has_activate_ = false;
            }

            sleep();
        }
    }

private:
    actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;
    std::vector<geometry_msgs::PointStamped> waypoints_;
    geometry_msgs::Pose finish_pose_;
    bool has_activate_;
    std::string robot_frame_, world_frame_;
    tf::TransformListener tf_listener_;
    ros::Rate rate_;
    ros::Subscriber syscommand_sub_;
    ros::Publisher marker_pub_;
};

int main(int argc, char *argv[]){
    ros::init(argc, argv, ROS_PACKAGE_NAME);
    WaypointsNavigation w_nav;
    w_nav.run();

    return 0;
}
<commit_msg>Add a service to clear costmaps<commit_after>#include <ros/ros.h>
#include <std_msgs/String.h>
#include <std_srvs/Empty.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>

#include <yaml-cpp/yaml.h>

#include <vector>
#include <fstream>
#include <string>

#include <visualization_msgs/MarkerArray.h>

class WaypointsNavigation{
public:
    WaypointsNavigation() :
        has_activate_(false),
        move_base_action_("move_base", true),
        rate_(10)
    {
        while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))
        {
            ROS_INFO("Waiting...");
        }

        ros::NodeHandle private_nh("~");
        private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
        private_nh.param("world_frame", world_frame_, std::string("/map"));

        double max_update_rate;
        private_nh.param("max_update_rate", max_update_rate, 10.0);
        rate_ = ros::Rate(max_update_rate);
        std::string filename = "";
        private_nh.param("filename", filename, filename);
        if(filename != ""){
            ROS_INFO_STREAM("Read waypoints data from " << filename);
            readFile(filename);
        }

        ros::NodeHandle nh;
        syscommand_sub_ = nh.subscribe("syscommand", 1, &WaypointsNavigation::syscommandCallback, this);
        marker_pub_ = nh.advertise<visualization_msgs::MarkerArray>("visualization_marker", 10);
        clear_costmaps_srv_ = nh.serviceClient<std_srvs::Empty>("/move_base/clear_costmaps");
    }

    void syscommandCallback(const std_msgs::String &msg){
        if(msg.data == "start"){
            has_activate_ = true;
        }
    }

    bool readFile(const std::string &filename){
        waypoints_.clear();
        try{
            std::ifstream ifs(filename.c_str(), std::ifstream::in);
            if(ifs.good() == false){
                return false;
            }

            YAML::Node node;
            node = YAML::Load(ifs);
            const YAML::Node &wp_node_tmp = node["waypoints"];
            const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;
            if(wp_node != NULL){
                for(int i=0; i < wp_node->size(); i++){
                    geometry_msgs::PointStamped point;

                    point.point.x = (*wp_node)[i]["point"]["x"].as<double>();
                    point.point.y = (*wp_node)[i]["point"]["y"].as<double>();
                    point.point.z = (*wp_node)[i]["point"]["z"].as<double>();

                    waypoints_.push_back(point);

                }
            }else{
                return false;
            }

            const YAML::Node &fp_node_tmp = node["finish_pose"];
            const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;

            if(fp_node != NULL){
                finish_pose_.position.x = (*fp_node)["pose"]["position"]["x"].as<double>();
                finish_pose_.position.y = (*fp_node)["pose"]["position"]["y"].as<double>();
                finish_pose_.position.z = (*fp_node)["pose"]["position"]["z"].as<double>();

                finish_pose_.orientation.x = (*fp_node)["pose"]["orientation"]["x"].as<double>();
                finish_pose_.orientation.y = (*fp_node)["pose"]["orientation"]["y"].as<double>();
                finish_pose_.orientation.z = (*fp_node)["pose"]["orientation"]["z"].as<double>();
                finish_pose_.orientation.w = (*fp_node)["pose"]["orientation"]["w"].as<double>();
            }else{
                return false;
            }

        }catch(YAML::ParserException &e){
            return false;

        }catch(YAML::RepresentationException &e){
            return false;
        }

        return true;
    }

    bool shouldSendGoal(){
        bool ret = true;
        actionlib::SimpleClientGoalState state = move_base_action_.getState();
        if((state != actionlib::SimpleClientGoalState::ACTIVE) &&
           (state != actionlib::SimpleClientGoalState::PENDING) &&
           (state != actionlib::SimpleClientGoalState::RECALLED) &&
           (state != actionlib::SimpleClientGoalState::PREEMPTED))
        {
            ret = false;
        }

        if(waypoints_.empty()){
            ret = false;
        }

        return ret;
    }

    bool navigationFinished(){
        return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;
    }

    bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){
        tf::StampedTransform robot_gl = getRobotPosGL();

        const double wx = dest.x;
        const double wy = dest.y;
        const double rx = robot_gl.getOrigin().x();
        const double ry = robot_gl.getOrigin().y();
        const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));

        return dist < dist_err;
    }

    tf::StampedTransform getRobotPosGL(){
        tf::StampedTransform robot_gl;
        try{
            tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
        }catch(tf::TransformException &e){
            ROS_WARN_STREAM("tf::TransformException: " << e.what());
        }

        return robot_gl;
    }

    void sleep(){
        rate_.sleep();
        ros::spinOnce();
        publishMarkers();
    }

    void startNavigationGL(const geometry_msgs::Point &dest){
        geometry_msgs::Pose pose;
        pose.position = dest;
        pose.orientation = tf::createQuaternionMsgFromYaw(0.0);
        startNavigationGL(pose);
    }

    void startNavigationGL(const geometry_msgs::Pose &dest){
        move_base_msgs::MoveBaseGoal move_base_goal;
        move_base_goal.target_pose.header.stamp = ros::Time::now();
        move_base_goal.target_pose.header.frame_id = world_frame_;
        move_base_goal.target_pose.pose.position = dest.position;
        move_base_goal.target_pose.pose.orientation = dest.orientation;

        move_base_action_.sendGoal(move_base_goal);
    }

    void publishMarkers(){
        visualization_msgs::MarkerArray markers_array;
        for(int i=0; i < waypoints_.size(); i++){
            visualization_msgs::Marker marker, label;
            marker.header.frame_id = world_frame_;
            marker.header.stamp = ros::Time::now();
            marker.scale.x = 0.2;
            marker.scale.y = 0.2;
            marker.scale.z = 0.2;
            marker.pose.position.z = marker.scale.z / 2.0;
            marker.color.r = 0.8f;
            marker.color.g = 0.2f;
            marker.color.b = 0.2f;

            std::stringstream name;
            name << "waypoint " << i;
            marker.ns = name.str();
            marker.id = i;
            marker.pose.position.x = waypoints_[i].point.x;
            marker.pose.position.y = waypoints_[i].point.y;
            marker.type = visualization_msgs::Marker::SPHERE;
            marker.action = visualization_msgs::Marker::ADD;
            marker.color.a = 1.0f;
            markers_array.markers.push_back(marker);

            //ROS_INFO_STREAM("waypoints \n" << waypoints_[i]);
        }
        marker_pub_.publish(markers_array);
    }

    void run(){
        while(ros::ok()){
            if(has_activate_){
                for(int i=0; i < waypoints_.size(); i++){
                    ROS_INFO_STREAM("waypoint = " << waypoints_[i]);
                    if(!ros::ok()) break;

                    startNavigationGL(waypoints_[i].point);
                    double old_time = ros::Time::now().toSec();
                    tf::StampedTransform old_robot_gl = getRobotPosGL();
                    while(!onNavigationPoint(waypoints_[i].point)){
                        if(ros::Time::now().toSec() - old_time > 10.0){
                            tf::StampedTransform robot_gl = getRobotPosGL();

                            const double old_x = old_robot_gl.getOrigin().x();
                            const double old_y = old_robot_gl.getOrigin().y();
                            const double x = robot_gl.getOrigin().x();
                            const double y = robot_gl.getOrigin().y();
                            const double dist = std::sqrt(std::pow(old_x - x, 2) + std::pow(old_y - y, 2));
                            if(dist < 0.5){
                                ROS_WARN("Resend the navigation goal.");
                                std_srvs::Empty empty;
                                clear_costmaps_srv_.call(empty);
                                //startNavigationGL(waypoints_[i].point);
                            }
                            old_time = ros::Time::now().toSec();
                            old_robot_gl = robot_gl;
                        }
                        actionlib::SimpleClientGoalState state = move_base_action_.getState();
                        sleep();
                    }
                    ROS_INFO("waypoint goal");
                }
                ROS_INFO("waypoints clear");
                waypoints_.clear();
                startNavigationGL(finish_pose_);
                while(!navigationFinished() && ros::ok()) sleep();
                has_activate_ = false;
            }

            sleep();
        }
    }

private:
    actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;
    std::vector<geometry_msgs::PointStamped> waypoints_;
    geometry_msgs::Pose finish_pose_;
    bool has_activate_;
    std::string robot_frame_, world_frame_;
    tf::TransformListener tf_listener_;
    ros::Rate rate_;
    ros::Subscriber syscommand_sub_;
    ros::Publisher marker_pub_;
    ros::ServiceClient clear_costmaps_srv_;
};

int main(int argc, char *argv[]){
    ros::init(argc, argv, ROS_PACKAGE_NAME);
    WaypointsNavigation w_nav;
    w_nav.run();

    return 0;
}
<|endoftext|>


<commit_before>//===-- MachineFunction.cpp -----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Collect native machine code information for a function.  This allows
// target-specific information about the generated code to be stored with each
// function.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Function.h"
#include "llvm/iOther.h"
#include "llvm/Type.h"
#include "Support/LeakDetector.h"

using namespace llvm;

static AnnotationID MF_AID(
                 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));

namespace {
  struct Printer : public MachineFunctionPass {
    std::ostream *OS;
    const std::string Banner;

    Printer (std::ostream *_OS, const std::string &_Banner) :
      OS (_OS), Banner (_Banner) { }

    const char *getPassName() const { return "MachineFunction Printer"; }

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesAll();
    }

    bool runOnMachineFunction(MachineFunction &MF) {
      (*OS) << Banner;
      MF.print (*OS);
      return false;
    }
  };
}

/// Returns a newly-created MachineFunction Printer pass. The default output
/// stream is std::cerr; the default banner is empty.
///
FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
                                                     const std::string &Banner) {
  return new Printer(OS, Banner);
}

namespace {
  struct Deleter : public MachineFunctionPass {
    const char *getPassName() const { return "Machine Code Deleter"; }

    bool runOnMachineFunction(MachineFunction &MF) {
      // Delete the annotation from the function now.
      MachineFunction::destruct(MF.getFunction());
      return true;
    }
  };
}

/// MachineCodeDeletion Pass - This pass deletes all of the machine code for
/// the current function, which should happen after the function has been
/// emitted to a .s file or to memory.
FunctionPass *llvm::createMachineCodeDeleter() {
  return new Deleter();
}

//===---------------------------------------------------------------------===//
// MachineFunction implementation
//===---------------------------------------------------------------------===//
MachineBasicBlock* ilist_traits<MachineBasicBlock>::createNode()
{
    MachineBasicBlock* dummy = new MachineBasicBlock();
    LeakDetector::removeGarbageObject(dummy);
    return dummy;
}

void ilist_traits<MachineBasicBlock>::transferNodesFromList(
    iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
    ilist_iterator<MachineBasicBlock> first,
    ilist_iterator<MachineBasicBlock> last)
{
    if (Parent != toList.Parent)
        for (; first != last; ++first)
            first->Parent = toList.Parent;
}

MachineFunction::MachineFunction(const Function *F,
                                 const TargetMachine &TM)
  : Annotation(MF_AID), Fn(F), Target(TM), NextMBBNumber(0) {
  SSARegMapping = new SSARegMap();
  MFInfo = new MachineFunctionInfo(*this);
  FrameInfo = new MachineFrameInfo();
  ConstantPool = new MachineConstantPool();
  BasicBlocks.Parent = this;
}

MachineFunction::~MachineFunction() {
  delete SSARegMapping;
  delete MFInfo;
  delete FrameInfo;
  delete ConstantPool;
}

void MachineFunction::dump() const { print(std::cerr); }

void MachineFunction::print(std::ostream &OS) const {
  OS << "# Machine code for " << Fn->getName () << "():\n";

  // Print Frame Information
  getFrameInfo()->print(*this, OS);

  // Print Constant Pool
  getConstantPool()->print(OS);

  for (const_iterator BB = begin(); BB != end(); ++BB)
    BB->print(OS);

  OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
}

// The next two methods are used to construct and to retrieve
// the MachineCodeForFunction object for the given function.
// construct() -- Allocates and initializes for a given function and target
// get()       -- Returns a handle to the object.
//                This should not be called before "construct()"
//                for a given Function.
//
MachineFunction&
MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
{
  assert(Fn->getAnnotation(MF_AID) == 0 &&
         "Object already exists for this function!");
  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
  Fn->addAnnotation(mcInfo);
  return *mcInfo;
}

void MachineFunction::destruct(const Function *Fn) {
  bool Deleted = Fn->deleteAnnotation(MF_AID);
  assert(Deleted && "Machine code did not exist for function!");
}

MachineFunction& MachineFunction::get(const Function *F)
{
  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
  assert(mc && "Call construct() method first to allocate the object");
  return *mc;
}

void MachineFunction::clearSSARegMap() {
  delete SSARegMapping;
  SSARegMapping = 0;
}

//===----------------------------------------------------------------------===//
//  MachineFrameInfo implementation
//===----------------------------------------------------------------------===//

/// CreateStackObject - Create a stack object for a value of the specified type.
///
int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));
}

int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {
  return CreateStackObject(RC->getSize(), RC->getAlignment());
}

void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();

  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
    const StackObject &SO = Objects[i];
    OS << "  <fi #" << (int)(i-NumFixedObjects) << "> is ";
    if (SO.Size == 0)
      OS << "variable sized";
    else
      OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");

    if (i < NumFixedObjects)
      OS << " fixed";
    if (i < NumFixedObjects || SO.SPOffset != -1) {
      int Off = SO.SPOffset - ValOffset;
      OS << " at location [SP";
      if (Off > 0)
	OS << "+" << Off;
      else if (Off < 0)
	OS << Off;
      OS << "]";
    }
    OS << "\n";
  }

  if (HasVarSizedObjects)
    OS << "  Stack frame contains variable sized objects\n";
}

void MachineFrameInfo::dump(const MachineFunction &MF) const {
  print(MF, std::cerr);
}

//===----------------------------------------------------------------------===//
//  MachineConstantPool implementation
//===----------------------------------------------------------------------===//

void MachineConstantPool::print(std::ostream &OS) const {
  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
    OS << "  <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
}

void MachineConstantPool::dump() const { print(std::cerr); }

//===----------------------------------------------------------------------===//
//  MachineFunctionInfo implementation
//===----------------------------------------------------------------------===//

static unsigned
ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
                           unsigned &maxOptionalNumArgs)
{
  const TargetFrameInfo &frameInfo = *target.getFrameInfo();

  unsigned maxSize = 0;

  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
      if (const CallInst *callInst = dyn_cast<CallInst>(I))
        {
          unsigned numOperands = callInst->getNumOperands() - 1;
          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
          if (numExtra <= 0)
            continue;

          unsigned sizeForThisCall;
          if (frameInfo.argsOnStackHaveFixedSize())
            {
              int argSize = frameInfo.getSizeOfEachArgOnStack();
              sizeForThisCall = numExtra * (unsigned) argSize;
            }
          else
            {
              assert(0 && "UNTESTED CODE: Size per stack argument is not "
                     "fixed on this architecture: use actual arg sizes to "
                     "compute MaxOptionalArgsSize");
              sizeForThisCall = 0;
              for (unsigned i = 0; i < numOperands; ++i)
                sizeForThisCall += target.getTargetData().getTypeSize(callInst->
                                              getOperand(i)->getType());
            }

          if (maxSize < sizeForThisCall)
            maxSize = sizeForThisCall;

          if ((int)maxOptionalNumArgs < numExtra)
            maxOptionalNumArgs = (unsigned) numExtra;
        }

  return maxSize;
}

// Align data larger than one L1 cache line on L1 cache line boundaries.
// Align all smaller data on the next higher 2^x boundary (4, 8, ...),
// but not higher than the alignment of the largest type we support
// (currently a double word). -- see class TargetData).
//
// This function is similar to the corresponding function in EmitAssembly.cpp
// but they are unrelated.  This one does not align at more than a
// double-word boundary whereas that one might.
//
inline unsigned
SizeToAlignment(unsigned size, const TargetMachine& target)
{
  const unsigned short cacheLineSize = 16;
  if (size > (unsigned) cacheLineSize / 2)
    return cacheLineSize;
  else
    for (unsigned sz=1; /*no condition*/; sz *= 2)
      if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
        return sz;
}

void MachineFunctionInfo::CalculateArgSize() {
  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
						   MF.getFunction(),
                                                   maxOptionalNumArgs);
  staticStackSize = maxOptionalArgsSize
    + MF.getTarget().getFrameInfo()->getMinStackFrameSize();
}

int
MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
					      unsigned &getPaddedSize,
					      unsigned  sizeToUse)
{
  if (sizeToUse == 0) {
    // All integer types smaller than ints promote to 4 byte integers.
    if (val->getType()->isIntegral() && val->getType()->getPrimitiveSize() < 4)
      sizeToUse = 4;
    else
      sizeToUse = MF.getTarget().getTargetData().getTypeSize(val->getType());
  }
  unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo()->getFirstAutomaticVarOffset(MF,
						 			     growUp);
  int offset = growUp? firstOffset + getAutomaticVarsSize()
                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);

  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);
  getPaddedSize = sizeToUse + abs(aligned - offset);

  return aligned;
}

int MachineFunctionInfo::allocateLocalVar(const Value* val,
                                          unsigned sizeToUse) {
  assert(! automaticVarsAreaFrozen &&
         "Size of auto vars area has been used to compute an offset so "
         "no more automatic vars should be allocated!");

  // Check if we've allocated a stack slot for this value already
  //
  hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
  if (pair != offsets.end())
    return pair->second;

  unsigned getPaddedSize;
  unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
  offsets[val] = offset;
  incrementAutomaticVarsSize(getPaddedSize);
  return offset;
}

int
MachineFunctionInfo::allocateSpilledValue(const Type* type)
{
  assert(! spillsAreaFrozen &&
         "Size of reg spills area has been used to compute an offset so "
         "no more register spill slots should be allocated!");

  unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);
  unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo()->getRegSpillAreaOffset(MF, growUp);

  int offset = growUp? firstOffset + getRegSpillsSize()
                     : firstOffset - (getRegSpillsSize() + size);

  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);
  size += abs(aligned - offset); // include alignment padding in size

  incrementRegSpillsSize(size);  // update size of reg. spills area

  return aligned;
}

int
MachineFunctionInfo::pushTempValue(unsigned size)
{
  unsigned align = SizeToAlignment(size, MF.getTarget());

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo()->getTmpAreaOffset(MF, growUp);

  int offset = growUp? firstOffset + currentTmpValuesSize
                     : firstOffset - (currentTmpValuesSize + size);

  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp,
							      align);
  size += abs(aligned - offset); // include alignment padding in size

  incrementTmpAreaSize(size);    // update "current" size of tmp area

  return aligned;
}

void MachineFunctionInfo::popAllTempValues() {
  resetTmpAreaSize();            // clear tmp area to reuse
}

<commit_msg>Instance var no longer exists<commit_after>//===-- MachineFunction.cpp -----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Collect native machine code information for a function.  This allows
// target-specific information about the generated code to be stored with each
// function.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Function.h"
#include "llvm/iOther.h"
#include "llvm/Type.h"
#include "Support/LeakDetector.h"

using namespace llvm;

static AnnotationID MF_AID(
                 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));

namespace {
  struct Printer : public MachineFunctionPass {
    std::ostream *OS;
    const std::string Banner;

    Printer (std::ostream *_OS, const std::string &_Banner) :
      OS (_OS), Banner (_Banner) { }

    const char *getPassName() const { return "MachineFunction Printer"; }

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesAll();
    }

    bool runOnMachineFunction(MachineFunction &MF) {
      (*OS) << Banner;
      MF.print (*OS);
      return false;
    }
  };
}

/// Returns a newly-created MachineFunction Printer pass. The default output
/// stream is std::cerr; the default banner is empty.
///
FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
                                                     const std::string &Banner) {
  return new Printer(OS, Banner);
}

namespace {
  struct Deleter : public MachineFunctionPass {
    const char *getPassName() const { return "Machine Code Deleter"; }

    bool runOnMachineFunction(MachineFunction &MF) {
      // Delete the annotation from the function now.
      MachineFunction::destruct(MF.getFunction());
      return true;
    }
  };
}

/// MachineCodeDeletion Pass - This pass deletes all of the machine code for
/// the current function, which should happen after the function has been
/// emitted to a .s file or to memory.
FunctionPass *llvm::createMachineCodeDeleter() {
  return new Deleter();
}

//===---------------------------------------------------------------------===//
// MachineFunction implementation
//===---------------------------------------------------------------------===//
MachineBasicBlock* ilist_traits<MachineBasicBlock>::createNode()
{
    MachineBasicBlock* dummy = new MachineBasicBlock();
    LeakDetector::removeGarbageObject(dummy);
    return dummy;
}

void ilist_traits<MachineBasicBlock>::transferNodesFromList(
    iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
    ilist_iterator<MachineBasicBlock> first,
    ilist_iterator<MachineBasicBlock> last)
{
    if (Parent != toList.Parent)
        for (; first != last; ++first)
            first->Parent = toList.Parent;
}

MachineFunction::MachineFunction(const Function *F,
                                 const TargetMachine &TM)
  : Annotation(MF_AID), Fn(F), Target(TM) {
  SSARegMapping = new SSARegMap();
  MFInfo = new MachineFunctionInfo(*this);
  FrameInfo = new MachineFrameInfo();
  ConstantPool = new MachineConstantPool();
  BasicBlocks.Parent = this;
}

MachineFunction::~MachineFunction() {
  delete SSARegMapping;
  delete MFInfo;
  delete FrameInfo;
  delete ConstantPool;
}

void MachineFunction::dump() const { print(std::cerr); }

void MachineFunction::print(std::ostream &OS) const {
  OS << "# Machine code for " << Fn->getName () << "():\n";

  // Print Frame Information
  getFrameInfo()->print(*this, OS);

  // Print Constant Pool
  getConstantPool()->print(OS);

  for (const_iterator BB = begin(); BB != end(); ++BB)
    BB->print(OS);

  OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
}

// The next two methods are used to construct and to retrieve
// the MachineCodeForFunction object for the given function.
// construct() -- Allocates and initializes for a given function and target
// get()       -- Returns a handle to the object.
//                This should not be called before "construct()"
//                for a given Function.
//
MachineFunction&
MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
{
  assert(Fn->getAnnotation(MF_AID) == 0 &&
         "Object already exists for this function!");
  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
  Fn->addAnnotation(mcInfo);
  return *mcInfo;
}

void MachineFunction::destruct(const Function *Fn) {
  bool Deleted = Fn->deleteAnnotation(MF_AID);
  assert(Deleted && "Machine code did not exist for function!");
}

MachineFunction& MachineFunction::get(const Function *F)
{
  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
  assert(mc && "Call construct() method first to allocate the object");
  return *mc;
}

void MachineFunction::clearSSARegMap() {
  delete SSARegMapping;
  SSARegMapping = 0;
}

//===----------------------------------------------------------------------===//
//  MachineFrameInfo implementation
//===----------------------------------------------------------------------===//

/// CreateStackObject - Create a stack object for a value of the specified type.
///
int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));
}

int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {
  return CreateStackObject(RC->getSize(), RC->getAlignment());
}

void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();

  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
    const StackObject &SO = Objects[i];
    OS << "  <fi #" << (int)(i-NumFixedObjects) << "> is ";
    if (SO.Size == 0)
      OS << "variable sized";
    else
      OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");

    if (i < NumFixedObjects)
      OS << " fixed";
    if (i < NumFixedObjects || SO.SPOffset != -1) {
      int Off = SO.SPOffset - ValOffset;
      OS << " at location [SP";
      if (Off > 0)
	OS << "+" << Off;
      else if (Off < 0)
	OS << Off;
      OS << "]";
    }
    OS << "\n";
  }

  if (HasVarSizedObjects)
    OS << "  Stack frame contains variable sized objects\n";
}

void MachineFrameInfo::dump(const MachineFunction &MF) const {
  print(MF, std::cerr);
}

//===----------------------------------------------------------------------===//
//  MachineConstantPool implementation
//===----------------------------------------------------------------------===//

void MachineConstantPool::print(std::ostream &OS) const {
  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
    OS << "  <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
}

void MachineConstantPool::dump() const { print(std::cerr); }

//===----------------------------------------------------------------------===//
//  MachineFunctionInfo implementation
//===----------------------------------------------------------------------===//

static unsigned
ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
                           unsigned &maxOptionalNumArgs)
{
  const TargetFrameInfo &frameInfo = *target.getFrameInfo();

  unsigned maxSize = 0;

  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
      if (const CallInst *callInst = dyn_cast<CallInst>(I))
        {
          unsigned numOperands = callInst->getNumOperands() - 1;
          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
          if (numExtra <= 0)
            continue;

          unsigned sizeForThisCall;
          if (frameInfo.argsOnStackHaveFixedSize())
            {
              int argSize = frameInfo.getSizeOfEachArgOnStack();
              sizeForThisCall = numExtra * (unsigned) argSize;
            }
          else
            {
              assert(0 && "UNTESTED CODE: Size per stack argument is not "
                     "fixed on this architecture: use actual arg sizes to "
                     "compute MaxOptionalArgsSize");
              sizeForThisCall = 0;
              for (unsigned i = 0; i < numOperands; ++i)
                sizeForThisCall += target.getTargetData().getTypeSize(callInst->
                                              getOperand(i)->getType());
            }

          if (maxSize < sizeForThisCall)
            maxSize = sizeForThisCall;

          if ((int)maxOptionalNumArgs < numExtra)
            maxOptionalNumArgs = (unsigned) numExtra;
        }

  return maxSize;
}

// Align data larger than one L1 cache line on L1 cache line boundaries.
// Align all smaller data on the next higher 2^x boundary (4, 8, ...),
// but not higher than the alignment of the largest type we support
// (currently a double word). -- see class TargetData).
//
// This function is similar to the corresponding function in EmitAssembly.cpp
// but they are unrelated.  This one does not align at more than a
// double-word boundary whereas that one might.
//
inline unsigned
SizeToAlignment(unsigned size, const TargetMachine& target)
{
  const unsigned short cacheLineSize = 16;
  if (size > (unsigned) cacheLineSize / 2)
    return cacheLineSize;
  else
    for (unsigned sz=1; /*no condition*/; sz *= 2)
      if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
        return sz;
}

void MachineFunctionInfo::CalculateArgSize() {
  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
						   MF.getFunction(),
                                                   maxOptionalNumArgs);
  staticStackSize = maxOptionalArgsSize
    + MF.getTarget().getFrameInfo()->getMinStackFrameSize();
}

int
MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
					      unsigned &getPaddedSize,
					      unsigned  sizeToUse)
{
  if (sizeToUse == 0) {
    // All integer types smaller than ints promote to 4 byte integers.
    if (val->getType()->isIntegral() && val->getType()->getPrimitiveSize() < 4)
      sizeToUse = 4;
    else
      sizeToUse = MF.getTarget().getTargetData().getTypeSize(val->getType());
  }
  unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo()->getFirstAutomaticVarOffset(MF,
						 			     growUp);
  int offset = growUp? firstOffset + getAutomaticVarsSize()
                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);

  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);
  getPaddedSize = sizeToUse + abs(aligned - offset);

  return aligned;
}

int MachineFunctionInfo::allocateLocalVar(const Value* val,
                                          unsigned sizeToUse) {
  assert(! automaticVarsAreaFrozen &&
         "Size of auto vars area has been used to compute an offset so "
         "no more automatic vars should be allocated!");

  // Check if we've allocated a stack slot for this value already
  //
  hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
  if (pair != offsets.end())
    return pair->second;

  unsigned getPaddedSize;
  unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
  offsets[val] = offset;
  incrementAutomaticVarsSize(getPaddedSize);
  return offset;
}

int
MachineFunctionInfo::allocateSpilledValue(const Type* type)
{
  assert(! spillsAreaFrozen &&
         "Size of reg spills area has been used to compute an offset so "
         "no more register spill slots should be allocated!");

  unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);
  unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo()->getRegSpillAreaOffset(MF, growUp);

  int offset = growUp? firstOffset + getRegSpillsSize()
                     : firstOffset - (getRegSpillsSize() + size);

  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);
  size += abs(aligned - offset); // include alignment padding in size

  incrementRegSpillsSize(size);  // update size of reg. spills area

  return aligned;
}

int
MachineFunctionInfo::pushTempValue(unsigned size)
{
  unsigned align = SizeToAlignment(size, MF.getTarget());

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo()->getTmpAreaOffset(MF, growUp);

  int offset = growUp? firstOffset + currentTmpValuesSize
                     : firstOffset - (currentTmpValuesSize + size);

  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp,
							      align);
  size += abs(aligned - offset); // include alignment padding in size

  incrementTmpAreaSize(size);    // update "current" size of tmp area

  return aligned;
}

void MachineFunctionInfo::popAllTempValues() {
  resetTmpAreaSize();            // clear tmp area to reuse
}

<|endoftext|>