<commit_before>/* String is constructed with these four characters:
 * w - represents wolf
 * s - represents sheep
 * . - represents empty space
 * # - represents fence
 * Write out how many sheeps have been slaughtered.
 *
 * For example:
 * #.vov#o.o#.v#o.v.o#v
 * Only two sheeps in between fence #o.o# will survive.
 */
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <vector>

using namespace std;
int howManySheepsHaveBeenEaten();
string genTerrain();
int roll(int min, int max);
void setChar(int num);
int loopBetweenFences(size_t, size_t, const string& );

string terrain;

int main( )
{
    srand(time(NULL));

    genTerrain();
    cout << "Slaughtered: " << howManySheepsHaveBeenEaten() << endl;

    return 0;
}

/* Idea:
 * 1. Find postion of every fence - #. Store it in fence_pos_vector
 * 2. Loop through every char in string from begining to next occurance
 *    of fence - #.
 * 3. If there is one or more wolf - w, count the number of slaughtered
 *    sheeps.
 */

int howManySheepsHaveBeenEaten()
{
    int num_of_dead_sheeps=0;
    size_t fence_pos=0;
    std::vector<size_t> fence_pos_vector;

    if (terrain.find("#", fence_pos) != -1){
        for (int i = 0; i < terrain.length(); i++) {
            if (i == 0) {
                fence_pos = terrain.find("#",0);
                fence_pos_vector.push_back(fence_pos);
                i = fence_pos;
            }
            else {
                if (terrain.find("#", fence_pos+1) != -1){
                    fence_pos = terrain.find("#", fence_pos+1);
                    fence_pos_vector.push_back(fence_pos);
                    i = fence_pos;
                }
                else break;
            }
        }
    }
    else {
        fence_pos_vector.at(0) = 0;
    }

    for (int i = 0; i < fence_pos_vector.size(); i++) {
        if (i == 0)
            loopBetweenFences(i, fence_pos_vector.at(i), terrain);

        else
            loopBetweenFences(fence_pos_vector.at(i-1),
                              fence_pos_vector.at(i), terrain);
        // Here is missing one more call to loopBetweenFences cuz we
        // will miss .sw#.sw#.sw last sheep
    }

    return num_of_dead_sheeps;
}

int loopBetweenFences(size_t start, size_t finish, const string& terrain)
{
    int num_of_dead_sheeps = 0;
    string temp;
    size_t sheep_pos=0;
    vector<size_t> sheep_pos_vec;
    sheep_pos_vec.clear();
    temp = terrain.substr(start, finish);

    // if distance between fence is bigger then 1
    if ( temp.length() > 1)
        // if there is at least one wolf
        if (temp.find("w") != -1 ){
            for (int i = 0; i < temp.length(); i++) {
                if (temp.find("s",sheep_pos) != -1){
                    if (i == 0){
                        sheep_pos = temp.find("s",0);
                        sheep_pos_vec.push_back(sheep_pos);
                        i = sheep_pos;
                        num_of_dead_sheeps++;
                    }
                    else {
                        if (temp.find("s",sheep_pos+1) != -1){
                            sheep_pos = terrain.find("s", sheep_pos+1);
                            sheep_pos_vec.push_back(sheep_pos);
                            i = sheep_pos;
                            num_of_dead_sheeps++;
                        }
                    }
                }
            }
        }

    // cout << "sheep pos vec: " << sheep_pos_vec.size() << endl;
    cout << "num of dead sheeps: " << num_of_dead_sheeps << endl;

    return num_of_dead_sheeps;
}

/* Idea, genarate a RAND number between 1 - 4
 * if 0 append . to terrain
 * if 1 append w to terrain
 * if 2 append s to terrain
 * if 3 append # to terrain
 */

string genTerrain()
{
    for (int i = 0; i < 2; i++) {
        int first = roll(0,3);
        setChar(first);

        int second = roll(0,3);
        while (second == first){
            second = roll(0,3);
            if (second != first) break;
        }
        setChar(second);

        int third = roll(0,3);
        while ((third == first) || (third == second)){
            third = roll(0,3);
            if ((third != first) && (third != second)) break;
        }
        setChar(third);

        int fourth = roll(0,3);
        while (1){
            fourth = roll(0,3);
            if ((fourth != first) && (fourth != second) && (fourth != third)) break;
        }
        setChar(fourth);

    }
    cout << terrain << endl;
    return terrain;
}

void setChar(int num){
    if (num == 0) terrain.append(".");
    if (num == 1) terrain.append("w");
    if (num == 2) terrain.append("s");
    if (num == 3) terrain.append("#");
}

int roll(int min, int max)
{
   // x is in [0,1[
   double x = rand()/static_cast<double>(RAND_MAX);

   // [0,1[ * (max - min) + min is in [min,max[
   int that = min + static_cast<int>( x * (max - min + 1) );

   return that;
}
<commit_msg>ugly but working version<commit_after>/* String is constructed with these four characters:
 * w - represents wolf
 * s - represents sheep
 * . - represents empty space
 * # - represents fence
 * Write out how many sheeps have been slaughtered.
 *
 * For example:
 * #.vov#o.o#.v#o.v.o#v
 * Only two sheeps in between fence #o.o# will survive.
 */
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <vector>

using namespace std;
int howManySheepsHaveBeenEaten();
string genTerrain();
int roll(int min, int max);
void setChar(int num);
int loopBetweenFences(size_t, size_t, const string& );

string terrain;

int main(int argc, const char *argv[])
{
    srand(time(NULL));
    if (argc > 1)
        terrain = argv[1];
    else
        genTerrain();

    cout << "Slaughtered: " << howManySheepsHaveBeenEaten() << endl;

    return 0;
}

/* Idea:
 * 1. Find postion of every fence - #. Store it in fence_pos_vector
 * 2. Loop through every char in string from begining to next occurance
 *    of fence - #.
 * 3. If there is one or more wolf - w, count the number of slaughtered
 *    sheeps.
 */

int howManySheepsHaveBeenEaten()
{
    int num_of_dead_sheeps=0;
    size_t fence_pos=0;
    std::vector<size_t> fence_pos_vector;

    if (terrain.find("#", fence_pos) != -1){
        for (int i = 0; i < terrain.length(); i++) {
            if (i == 0) {
                fence_pos = terrain.find("#",0);
                fence_pos_vector.push_back(fence_pos);
                i = fence_pos;
            }
            else {
                if (terrain.find("#", fence_pos+1) != -1){
                    fence_pos = terrain.find("#", fence_pos+1);
                    fence_pos_vector.push_back(fence_pos);
                    i = fence_pos;
                }
                else break;
            }
        }
    }
    else {
        fence_pos_vector.at(0) = 0;
    }

    for (int i = 0; i < fence_pos_vector.size(); i++) {
        if (i == 0)
            loopBetweenFences(i, fence_pos_vector.at(i), terrain);

        // For not missing last sheep in this example: .sw#.sw#.sw
        else if (i == (fence_pos_vector.size() - 1)){
            loopBetweenFences(fence_pos_vector.at(i-1),
                              fence_pos_vector.at(i) - fence_pos_vector.at(i-1),
                              terrain);
            loopBetweenFences(fence_pos_vector.at(i), terrain.size(), terrain);
        }

        else
            loopBetweenFences(fence_pos_vector.at(i-1),
                              fence_pos_vector.at(i) - fence_pos_vector.at(i-1),
                              terrain);
    }

    return num_of_dead_sheeps;
}

int loopBetweenFences(size_t start, size_t count, const string& terrain)
{
    int num_of_dead_sheeps = 0, num_of_fences = 0;
    string temp;
    size_t sheep_pos=0;
    vector<size_t> sheep_pos_vec;
    sheep_pos_vec.clear();
    temp = terrain.substr(start, count);

    num_of_fences++;
    cout << "fence(" << num_of_fences << "): " << temp << endl;
    // if distance between fence is bigger then 1
    if ( temp.length() > 1)
        // if there is at least one wolf
        if (temp.find("w") != -1 ){
            for (int i = 0; i < temp.length(); i++) {
                if (temp.find("s",sheep_pos) != -1){
                    if (i == 0){
                        sheep_pos = temp.find("s",0);
                        sheep_pos_vec.push_back(sheep_pos);
                        i = sheep_pos;
                        num_of_dead_sheeps++;
                    }
                    else {
                        if (temp.find("s",sheep_pos+1) != -1){
                            sheep_pos = temp.find("s", sheep_pos+1);
                            sheep_pos_vec.push_back(sheep_pos);
                            i = sheep_pos;
                            num_of_dead_sheeps++;
                        }
                        else break;
                    }
                }
            }
        }

    // cout << "sheep pos vec: " << sheep_pos_vec.size() << endl;
    cout << "num of dead sheeps: " << num_of_dead_sheeps << endl;

    return num_of_dead_sheeps;
}

/* Idea, genarate a RAND number between 1 - 4
 * if 0 append . to terrain
 * if 1 append w to terrain
 * if 2 append s to terrain
 * if 3 append # to terrain
 */

string genTerrain()
{
    for (int i = 0; i < 2; i++) {
        int first = roll(0,3);
        setChar(first);

        int second = roll(0,3);
        while (second == first){
            second = roll(0,3);
            if (second != first) break;
        }
        setChar(second);

        int third = roll(0,3);
        while ((third == first) || (third == second)){
            third = roll(0,3);
            if ((third != first) && (third != second)) break;
        }
        setChar(third);

        int fourth = roll(0,3);
        while (1){
            fourth = roll(0,3);
            if ((fourth != first) && (fourth != second) && (fourth != third)) break;
        }
        setChar(fourth);

    }
    cout << terrain << endl;
    return terrain;
}

void setChar(int num){
    if (num == 0) terrain.append(".");
    if (num == 1) terrain.append("w");
    if (num == 2) terrain.append("s");
    if (num == 3) terrain.append("#");
}

int roll(int min, int max)
{
   // x is in [0,1[
   double x = rand()/static_cast<double>(RAND_MAX);

   // [0,1[ * (max - min) + min is in [min,max[
   int that = min + static_cast<int>( x * (max - min + 1) );

   return that;
}
<|endoftext|>


<commit_before>#include "PidProbabilityMapper.h"
#include "PidPhaseSpace.h"
#include "TSF/FitRunner.h"
#include "TH1D.h"

PidProbabilityMapper::PidProbabilityMapper( XmlConfig * _cfg, string _nodePath ) : HistoAnalyzer( _cfg, _nodePath ){

	logger->setClassSpace( "PidProbabilityMapper" );

	// set up the binning
	binsPt 		= unique_ptr<HistoBins>(	new HistoBins( cfg, nodePath + "PSBinning.pt" ) 			);
	binsEta 	= unique_ptr<HistoBins>(	new HistoBins( cfg, nodePath + "PSBinning.eta" ) 		);
	binsCharge 	= unique_ptr<HistoBins>(	new HistoBins( cfg, nodePath + "PSBinning.charge" ) 		);

}

PidProbabilityMapper::~PidProbabilityMapper(){

}

double PidProbabilityMapper::evaluateGauss( double x, double y, double m, double s ){
	return (y / (s *TMath::Sqrt( 2 * 3.1415926 ) )) * TMath::Exp(  -(x - m)*( x - m ) / ( 2 * s*s )  );
}

map<string, double> PidProbabilityMapper::pidWeights( int charge, int iCen, double pt, double eta, double zb, double zd ){

	map< string, double > weights;
	if (  TMath::Abs(charge) != 1 ){
		logger->error( __FUNCTION__ ) << "charge zero plc" << endl;
		return weights;
	}

	logger->debug( __FUNCTION__ ) << endl;

	int iPt = binsPt->findBin( pt );
	int iEta = binsEta->findBin( TMath::Abs(eta) );

	if ( iPt < 0 || iEta < 0  )
		return weights;

	logger->debug( __FUNCTION__ ) << "pt Bin : " << iPt << ", eta Bin : " << iEta << endl;

	vector<double> sigmas;
	vector<double> mus;
	vector<double> yields;

	string model = "zb";

	double eVal = zd;

	if ( "zb" == model )
		eVal = zb;

	for ( string plc : PidPhaseSpace::species ){
		string name = TSF::FitRunner::sigmaName(plc, iCen, charge, iEta);
		string fName = plc + "_" + model + "Sigma/" + name;
		TH1D * h = ( TH1D * )inFile->Get( fName.c_str()   );
		if ( !h ){
			logger->error( __FUNCTION__ ) << fName << " not found " << endl;
			return weights;
		}
		sigmas.push_back( h->GetBinContent( iPt+1 ) );

		name = TSF::FitRunner::muName(plc, iCen, charge, iEta);
		fName = plc + "_" + model + "Mu/" + name;
		h = ( TH1D * )inFile->Get( fName.c_str()   );
		mus.push_back( h->GetBinContent( iPt+1 ) );

		name = TSF::FitRunner::yieldName(plc, iCen, charge, iEta);
		fName = plc + "_yield/" + name;
		h = ( TH1D * )inFile->Get( fName.c_str()   );
		yields.push_back( h->GetBinContent( iPt+1 ) );
	}

	logger->debug( __FUNCTION__ ) << "parameters loaded" << endl;

	double total = 0.0;

	int i = 0;
	for ( string plc : PidPhaseSpace::species ){

		double v = evaluateGauss( eVal, yields[ i ], mus[ i ], sigmas[ i ] );
		if ( (eVal - mus[ i ]) / sigmas[ i ] > 8 )
			v = 0;

		total += v;

		weights[ plc ] = v;

		//total += yields[ i ];
		//weights[ plc ] = yields[ i ];
		i++;
	}

	// normalize
	for ( string plc : PidPhaseSpace::species ){
		if ( total > 0 )
			weights[ plc ] = weights[ plc ] / total;
		else
			weights[ plc ] = 0;
		logger->debug(__FUNCTION__) << "weight[ " << plc << " ] = " << weights[ plc ] << endl;
	}

	return weights;

}

<commit_msg>set pid mapper to use yield only<commit_after>#include "PidProbabilityMapper.h"
#include "PidPhaseSpace.h"
#include "TSF/FitRunner.h"
#include "TH1D.h"

PidProbabilityMapper::PidProbabilityMapper( XmlConfig * _cfg, string _nodePath ) : HistoAnalyzer( _cfg, _nodePath ){

	logger->setClassSpace( "PidProbabilityMapper" );

	// set up the binning
	binsPt 		= unique_ptr<HistoBins>(	new HistoBins( cfg, nodePath + "PSBinning.pt" ) 			);
	binsEta 	= unique_ptr<HistoBins>(	new HistoBins( cfg, nodePath + "PSBinning.eta" ) 		);
	binsCharge 	= unique_ptr<HistoBins>(	new HistoBins( cfg, nodePath + "PSBinning.charge" ) 		);

}

PidProbabilityMapper::~PidProbabilityMapper(){

}

double PidProbabilityMapper::evaluateGauss( double x, double y, double m, double s ){
	return (y / (s *TMath::Sqrt( 2 * 3.1415926 ) )) * TMath::Exp(  -(x - m)*( x - m ) / ( 2 * s*s )  );
}

map<string, double> PidProbabilityMapper::pidWeights( int charge, int iCen, double pt, double eta, double zb, double zd ){

	map< string, double > weights;
	if (  TMath::Abs(charge) != 1 ){
		logger->error( __FUNCTION__ ) << "charge zero plc" << endl;
		return weights;
	}

	logger->debug( __FUNCTION__ ) << endl;

	int iPt = binsPt->findBin( pt );
	int iEta = binsEta->findBin( TMath::Abs(eta) );

	if ( iPt < 0 || iEta < 0  )
		return weights;

	logger->debug( __FUNCTION__ ) << "pt Bin : " << iPt << ", eta Bin : " << iEta << endl;

	vector<double> sigmas;
	vector<double> mus;
	vector<double> yields;

	string model = "zb";

	double eVal = zd;

	if ( "zb" == model )
		eVal = zb;

	for ( string plc : PidPhaseSpace::species ){
		string name = TSF::FitRunner::sigmaName(plc, iCen, charge, iEta);
		string fName = plc + "_" + model + "Sigma/" + name;
		TH1D * h = ( TH1D * )inFile->Get( fName.c_str()   );
		if ( !h ){
			logger->error( __FUNCTION__ ) << fName << " not found " << endl;
			return weights;
		}
		sigmas.push_back( h->GetBinContent( iPt+1 ) );

		name = TSF::FitRunner::muName(plc, iCen, charge, iEta);
		fName = plc + "_" + model + "Mu/" + name;
		h = ( TH1D * )inFile->Get( fName.c_str()   );
		mus.push_back( h->GetBinContent( iPt+1 ) );

		name = TSF::FitRunner::yieldName(plc, iCen, charge, iEta);
		fName = plc + "_yield/" + name;
		h = ( TH1D * )inFile->Get( fName.c_str()   );
		yields.push_back( h->GetBinContent( iPt+1 ) );
	}

	logger->debug( __FUNCTION__ ) << "parameters loaded" << endl;

	double total = 0.0;

	int i = 0;
	for ( string plc : PidPhaseSpace::species ){

/*
		double v = evaluateGauss( eVal, yields[ i ], mus[ i ], sigmas[ i ] );
		if ( (eVal - mus[ i ]) / sigmas[ i ] > 8 )
			v = 0;

		total += v;

		weights[ plc ] = v;*/

		total += yields[ i ];
		weights[ plc ] = yields[ i ];
		i++;
	}

	// normalize
	for ( string plc : PidPhaseSpace::species ){
		if ( total > 0 )
			weights[ plc ] = weights[ plc ] / total;
		else
			weights[ plc ] = 0;
		logger->debug(__FUNCTION__) << "weight[ " << plc << " ] = " << weights[ plc ] << endl;
	}

	return weights;

}

<|endoftext|>


<commit_before>// -*- c++ -*-
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    SLACParticleReader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2009 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCompositeDataGeometryFilter.h"
#include "vtkInformation.h"
#include "vtkLookupTable.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSLACParticleReader.h"
#include "vtkSLACReader.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTestUtilities.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

#include <vtksys/ios/sstream>

int SLACParticleReader(int argc, char *argv[])
{
  char *meshFileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
                                             "Data/SLAC/pic-example/mesh.ncdf");
  char *modeFileNamePattern = vtkTestUtilities::ExpandDataFileName(argc, argv,
                                         "Data/SLAC/pic-example/fields_%d.mod");
  char *particleFileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
                                      "Data/SLAC/pic-example/particles_5.ncdf");

  // Set up mesh reader.
  VTK_CREATE(vtkSLACReader, meshReader);
  meshReader->SetMeshFileName(meshFileName);
  char *modeFileName = new char[strlen(modeFileNamePattern + 10)];
  for (int i = 0; i < 9; i++)
    {
    sprintf(modeFileName, modeFileNamePattern, i);
    meshReader->AddModeFileName(modeFileName);
    }
  delete[] modeFileName;

  meshReader->ReadInternalVolumeOn();
  meshReader->ReadExternalSurfaceOff();
  meshReader->ReadMidpointsOff();

  // Extract geometry that we can render.
  VTK_CREATE(vtkCompositeDataGeometryFilter, geometry);
  geometry->SetInputConnection(meshReader->GetOutputPort());

  // Set up particle reader.
  VTK_CREATE(vtkSLACParticleReader, particleReader);
  particleReader->SetFileName(particleFileName);

  // Set up rendering stuff.
  VTK_CREATE(vtkPolyDataMapper, meshMapper);
  meshMapper->SetInputConnection(geometry->GetOutputPort());
  meshMapper->SetScalarModeToUsePointFieldData();
  meshMapper->ColorByArrayComponent("efield", 2);
  meshMapper->UseLookupTableScalarRangeOff();
  meshMapper->SetScalarRange(1.0, 1e+05);

  VTK_CREATE(vtkLookupTable, lut);
  lut->SetHueRange(0.66667, 0.0);
  lut->SetScaleToLog10();
  meshMapper->SetLookupTable(lut);

  VTK_CREATE(vtkActor, meshActor);
  meshActor->SetMapper(meshMapper);
  meshActor->GetProperty()->FrontfaceCullingOn();

  VTK_CREATE(vtkPolyDataMapper, particleMapper);
  particleMapper->SetInputConnection(particleReader->GetOutputPort());
  particleMapper->ScalarVisibilityOff();

  VTK_CREATE(vtkActor, particleActor);
  particleActor->SetMapper(particleMapper);

  VTK_CREATE(vtkRenderer, renderer);
  renderer->AddActor(meshActor);
  renderer->AddActor(particleActor);
  vtkCamera *camera = renderer->GetActiveCamera();
  camera->SetPosition(-0.2, 0.05, 0.0);
  camera->SetFocalPoint(0.0, 0.05, 0.0);
  camera->SetViewUp(0.0, 1.0, 0.0);

  VTK_CREATE(vtkRenderWindow, renwin);
  renwin->SetSize(300, 200);
  renwin->AddRenderer(renderer);
  VTK_CREATE(vtkRenderWindowInteractor, iren);
  iren->SetRenderWindow(renwin);
  renwin->Render();

  double time
    = particleReader->GetOutput()->GetInformation()->Get(vtkDataObject::DATA_TIME_STEPS())[0];
  cout << "Time in particle reader: " << time << endl;

  // Change the time to test the time step field load and to have the field
  // match the particles in time.
  vtkStreamingDemandDrivenPipeline *sdd
    = vtkStreamingDemandDrivenPipeline::SafeDownCast(geometry->GetExecutive());
  sdd->SetUpdateTimeStep(0, time);
  renwin->Render();

  // Do the test comparison.
  int retVal = vtkRegressionTestImage(renwin);
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    retVal = vtkRegressionTester::PASSED;
    }

  return (retVal == vtkRegressionTester::PASSED) ? 0 : 1;
}
<commit_msg>BUG: Misplaced parenthesis caused a char array to be 20 shorter than it should be and guaranteed overflow.<commit_after>// -*- c++ -*-
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    SLACParticleReader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2009 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCompositeDataGeometryFilter.h"
#include "vtkInformation.h"
#include "vtkLookupTable.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSLACParticleReader.h"
#include "vtkSLACReader.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTestUtilities.h"

#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
  vtkSmartPointer<type> name = vtkSmartPointer<type>::New()

#include <vtksys/ios/sstream>

int SLACParticleReader(int argc, char *argv[])
{
  char *meshFileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
                                             "Data/SLAC/pic-example/mesh.ncdf");
  char *modeFileNamePattern = vtkTestUtilities::ExpandDataFileName(argc, argv,
                                         "Data/SLAC/pic-example/fields_%d.mod");
  char *particleFileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
                                      "Data/SLAC/pic-example/particles_5.ncdf");

  // Set up mesh reader.
  VTK_CREATE(vtkSLACReader, meshReader);
  meshReader->SetMeshFileName(meshFileName);
  char *modeFileName = new char[strlen(modeFileNamePattern) + 10];
  for (int i = 0; i < 9; i++)
    {
    sprintf(modeFileName, modeFileNamePattern, i);
    meshReader->AddModeFileName(modeFileName);
    }
  delete[] modeFileName;

  meshReader->ReadInternalVolumeOn();
  meshReader->ReadExternalSurfaceOff();
  meshReader->ReadMidpointsOff();

  // Extract geometry that we can render.
  VTK_CREATE(vtkCompositeDataGeometryFilter, geometry);
  geometry->SetInputConnection(meshReader->GetOutputPort());

  // Set up particle reader.
  VTK_CREATE(vtkSLACParticleReader, particleReader);
  particleReader->SetFileName(particleFileName);

  // Set up rendering stuff.
  VTK_CREATE(vtkPolyDataMapper, meshMapper);
  meshMapper->SetInputConnection(geometry->GetOutputPort());
  meshMapper->SetScalarModeToUsePointFieldData();
  meshMapper->ColorByArrayComponent("efield", 2);
  meshMapper->UseLookupTableScalarRangeOff();
  meshMapper->SetScalarRange(1.0, 1e+05);

  VTK_CREATE(vtkLookupTable, lut);
  lut->SetHueRange(0.66667, 0.0);
  lut->SetScaleToLog10();
  meshMapper->SetLookupTable(lut);

  VTK_CREATE(vtkActor, meshActor);
  meshActor->SetMapper(meshMapper);
  meshActor->GetProperty()->FrontfaceCullingOn();

  VTK_CREATE(vtkPolyDataMapper, particleMapper);
  particleMapper->SetInputConnection(particleReader->GetOutputPort());
  particleMapper->ScalarVisibilityOff();

  VTK_CREATE(vtkActor, particleActor);
  particleActor->SetMapper(particleMapper);

  VTK_CREATE(vtkRenderer, renderer);
  renderer->AddActor(meshActor);
  renderer->AddActor(particleActor);
  vtkCamera *camera = renderer->GetActiveCamera();
  camera->SetPosition(-0.2, 0.05, 0.0);
  camera->SetFocalPoint(0.0, 0.05, 0.0);
  camera->SetViewUp(0.0, 1.0, 0.0);

  VTK_CREATE(vtkRenderWindow, renwin);
  renwin->SetSize(300, 200);
  renwin->AddRenderer(renderer);
  VTK_CREATE(vtkRenderWindowInteractor, iren);
  iren->SetRenderWindow(renwin);
  renwin->Render();

  double time
    = particleReader->GetOutput()->GetInformation()->Get(vtkDataObject::DATA_TIME_STEPS())[0];
  cout << "Time in particle reader: " << time << endl;

  // Change the time to test the time step field load and to have the field
  // match the particles in time.
  vtkStreamingDemandDrivenPipeline *sdd
    = vtkStreamingDemandDrivenPipeline::SafeDownCast(geometry->GetExecutive());
  sdd->SetUpdateTimeStep(0, time);
  renwin->Render();

  // Do the test comparison.
  int retVal = vtkRegressionTestImage(renwin);
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    retVal = vtkRegressionTester::PASSED;
    }

  return (retVal == vtkRegressionTester::PASSED) ? 0 : 1;
}
<|endoftext|>


<commit_before>#include "shape/compound.h"

#define rb_array_p(x) RB_TYPE_P(x, T_ARRAY)

VALUE sr_cCompound;

SR_SHAPE_GET(Compound, compound)
SR_SHAPE_CHECK(Compound, compound)

bool siren_compound_install()
{
  SR_SHAPE_INIT(Compound)
  rb_define_method(sr_cCompound, "initialize", RUBY_METHOD_FUNC(siren_compound_init),   -1);
  rb_define_method(sr_cCompound, "push",       RUBY_METHOD_FUNC(siren_compound_push),   -1);
  rb_define_method(sr_cCompound, "<<",         RUBY_METHOD_FUNC(siren_compound_push),   -1);
  rb_define_method(sr_cCompound, "delete",     RUBY_METHOD_FUNC(siren_compound_delete), -1);
  return true;
}

VALUE siren_compound_init(int argc, VALUE* argv, VALUE self)
{
  VALUE a;
  rb_scan_args(argc, argv, "*", &a);

  TopoDS_Compound comp;
  BRep_Builder B;
  B.MakeCompound(comp);

  rb_funcall(a, rb_intern("flatten!"), 0);

  for (int i = 0; i < RARRAY_LEN(a); i++) {
    VALUE item = RARRAY_AREF(a, i);
    TopoDS_Shape* shape = siren_shape_get(item);
    B.Add(comp, *shape);
  }

  auto p = siren_shape_get(self);
  *p = comp;
  return self;
}

VALUE siren_compound_push(int argc, VALUE* argv, VALUE self)
{
  VALUE* a;
  VALUE len;
  rb_scan_args(argc, argv, "*", &a, &len);
  TopoDS_Compound comp = siren_compound_get(self);
  BRep_Builder B;
  for (int i = 0; i < len; i++) {
    VALUE arg = *(a + i);
    if (rb_array_p(arg)) {
      VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0);
      for (int j = 0; j < RARRAY_LEN(subary); j++) {
        TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j));
        B.Add(comp, *shape);
      }
    }
    else {
      TopoDS_Shape* shape = siren_shape_get(arg);
      B.Add(comp, *shape);
    }
  }
  return self;
}

VALUE siren_compound_delete(int argc, VALUE* argv, VALUE self)
{
  VALUE* a;
  VALUE len;
  rb_scan_args(argc, argv, "*", &a, &len);
  TopoDS_Compound comp = siren_compound_get(self);
  BRep_Builder B;
  for (int i = 0; i < len; i++) {
    VALUE arg = *(a + i);
    if (rb_array_p(arg)) {
      VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0);
      for (int j = 0; j < RARRAY_LEN(subary); j++) {
        TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j));
        B.Remove(comp, *shape);
      }
    }
    else {
      TopoDS_Shape* shape = siren_shape_get(arg);
      B.Remove(comp, *shape);
    }
  }
  return self;
}
<commit_msg>Update Siren::Compound#push method.<commit_after>#include "shape/compound.h"

#define rb_array_p(x) RB_TYPE_P(x, T_ARRAY)

VALUE sr_cCompound;

SR_SHAPE_GET(Compound, compound)
SR_SHAPE_CHECK(Compound, compound)

bool siren_compound_install()
{
  SR_SHAPE_INIT(Compound)
  rb_define_method(sr_cCompound, "initialize", RUBY_METHOD_FUNC(siren_compound_init),   -1);
  rb_define_method(sr_cCompound, "push",       RUBY_METHOD_FUNC(siren_compound_push),   -1);
  rb_define_method(sr_cCompound, "<<",         RUBY_METHOD_FUNC(siren_compound_push),   -1);
  rb_define_method(sr_cCompound, "delete",     RUBY_METHOD_FUNC(siren_compound_delete), -1);
  return true;
}

VALUE siren_compound_init(int argc, VALUE* argv, VALUE self)
{
  VALUE a;
  rb_scan_args(argc, argv, "*", &a);
  TopoDS_Compound comp;
  BRep_Builder B;
  B.MakeCompound(comp);
  VALUE b = rb_funcall(a, rb_intern("flatten"), 0);
  for (int i = 0; i < RARRAY_LEN(b); i++) {
    TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(b, i));
    B.Add(comp, *shape);
  }
  auto p = siren_shape_get(self);
  *p = comp;
  return self;
}

VALUE siren_compound_push(int argc, VALUE* argv, VALUE self)
{
  VALUE a;
  rb_scan_args(argc, argv, "*", &a);
  TopoDS_Compound comp = siren_compound_get(self);
  BRep_Builder B;
  VALUE b = rb_funcall(a, rb_intern("flatten"), 0);
  for (int i = 0; i < RARRAY_LEN(b); i++) {
    TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(b, i));
    B.Add(comp, *shape);
  }
  return self;
}

VALUE siren_compound_delete(int argc, VALUE* argv, VALUE self)
{
  VALUE a;
  rb_scan_args(argc, argv, "*", &a);
  TopoDS_Compound comp = siren_compound_get(self);
  BRep_Builder B;
  VALUE b = rb_funcall(a, rb_intern("flatten"), 0);
  for (int i = 0; i < RARRAY_LEN(b); i++) {
    TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(b, i));
    B.Remove(comp, *shape);
  }
  return self;
}
<|endoftext|>


<commit_before>#ifndef VOXEL_MATH_VECTOR3_H
#define VOXEL_MATH_VECTOR3_H

namespace math
{

template <typename Ty>
struct basic_vector3
{
	typedef Ty scalar;

	basic_vector3() {}
	basic_vector3(const basic_vector3 &copy) : x(copy.x), y(copy.y), z(copy.z) {}
	basic_vector3(scalar x, scalar y, scalar z) : x(x), y(y), z(z) {}

	friend basic_vector3 operator +(const basic_vector3 &a, const basic_vector3 &b)
		{ return basic_vector3(a.x+b.x, a.y+b.y, a.z+b.z); }
	friend basic_vector3 operator -(const basic_vector3 &a, const basic_vector3 &b)
		{ return basic_vector3(a.x-b.x, a.y-b.y, a.z-b.z); }
	friend basic_vector3 operator *(const basic_vector3 &a, scalar b)
		{ return basic_vector3(a.x*b, a.y*b, a.z*b); }
	friend basic_vector3 operator /(const basic_vector3 &a, scalar b)
		{ return basic_vector3(a.x/b, a.y/b, a.z/b); }

	basic_vector3 &operator +=(const basic_vector3 &b)
		{ x+=b.x, y+=b.y, z+=b.z; return *this; }
	basic_vector3 &operator -=(const basic_vector3 &b)
		{ x-=b.x, y-=b.y, z-=b.z; return *this; }
	basic_vector3 &operator *=(scalar b)
		{ x*=b, y*=b, z*=b; return *this; }
	basic_vector3 &operator /=(scalar b)
		{ x/=b, y/=b, z/=b; return *this; }

	scalar &operator [](size_t i) { return (&x)[i]; }
	scalar operator [](size_t i) const { return (&x)[i]; }

	static const basic_vector3 zero()
		{ return basic_vector3(0, 0, 0); }

	scalar x, y, z;
};

template <typename Ty>
Ty dot(const basic_vector3<Ty> &a, const basic_vector3<Ty> &b)
	{ return a.x*b.x + a.y*b.y + a.z*b.z; }

template <typename Ty>
basic_vector3<Ty> cross(const basic_vector3<Ty> &a, const basic_vector3<Ty> &b)
	{ return basic_vector3<Ty>(a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x); }

typedef basic_vector3<float> vector3f;

}; // math

#endif // VOXEL_MATH_VECTOR_H
<commit_msg>Potential fix for bad hack in vector class.<commit_after>#ifndef VOXEL_MATH_VECTOR3_H
#define VOXEL_MATH_VECTOR3_H

namespace math
{

template <typename Ty>
struct basic_vector3
{
	typedef Ty scalar;

	basic_vector3() : x(els[0]), y(els[1]), z(els[2]) {}
	basic_vector3(const basic_vector3 &copy)
		: x(els[0]), y(els[1]), z(els[2]), els{copy.x, copy.y, copy.z} {}
	basic_vector3(scalar x, scalar y, scalar z)
		: x(els[0]), y(els[1]), z(els[2]), els{x, y, z} {}

	friend basic_vector3 operator +(const basic_vector3 &a, const basic_vector3 &b)
		{ return basic_vector3(a.x+b.x, a.y+b.y, a.z+b.z); }
	friend basic_vector3 operator -(const basic_vector3 &a, const basic_vector3 &b)
		{ return basic_vector3(a.x-b.x, a.y-b.y, a.z-b.z); }
	friend basic_vector3 operator *(const basic_vector3 &a, scalar b)
		{ return basic_vector3(a.x*b, a.y*b, a.z*b); }
	friend basic_vector3 operator /(const basic_vector3 &a, scalar b)
		{ return basic_vector3(a.x/b, a.y/b, a.z/b); }

	basic_vector3 &operator +=(const basic_vector3 &b)
		{ x+=b.x, y+=b.y, z+=b.z; return *this; }
	basic_vector3 &operator -=(const basic_vector3 &b)
		{ x-=b.x, y-=b.y, z-=b.z; return *this; }
	basic_vector3 &operator *=(scalar b)
		{ x*=b, y*=b, z*=b; return *this; }
	basic_vector3 &operator /=(scalar b)
		{ x/=b, y/=b, z/=b; return *this; }

	scalar &operator [](size_t i) { return (&x)[i]; }
	scalar operator [](size_t i) const { return (&x)[i]; }

	static const basic_vector3 zero()
		{ return basic_vector3(0, 0, 0); }

	scalar &x, &y, &z;

private:
	scalar els[3];
};

template <typename Ty>
Ty dot(const basic_vector3<Ty> &a, const basic_vector3<Ty> &b)
	{ return a.x*b.x + a.y*b.y + a.z*b.z; }

template <typename Ty>
basic_vector3<Ty> cross(const basic_vector3<Ty> &a, const basic_vector3<Ty> &b)
	{ return basic_vector3<Ty>(a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x); }

typedef basic_vector3<float> vector3f;

}; // math

#endif // VOXEL_MATH_VECTOR_H
<|endoftext|>


<commit_before>/*
-------------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2014-2019 Kim Kulling

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------------------------
*/
#include <cppcore/Container/TArray.h>
#include <cppcore/CPPCoreCommon.h>

#include "gtest/gtest.h"

#include <sstream>
#include <iostream>

using namespace CPPCore;

static const size_t ArraySize = 4;

static const float ArrayData[ ArraySize ] = {
	0.0f,
	1.0f,
	2.0f,
	3.0f
};

//-------------------------------------------------------------------------------------------------
///	@class		TArrayTest
///	@ingroup	UnitTest
///
///	@brief	The array tests.
//-------------------------------------------------------------------------------------------------
class TArrayTest : public testing::Test {
protected:
    void createArray( const float *pOrig, size_t numItems, TArray<float> &arrayInstance ) {
		for ( size_t i=0; i<numItems; ++i ) {
			arrayInstance.add( pOrig[ i ] );
		}
	}
};

TEST_F( TArrayTest, constructTest ) {
    TArray<float> arrayInstance;
	EXPECT_EQ( true, arrayInstance.isEmpty() );
    EXPECT_EQ( 0U, arrayInstance.size() );
    EXPECT_EQ( arrayInstance.begin(), arrayInstance.end() );
}

TEST_F( TArrayTest, constructWithSizeTest) {
    TArray<float> arrayInstance( 4 );
	EXPECT_EQ( 4u, arrayInstance.size() );
}

TEST_F( TArrayTest, addTest) {
    TArray<float> arrayInstance;
	arrayInstance.add( 0.0f );
	arrayInstance.add( 1.0f );

	EXPECT_EQ( 2u, arrayInstance.size() );
	EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
	EXPECT_EQ( 1.0f, arrayInstance[ 1 ] );
}

TEST_F( TArrayTest, addItemsTest ) {
    TArray<float> arrayInstance;
    arrayInstance.add( 0.0f );

    float data[2] = { 0, 1 };
    arrayInstance.add( data, 2 );
    EXPECT_EQ( 3u, arrayInstance.size() );
    EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
    EXPECT_EQ( 0.0f, arrayInstance[ 1 ] );
    EXPECT_EQ( 1.0f, arrayInstance[ 2 ] );

    arrayInstance.add( nullptr, 0 );
    EXPECT_EQ( 3u, arrayInstance.size() );
}

TEST_F( TArrayTest, accessTest) {
    TArray<float> arrayInstance;
	arrayInstance.add( 0.0f );
	arrayInstance.add( 1.0f );

	EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
	EXPECT_EQ( 1.0f, arrayInstance[ 1 ] );
}

TEST_F( TArrayTest, backTest ) {
    float item( 0.0f );
    TArray<float> arrayInstance;
    arrayInstance.add( 1.0f );
    item = arrayInstance.back();
    EXPECT_FLOAT_EQ( 1.0f, item );

    arrayInstance.add( 2.0f );
    item = arrayInstance.back();
    EXPECT_FLOAT_EQ( 2.0f, item );
}

struct foo {
    float m_item;
    foo() : m_item( 1.0f ) {}
};

TEST_F( TArrayTest, constBackTest ) {
    TArray<foo> fooArrayInstance;
    foo foo1;
    foo1.m_item = 1.0f;
    fooArrayInstance.add( foo1 );
    const foo &res1 = fooArrayInstance.back();
    EXPECT_FLOAT_EQ( 1.0f, res1.m_item );

    foo foo2;
    foo2.m_item = 2.0f;
    fooArrayInstance.add( foo2 );
    const foo &res2 = fooArrayInstance.back();
    EXPECT_FLOAT_EQ( 2.0f, res2.m_item );

}

TEST_F( TArrayTest, removeTest) {
    TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	std::stringstream stream;
	static const size_t Size = 3;
	arrayInstance.remove( 1 );
	EXPECT_EQ( Size, arrayInstance.size() );
	float expectedResult[ Size ] = { 0.0f, 2.0f, 3.0f };
	bool equal = true;
	for ( size_t i=0; i<Size; ++i ) {
		if ( arrayInstance[ i ] != expectedResult[ i ] ) {
			stream << "error in index " << i << std::endl;
			equal = false;
			break;
		}
	}
    EXPECT_TRUE( equal ) << stream.str();
}

TEST_F( TArrayTest, removeItTest) {
    TArray<float> arrayInstance;
    arrayInstance.add( 1.0f );
    EXPECT_EQ( 1u, arrayInstance.size() );
    TArray<float>::Iterator it = arrayInstance.find( 1.0f );
    EXPECT_NE( arrayInstance.end(), it );

    arrayInstance.remove( it );
    EXPECT_EQ( 0u, arrayInstance.size() );
}

TEST_F( TArrayTest, removeBackTest) {
    TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	arrayInstance.removeBack();
	EXPECT_EQ( 3u, arrayInstance.size() );
	EXPECT_EQ( 2.0f, arrayInstance[ 2 ] );
}

TEST_F( TArrayTest, resizeTest ) {
    TArray<float> arrayInstance;
	EXPECT_EQ( 0u, arrayInstance.size() );

	arrayInstance.resize( 5 );
	EXPECT_EQ( 5u, arrayInstance.size() );
}

TEST_F( TArrayTest, moveTest ) {
    TArray<float> arrayInstance;
    arrayInstance.add( 1.0f );
    arrayInstance.add( 2.0f );
    arrayInstance.add( 3.0f );
    arrayInstance.move( 1, 3 );
}

TEST_F( TArrayTest, reserveTest ) {
    TArray<float> arrayInstance;
	EXPECT_EQ( 0u, arrayInstance.capacity() );

	arrayInstance.reserve( 5 );
	EXPECT_EQ( 5u, arrayInstance.capacity() );

    static const size_t NewSize = 2000;
	arrayInstance.reserve(NewSize);
	EXPECT_EQ( NewSize, arrayInstance.capacity() );
}

TEST_F( TArrayTest, resize_with_init_Test ) {
    TArray<float> arrayInstance;
    EXPECT_EQ( 0u, arrayInstance.capacity() );

    arrayInstance.resize( 10, 1.0f );
    EXPECT_EQ( 10u, arrayInstance.size() );
    for ( size_t i = 0; i < 10; ++i ) {
        EXPECT_FLOAT_EQ( 1.0f, arrayInstance[ i ] );
    }
}

TEST_F( TArrayTest, iterateTest ) {
    TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	size_t i( 0 );
    for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) {
        ++i;
	}
	EXPECT_EQ( i, arrayInstance.size() );
}

TEST_F( TArrayTest, preIncIterateTest ) {
    TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	bool ok = true;
	try {
		size_t i( 0 );
        for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) {
            float tmp = *it;
			EXPECT_EQ( tmp, ArrayData[ i ] );
			++i;
		}
	} catch (...)	{
		ok = false;
	}
	EXPECT_TRUE( ok );
}

TEST_F( TArrayTest, postIncIterateTest ) {
	TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	bool ok = true;
	try {
		size_t i(0);
        for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); it++ ) {
            float tmp = *it;
			EXPECT_EQ( tmp, ArrayData[ i ] );
			++i;
		}
	} catch (...) {
		ok = false;
	}
	EXPECT_TRUE( ok );
}

TEST_F( TArrayTest, findTest )	{
    TArray<float> arrayInstance;
	arrayInstance.add( 0.0f );
	arrayInstance.add( 1.0f );
	arrayInstance.add( 2.0f );
	arrayInstance.add( 3.0f );
	EXPECT_EQ( 4u, arrayInstance.size() );

    TArray<float>::Iterator it = arrayInstance.find( 1.0f );
	EXPECT_NE( it, arrayInstance.end() );
	EXPECT_EQ( *it, 1.0f );
}

TEST_F( TArrayTest, ContainerClearTest ) {
    TArray<float*> arrayInstance;
    ContainerClear( arrayInstance );
    EXPECT_TRUE( arrayInstance.isEmpty() );

    arrayInstance.add( new float( 0.0f ) );
    arrayInstance.add( new float( 1.0f ) );
    arrayInstance.add( new float( 2.0f ) );

    EXPECT_EQ( arrayInstance.size(), 3U );
    ContainerClear( arrayInstance );
    EXPECT_EQ( arrayInstance.size(), 0U );
    EXPECT_TRUE( arrayInstance.isEmpty() );
}

//---------------------------------------------------------------------------------------------
//	Crash when iterating an empty array.
//---------------------------------------------------------------------------------------------
TEST_F( TArrayTest, bug_IterateEmptyListTest )	{
    TArray<float> arrayInstance;
	bool ok = true;
	try {
        for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it );
	} catch ( ... ) {
		ok = false;
	}
	EXPECT_TRUE( ok );
}

//---------------------------------------------------------------------------------------------
//	Heap corruption after grow.
//---------------------------------------------------------------------------------------------
TEST_F( TArrayTest, bug_AddHeapCorruptTest ) {
    TArray<float> arrayInstance;
	for ( size_t i=0; i<50; ++i ) {
        arrayInstance.add( ( float ) i );
	}
}
<commit_msg>fix broken unittest.<commit_after>/*
-------------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2014-2019 Kim Kulling

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------------------------
*/
#include <cppcore/Container/TArray.h>
#include <cppcore/CPPCoreCommon.h>

#include "gtest/gtest.h"

#include <sstream>
#include <iostream>

using namespace CPPCore;

static const size_t ArraySize = 4;

static const float ArrayData[ ArraySize ] = {
	0.0f,
	1.0f,
	2.0f,
	3.0f
};

//-------------------------------------------------------------------------------------------------
///	@class		TArrayTest
///	@ingroup	UnitTest
///
///	@brief	The array tests.
//-------------------------------------------------------------------------------------------------
class TArrayTest : public testing::Test {
protected:
    void createArray( const float *pOrig, size_t numItems, TArray<float> &arrayInstance ) {
		for ( size_t i=0; i<numItems; ++i ) {
			arrayInstance.add( pOrig[ i ] );
		}
	}
};

TEST_F( TArrayTest, constructTest ) {
    TArray<float> arrayInstance;
	EXPECT_EQ( true, arrayInstance.isEmpty() );
    EXPECT_EQ( 0U, arrayInstance.size() );
    EXPECT_EQ( arrayInstance.begin(), arrayInstance.end() );
}

TEST_F( TArrayTest, constructWithSizeTest) {
    TArray<float> arrayInstance( 4 );
	EXPECT_EQ( 4u, arrayInstance.size() );
}

TEST_F( TArrayTest, addTest) {
    TArray<float> arrayInstance;
	arrayInstance.add( 0.0f );
	arrayInstance.add( 1.0f );

	EXPECT_EQ( 2u, arrayInstance.size() );
	EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
	EXPECT_EQ( 1.0f, arrayInstance[ 1 ] );
}

TEST_F( TArrayTest, addItemsTest ) {
    TArray<float> arrayInstance;
    arrayInstance.add( 0.0f );

    float data[2] = { 0, 1 };
    arrayInstance.add( data, 2 );
    EXPECT_EQ( 3u, arrayInstance.size() );
    EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
    EXPECT_EQ( 0.0f, arrayInstance[ 1 ] );
    EXPECT_EQ( 1.0f, arrayInstance[ 2 ] );

    arrayInstance.add( nullptr, 0 );
    EXPECT_EQ( 3u, arrayInstance.size() );
}

TEST_F( TArrayTest, accessTest) {
    TArray<float> arrayInstance;
	arrayInstance.add( 0.0f );
	arrayInstance.add( 1.0f );

	EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
	EXPECT_EQ( 1.0f, arrayInstance[ 1 ] );
}

TEST_F( TArrayTest, backTest ) {
    float item( 0.0f );
    TArray<float> arrayInstance;
    arrayInstance.add( 1.0f );
    item = arrayInstance.back();
    EXPECT_FLOAT_EQ( 1.0f, item );

    arrayInstance.add( 2.0f );
    item = arrayInstance.back();
    EXPECT_FLOAT_EQ( 2.0f, item );
}

struct foo {
    float m_item;
    foo() : m_item( 1.0f ) {}
};

TEST_F( TArrayTest, constBackTest ) {
    TArray<foo> fooArrayInstance;
    foo foo1;
    foo1.m_item = 1.0f;
    fooArrayInstance.add( foo1 );
    const foo &res1 = fooArrayInstance.back();
    EXPECT_FLOAT_EQ( 1.0f, res1.m_item );

    foo foo2;
    foo2.m_item = 2.0f;
    fooArrayInstance.add( foo2 );
    const foo &res2 = fooArrayInstance.back();
    EXPECT_FLOAT_EQ( 2.0f, res2.m_item );

}

TEST_F( TArrayTest, removeTest) {
    TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	std::stringstream stream;
	static const size_t Size = 3;
	arrayInstance.remove( 1 );
	EXPECT_EQ( Size, arrayInstance.size() );
	float expectedResult[ Size ] = { 0.0f, 2.0f, 3.0f };
	bool equal = true;
	for ( size_t i=0; i<Size; ++i ) {
		if ( arrayInstance[ i ] != expectedResult[ i ] ) {
			stream << "error in index " << i << std::endl;
			equal = false;
			break;
		}
	}
    EXPECT_TRUE( equal ) << stream.str();
}

TEST_F( TArrayTest, removeItTest) {
    TArray<float> arrayInstance;
    arrayInstance.add( 1.0f );
    EXPECT_EQ( 1u, arrayInstance.size() );
    TArray<float>::Iterator it = arrayInstance.find( 1.0f );
    EXPECT_NE( arrayInstance.end(), it );

    arrayInstance.remove( it );
    EXPECT_EQ( 0u, arrayInstance.size() );
}

TEST_F( TArrayTest, removeBackTest) {
    TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	arrayInstance.removeBack();
	EXPECT_EQ( 3u, arrayInstance.size() );
	EXPECT_EQ( 2.0f, arrayInstance[ 2 ] );
}

TEST_F( TArrayTest, resizeTest ) {
    TArray<float> arrayInstance;
	EXPECT_EQ( 0u, arrayInstance.size() );

	arrayInstance.resize( 5 );
	EXPECT_EQ( 5u, arrayInstance.size() );
}

TEST_F( TArrayTest, moveTest ) {
    TArray<float> arrayInstance;
    arrayInstance.add( 1.0f );
    arrayInstance.add( 2.0f );
    arrayInstance.add( 3.0f );
    arrayInstance.move( 1, 2 );
}

TEST_F( TArrayTest, reserveTest ) {
    TArray<float> arrayInstance;
	EXPECT_EQ( 0u, arrayInstance.capacity() );

	arrayInstance.reserve( 5 );
	EXPECT_EQ( 5u, arrayInstance.capacity() );

    static const size_t NewSize = 2000;
	arrayInstance.reserve(NewSize);
	EXPECT_EQ( NewSize, arrayInstance.capacity() );
}

TEST_F( TArrayTest, resize_with_init_Test ) {
    TArray<float> arrayInstance;
    EXPECT_EQ( 0u, arrayInstance.capacity() );

    arrayInstance.resize( 10, 1.0f );
    EXPECT_EQ( 10u, arrayInstance.size() );
    for ( size_t i = 0; i < 10; ++i ) {
        EXPECT_FLOAT_EQ( 1.0f, arrayInstance[ i ] );
    }
}

TEST_F( TArrayTest, iterateTest ) {
    TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	size_t i( 0 );
    for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) {
        ++i;
	}
	EXPECT_EQ( i, arrayInstance.size() );
}

TEST_F( TArrayTest, preIncIterateTest ) {
    TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	bool ok = true;
	try {
		size_t i( 0 );
        for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) {
            float tmp = *it;
			EXPECT_EQ( tmp, ArrayData[ i ] );
			++i;
		}
	} catch (...)	{
		ok = false;
	}
	EXPECT_TRUE( ok );
}

TEST_F( TArrayTest, postIncIterateTest ) {
	TArray<float> arrayInstance;
	createArray( ArrayData, ArraySize, arrayInstance );

	bool ok = true;
	try {
		size_t i(0);
        for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); it++ ) {
            float tmp = *it;
			EXPECT_EQ( tmp, ArrayData[ i ] );
			++i;
		}
	} catch (...) {
		ok = false;
	}
	EXPECT_TRUE( ok );
}

TEST_F( TArrayTest, findTest )	{
    TArray<float> arrayInstance;
	arrayInstance.add( 0.0f );
	arrayInstance.add( 1.0f );
	arrayInstance.add( 2.0f );
	arrayInstance.add( 3.0f );
	EXPECT_EQ( 4u, arrayInstance.size() );

    TArray<float>::Iterator it = arrayInstance.find( 1.0f );
	EXPECT_NE( it, arrayInstance.end() );
	EXPECT_EQ( *it, 1.0f );
}

TEST_F( TArrayTest, ContainerClearTest ) {
    TArray<float*> arrayInstance;
    ContainerClear( arrayInstance );
    EXPECT_TRUE( arrayInstance.isEmpty() );

    arrayInstance.add( new float( 0.0f ) );
    arrayInstance.add( new float( 1.0f ) );
    arrayInstance.add( new float( 2.0f ) );

    EXPECT_EQ( arrayInstance.size(), 3U );
    ContainerClear( arrayInstance );
    EXPECT_EQ( arrayInstance.size(), 0U );
    EXPECT_TRUE( arrayInstance.isEmpty() );
}

//---------------------------------------------------------------------------------------------
//	Crash when iterating an empty array.
//---------------------------------------------------------------------------------------------
TEST_F( TArrayTest, bug_IterateEmptyListTest )	{
    TArray<float> arrayInstance;
	bool ok = true;
	try {
        for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it );
	} catch ( ... ) {
		ok = false;
	}
	EXPECT_TRUE( ok );
}

//---------------------------------------------------------------------------------------------
//	Heap corruption after grow.
//---------------------------------------------------------------------------------------------
TEST_F( TArrayTest, bug_AddHeapCorruptTest ) {
    TArray<float> arrayInstance;
	for ( size_t i=0; i<50; ++i ) {
        arrayInstance.add( ( float ) i );
	}
}
<|endoftext|>


<commit_before><commit_msg>attempt to fix web build<commit_after><|endoftext|>


<commit_before>//===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/CGSCCPassManager.h"
#include "llvm/IR/CallSite.h"

using namespace llvm;

namespace llvm {

// Explicit instantiations for the core proxy templates.
template class AllAnalysesOn<LazyCallGraph::SCC>;
template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
                           LazyCallGraph &, CGSCCUpdateResult &>;
template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
                                         LazyCallGraph::SCC>;
template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
                                         LazyCallGraph::SCC>;
template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;

/// Explicitly specialize the pass manager run method to handle call graph
/// updates.
template <>
PreservedAnalyses
PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
            CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
                                      CGSCCAnalysisManager &AM,
                                      LazyCallGraph &G, CGSCCUpdateResult &UR) {
  PreservedAnalyses PA = PreservedAnalyses::all();

  if (DebugLogging)
    dbgs() << "Starting CGSCC pass manager run.\n";

  // The SCC may be refined while we are running passes over it, so set up
  // a pointer that we can update.
  LazyCallGraph::SCC *C = &InitialC;

  for (auto &Pass : Passes) {
    if (DebugLogging)
      dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";

    PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);

    // Update the SCC if necessary.
    C = UR.UpdatedC ? UR.UpdatedC : C;

    // Check that we didn't miss any update scenario.
    assert(!UR.InvalidatedSCCs.count(C) && "Processing an invalid SCC!");
    assert(C->begin() != C->end() && "Cannot have an empty SCC!");

    // Update the analysis manager as each pass runs and potentially
    // invalidates analyses.
    AM.invalidate(*C, PassPA);

    // Finally, we intersect the final preserved analyses to compute the
    // aggregate preserved set for this pass manager.
    PA.intersect(std::move(PassPA));

    // FIXME: Historically, the pass managers all called the LLVM context's
    // yield function here. We don't have a generic way to acquire the
    // context and it isn't yet clear what the right pattern is for yielding
    // in the new pass manager so it is currently omitted.
    // ...getContext().yield();
  }

  // Invaliadtion was handled after each pass in the above loop for the current
  // SCC. Therefore, the remaining analysis results in the AnalysisManager are
  // preserved. We mark this with a set so that we don't need to inspect each
  // one individually.
  PA.preserve<AllAnalysesOn<LazyCallGraph::SCC>>();

  if (DebugLogging)
    dbgs() << "Finished CGSCC pass manager run.\n";

  return PA;
}

} // End llvm namespace

namespace {
/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
/// added SCCs.
///
/// The range of new SCCs must be in postorder already. The SCC they were split
/// out of must be provided as \p C. The current node being mutated and
/// triggering updates must be passed as \p N.
///
/// This function returns the SCC containing \p N. This will be either \p C if
/// no new SCCs have been split out, or it will be the new SCC containing \p N.
template <typename SCCRangeT>
LazyCallGraph::SCC *
incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
                       LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
                       CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
                       bool DebugLogging = false) {
  typedef LazyCallGraph::SCC SCC;

  if (NewSCCRange.begin() == NewSCCRange.end())
    return C;

  // Invalidate the analyses of the current SCC and add it to the worklist since
  // it has changed its shape.
  AM.invalidate(*C, PreservedAnalyses::none());
  UR.CWorklist.insert(C);
  if (DebugLogging)
    dbgs() << "Enqueuing the existing SCC in the worklist:" << *C << "\n";

  SCC *OldC = C;
  (void)OldC;

  // Update the current SCC. Note that if we have new SCCs, this must actually
  // change the SCC.
  assert(C != &*NewSCCRange.begin() &&
         "Cannot insert new SCCs without changing current SCC!");
  C = &*NewSCCRange.begin();
  assert(G.lookupSCC(N) == C && "Failed to update current SCC!");

  for (SCC &NewC :
       reverse(make_range(std::next(NewSCCRange.begin()), NewSCCRange.end()))) {
    assert(C != &NewC && "No need to re-visit the current SCC!");
    assert(OldC != &NewC && "Already handled the original SCC!");
    UR.CWorklist.insert(&NewC);
    if (DebugLogging)
      dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n";
  }
  return C;
}
}

LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
    LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
    CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool DebugLogging) {
  typedef LazyCallGraph::Node Node;
  typedef LazyCallGraph::Edge Edge;
  typedef LazyCallGraph::SCC SCC;
  typedef LazyCallGraph::RefSCC RefSCC;

  RefSCC &InitialRC = InitialC.getOuterRefSCC();
  SCC *C = &InitialC;
  RefSCC *RC = &InitialRC;
  Function &F = N.getFunction();

  // Walk the function body and build up the set of retained, promoted, and
  // demoted edges.
  SmallVector<Constant *, 16> Worklist;
  SmallPtrSet<Constant *, 16> Visited;
  SmallPtrSet<Function *, 16> RetainedEdges;
  SmallSetVector<Function *, 4> PromotedRefTargets;
  SmallSetVector<Function *, 4> DemotedCallTargets;
  // First walk the function and handle all called functions. We do this first
  // because if there is a single call edge, whether there are ref edges is
  // irrelevant.
  for (BasicBlock &BB : F)
    for (Instruction &I : BB)
      if (auto CS = CallSite(&I))
        if (Function *Callee = CS.getCalledFunction())
          if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
            const Edge *E = N.lookup(*Callee);
            // FIXME: We should really handle adding new calls. While it will
            // make downstream usage more complex, there is no fundamental
            // limitation and it will allow passes within the CGSCC to be a bit
            // more flexible in what transforms they can do. Until then, we
            // verify that new calls haven't been introduced.
            assert(E && "No function transformations should introduce *new* "
                        "call edges! Any new calls should be modeled as "
                        "promoted existing ref edges!");
            RetainedEdges.insert(Callee);
            if (!E->isCall())
              PromotedRefTargets.insert(Callee);
          }

  // Now walk all references.
  for (BasicBlock &BB : F)
    for (Instruction &I : BB) {
      for (Value *Op : I.operand_values())
        if (Constant *C = dyn_cast<Constant>(Op))
          if (Visited.insert(C).second)
            Worklist.push_back(C);

      LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &Referee) {
        // Skip declarations.
        if (Referee.isDeclaration())
          return;

        const Edge *E = N.lookup(Referee);
        // FIXME: Similarly to new calls, we also currently preclude
        // introducing new references. See above for details.
        assert(E && "No function transformations should introduce *new* ref "
                    "edges! Any new ref edges would require IPO which "
                    "function passes aren't allowed to do!");
        RetainedEdges.insert(&Referee);
        if (E->isCall())
          DemotedCallTargets.insert(&Referee);
      });
    }

  // First remove all of the edges that are no longer present in this function.
  // We have to build a list of dead targets first and then remove them as the
  // data structures will all be invalidated by removing them.
  SmallVector<PointerIntPair<Node *, 1, Edge::Kind>, 4> DeadTargets;
  for (Edge &E : N)
    if (!RetainedEdges.count(&E.getFunction()))
      DeadTargets.push_back({E.getNode(), E.getKind()});
  for (auto DeadTarget : DeadTargets) {
    Node &TargetN = *DeadTarget.getPointer();
    bool IsCall = DeadTarget.getInt() == Edge::Call;
    SCC &TargetC = *G.lookupSCC(TargetN);
    RefSCC &TargetRC = TargetC.getOuterRefSCC();

    if (&TargetRC != RC) {
      RC->removeOutgoingEdge(N, TargetN);
      if (DebugLogging)
        dbgs() << "Deleting outgoing edge from '" << N << "' to '" << TargetN
               << "'\n";
      continue;
    }
    if (DebugLogging)
      dbgs() << "Deleting internal " << (IsCall ? "call" : "ref")
             << " edge from '" << N << "' to '" << TargetN << "'\n";

    if (IsCall)
      C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N,
                                 C, AM, UR, DebugLogging);

    auto NewRefSCCs = RC->removeInternalRefEdge(N, TargetN);
    if (!NewRefSCCs.empty()) {
      // Note that we don't bother to invalidate analyses as ref-edge
      // connectivity is not really observable in any way and is intended
      // exclusively to be used for ordering of transforms rather than for
      // analysis conclusions.

      // The RC worklist is in reverse postorder, so we first enqueue the
      // current RefSCC as it will remain the parent of all split RefSCCs, then
      // we enqueue the new ones in RPO except for the one which contains the
      // source node as that is the "bottom" we will continue processing in the
      // bottom-up walk.
      UR.RCWorklist.insert(RC);
      if (DebugLogging)
        dbgs() << "Enqueuing the existing RefSCC in the update worklist: "
               << *RC << "\n";
      // Update the RC to the "bottom".
      assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
      RC = &C->getOuterRefSCC();
      assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
      for (RefSCC *NewRC : reverse(NewRefSCCs))
        if (NewRC != RC) {
          UR.RCWorklist.insert(NewRC);
          if (DebugLogging)
            dbgs() << "Enqueuing a new RefSCC in the update worklist: "
                   << *NewRC << "\n";
        }
    }
  }

  // Next demote all the call edges that are now ref edges. This helps make
  // the SCCs small which should minimize the work below as we don't want to
  // form cycles that this would break.
  for (Function *RefTarget : DemotedCallTargets) {
    Node &TargetN = *G.lookup(*RefTarget);
    SCC &TargetC = *G.lookupSCC(TargetN);
    RefSCC &TargetRC = TargetC.getOuterRefSCC();

    // The easy case is when the target RefSCC is not this RefSCC. This is
    // only supported when the target RefSCC is a child of this RefSCC.
    if (&TargetRC != RC) {
      assert(RC->isAncestorOf(TargetRC) &&
             "Cannot potentially form RefSCC cycles here!");
      RC->switchOutgoingEdgeToRef(N, TargetN);
      if (DebugLogging)
        dbgs() << "Switch outgoing call edge to a ref edge from '" << N
               << "' to '" << TargetN << "'\n";
      continue;
    }

    // Otherwise we are switching an internal call edge to a ref edge. This
    // may split up some SCCs.
    C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N, C,
                               AM, UR, DebugLogging);
  }

  // Now promote ref edges into call edges.
  for (Function *CallTarget : PromotedRefTargets) {
    Node &TargetN = *G.lookup(*CallTarget);
    SCC &TargetC = *G.lookupSCC(TargetN);
    RefSCC &TargetRC = TargetC.getOuterRefSCC();

    // The easy case is when the target RefSCC is not this RefSCC. This is
    // only supported when the target RefSCC is a child of this RefSCC.
    if (&TargetRC != RC) {
      assert(RC->isAncestorOf(TargetRC) &&
             "Cannot potentially form RefSCC cycles here!");
      RC->switchOutgoingEdgeToCall(N, TargetN);
      if (DebugLogging)
        dbgs() << "Switch outgoing ref edge to a call edge from '" << N
               << "' to '" << TargetN << "'\n";
      continue;
    }
    if (DebugLogging)
      dbgs() << "Switch an internal ref edge to a call edge from '" << N
             << "' to '" << TargetN << "'\n";

    // Otherwise we are switching an internal ref edge to a call edge. This
    // may merge away some SCCs, and we add those to the UpdateResult. We also
    // need to make sure to update the worklist in the event SCCs have moved
    // before the current one in the post-order sequence.
    auto InitialSCCIndex = RC->find(*C) - RC->begin();
    auto InvalidatedSCCs = RC->switchInternalEdgeToCall(N, TargetN);
    if (!InvalidatedSCCs.empty()) {
      C = &TargetC;
      assert(G.lookupSCC(N) == C && "Failed to update current SCC!");

      // Any analyses cached for this SCC are no longer precise as the shape
      // has changed by introducing this cycle.
      AM.invalidate(*C, PreservedAnalyses::none());

      for (SCC *InvalidatedC : InvalidatedSCCs) {
        assert(InvalidatedC != C && "Cannot invalidate the current SCC!");
        UR.InvalidatedSCCs.insert(InvalidatedC);

        // Also clear any cached analyses for the SCCs that are dead. This
        // isn't really necessary for correctness but can release memory.
        AM.clear(*InvalidatedC);
      }
    }
    auto NewSCCIndex = RC->find(*C) - RC->begin();
    if (InitialSCCIndex < NewSCCIndex) {
      // Put our current SCC back onto the worklist as we'll visit other SCCs
      // that are now definitively ordered prior to the current one in the
      // post-order sequence, and may end up observing more precise context to
      // optimize the current SCC.
      UR.CWorklist.insert(C);
      if (DebugLogging)
        dbgs() << "Enqueuing the existing SCC in the worklist: " << *C << "\n";
      // Enqueue in reverse order as we pop off the back of the worklist.
      for (SCC &MovedC : reverse(make_range(RC->begin() + InitialSCCIndex,
                                            RC->begin() + NewSCCIndex))) {
        UR.CWorklist.insert(&MovedC);
        if (DebugLogging)
          dbgs() << "Enqueuing a newly earlier in post-order SCC: " << MovedC
                 << "\n";
      }
    }
  }

  assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
  assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
  assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");

  // Record the current RefSCC and SCC for higher layers of the CGSCC pass
  // manager now that all the updates have been applied.
  if (RC != &InitialRC)
    UR.UpdatedRC = RC;
  if (C != &InitialC)
    UR.UpdatedC = C;

  return *C;
}
<commit_msg>[PM] Basic cleanups to CGSCC update code, NFC.<commit_after>//===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/CGSCCPassManager.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/InstIterator.h"

using namespace llvm;

namespace llvm {

// Explicit instantiations for the core proxy templates.
template class AllAnalysesOn<LazyCallGraph::SCC>;
template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
                           LazyCallGraph &, CGSCCUpdateResult &>;
template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
                                         LazyCallGraph::SCC>;
template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
                                         LazyCallGraph::SCC>;
template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;

/// Explicitly specialize the pass manager run method to handle call graph
/// updates.
template <>
PreservedAnalyses
PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
            CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
                                      CGSCCAnalysisManager &AM,
                                      LazyCallGraph &G, CGSCCUpdateResult &UR) {
  PreservedAnalyses PA = PreservedAnalyses::all();

  if (DebugLogging)
    dbgs() << "Starting CGSCC pass manager run.\n";

  // The SCC may be refined while we are running passes over it, so set up
  // a pointer that we can update.
  LazyCallGraph::SCC *C = &InitialC;

  for (auto &Pass : Passes) {
    if (DebugLogging)
      dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";

    PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);

    // Update the SCC if necessary.
    C = UR.UpdatedC ? UR.UpdatedC : C;

    // Check that we didn't miss any update scenario.
    assert(!UR.InvalidatedSCCs.count(C) && "Processing an invalid SCC!");
    assert(C->begin() != C->end() && "Cannot have an empty SCC!");

    // Update the analysis manager as each pass runs and potentially
    // invalidates analyses.
    AM.invalidate(*C, PassPA);

    // Finally, we intersect the final preserved analyses to compute the
    // aggregate preserved set for this pass manager.
    PA.intersect(std::move(PassPA));

    // FIXME: Historically, the pass managers all called the LLVM context's
    // yield function here. We don't have a generic way to acquire the
    // context and it isn't yet clear what the right pattern is for yielding
    // in the new pass manager so it is currently omitted.
    // ...getContext().yield();
  }

  // Invaliadtion was handled after each pass in the above loop for the current
  // SCC. Therefore, the remaining analysis results in the AnalysisManager are
  // preserved. We mark this with a set so that we don't need to inspect each
  // one individually.
  PA.preserve<AllAnalysesOn<LazyCallGraph::SCC>>();

  if (DebugLogging)
    dbgs() << "Finished CGSCC pass manager run.\n";

  return PA;
}

} // End llvm namespace

namespace {
/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
/// added SCCs.
///
/// The range of new SCCs must be in postorder already. The SCC they were split
/// out of must be provided as \p C. The current node being mutated and
/// triggering updates must be passed as \p N.
///
/// This function returns the SCC containing \p N. This will be either \p C if
/// no new SCCs have been split out, or it will be the new SCC containing \p N.
template <typename SCCRangeT>
LazyCallGraph::SCC *
incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
                       LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
                       CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
                       bool DebugLogging = false) {
  typedef LazyCallGraph::SCC SCC;

  if (NewSCCRange.begin() == NewSCCRange.end())
    return C;

  // Invalidate the analyses of the current SCC and add it to the worklist since
  // it has changed its shape.
  AM.invalidate(*C, PreservedAnalyses::none());
  UR.CWorklist.insert(C);
  if (DebugLogging)
    dbgs() << "Enqueuing the existing SCC in the worklist:" << *C << "\n";

  SCC *OldC = C;
  (void)OldC;

  // Update the current SCC. Note that if we have new SCCs, this must actually
  // change the SCC.
  assert(C != &*NewSCCRange.begin() &&
         "Cannot insert new SCCs without changing current SCC!");
  C = &*NewSCCRange.begin();
  assert(G.lookupSCC(N) == C && "Failed to update current SCC!");

  for (SCC &NewC :
       reverse(make_range(std::next(NewSCCRange.begin()), NewSCCRange.end()))) {
    assert(C != &NewC && "No need to re-visit the current SCC!");
    assert(OldC != &NewC && "Already handled the original SCC!");
    UR.CWorklist.insert(&NewC);
    if (DebugLogging)
      dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n";
  }
  return C;
}
}

LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
    LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
    CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool DebugLogging) {
  typedef LazyCallGraph::Node Node;
  typedef LazyCallGraph::Edge Edge;
  typedef LazyCallGraph::SCC SCC;
  typedef LazyCallGraph::RefSCC RefSCC;

  RefSCC &InitialRC = InitialC.getOuterRefSCC();
  SCC *C = &InitialC;
  RefSCC *RC = &InitialRC;
  Function &F = N.getFunction();

  // Walk the function body and build up the set of retained, promoted, and
  // demoted edges.
  SmallVector<Constant *, 16> Worklist;
  SmallPtrSet<Constant *, 16> Visited;
  SmallPtrSet<Function *, 16> RetainedEdges;
  SmallSetVector<Function *, 4> PromotedRefTargets;
  SmallSetVector<Function *, 4> DemotedCallTargets;

  // First walk the function and handle all called functions. We do this first
  // because if there is a single call edge, whether there are ref edges is
  // irrelevant.
  for (Instruction &I : instructions(F))
    if (auto CS = CallSite(&I))
      if (Function *Callee = CS.getCalledFunction())
        if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
          const Edge *E = N.lookup(*Callee);
          // FIXME: We should really handle adding new calls. While it will
          // make downstream usage more complex, there is no fundamental
          // limitation and it will allow passes within the CGSCC to be a bit
          // more flexible in what transforms they can do. Until then, we
          // verify that new calls haven't been introduced.
          assert(E && "No function transformations should introduce *new* "
                      "call edges! Any new calls should be modeled as "
                      "promoted existing ref edges!");
          RetainedEdges.insert(Callee);
          if (!E->isCall())
            PromotedRefTargets.insert(Callee);
        }

  // Now walk all references.
  for (Instruction &I : instructions(F))
    for (Value *Op : I.operand_values())
      if (Constant *C = dyn_cast<Constant>(Op))
        if (Visited.insert(C).second)
          Worklist.push_back(C);

  LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &Referee) {
    const Edge *E = N.lookup(Referee);
    // FIXME: Similarly to new calls, we also currently preclude
    // introducing new references. See above for details.
    assert(E && "No function transformations should introduce *new* ref "
                "edges! Any new ref edges would require IPO which "
                "function passes aren't allowed to do!");
    RetainedEdges.insert(&Referee);
    if (E->isCall())
      DemotedCallTargets.insert(&Referee);
  });

  // First remove all of the edges that are no longer present in this function.
  // We have to build a list of dead targets first and then remove them as the
  // data structures will all be invalidated by removing them.
  SmallVector<PointerIntPair<Node *, 1, Edge::Kind>, 4> DeadTargets;
  for (Edge &E : N)
    if (!RetainedEdges.count(&E.getFunction()))
      DeadTargets.push_back({E.getNode(), E.getKind()});
  for (auto DeadTarget : DeadTargets) {
    Node &TargetN = *DeadTarget.getPointer();
    bool IsCall = DeadTarget.getInt() == Edge::Call;
    SCC &TargetC = *G.lookupSCC(TargetN);
    RefSCC &TargetRC = TargetC.getOuterRefSCC();

    if (&TargetRC != RC) {
      RC->removeOutgoingEdge(N, TargetN);
      if (DebugLogging)
        dbgs() << "Deleting outgoing edge from '" << N << "' to '" << TargetN
               << "'\n";
      continue;
    }
    if (DebugLogging)
      dbgs() << "Deleting internal " << (IsCall ? "call" : "ref")
             << " edge from '" << N << "' to '" << TargetN << "'\n";

    if (IsCall)
      C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N,
                                 C, AM, UR, DebugLogging);

    auto NewRefSCCs = RC->removeInternalRefEdge(N, TargetN);
    if (!NewRefSCCs.empty()) {
      // Note that we don't bother to invalidate analyses as ref-edge
      // connectivity is not really observable in any way and is intended
      // exclusively to be used for ordering of transforms rather than for
      // analysis conclusions.

      // The RC worklist is in reverse postorder, so we first enqueue the
      // current RefSCC as it will remain the parent of all split RefSCCs, then
      // we enqueue the new ones in RPO except for the one which contains the
      // source node as that is the "bottom" we will continue processing in the
      // bottom-up walk.
      UR.RCWorklist.insert(RC);
      if (DebugLogging)
        dbgs() << "Enqueuing the existing RefSCC in the update worklist: "
               << *RC << "\n";
      // Update the RC to the "bottom".
      assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
      RC = &C->getOuterRefSCC();
      assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
      for (RefSCC *NewRC : reverse(NewRefSCCs))
        if (NewRC != RC) {
          UR.RCWorklist.insert(NewRC);
          if (DebugLogging)
            dbgs() << "Enqueuing a new RefSCC in the update worklist: "
                   << *NewRC << "\n";
        }
    }
  }

  // Next demote all the call edges that are now ref edges. This helps make
  // the SCCs small which should minimize the work below as we don't want to
  // form cycles that this would break.
  for (Function *RefTarget : DemotedCallTargets) {
    Node &TargetN = *G.lookup(*RefTarget);
    SCC &TargetC = *G.lookupSCC(TargetN);
    RefSCC &TargetRC = TargetC.getOuterRefSCC();

    // The easy case is when the target RefSCC is not this RefSCC. This is
    // only supported when the target RefSCC is a child of this RefSCC.
    if (&TargetRC != RC) {
      assert(RC->isAncestorOf(TargetRC) &&
             "Cannot potentially form RefSCC cycles here!");
      RC->switchOutgoingEdgeToRef(N, TargetN);
      if (DebugLogging)
        dbgs() << "Switch outgoing call edge to a ref edge from '" << N
               << "' to '" << TargetN << "'\n";
      continue;
    }

    // Otherwise we are switching an internal call edge to a ref edge. This
    // may split up some SCCs.
    C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N, C,
                               AM, UR, DebugLogging);
  }

  // Now promote ref edges into call edges.
  for (Function *CallTarget : PromotedRefTargets) {
    Node &TargetN = *G.lookup(*CallTarget);
    SCC &TargetC = *G.lookupSCC(TargetN);
    RefSCC &TargetRC = TargetC.getOuterRefSCC();

    // The easy case is when the target RefSCC is not this RefSCC. This is
    // only supported when the target RefSCC is a child of this RefSCC.
    if (&TargetRC != RC) {
      assert(RC->isAncestorOf(TargetRC) &&
             "Cannot potentially form RefSCC cycles here!");
      RC->switchOutgoingEdgeToCall(N, TargetN);
      if (DebugLogging)
        dbgs() << "Switch outgoing ref edge to a call edge from '" << N
               << "' to '" << TargetN << "'\n";
      continue;
    }
    if (DebugLogging)
      dbgs() << "Switch an internal ref edge to a call edge from '" << N
             << "' to '" << TargetN << "'\n";

    // Otherwise we are switching an internal ref edge to a call edge. This
    // may merge away some SCCs, and we add those to the UpdateResult. We also
    // need to make sure to update the worklist in the event SCCs have moved
    // before the current one in the post-order sequence.
    auto InitialSCCIndex = RC->find(*C) - RC->begin();
    auto InvalidatedSCCs = RC->switchInternalEdgeToCall(N, TargetN);
    if (!InvalidatedSCCs.empty()) {
      C = &TargetC;
      assert(G.lookupSCC(N) == C && "Failed to update current SCC!");

      // Any analyses cached for this SCC are no longer precise as the shape
      // has changed by introducing this cycle.
      AM.invalidate(*C, PreservedAnalyses::none());

      for (SCC *InvalidatedC : InvalidatedSCCs) {
        assert(InvalidatedC != C && "Cannot invalidate the current SCC!");
        UR.InvalidatedSCCs.insert(InvalidatedC);

        // Also clear any cached analyses for the SCCs that are dead. This
        // isn't really necessary for correctness but can release memory.
        AM.clear(*InvalidatedC);
      }
    }
    auto NewSCCIndex = RC->find(*C) - RC->begin();
    if (InitialSCCIndex < NewSCCIndex) {
      // Put our current SCC back onto the worklist as we'll visit other SCCs
      // that are now definitively ordered prior to the current one in the
      // post-order sequence, and may end up observing more precise context to
      // optimize the current SCC.
      UR.CWorklist.insert(C);
      if (DebugLogging)
        dbgs() << "Enqueuing the existing SCC in the worklist: " << *C << "\n";
      // Enqueue in reverse order as we pop off the back of the worklist.
      for (SCC &MovedC : reverse(make_range(RC->begin() + InitialSCCIndex,
                                            RC->begin() + NewSCCIndex))) {
        UR.CWorklist.insert(&MovedC);
        if (DebugLogging)
          dbgs() << "Enqueuing a newly earlier in post-order SCC: " << MovedC
                 << "\n";
      }
    }
  }

  assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
  assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
  assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");

  // Record the current RefSCC and SCC for higher layers of the CGSCC pass
  // manager now that all the updates have been applied.
  if (RC != &InitialRC)
    UR.UpdatedRC = RC;
  if (C != &InitialC)
    UR.UpdatedC = C;

  return *C;
}
<|endoftext|>