text
stringlengths 5
1.04M
|
|---|
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_UNITS_CGS_ENERGY_HPP
#define BOOST_UNITS_CGS_ENERGY_HPP
#include <boost/units/systems/cgs/base.hpp>
#include <boost/units/physical_dimensions/energy.hpp>
namespace boost {
namespace units {
namespace cgs {
typedef unit<energy_dimension,cgs::system> energy;
BOOST_UNITS_STATIC_CONSTANT(erg,energy);
BOOST_UNITS_STATIC_CONSTANT(ergs,energy);
} // namespace cgs
} // namespace units
} // namespace boost
#endif // BOOST_UNITS_CGS_ENERGY_HPP
|
/* $Id: taxid_set.hpp 610974 2020-06-26 12:59:33Z grichenk $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Kevin Bealer
*
*/
/** @file taxid_set.hpp
* Class which defines sequence id to taxid mapping.
*/
#ifndef OBJTOOLS_BLAST_SEQDB_WRITER___TAXID_SET__HPP
#define OBJTOOLS_BLAST_SEQDB_WRITER___TAXID_SET__HPP
#include <corelib/ncbistd.hpp>
// Blast databases
#include <objects/blastdb/Blast_def_line.hpp>
#include <objects/blastdb/Blast_def_line_set.hpp>
BEGIN_NCBI_SCOPE
class NCBI_XOBJWRITE_EXPORT CTaxIdSet : public CObject {
public:
static const TTaxId kTaxIdNotSet;
CTaxIdSet(TTaxId global_taxid = kTaxIdNotSet)
: m_GlobalTaxId(global_taxid),
m_Matched(true) {}
void SetMappingFromFile(CNcbiIstream & f);
/// Check that each defline has the specified taxid; if not,
/// replace the defline and set the taxid.
/// @param deflines Deflines to fix taxIDs [in|out]
void FixTaxId(CRef<objects::CBlast_def_line_set> deflines);
bool HasEverFixedId() const { return m_Matched; };
private:
TTaxId m_GlobalTaxId;
map< string, TTaxId > m_TaxIdMap;
bool m_Matched;
/// Selects the most suitable tax id for the input passed in, checking the
/// global taxid first, then the mapping provided by an input file, and
/// finally what's found in the defline argument
TTaxId x_SelectBestTaxid(const objects::CBlast_def_line & defline);
};
END_NCBI_SCOPE
#endif // OBJTOOLS_BLAST_SEQDB_WRITER___TAXID_SET__HPP
|
/*Copyright (c) 2014 The Paradox Game Converters Project
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 "EU3Province.h"
#include "EU3Country.h"
#include "EU3Religion.h"
#include "../Log.h"
#include "../Parsers/Object.h"
#include "../Configuration.h"
#include <algorithm>
#include <fstream>
EU3Province::EU3Province(Object* obj)
{
provTaxIncome = 0;
provProdIncome = 0;
provMPWeight = 0;
provBuildingWeight = 0;
provTradeGoodWeight = 0;
numV2Provs = 0;
num = atoi(obj->getKey().c_str());
vector<Object*> baseTaxObjs; // the object holding the base tax
baseTaxObjs = obj->getValue("base_tax");
baseTax = (baseTaxObjs.size() > 0) ? atof(baseTaxObjs[0]->getLeaf().c_str()) : 0.0f;
vector<Object*> ownerObjs;
ownerObjs = obj->getValue("owner");
if (ownerObjs.size() == 0)
{
ownerString = "";
}
else
{
ownerString = ownerObjs[0]->getLeaf();
}
owner = NULL;
cores.clear();
vector<Object*> coreObjs;
coreObjs = obj->getValue("core");
for (unsigned int i = 0; i < coreObjs.size(); i++)
{
cores.push_back(coreObjs[i]->getLeaf());
}
colony = true;
vector<Object*> popObj = obj->getValue("citysize");
if (popObj.size() > 0)
{
population = atoi( (popObj)[0]->getLeaf().c_str() );
if (population >= 1000)
{
colony = false;
}
}
else
{
popObj = obj->getValue("native_size");
if (popObj.size() > 0)
{
population = atoi( (popObj)[0]->getLeaf().c_str() );
}
else
{
population = 0;
}
}
centerOfTrade = false;
ownershipHistory.clear();
lastPossessedDate.clear();
religionHistory.clear();
cultureHistory.clear();
vector<Object*> historyObj = obj->getValue("history");
if (historyObj.size() > 0)
{
vector<Object*> historyObjs = historyObj[0]->getLeaves();
string lastOwner;
string thisCountry;
for (unsigned int i = 0; i < historyObjs.size(); i++)
{
if (historyObjs[i]->getKey() == "owner")
{
thisCountry = historyObjs[i]->getLeaf();
lastOwner = thisCountry;
ownershipHistory.push_back(make_pair(date(), thisCountry));
continue;
}
else if (historyObjs[i]->getKey() == "culture")
{
cultureHistory.push_back(make_pair(date(), historyObjs[i]->getLeaf()));
continue;
}
else if (historyObjs[i]->getKey() == "religion")
{
religionHistory.push_back(make_pair(date(), historyObjs[i]->getLeaf()));
continue;
}
vector<Object*> ownerObj = historyObjs[i]->getValue("owner");
if (ownerObj.size() > 0)
{
date newDate(historyObjs[i]->getKey());
thisCountry = ownerObj[0]->getLeaf();
map<string, date>::iterator itr = lastPossessedDate.find(lastOwner);
if (itr != lastPossessedDate.end())
itr->second = newDate;
else
lastPossessedDate.insert(make_pair(lastOwner, newDate));
lastOwner = thisCountry;
ownershipHistory.push_back(make_pair(newDate, thisCountry));
}
vector<Object*> culObj = historyObjs[i]->getValue("culture");
if (culObj.size() > 0)
{
date newDate(historyObjs[i]->getKey());
cultureHistory.push_back(make_pair(newDate, culObj[0]->getLeaf()));
}
vector<Object*> religObj = historyObjs[i]->getValue("religion");
if (religObj.size() > 0)
{
date newDate(historyObjs[i]->getKey());
religionHistory.push_back(make_pair(newDate, religObj[0]->getLeaf()));
}
}
}
sort(ownershipHistory.begin(), ownershipHistory.end());
sort(cultureHistory.begin(), cultureHistory.end());
sort(religionHistory.begin(), religionHistory.end());
if (num == 1)
{
Configuration::setFirstEU3Date(ownershipHistory[0].first);
}
if (cultureHistory.size() == 0)
{
vector<Object*> culObj = obj->getValue("culture");
if (culObj.size() > 0)
{
date newDate;
cultureHistory.push_back(make_pair(newDate, culObj[0]->getLeaf()));
}
}
if (religionHistory.size() == 0)
{
vector<Object*> religObj = obj->getValue("religion");
if (religObj.size() > 0)
{
date newDate;
religionHistory.push_back(make_pair(newDate, religObj[0]->getLeaf()));
}
}
popRatios.clear();
buildings.clear();
vector<Object*> tradegoodsObj = obj->getValue("trade_goods");
if (tradegoodsObj.size() > 0)
{
tradeGoods = tradegoodsObj[0]->getLeaf();
}
else
{
tradeGoods = "";
}
vector<Object*> provNameObj = obj->getValue("name");
if (provNameObj.size() > 0)
{
provName = provNameObj[0]->getLeaf();
}
else
{
provName = "";
}
vector<Object*> manpowerObj = obj->getValue("manpower");
if (manpowerObj.size() > 0)
{
string manpowerStr = manpowerObj[0]->getLeaf();
manpower = stod(manpowerStr);
}
else
{
manpower = 0.0;
}
//LOG(LogLevel::Info) << "Check unique Buildings...";
// unique buildings
checkBuilding(obj, "tax_assessor");
checkBuilding(obj, "embassy");
checkBuilding(obj, "glorious_monument");
checkBuilding(obj, "march");
checkBuilding(obj, "grain_depot");
checkBuilding(obj, "royal_palace");
checkBuilding(obj, "war_college");
checkBuilding(obj, "admiralty");
//LOG(LogLevel::Info) << "Check manus...";
// Manufacturies
checkBuilding(obj, "weapons");
checkBuilding(obj, "university");
checkBuilding(obj, "wharf");
checkBuilding(obj, "textile");
checkBuilding(obj, "fine_arts_academy");
checkBuilding(obj, "refinery");
//LOG(LogLevel::Info) << "Check buildings...";
// base buildings
checkBuilding(obj, "fort1");
checkBuilding(obj, "fort2");
checkBuilding(obj, "fort3");
checkBuilding(obj, "fort4");
checkBuilding(obj, "fort5");
checkBuilding(obj, "fort6");
checkBuilding(obj, "dock");
checkBuilding(obj, "drydock");
checkBuilding(obj, "shipyard");
checkBuilding(obj, "grand_shipyard");
checkBuilding(obj, "naval_arsenal");
checkBuilding(obj, "naval_base");
checkBuilding(obj, "temple");
checkBuilding(obj, "courthouse");
checkBuilding(obj, "spy_agency");
checkBuilding(obj, "town_hall");
checkBuilding(obj, "college");
checkBuilding(obj, "cathedral");
checkBuilding(obj, "armory");
checkBuilding(obj, "training_fields");
checkBuilding(obj, "barracks");
checkBuilding(obj, "regimental_camp");
checkBuilding(obj, "arsenal");
checkBuilding(obj, "conscription_center");
checkBuilding(obj, "constable");
checkBuilding(obj, "workshop");
checkBuilding(obj, "counting_house");
checkBuilding(obj, "treasury_office");
checkBuilding(obj, "mint");
checkBuilding(obj, "stock_exchange");
checkBuilding(obj, "marketplace");
checkBuilding(obj, "trade_depot");
checkBuilding(obj, "canal");
checkBuilding(obj, "road_network");
checkBuilding(obj, "post_office");
checkBuilding(obj, "customs_house");
buildPopRatios();
}
void EU3Province::addCore(string tag)
{
cores.push_back(tag);
}
void EU3Province::removeCore(string tag)
{
for (vector<string>::iterator i = cores.begin(); i != cores.end(); i++)
{
if (*i == tag)
{
cores.erase(i);
if (cores.size() == 0)
{
break;
}
i = cores.begin();
}
}
}
bool EU3Province::wasColonised() const
{
// returns true if the first owner did not own the province at the beginning of the game,
// but acquired it later through colonization
if (ownershipHistory.size() > 0)
{
if ((ownershipHistory[0].first != date()) && (ownershipHistory[0].first != Configuration::getFirstEU3Date()))
{
return true;
}
}
return false;
}
bool EU3Province::wasInfidelConquest() const
{
// returns true if the province was originally pagan, the current owner is non-pagan,
// and the province was NOT colonized
if (religionHistory.size() > 0 && !wasColonised())
{
EU3Religion* firstReligion = EU3Religion::getReligion(religionHistory[0].second);
EU3Religion* ownerReligion = EU3Religion::getReligion(owner->getReligion());
if ((firstReligion == NULL) || (ownerReligion == NULL))
{
LOG(LogLevel::Warning) << "Unhandled religion in EU3 province " << num;
return true;
}
else
{
return firstReligion->isInfidelTo(ownerReligion);
}
}
return false;
}
bool EU3Province::hasBuilding(string building) const
{
int num = buildings.count(building);
return (num > 0);
}
vector<EU3Country*> EU3Province::getCores(const map<string, EU3Country*>& countries) const
{
vector<EU3Country*> coreOwners;
for (vector<string>::const_iterator i = cores.begin(); i != cores.end(); i++)
{
map<string, EU3Country*>::const_iterator j = countries.find(*i);
if (j != countries.end())
{
coreOwners.push_back(j->second);
}
}
return coreOwners;
}
date EU3Province::getLastPossessedDate(string tag) const
{
map<string, date>::const_iterator itr = lastPossessedDate.find(tag);
if (itr != lastPossessedDate.end())
{
return itr->second;
}
return date();
}
void EU3Province::checkBuilding(const Object* provinceObj, string building)
{
vector<Object*> buildingObj;
buildingObj = provinceObj->getValue(building);
if ((buildingObj.size() > 0) && (buildingObj[0]->getLeaf() == "yes"))
{
buildings[building] = true;
}
}
void EU3Province::buildPopRatios()
{
date endDate = Configuration::getLastEU3Date();
if (endDate < date("1821.1.1"))
{
endDate = date("1821.1.1");
}
date cutoffDate = endDate;
cutoffDate.year -= 200;
// fast-forward to 200 years before the end date (200 year decay means any changes before then will be at 100%)
string curCulture = "";
string curReligion = "";
vector< pair<date, string> >::iterator cItr = cultureHistory.begin();
vector< pair<date, string> >::iterator rItr = religionHistory.begin();
while (cItr != cultureHistory.end() && cItr->first.year < cutoffDate.year)
{
curCulture = cItr->second;
++cItr;
}
if (cItr != cultureHistory.end() && curCulture == "")
{
// no starting culture; use first settlement culture for starting pop even if it's after 1620
curCulture = cItr->second;
}
while (rItr != religionHistory.end() && rItr->first.year < cutoffDate.year)
{
curReligion = rItr->second;
++rItr;
}
if (rItr != religionHistory.end() && curReligion == "")
{
// no starting religion; use first settlement religion for starting pop even if it's after 1620
curReligion = rItr->second;
}
// build and scale historic culture-religion pairs
EU3PopRatio pr;
pr.culture = curCulture;
pr.religion = curReligion;
pr.popRatio = 1.0;
date cDate, rDate, lastLoopDate;
while (cItr != cultureHistory.end() || rItr != religionHistory.end())
{
if (cItr == cultureHistory.end())
{
cDate = date("2000.1.1");
}
else
{
cDate = cItr->first;
}
if (rItr == religionHistory.end())
{
rDate = date("2000.1.1");
}
else
{
rDate = rItr->first;
}
if (cDate < rDate)
{
decayPopRatios(lastLoopDate, cDate, pr);
if ((pr.culture != "") || (pr.religion != ""))
{
popRatios.push_back(pr);
}
for (vector<EU3PopRatio>::iterator itr = popRatios.begin(); itr != popRatios.end(); ++itr)
{
itr->popRatio /= 2.0;
}
pr.popRatio = 0.5;
pr.culture = cItr->second;
lastLoopDate = cDate;
++cItr;
}
else if (cDate == rDate)
{
// culture and religion change on the same day;
decayPopRatios(lastLoopDate, cDate, pr);
popRatios.push_back(pr);
for (vector<EU3PopRatio>::iterator itr = popRatios.begin(); itr != popRatios.end(); ++itr)
{
itr->popRatio /= 2.0;
}
pr.popRatio = 0.5;
pr.culture = cItr->second;
pr.religion = rItr->second;
lastLoopDate = cDate;
++cItr;
++rItr;
}
else if (rDate < cDate)
{
decayPopRatios(lastLoopDate, rDate, pr);
popRatios.push_back(pr);
for (vector<EU3PopRatio>::iterator itr = popRatios.begin(); itr != popRatios.end(); ++itr)
{
itr->popRatio /= 2.0;
}
pr.popRatio = 0.5;
pr.religion = rItr->second;
lastLoopDate = rDate;
++rItr;
}
}
decayPopRatios(lastLoopDate, endDate, pr);
popRatios.push_back(pr);
}
void EU3Province::decayPopRatios(date oldDate, date newDate, EU3PopRatio& currentPop)
{
// quick out for initial state (no decay needed)
if (oldDate == date())
{
return;
}
// quick out for same year (we do decay at year end)
if (oldDate.year == newDate.year)
{
return;
}
// drop all non-current pops by a total of .0025 per year, divided proportionally
double nonCurrentRatio = (1.0 - currentPop.popRatio);
for (vector<EU3PopRatio>::iterator itr = popRatios.begin(); itr != popRatios.end(); ++itr)
{
itr->popRatio -= .0025 * (newDate.year - oldDate.year) * itr->popRatio / nonCurrentRatio ;
}
// increase current pop by .0025 per year
currentPop.popRatio += .0025 * (newDate.year - oldDate.year);
}
void EU3Province::determineProvinceWeight()
{
double trade_goods_weight = getTradeGoodWeight();
double manpower_weight = manpower;
double building_weight = 0.0;
double manpower_modifier = 0.0;
double manu_gp_mod = 0.0;
double building_tx_eff = 0.0;
double production_eff = 0.0;
double building_tx_income = 0.0;
double manpower_eff = 0.0;
double goods_produced_perc_mod = 0.0;
double trade_power = 0.0;
double trade_value = 0.0;
double trade_value_eff = 0.0;
double trade_power_eff = 0.0;
std::vector<double> provBuildingWeightVec = getProvBuildingWeight();
// 0 building_weight, 1 manpower_modifier, 2 manu_gp_mod, 3 building_tx_eff, 4 production_eff
// 5 building_tx_income, 6 manpower_eff, 7 goods_produced_perc_mod, 8 trade_power 9 trade_value
// 10 trade_value_eff, 11 trade_power_eff;
try {
building_weight = provBuildingWeightVec.at(0);
manpower_modifier = provBuildingWeightVec.at(1);
manu_gp_mod = provBuildingWeightVec.at(2);
building_tx_eff = provBuildingWeightVec.at(3);
production_eff = provBuildingWeightVec.at(4);
building_tx_income = provBuildingWeightVec.at(5);
manpower_eff = provBuildingWeightVec.at(6);
goods_produced_perc_mod = provBuildingWeightVec.at(7);
trade_power = provBuildingWeightVec.at(8);
trade_value = provBuildingWeightVec.at(9);
trade_value_eff = provBuildingWeightVec.at(10);
trade_power_eff = provBuildingWeightVec.at(11);
}
catch (exception &e)
{
LOG(LogLevel::Error) << "Error in building weight vector: " << e.what();
}
// Check tag, ex. TIB has goods_produced +0.05
// This needs to be hard coded unless there's some other way of figuring out modded national ambitions/ideas
if (this->getOwnerString() == "TIB")
{
goods_produced_perc_mod += 0.05;
}
double goods_produced = (baseTax * 0.2) + manu_gp_mod + goods_produced_perc_mod + 0.03;
// idea effects
if ( (owner != NULL) && (owner->hasNationalIdea("bureaucracy")) )
{
building_tx_eff += 0.10;
}
if ( (owner != NULL) && (owner->hasNationalIdea("smithian_economics")) )
{
production_eff += 0.10;
}
// manpower
manpower_weight *= 25;
manpower_weight += manpower_modifier;
manpower_weight *= ((1 + manpower_modifier) / 1005);
//LOG(LogLevel::Info) << "Manpower Weight: " << manpower_weight;
double total_tx = (baseTax + building_tx_income) * (1.0 + building_tx_eff + 0.15);
double production_eff_tech = 1.0;
double total_trade_value = ((getTradeGoodPrice() * goods_produced) + trade_value) * (1 + trade_value_eff);
double production_income = total_trade_value * (1 + production_eff_tech + production_eff);
//LOG(LogLevel::Info) << "province name: " << this->getProvName()
// << " trade good: " << tradeGoods
// << " Price: " << getTradeGoodPrice()
// << " trade value: " << trade_value
// << " trade value eff: "
// << (1 + trade_value_eff)
// << " goods produced: " << goods_produced
// << " production eff: " << production_eff
// << " Production: " << production_income;
total_tx *= 1;
manpower_weight *= 1;
production_income *= 1;
provBuildingWeight = building_weight;
provTaxIncome = total_tx;
provProdIncome = production_income;
provMPWeight = manpower_weight;
provTradeGoodWeight = trade_goods_weight;
totalWeight = building_weight + ((2 * baseTax) + manpower_weight + trade_goods_weight + production_income + total_tx);
if (owner == NULL)
{
totalWeight = 0;
}
// 0: Goods produced; 1 trade goods price; 2: trade value efficiency; 3: production effiency; 4: trade value; 5: production income
// 6: base tax; 7: building tax income 8: building tax eff; 9: total tax income; 10: total_trade_value
provProductionVec.push_back(goods_produced);
provProductionVec.push_back(getTradeGoodPrice());
provProductionVec.push_back(1 + trade_value_eff);
provProductionVec.push_back(1 + production_eff);
provProductionVec.push_back(trade_value);
provProductionVec.push_back(production_income);
provProductionVec.push_back(baseTax);
provProductionVec.push_back(building_tx_income);
provProductionVec.push_back(1 + building_tx_eff);
provProductionVec.push_back(total_tx);
provProductionVec.push_back(total_trade_value);
//LOG(LogLevel::Info) << "Num: " << num << " TAG: " << ownerString << " Weight: " << totalWeight;
}
double EU3Province::getTradeGoodPrice() const
{
// Trade goods
/*
chinaware
grain
fish
tabacco
iron
copper
cloth
ivory
slaves
salt
wool
fur
gold
sugar
naval_supplies
tea
coffee
spices
wine
cocoa
*/
//LOG(LogLevel::Info) << "Trade Goods Price";
double tradeGoodsPrice = 0;
if (tradeGoods == "chinaware")
{
tradeGoodsPrice = 9.66;
}
else if (tradeGoods == "grain")
{
tradeGoodsPrice = 5.0;
}
else if (tradeGoods == "fish")
{
tradeGoodsPrice = 5.00;
}
else if (tradeGoods == "tabacco")
{
tradeGoodsPrice = 7.82;
}
else if (tradeGoods == "iron")
{
tradeGoodsPrice = 5.94;
}
else if (tradeGoods == "copper")
{
tradeGoodsPrice = 5.0;
}
else if (tradeGoods == "cloth")
{
tradeGoodsPrice = 5.00;
}
else if (tradeGoods == "slaves")
{
tradeGoodsPrice = 2.91;
}
else if (tradeGoods == "salt")
{
tradeGoodsPrice = 3.30;
}
else if (tradeGoods == "gold")
{
tradeGoodsPrice = 4.0;
}
else if (tradeGoods == "fur")
{
tradeGoodsPrice = 7.03;
}
else if (tradeGoods == "sugar")
{
tradeGoodsPrice = 3.40;
}
else if (tradeGoods == "naval_supplies")
{
tradeGoodsPrice = 5.0;
}
else if (tradeGoods == "tea")
{
tradeGoodsPrice = 6.88;
}
else if (tradeGoods == "coffee")
{
tradeGoodsPrice = 9.58;
}
else if (tradeGoods == "spices")
{
tradeGoodsPrice = 7.91;
}
else if (tradeGoods == "wine")
{
tradeGoodsPrice = 5.18;
}
else if (tradeGoods == "cocoa")
{
tradeGoodsPrice = 7.50;
}
else if (tradeGoods == "ivory")
{
tradeGoodsPrice = 4.32;
}
else if (tradeGoods == "wool")
{
tradeGoodsPrice = 2.26;
}
else if (tradeGoods == "cotton")
{
tradeGoodsPrice = 3.96;
}
else
{
// anything ive missed
tradeGoodsPrice = 1;
}
return tradeGoodsPrice;
}
double EU3Province::getTradeGoodWeight() const
{
// Trade goods
/*
chinaware
grain
fish
tabacco
iron
copper
cloth
ivory
slaves
salt
wool
fur
gold
sugar
naval_supplies
tea
coffee
spices
wine
cocoa
*/
double trade_goods_weight = 0;
if (tradeGoods == "chinaware")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "grain")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "fish")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "tabacco")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "iron")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "copper")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "cloth")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "slaves")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "salt")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "gold")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "fur")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "sugar")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "naval_supplies")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "tea")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "coffee")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "spices")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "wine")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "cocoa")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "ivory")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "wool")
{
trade_goods_weight = 2;
}
else if (tradeGoods == "cotton")
{
trade_goods_weight = 2;
}
else
{
// anything ive missed
trade_goods_weight = 0;
}
return trade_goods_weight;
}
vector<double> EU3Province::getProvBuildingWeight() const
{
double building_weight = 0.0;
double manpower_modifier = 0.0;
double manu_gp_mod = 0.0;
double building_tx_eff = 0.0;
double production_eff = 0.0;
double building_tx_income = 0.0;
double manpower_eff = 0.0;
double goods_produced_perc_mod = 0.0;
double trade_power = 0.0;
double trade_value = 0.0;
double trade_value_eff = 0.0;
double trade_power_eff = 0.0;
// unique buildings
/*
if (hasBuilding("march"))
{
building_weight += 2;
manpower_modifier += 75;
}
if (hasBuilding("glorious_monument"))
{
building_weight += 2;
}
if (hasBuilding("royal_palace"))
{
building_weight += 2;
}
if (hasBuilding("admiralty"))
{
building_weight += 2;
}
if (hasBuilding("war_college"))
{
building_weight += 2;
}
if (hasBuilding("embassy"))
{
building_weight += 2;
}
if (hasBuilding("tax_assessor"))
{
building_weight += 2;
}
if (hasBuilding("grain_depot"))
{
building_weight += 2;
}
if (hasBuilding("university"))
{
building_weight += 2;
}
if (hasBuilding("fine_arts_academy"))
{
building_weight += 2;
}
// manfacturies building
if (hasBuilding("weapons"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("wharf"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("textile"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("refinery"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("plantations"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("farm_estate"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("tradecompany"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
// Base buildings
if (hasBuilding("fort1"))
{
building_weight += 1;
}
if (hasBuilding("fort2"))
{
building_weight += 2;
}
if (hasBuilding("fort3"))
{
building_weight += 3;
}
if (hasBuilding("fort4"))
{
building_weight += 4;
}
if (hasBuilding("fort5"))
{
building_weight += 5;
}
if (hasBuilding("fort6"))
{
building_weight += 6;
}
if (hasBuilding("dock"))
{
building_weight++;
}
if (hasBuilding("drydock"))
{
building_weight += 2;
}
if (hasBuilding("shipyard"))
{
building_weight += 3;
}
if (hasBuilding("grand_shipyard"))
{
building_weight += 4;
}
if (hasBuilding("naval_arsenal"))
{
building_weight += 5;
}
if (hasBuilding("naval_base"))
{
building_weight += 6;
}
if (hasBuilding("temple"))
{
building_weight += 1;
building_tx_income += 1.0;
}
if (hasBuilding("courthouse"))
{
building_weight += 2;
building_tx_eff += 0.10;
}
if (hasBuilding("spy_agency"))
{
building_weight += 3;
building_tx_eff += 0.20;
}
if (hasBuilding("town_hall"))
{
building_weight += 4;
building_tx_eff += 0.25;
}
if (hasBuilding("college"))
{
building_weight += 5;
building_tx_eff += 0.50;
}
if (hasBuilding("cathedral"))
{
building_weight += 6;
building_tx_income += 3.0;
}
if (hasBuilding("armory"))
{
building_weight += 1;
manpower_modifier += 25;
}
if (hasBuilding("training_fields"))
{
building_weight += 2;
manpower_modifier += 25;
}
if (hasBuilding("barracks"))
{
building_weight += 3;
manpower_modifier += 25;
manpower_eff += 0.10;
}
if (hasBuilding("regimental_camp"))
{
building_weight += 4;
manpower_eff += 0.20;
}
if (hasBuilding("arsenal"))
{
building_weight += 5;
manpower_modifier += 50;
}
if (hasBuilding("conscription_center"))
{
building_weight += 6;
manpower_modifier += 50;
manpower_eff += 0.50;
}
if (hasBuilding("constable"))
{
building_weight += 1;
production_eff += 0.2;
}
if (hasBuilding("workshop"))
{
building_weight += 2;
goods_produced_perc_mod += 0.2;
}
if (hasBuilding("counting_house"))
{
building_weight += 3;
}
if (hasBuilding("treasury_office"))
{
building_weight += 4;
}
if (hasBuilding("mint"))
{
building_weight += 5;
production_eff += 0.5;
}
if (hasBuilding("stock_exchange"))
{
building_weight += 6;
goods_produced_perc_mod += 0.50;
}
if (hasBuilding("customs_house"))
{
building_weight += 6;
trade_power += 10;
trade_value += 2;
}
if (hasBuilding("marketplace"))
{
building_weight++;
trade_power += 2;
}
if (hasBuilding("trade_depot"))
{
building_weight += 2;
trade_value += 1;
trade_power_eff += 0.25;
}
if (hasBuilding("canal"))
{
building_weight += 3;
trade_power += 2;
trade_value_eff += 0.25;
}
if (hasBuilding("road_network"))
{
building_weight += 4;
trade_power_eff += 0.25;
}
if (hasBuilding("post_office"))
{
building_weight += 5;
trade_power += 3;
trade_power_eff += 0.5;
}*/
if (hasBuilding("march"))
{
building_weight += 2;
manpower_modifier += 75;
}
if (hasBuilding("glorious_monument"))
{
building_weight += 2;
building_tx_income += 1;
manpower_eff += 0.05;
}
if (hasBuilding("royal_palace"))
{
building_weight += 2;
}
if (hasBuilding("admiralty"))
{
building_weight += 2;
}
if (hasBuilding("war_college"))
{
building_weight += 2;
}
if (hasBuilding("embassy"))
{
building_weight += 2;
}
if (hasBuilding("tax_assessor"))
{
building_weight += 2;
}
if (hasBuilding("grain_depot"))
{
building_weight += 2;
}
if (hasBuilding("university"))
{
building_weight += 2;
}
if (hasBuilding("fine_arts_academy"))
{
building_weight += 2;
}
// manfacturies building
if (hasBuilding("weapons"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("wharf"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("textile"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("refinery"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("plantations"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("farm_estate"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
if (hasBuilding("tradecompany"))
{
building_weight += 5;
manu_gp_mod = 1.0;
}
// Base buildings
if (hasBuilding("fort1"))
{
building_weight += 1;
}
if (hasBuilding("fort2"))
{
building_weight += 2;
}
if (hasBuilding("fort3"))
{
building_weight += 3;
}
if (hasBuilding("fort4"))
{
building_weight += 4;
}
if (hasBuilding("fort5"))
{
building_weight += 5;
}
if (hasBuilding("fort6"))
{
building_weight += 6;
}
if (hasBuilding("dock"))
{
building_weight++;
}
if (hasBuilding("drydock"))
{
building_weight += 2;
}
if (hasBuilding("shipyard"))
{
building_weight += 3;
}
if (hasBuilding("grand_shipyard"))
{
building_weight += 4;
}
if (hasBuilding("naval_arsenal"))
{
building_weight += 5;
}
if (hasBuilding("naval_base"))
{
building_weight += 6;
}
if (hasBuilding("temple"))
{
building_weight += 1;
building_tx_income += 1.0;
}
if (hasBuilding("courthouse"))
{
building_weight += 2;
building_tx_eff += 0.10;
building_tx_income += 1.0;
}
if (hasBuilding("spy_agency"))
{
building_weight += 3;
building_tx_eff += 0.30;
building_tx_income += 1.0;
}
if (hasBuilding("town_hall"))
{
building_weight += 4;
building_tx_eff += 0.55;
building_tx_income += 1.0;
}
if (hasBuilding("college"))
{
building_weight += 5;
building_tx_eff += 1.05;
building_tx_income += 1.0;
}
if (hasBuilding("cathedral"))
{
building_weight += 6;
building_tx_eff += 1.05;
building_tx_income += 4.0;
}
if (hasBuilding("armory"))
{
building_weight += 1;
manpower_modifier += 25;
}
if (hasBuilding("training_fields"))
{
building_weight += 2;
manpower_modifier += 50;
}
if (hasBuilding("barracks"))
{
building_weight += 3;
manpower_modifier += 75;
manpower_eff += 0.10;
}
if (hasBuilding("regimental_camp"))
{
building_weight += 4;
manpower_eff += 0.30;
manpower_modifier += 75;
}
if (hasBuilding("arsenal"))
{
building_weight += 5;
manpower_eff += 0.30;
manpower_modifier += 125;
}
if (hasBuilding("conscription_center"))
{
building_weight += 6;
manpower_modifier += 175;
manpower_eff += 0.80;
}
if (hasBuilding("constable"))
{
building_weight += 1;
production_eff += 0.2;
}
if (hasBuilding("workshop"))
{
building_weight += 2;
goods_produced_perc_mod += 0.2;
production_eff += 0.2;
}
if (hasBuilding("counting_house"))
{
goods_produced_perc_mod += 0.2;
production_eff += 0.2;
building_weight += 3;
}
if (hasBuilding("treasury_office"))
{
building_weight += 4;
goods_produced_perc_mod += 0.2;
production_eff += 0.2;
}
if (hasBuilding("mint"))
{
building_weight += 5;
goods_produced_perc_mod += 0.2;
production_eff += 0.7;
}
if (hasBuilding("stock_exchange"))
{
building_weight += 6;
production_eff += 0.7;
goods_produced_perc_mod += 0.70;
}
if (hasBuilding("customs_house"))
{
building_weight += 6;
trade_value_eff += 0.25;
trade_value += 3;
trade_power_eff += 1;
trade_power += 17;
}
if (hasBuilding("marketplace"))
{
building_weight++;
trade_power += 2;
}
if (hasBuilding("trade_depot"))
{
building_weight += 2;
trade_value += 1;
trade_power_eff += 0.25;
trade_power += 2;
}
if (hasBuilding("canal"))
{
building_weight += 3;
trade_value_eff += 0.25;
trade_value += 1;
trade_power_eff += 0.25;
trade_power += 4;
}
if (hasBuilding("road_network"))
{
building_weight += 4;
trade_value_eff += 0.25;
trade_value += 1;
trade_power_eff += 0.5;
trade_power += 4;
}
if (hasBuilding("post_office"))
{
building_weight += 5;
trade_value_eff += 0.25;
trade_value += 1;
trade_power_eff += 1;
trade_power += 7;
}
std::vector<double> provBuildingWeightVec;
provBuildingWeightVec.push_back(building_weight);
provBuildingWeightVec.push_back(manpower_modifier);
provBuildingWeightVec.push_back(manu_gp_mod);
provBuildingWeightVec.push_back(building_tx_eff);
provBuildingWeightVec.push_back(production_eff);
provBuildingWeightVec.push_back(building_tx_income);
provBuildingWeightVec.push_back(manpower_eff);
provBuildingWeightVec.push_back(goods_produced_perc_mod);
provBuildingWeightVec.push_back(trade_power);
provBuildingWeightVec.push_back(trade_value);
provBuildingWeightVec.push_back(trade_value_eff);
provBuildingWeightVec.push_back(trade_power_eff);
// 0 building_weight, 1 manpower_modifier, 2 manu_gp_mod, 3 building_tx_eff, 4 production_eff
// 5 building_tx_income, 6 manpower_eff, 7 goods_produced_perc_mod, 8 trade_power 9 trade_value
// 10 trade_value_eff, 11 trade_power_eff;
return provBuildingWeightVec;
}
|
#ifndef __kdtree_HPP
#define __kdtree_HPP
//
// KdTree implementation.
//
// Copyright: Christoph Dalitz, 2018
// Jens Wilberg, 2018
// License: BSD style license
// (see the file LICENSE for details)
//
#include <cstdlib>
#include <queue>
#include <vector>
namespace Kdtree {
typedef std::vector<double> CoordPoint;
typedef std::vector<double> DoubleVector;
// for passing points to the constructor of kdtree
struct KdNode {
CoordPoint point;
void* data;
KdNode(const CoordPoint& p, void* d = NULL) {
point = p;
data = d;
}
KdNode() { data = NULL; }
};
typedef std::vector<KdNode> KdNodeVector;
// base function object for search predicate in knn search
// returns true when the given KdNode is an admissible neighbor
// To define an own search predicate, derive from this class
// and overwrite the call operator operator()
struct KdNodePredicate {
virtual ~KdNodePredicate() {}
virtual bool operator()(const KdNode& kn) const { return true; }
};
//--------------------------------------------------------
// private helper classes used internally by KdTree
//
// the internal node structure used by kdtree
class kdtree_node;
// base class for different distance computations
class DistanceMeasure;
// helper class for priority queue in k nearest neighbor search
class nn4heap {
public:
size_t dataindex; // index of actual kdnode in *allnodes*
double distance; // distance of this neighbor from *point*
nn4heap(size_t i, double d) {
dataindex = i;
distance = d;
}
};
class compare_nn4heap {
public:
bool operator()(const nn4heap& n, const nn4heap& m) {
return (n.distance < m.distance);
}
};
//--------------------------------------------------------
// kdtree class
class KdTree {
private:
// recursive build of tree
kdtree_node* build_tree(size_t depth, size_t a, size_t b);
// helper variable for keeping track of subtree bounding box
CoordPoint lobound, upbound;
// helper variables and functions for k nearest neighbor search
std::priority_queue<nn4heap, std::vector<nn4heap>, compare_nn4heap>*
neighborheap;
std::vector<size_t> range_result;
// helper variable to check the distance method
int distance_type;
bool neighbor_search(const CoordPoint& point, kdtree_node* node, size_t k);
void range_search(const CoordPoint& point, kdtree_node* node, double r);
bool bounds_overlap_ball(const CoordPoint& point, double dist,
kdtree_node* node);
bool ball_within_bounds(const CoordPoint& point, double dist,
kdtree_node* node);
// class implementing the distance computation
DistanceMeasure* distance;
// search predicate in knn searches
KdNodePredicate* searchpredicate;
public:
KdNodeVector allnodes;
size_t dimension;
kdtree_node* root;
// distance_type can be 0 (max), 1 (city block), or 2 (euklid)
KdTree(const KdNodeVector* nodes, int distance_type = 2);
~KdTree();
void set_distance(int distance_type, const DoubleVector* weights = NULL);
void k_nearest_neighbors(const CoordPoint& point, size_t k,
KdNodeVector* result, std::vector<double>* distances,
KdNodePredicate* pred = NULL);
void range_nearest_neighbors(const CoordPoint& point, double r,
KdNodeVector* result);
};
} // end namespace Kdtree
#endif
|
#pragma once
#include "generator/feature_builder.hpp"
#include "generator/regions/collector_region_info.hpp"
#include "generator/regions/region_base.hpp"
#include <unordered_map>
namespace generator
{
namespace regions
{
class PlacePoint;
using PlacePointsMap = std::unordered_map<base::GeoObjectId, PlacePoint>;
// PlacePoint objects presents centers (place=* nodes) of localities (city/town/village/...)
// and their subdivision parts (suburb/quarter/...).
// PlacePoint objects are converted to Region objects with approximated boundaries
// when there is no the same places with original boundaries.
// Approximation depends on place type of point (see MakePolygonWithRadius()).
// Conversion is performed by Region constructor: Region{placePoint}.
class PlacePoint : public RegionWithName, public RegionWithData
{
public:
explicit PlacePoint(FeatureBuilder1 const & fb, RegionDataProxy const & rd)
: RegionWithName(fb.GetParams().name),
RegionWithData(rd)
{
auto const p = fb.GetKeyPoint();
m_position = {p.x, p.y};
}
BoostPoint GetPosition() const { return m_position; }
private:
BoostPoint m_position;
};
} // namespace regions
} // namespace generator
|
// Font generated by stb_font_inl_generator.c (4/1 bpp)
//
// Following instructions show how to use the only included font, whatever it is, in
// a generic way so you can replace it with any other font by changing the include.
// To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_courier_bold_10_latin_ext_*,
// and separately install each font. Note that the CREATE function call has a
// totally different name; it's just 'stb_font_courier_bold_10_latin_ext'.
//
/* // Example usage:
static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS];
static void init(void)
{
// optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2
static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH];
STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT);
... create texture ...
// for best results rendering 1:1 pixels texels, use nearest-neighbor sampling
// if allowed to scale up, use bilerp
}
// This function positions characters on integer coordinates, and assumes 1:1 texels to pixels
// Appropriate if nearest-neighbor sampling is used
static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0);
glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0);
glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1);
glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance_int;
}
glEnd();
}
// This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels
// Appropriate if bilinear filtering is used
static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f);
glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance;
}
glEnd();
}
*/
#ifndef STB_FONTCHAR__TYPEDEF
#define STB_FONTCHAR__TYPEDEF
typedef struct
{
// coordinates if using integer positioning
float s0,t0,s1,t1;
signed short x0,y0,x1,y1;
int advance_int;
// coordinates if using floating positioning
float s0f,t0f,s1f,t1f;
float x0f,y0f,x1f,y1f;
float advance;
} stb_fontchar;
#endif
#define STB_FONT_courier_bold_10_latin_ext_BITMAP_WIDTH 256
#define STB_FONT_courier_bold_10_latin_ext_BITMAP_HEIGHT 76
#define STB_FONT_courier_bold_10_latin_ext_BITMAP_HEIGHT_POW2 128
#define STB_FONT_courier_bold_10_latin_ext_FIRST_CHAR 32
#define STB_FONT_courier_bold_10_latin_ext_NUM_CHARS 560
#define STB_FONT_courier_bold_10_latin_ext_LINE_SPACING 5
static unsigned int stb__courier_bold_10_latin_ext_pixels[]={
0x00201010,0x81b80620,0x20002200,0x00200010,0x00202a98,0x00000000,
0x06666204,0x00100000,0x00400022,0x00180000,0x20970000,0x0c815c3b,
0x20383ca8,0x2a075038,0x41e5c09a,0x82a80aba,0x265409aa,0xa81c80ca,
0xa83ca84c,0xa80c884c,0xdc83904b,0x20f6a6cf,0xa81e84ca,0x0ae1e543,
0x381b81c8,0x97709930,0x36a05710,0x1c825dc3,0x5434074c,0x4404c0b8,
0x406e2099,0x428a80ba,0x28a83328,0x45419944,0xa8199442,0x206a5109,
0x41989882,0x31050098,0x41350331,0x27219898,0x40cc62d6,0x0bb3a08a,
0x84d44135,0x9a83fff8,0x40a04540,0x22620a98,0x06666219,0x980a0666,
0x0ea06c09,0x6744dd9d,0x1b73a21e,0x8c0a6015,0x076cf641,0xdb3d9063,
0x4f6418c1,0xdb9d10ed,0x443b67b2,0x27b21ece,0x3d9d10ed,0xd90f6744,
0x33621db3,0x3b67b26d,0x367b2340,0xe93b3a0e,0x9b73a20a,0x20ae4ece,
0x33a6dce8,0x4dddb14e,0x3b26dcd8,0xb3d90ed9,0x8ef6441d,0x3621ece8,
0x3a06c6dc,0xb9ba2ae0,0x2715cb12,0xfd885ee8,0x51fc6e42,0xf8dc9267,
0xb924cea3,0x499d47f1,0x267538ae,0x752c4ae4,0x4b12b926,0x99d4b12b,
0x4ea28ae4,0x99d46849,0x88623624,0x89c571eb,0x20ae188d,0x446c4e2b,
0x2b8f2771,0x54933a8a,0xb8720933,0x8515cb12,0xd3b12a0d,0x6cd06cd3,
0x703d7300,0x475588d7,0xaac4933a,0xb124cea3,0x4933a8ea,0x4933a80d,
0x933a9a0d,0xd06cd06c,0x236499d4,0x26750bc8,0x3a877ec4,0x31eda893,
0x4036793b,0x3ba21eda,0x36a01b0e,0xd8f2571e,0x2750bc88,0x124cea49,
0x9a0d8721,0x360bc88d,0x37d703a0,0x2e599d49,0x16d6d463,0x2b10f5f4,
0x11d5263a,0x75498eab,0x5263aac4,0x9318ee3a,0x4b33a8ea,0x99d47549,
0x932ccea5,0x7a8bc8ea,0x2141d526,0x994c7549,0x1dc9f915,0x262cca63,
0x4a631dc1,0x47ddb159,0x5267a8bc,0x71d5263a,0xb33a8725,0xf53d45e4,
0x3bae1621,0x206f640d,0xfdd34eed,0x44dcea8d,0x6f6c6fee,0x3637f740,
0x37f740de,0xddb037b6,0x3206f6c9,0x06f6c0de,0xbd9037b2,0x220ded81,
0x6f6c4eee,0x0ded8480,0x0b07bbaa,0x3baa9ddb,0x76c0541e,0x03ddd54e,
0x27774479,0xbdb037b6,0x642f7541,0x3bba20de,0x00e00a64,0x74404000,
0x00083f96,0x00200010,0x00000000,0x00000000,0x00100010,0x00040200,
0x00275404,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x02101080,0x22310004,
0x0001e5c0,0x1e440000,0x00265410,0x91001e5c,0x10000003,0x540cc400,
0x2000d408,0x0414a02c,0x0cc44800,0x2880825c,0x22e00005,0x440cc884,
0xa82b80cc,0x3647643c,0xb80d814a,0x9104ca81,0x46215901,0x06631598,
0x5131132e,0x4544ca83,0xca83ca82,0x0e425dc4,0x39f912ee,0x40a27674,
0x204b81b8,0x97058831,0xd9d70a09,0x40e416c3,0x80d81b1d,0x198c44ac,
0x4c4c4098,0x3304ccc1,0x8933a866,0x81333031,0x4099980a,0x3ae09999,
0x3d91d90c,0x303b67b2,0x1db3d903,0x8ec84ccc,0x10cc626c,0x2a623333,
0x41333109,0x106c09a9,0x23b2311b,0xea80a86c,0x323b21ef,0x06620ec6,
0x2ab107ec,0x01988364,0x9998361b,0x4f6414c0,0x3d9d10ed,0x8876cf64,
0x237a2ece,0x926751fb,0x3a23f8dc,0x7f1b92ec,0xd1176744,0x0f445dbd,
0x33a92675,0x542fd889,0x67e44933,0x7b8b2d11,0xb67ee4bb,0x9d74dceb,
0x073f229b,0x11eda81b,0x5ee88b2d,0xb44d15a8,0x3ae2cc2c,0x220d81ec,
0xb8360eef,0xd9a61ece,0x4439f910,0x499d42fd,0x2752c4ae,0x9166e249,
0xaa4cd3f5,0x711d5623,0x23aac4b3,0xbcd859b8,0x27506c1b,0x424cea49,
0x499d46bb,0x435e40d8,0x5a720ebc,0x22533b16,0x406c299d,0x92cca60d,
0x83d730d7,0x5e4588ea,0xaac41b06,0x23620d84,0x5588362e,0xd81b3449,
0x9d46bb80,0x2a683649,0x40e88933,0x7645dedb,0x21d5620e,0x1d5620e8,
0x3f7a03a2,0x3aa4c682,0x5f41d526,0x41d5261e,0x4417c40d,0xef88d02f,
0x360bbe22,0xea8f7ec0,0x50be21ee,0xeea85b5b,0xa817c41d,0x883bbe24,
0x15f92efe,0xef88363d,0x40d86c0e,0x21ebe80d,0x99d47549,0x3a1d5265,
0x3ebea499,0xfee82c84,0xdd24cf46,0x2499e8df,0xd319adca,0xd81bd909,
0x6e7540de,0x6c06f6c4,0x01b03440,0x2b11b11a,0x06c588d8,0x220e40ec,
0x46fee986,0xd01a204a,0x20ba3621,0x26c0a81d,0x3d85d1b1,0x7540d81b,
0x06f6c4dc,0xbdb037b2,0x32777d41,0x40220f2f,0x44eefa80,0x24eefa80,
0x003eefde,0x32dd1000,0xefe8801f,0xfb01dd92,0x90efd81d,0x3bf2dddf,
0x85dfd16e,0xd9064408,0x76c0201d,0x200eec83,0x3d15f93a,0x541c8088,
0x87a2bf22,0x77f44318,0x07f2dd12,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x54150198,0x4c08004c,0x40000182,0x10003309,0x80040e28,
0x64060000,0x0600cc44,0x82545500,0x64418898,0xaa409981,0x22080001,
0x00000999,0x048b8100,0x36207220,0x80c3442f,0x440c83cb,0x207b3a26,
0xd81b04ca,0x02c0ed8f,0x0590d857,0x901c8091,0x202ea039,0x077aa0e9,
0x40322064,0x75c1a219,0x114545ea,0x1328db9d,0x16ea1e54,0x4dceb832,
0x1e541e54,0x40641ed4,0x8a899501,0x4a8d7702,0x9887b3a2,0x20c44c41,
0x262c4ae6,0x26621988,0x1673aa09,0x444c19f3,0x42cc3619,0x98066019,
0x6c053009,0x44c80e40,0x7fe88198,0xbb11fd74,0x15cffd09,0x8bfe7f47,
0x1aea0999,0x27621333,0x2204ee29,0x4ccc0989,0x22133310,0x26621ece,
0x1fdfb109,0x8b21ebe8,0x6764b12b,0xb176f71e,0x7ec68367,0xb9d70ed8,
0x22dedd49,0x23f62c9e,0x447830ed,0x2fd882fd,0xd882fd88,0x1c81b02f,
0x3aa0e981,0x3df1a01d,0x9a03ef88,0xbb43600d,0xfff14dce,0x4473f227,
0xa82cc2ef,0x3f225d9e,0x29b9d71c,0x675cb12b,0x50f2774d,0xb1649b9d,
0x96695341,0xb8ec0ebc,0x9cea8b33,0xa8a67625,0x41625f8b,0xd0e59cea,
0x2ee0d770,0x2e0d7706,0x1c81b06b,0x01c81b0d,0xb10f7e34,0x4773403a,
0x3b1686c1,0x6c35e453,0x89623620,0x55620eef,0x27620d83,0xb1341b29,
0x1e4ae533,0x547f2dd1,0x952ccea4,0x8d05f134,0x6dd40ded,0xb0bbe25b,
0xeec8b73d,0xd96f6ea1,0x3d7d0b50,0x7d03d7d0,0x43d7d03d,0xdf73efe9,
0x1c81b0fd,0xdf7b9a01,0x4074d7e4,0xe8a776c6,0x5df169ef,0x3617f7cc,
0x89bbbf20,0x777c4756,0x3be20d83,0xf12ccea2,0x1ff6c45d,0x320e8b20,
0x2cd2a0de,0xfd8d3036,0x2fc5d45d,0x150b11b1,0xf1750360,0x541d86cb,
0x67544dce,0x26e7544d,0x2a1373aa,0x81b00a80,0x50d10d1c,0x86880540,
0x6c5a201c,0x216b6588,0x2219300d,0x3aac4755,0x223620d8,0xd8837b25,
0x01644588,0x776c0020,0x883bf60d,0x3604c440,0x3bf25b9e,0x0101c86e,
0x30cb73db,0x23f96e88,0x223f96e8,0x3a23f96e,0x06443f96,0x3bfa60e4,
0x44fddf73,0x406442de,0x82dd80c8,0x323bb00c,0x8e726eef,0xc802efe8,
0x27f26e9f,0x4bbfa26e,0xc806eefc,0x13b26eef,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x09980407,0x1e5c1454,0x1110c422,0x41909383,0x004c43ca,0x0000e6a0,
0x31070595,0xab828a81,0x32a04c41,0x28a85703,0x28a85570,0x55703998,
0x2b8000a8,0x20710188,0x43880061,0x2620028a,0x10e40500,0x1b88db9b,
0xd74d8350,0x44f77ae1,0x261f8111,0x70aa6099,0x41701bdd,0x3b21ede9,
0x502a660e,0x1b885530,0x154c1444,0xb9013331,0xca80dc41,0x1a80dc42,
0x88182988,0x144c5ede,0x1307b3ae,0x7457d9d0,0x3710505e,0x54c5dd90,
0x07f7ec42,0x28ae1333,0x443fbf62,0x58ae1ece,0xb7bac566,0xbf910f8b,
0x88fa3323,0x0eec8756,0x56dd2a3a,0x43bf915c,0x37b20eec,0x6643bb20,
0x877643e8,0x3b24dceb,0x906f644e,0xe8cc89dd,0x322775c3,0x13bae0de,
0xeeb811b5,0xb9622264,0x3c4aa4ee,0xdd907ae6,0x5f42f745,0x7717ba0a,
0x1cfc88f2,0x2e17911b,0x5895c793,0x68e658ae,0xb03a1af2,0xac475588,
0x972b6e3a,0x2ef6e936,0x32b6e2c2,0x6dd66975,0x8eab15ca,0x3b15cadb,
0x725cee53,0x4b9dd669,0x5263aac4,0x9acd2e48,0x982a8914,0x7776c914,
0x0d922937,0x41dada9a,0x3ae60abe,0x98f6a621,0x1e4ae1eb,0xf517906c,
0x8363c95c,0x99636ae6,0x40fc4b13,0x3aac4581,0xdb9b67f2,0x933f52bb,
0x8b13b762,0x2772bbdb,0x2577b768,0x5edc7558,0x5c5df12b,0x689dc951,
0x2b112a37,0x2e08e63a,0x208e6d13,0x8e60effa,0x39a4cea0,0x4cb33a82,
0x2a626fee,0x43b5b53d,0x5b51edf9,0x1ff6c43b,0x9ddd106c,0x751ff6c4,
0x2edcd966,0x4161edb2,0x6fee8584,0x76ec4098,0x40ec3c84,0x8a76ec45,
0xdbb11eed,0xb137f749,0x223629db,0x23ffdb15,0xdb11eed8,0x6fee83ff,
0xdb126f6c,0x426f6c3d,0xc89bdb02,0x137b60de,0x36101bd9,0x263dbf31,
0x21c86fee,0xc886fee9,0x00a80d82,0x0dec8591,0x0efd8000,0x10bbfa20,
0xb0080e40,0x3a20881b,0x008042ef,0x64080201,0x10046eef,0x00010020,
0x01910002,0x00000000,0x05c01008,0x444ec804,0x40e42efe,0x000004ec,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x0f2a0000,0x07220262,0x19105280,0x350006a0,
0x518e0887,0x0e440988,0x2605c0d4,0x4c137102,0x57000002,0x81c88518,
0x40014c1a,0x300882bc,0x2202620a,0x0e03501c,0x0ccc05cc,0x44621c64,
0x06609981,0x14541d4c,0xa818c0aa,0xdb105028,0x540a81dd,0xa98318a2,
0x00c14543,0x3b660303,0xdd902ae0,0x0ef7743f,0x5418c4a8,0x0980c428,
0x54c2775c,0x06302a80,0x0a2a0ea6,0x5d03100c,0x41dec88b,0xed9ec819,
0x22db9d10,0x746642fd,0xe8977643,0x3a3321ff,0xc8fa3323,0x64ae3e8c,
0xf8977643,0x06f642ff,0x6f641bd9,0xec837b20,0x87d1990d,0x272e2dca,
0xb312a771,0x4eec8b11,0xdd907764,0xd9077641,0x2245261d,0x7fc42fd8,
0x742f742f,0xe85ee85e,0x445ee85e,0x883705cd,0x489d42fd,0x16ee38ae,
0x57d0eab1,0x56216641,0x11d5623a,0x792b8eab,0x0aa0abe8,0x34bacd2e,
0x4bacd2eb,0x8acd2eb3,0x646cc755,0x9d479714,0x2cc74c4b,0xadb92e77,
0x2b95b75c,0x5b75cadb,0xb808e6b9,0x7302a85b,0x41eb983d,0x75cc1eb9,
0xb10f5cc1,0x0dc263b3,0x44ea2ddc,0x75740364,0x311d5620,0x0b7627b5,
0x5588eab1,0x223aac47,0x2a623fed,0x4ee0aa3d,0x5da27768,0xb44eed13,
0x5562d13b,0x321d4ee3,0x3137b21a,0xa8dc3bdd,0x5caef6e4,0x77b72bbd,
0xd8aef6e5,0x0eae84de,0x6d6d4154,0xa876b6a1,0x2b6a1dad,0x876b6a1d,
0x257499d8,0x20eae81c,0x31dc7349,0xdd133366,0x0f6fccdf,0xfee8bdd1,
0x3a37f746,0x22c886fe,0x3a21edf9,0x3ddb10ee,0x6c47bb62,0x3ddb11ee,
0xee87bb62,0x0377626f,0xa8930199,0x3ffdb104,0x6c53b762,0x9dbb14ed,
0x3913b762,0x88999b30,0xfdd30eee,0x337f74cd,0x774cdfdd,0x9bfba66f,
0xdd31edfc,0x8999b30b,0x776c0ded,0x107f2dd4,0x02010040,0x75c02008,
0x08040104,0x80402010,0x40000100,0x0fb61ee8,0x80402008,0x202e0100,
0x0103f96e,0x80200802,0x80000200,0x0003f96e,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x05910735,0x09981713,0x82260164,0x01cdc39a,0x20b2a071,0x8245c0a8,
0x99910200,0x64c245c3,0xcc8b2e62,0x9910080c,0x05950183,0x88591071,
0x2e164c2c,0x40910029,0x2033102a,0x402ea28a,0x204c4098,0x47d19902,
0x65202e0a,0xc897b3a0,0xd01dc6dc,0xb80b87d9,0x44440a00,0x30f6741a,
0x5d644133,0x6d5cc582,0x54133312,0x899b309d,0x5d6442ae,0x9d144642,
0x42c9c83d,0x21d9e832,0x367a2d9e,0x3a970e21,0x1c410e3b,0x4406f541,
0x4c08e41b,0xd71d4c2a,0xd8eab107,0xab88bdd0,0x4dd1550d,0xbdd30a2b,
0x90c46c43,0x3a3321bd,0x22f6f5c3,0x460ed8ed,0x43bf913b,0x7443abbc,
0x9d70e809,0x95156c9b,0x643df899,0x332a3cb9,0x542c4aa0,0x897bb61d,
0x24bb4754,0x11fa1dae,0x4e4436ab,0x2e3262c8,0x3f416644,0xfd132aa6,
0xdef88fd0,0x491d5620,0x32a21eb9,0x4b3d1b0a,0xacc3b88d,0xb8f6d458,
0x1d562b34,0x987b3ae6,0x0dc848ce,0x4d655c2c,0x889bfb51,0xf8a67625,
0x513ae2cc,0x331dc571,0x06cb2766,0x2ee3d70d,0x1d5266ea,0x7ef49fd7,
0x1d5622c0,0x2579b931,0x3a66bdb9,0xdb88b014,0x88b0586a,0x3be23a8e,
0x1dada86f,0x75c76ae2,0x2a2ae49a,0x94cd2cc6,0x45a27749,0x75744755,
0x2b6e60bc,0x790b0184,0x2e0b0775,0x1d0bbe23,0x7304c891,0x221d5ce4,
0x166755bc,0x68ecba4c,0x32215da2,0x0b0eab11,0x2288bfdb,0xb9722e1b,
0x270b0d1d,0x88b0585d,0x006c4755,0x158dfdd3,0xd106f75c,0xeefe89dd,
0x447bbaa2,0x3fba1eed,0x0f77f6c6,0x1909f173,0x377910b0,0xd8836070,
0x07baa588,0x06f74c99,0x8c437791,0xd306f645,0x3bbea3dd,0x3b6275c1,
0xe98776c3,0xdc8003ef,0xdf70fb81,0x1f7f4cfd,0xefe987dc,0x2e7dfd33,
0x801c6d8f,0x01c79300,0x20100400,0xb0040100,0xd100973f,0x3ae005df,
0x77e405ee,0x3cda806e,0x1e6c4000,0x01150200,0x00004000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x05300000,0x82e660a6,0x0ea09998,0x31990700,0x33000662,0x22309901,
0x1901c880,0x20c01988,0x50710198,0x9a809981,0x52e2b983,0x4199983e,
0x2088444b,0x01301198,0x44449071,0x302e6608,0x00333003,0x86cb6400,
0x20d40502,0x22a6dfdc,0x13177641,0x3aa31d30,0x20dec80d,0x546982ba,
0x28a84d9e,0x3dbd9010,0x3b22f76c,0x098141ed,0x05c0b7a6,0x5588aba2,
0x1edee887,0x976f71a6,0x66459dea,0x04080285,0xa803606a,0x3ae1edee,
0x76f5c5eb,0x3a165a25,0x12f6f447,0xac5cbdbd,0x2afa1fa5,0x206c1fa0,
0x59a5c49c,0x1b01bdd7,0xb1bb7ee5,0x50d03aeb,0x755dd669,0xf159a546,
0x3ffe25ff,0xf8977762,0x2213a2ff,0x779b0755,0x2f20dd81,0x7418e40e,
0x206f75c0,0x3bae1025,0x176ee40d,0x1d05de5a,0x75cc3d9f,0x41af21ec,
0x5408da85,0x0675408d,0x87b53116,0x13390b05,0x2d1689dc,0xf128d83a,
0xaeba87fd,0xa7741f45,0xe8d1d976,0x22d54d4e,0x4686c5aa,0xd824c5aa,
0x1fde85fe,0x13ea17dc,0x3dd70472,0x87c3ab44,0x07568840,0xcac4b157,
0x0bceac1f,0x4179d5d1,0x550b02f8,0x174c0aa0,0x07b7e62c,0x2c72160b,
0x5623ddb1,0xaac4583a,0x11ff7c43,0x99cc371b,0x983ddf55,0x046dcb33,
0x6eec11b7,0x93046dc3,0x3260ca80,0x216619ad,0x8b1c83ea,0x1d56211c,
0xac42047e,0x4589b83a,0x2e19ac8e,0x3b61eede,0x21a21eef,0xff53efe9,
0x077fd41d,0xefe997f2,0x3bfa6043,0x2e7dfd33,0x64087eef,0x3fa66d9f,
0x0db1f73e,0xcda83d3d,0x5437bf20,0x1bdf9008,0x7cd3bbe6,0x85df34ee,
0xfd14eef9,0x7ef40809,0x7dfd33fe,0x3bee37dc,0x57bbea7e,0x8646d9fc,
0x3f908889,0x8d5bd0db,0x103fefd8,0x07764020,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x3a899000,0x05712000,0x1dcc0c54,0x20009980,
0x33000198,0x2003b620,0x01260198,0x23109998,0x20446208,0x11983118,
0x2622ca83,0x31126099,0x21999883,0x13109998,0x44220011,0x4c430441,
0x98111881,0x7d199099,0xd11a60d8,0x205f7640,0x06302cc2,0xeec855b1,
0xb89bbd30,0x3b7ae4ee,0x6c42f741,0x200ba82f,0x03d9d75b,0x4406dcfd,
0x36f72fce,0x3a2edee5,0x57a0fb8d,0x3b3b31fb,0x645b7f72,0x98f6f646,
0x9d70eccf,0x17abae9b,0x3b63b616,0xa8fdd7a0,0x6cf540de,0x4477f225,
0x85808755,0x4d2a3fae,0x3be23f46,0x3a23f40e,0x32b6e2ff,0x29334365,
0x22556248,0x5bb81eb9,0x75429fa8,0x512e3623,0x20cea8d9,0x35e459b8,
0x74e43664,0x43aacc69,0x35672590,0xe9667316,0x33b10aa8,0x2c133625,
0x3224674c,0x40e47e9e,0x4583a8d8,0x0b007558,0xd13b83df,0x075688b0,
0x7b70930b,0x3276ec57,0x1ddf1047,0x740ed6d4,0x1fd740ea,0xfef883f9,
0x6c1a7a23,0xf103a20e,0x9707f103,0x1d1d0b9d,0x160b0990,0x89dd3473,
0x3be22ef8,0x32f7f543,0xebc895b7,0x2208e46c,0xe8583fef,0x160746fe,
0xddb10f7a,0x75588b03,0xb10930b0,0x404ec9db,0x23624ded,0x1bfba62e,
0xec8999b3,0xb11f544f,0x43fbb334,0x44f40cea,0x1ead82c4,0x5427d7d4,
0x581ec45d,0x493398b0,0x588d8836,0x216036b1,0x4e44f8b9,0x258e468c,
0x20b07558,0x77f4c100,0x021bed73,0x7e4fbfa6,0x3bfa66d9,0x103dfd33,
0x2002ef98,0x041e8afc,0x083f96e8,0xeefcadc0,0x1971fc84,0x6c9ddf30,
0x363f60ef,0x8265e60f,0x1777dc1f,0x3fa21dfb,0x21bdf92e,0x77e42efa,
0x1d35f96e,0x4b9fd858,0xf71fcb74,0x74fe4fdd,0x00bbfa26,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00e05000,0xa8821000,0x7c4ea29a,0x75d762ff,0x81dd1db0,
0x22f47d43,0x5c46e609,0xf3d52941,0xe82224c9,0x313144c7,0xeee80103,
0x4bddd76e,0x306e62b9,0x4ccc3501,0x8c30e099,0x37777622,0x005ddd12,
0x00000000,0x5106f75c,0xddd0035d,0x2f6f449d,0xecf87aba,0x45aa8221,
0x5a25aeba,0x2e2f5c2c,0x896ae0de,0x4ec52a38,0x120f7a0d,0x346c583b,
0x4390b272,0x4cc5a00e,0x9751d209,0x432676cc,0x22ccccc8,0x418c3618,
0x00008888,0x00000000,0xf90ead10,0x97bbae1b,0x6d468d9c,0x5a1fcc08,
0x8db8221c,0x70ffbe20,0x457588d7,0x96ee0ddc,0x269311da,0x173e0d9d,
0x22c2c1b1,0x43bbc894,0x6dd6000b,0xa8ae65dd,0x0000504b,0x00000000,
0x00000000,0x5e43aac4,0xd1b39005,0x3d5d02a8,0x0d8bfbe2,0x9e89ddf3,
0x8017c41e,0x20c6e9fc,0x44131198,0xd93f538b,0x74c104c4,0x266603ef,
0x00000001,0x00000000,0x00000000,0x90000000,0x1c00db3f,0xa975ee74,
0x20840eff,0x05118888,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
};
static signed short stb__courier_bold_10_latin_ext_x[560]={ 0,1,1,0,0,0,0,2,2,1,0,0,1,0,
1,0,0,0,0,0,0,0,0,0,0,0,1,1,-1,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,
0,-1,-1,0,0,0,0,0,0,0,-1,-1,0,0,0,2,0,1,0,-1,1,0,-1,0,0,0,0,0,0,0,
0,0,0,-1,0,0,-1,0,0,0,0,0,0,-1,0,0,0,1,2,1,0,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,
2,0,1,-1,1,0,-1,0,-1,-1,1,0,1,1,1,0,0,1,1,1,1,0,0,-1,0,0,-1,-1,-1,-1,
-1,-1,-1,0,0,0,0,0,0,0,0,0,-1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,
-1,0,-1,0,-1,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,-1,0,-1,0,-1,0,-1,0,0,0,0,0,0,0,0,-1,-1,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,-1,0,0,
0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,
1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,-1,0,-1,-1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1, };
static signed short stb__courier_bold_10_latin_ext_y[560]={ 7,1,1,0,0,1,2,1,1,1,1,1,5,4,
5,0,1,1,1,1,1,1,1,1,1,1,3,3,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,8,1,2,1,2,1,2,1,2,1,1,
1,1,1,2,2,2,2,2,2,2,1,3,3,3,3,3,3,1,1,1,3,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,7,3,0,1,2,1,
1,1,1,1,1,3,4,4,1,0,0,0,1,1,1,3,1,3,6,1,1,3,1,1,1,3,-1,-1,-1,0,
0,-1,1,1,-1,-1,-1,0,-1,-1,-1,0,1,0,-1,-1,-1,0,0,2,1,-1,-1,-1,0,-1,1,1,1,1,
1,1,1,0,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,1,1,1,1,1,1,1,
0,1,-1,1,1,2,-1,1,-1,1,-1,1,-1,1,-1,1,1,1,0,1,-1,1,-1,1,1,2,-1,1,-1,1,
-1,1,-1,1,1,0,-1,-1,1,1,0,1,0,1,-1,1,1,1,-1,3,1,1,-1,1,1,1,3,-1,-1,1,
1,1,1,1,1,1,1,-1,1,1,2,-1,1,1,1,2,0,1,-1,1,-1,1,1,2,-1,1,1,2,-1,1,
-1,1,-1,1,1,2,-1,1,1,1,-1,1,1,1,0,1,0,1,-1,1,-1,0,-1,1,1,3,-1,1,-1,1,
0,-1,1,-1,1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,0,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,1,-1,1,-1,
1,-1,1,-1,0,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,-2,-1,-1,1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1, };
static unsigned short stb__courier_bold_10_latin_ext_w[560]={ 0,3,4,5,5,5,5,2,3,3,5,5,3,5,
3,5,5,5,5,5,5,5,5,5,5,5,3,3,6,6,6,5,5,7,6,5,5,5,6,6,6,5,6,6,
6,7,7,6,6,6,6,5,5,6,7,7,6,6,5,3,5,3,5,7,3,6,7,6,6,5,6,6,6,5,
5,6,5,7,6,5,7,6,6,5,6,6,6,7,6,6,5,3,2,3,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0,3,5,5,5,6,
2,5,4,7,4,5,6,5,7,7,4,5,3,3,3,6,5,3,3,3,4,6,6,7,6,5,7,7,7,7,
7,7,7,5,5,5,5,5,5,5,5,5,6,7,6,6,6,6,6,5,6,6,6,6,6,6,6,5,6,6,
6,6,6,6,7,6,5,5,5,5,5,5,5,5,5,6,5,5,5,5,5,5,6,6,6,6,6,6,7,6,
7,6,7,6,7,6,5,6,5,6,5,6,5,6,5,7,6,6,5,5,5,5,5,5,6,5,5,5,6,6,
6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,6,6,6,5,6,6,6,6,5,6,
5,6,5,6,5,6,5,7,6,7,6,7,6,7,5,5,6,5,6,5,6,5,7,7,6,6,6,6,6,6,
5,5,5,5,5,5,5,5,5,6,5,6,5,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,6,6,
6,5,5,5,5,5,5,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,7,6,5,5,6,
5,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,7,6,7,7,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5, };
static unsigned short stb__courier_bold_10_latin_ext_h[560]={ 0,7,4,8,9,7,6,4,8,8,5,6,4,1,
3,9,7,6,6,7,6,7,7,7,7,7,5,5,6,3,6,7,7,6,6,7,6,6,6,7,6,6,7,6,
6,6,6,7,6,8,6,7,6,7,6,6,6,6,6,8,8,8,4,2,2,6,7,6,7,6,6,7,6,6,
8,6,6,5,5,6,7,7,5,6,7,5,4,4,4,6,4,8,8,8,3,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,0,6,8,6,5,6,
8,7,2,7,3,4,3,1,7,2,4,7,4,4,2,6,7,2,3,4,3,4,6,6,6,6,8,8,8,7,
7,8,6,8,8,8,8,7,8,8,8,7,6,7,9,9,9,8,8,5,7,9,9,9,8,8,6,7,7,7,
7,7,7,8,6,7,7,7,7,7,6,6,6,6,7,6,7,7,7,7,7,5,6,7,7,7,7,8,8,8,
7,7,8,7,8,7,9,7,9,7,9,7,9,7,8,7,6,7,7,7,8,7,8,7,8,7,8,7,9,8,
9,8,9,8,8,9,8,8,6,6,7,6,7,6,8,6,8,8,8,4,7,8,9,8,8,8,4,8,8,8,
8,6,6,6,6,6,6,8,6,8,7,8,6,6,7,7,8,7,9,7,9,7,6,6,8,6,8,7,8,6,
9,7,9,7,8,7,9,7,9,9,8,7,6,7,8,7,8,7,9,7,9,8,9,7,8,6,8,6,8,8,
7,8,6,8,6,8,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,6,6,8,6,6,6,
6,6,6,6,6,6,6,6,6,6,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,8,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,8,7,8,6,9,
7,9,7,9,8,9,9,9,9,9,9,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,9,9,8,7,9,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6, };
static unsigned short stb__courier_bold_10_latin_ext_s[560]={ 255,55,125,190,165,113,89,253,9,83,8,
202,115,208,141,1,161,170,158,148,109,121,109,97,173,167,251,47,95,152,115,
71,8,81,102,250,176,189,182,21,231,238,228,195,224,216,208,141,53,37,67,
36,164,243,150,142,135,128,122,216,190,251,72,179,187,74,28,60,134,47,40,
50,27,21,145,7,1,20,1,236,126,119,28,211,180,244,65,57,78,172,51,
227,231,33,169,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,
127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,255,123,66,
110,41,96,80,135,195,127,164,98,145,208,83,200,85,91,90,94,175,246,115,
191,137,111,159,130,200,192,220,16,87,95,103,172,235,111,82,171,137,229,184,
103,8,196,223,77,22,63,14,97,111,28,235,35,14,125,139,152,248,26,55,
222,215,208,201,194,187,168,164,165,159,153,147,141,179,217,205,34,107,242,94,
88,82,76,70,14,29,100,43,36,29,161,175,183,1,248,240,235,1,222,171,
208,21,195,190,181,84,168,20,153,36,140,134,128,131,115,52,103,202,91,242,
79,209,248,132,21,244,1,14,202,216,209,1,239,97,233,59,227,143,214,149,
203,234,119,35,177,230,165,158,151,104,138,132,125,119,103,223,229,249,207,90,
72,116,58,72,44,133,140,42,85,13,109,237,147,1,175,148,156,220,185,209,
188,196,192,196,229,177,16,155,242,159,57,146,183,125,63,199,22,98,9,83,
65,216,161,223,49,8,121,29,75,21,8,118,111,48,15,43,43,49,56,62,
68,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,202,127,127,70,
127,127,127,127,127,127,127,127,127,127,127,127,127,215,14,127,127,127,127,127,
127,127,127,127,127,127,127,127,76,185,127,127,127,127,127,127,127,127,127,127,
127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,90,1,
105,179,118,42,104,48,90,36,77,70,63,56,49,42,127,127,127,127,127,127,
127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,
127,127,127,34,27,62,55,7,154,127,127,127,127,127,127,127,127,127,127,127,
127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,
127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,
127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,127,
127,127,127,127,127,127,127,127,127, };
static unsigned short stb__courier_bold_10_latin_ext_t[560]={ 1,30,69,21,1,39,62,47,21,21,69,
62,69,69,69,1,47,62,62,47,62,47,47,47,47,47,62,69,62,69,62,
47,47,62,62,39,62,62,62,47,62,62,39,62,62,62,62,47,62,21,62,
47,62,39,62,62,62,62,62,11,11,1,69,69,69,62,47,62,39,62,62,
39,62,62,21,62,62,69,69,54,39,39,69,54,39,62,69,69,69,55,69,
11,11,21,69,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,
55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,1,55,21,
55,69,55,21,47,69,47,69,69,69,69,47,69,69,47,69,69,69,47,47,
69,69,69,69,69,47,47,47,55,21,21,21,39,39,21,55,21,11,21,21,
47,30,21,21,47,55,47,1,1,1,30,21,69,47,1,1,1,11,21,55,
39,39,39,39,39,39,11,55,39,39,39,39,39,54,54,54,62,39,54,39,
39,39,39,39,69,55,39,39,39,39,11,11,11,39,30,11,30,21,30,1,
30,1,30,1,30,1,30,21,30,55,30,30,30,11,30,21,30,21,30,21,
30,1,21,1,30,1,30,30,1,21,21,55,47,30,47,30,47,11,47,11,
11,11,69,30,21,1,21,21,21,69,21,21,21,21,55,54,54,54,47,55,
21,55,21,30,21,55,55,30,30,21,30,1,30,11,30,55,55,11,54,11,
30,11,54,1,30,1,39,11,30,1,39,1,1,11,39,54,39,11,39,11,
30,1,30,1,11,11,30,11,55,11,55,11,11,30,11,55,11,55,11,55,
55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,30,55,55,11,
55,55,55,55,55,55,55,55,55,55,55,55,55,30,62,55,55,55,55,55,
55,55,55,55,55,55,55,55,11,47,55,55,55,55,55,55,55,55,55,55,
55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,11,47,
11,47,1,47,1,47,1,11,1,1,1,1,1,1,55,55,55,55,55,55,
55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,
55,55,55,1,1,11,47,1,47,55,55,55,55,55,55,55,55,55,55,55,
55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,
55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,
55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,55,
55,55,55,55,55,55,55,55,55, };
static unsigned short stb__courier_bold_10_latin_ext_a[560]={ 85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,85,
85,85,85,85,85,85,85,85, };
// Call this function with
// font: NULL or array length
// data: NULL or specified size
// height: STB_FONT_courier_bold_10_latin_ext_BITMAP_HEIGHT or STB_FONT_courier_bold_10_latin_ext_BITMAP_HEIGHT_POW2
// return value: spacing between lines
static void stb_font_courier_bold_10_latin_ext(stb_fontchar font[STB_FONT_courier_bold_10_latin_ext_NUM_CHARS],
unsigned char data[STB_FONT_courier_bold_10_latin_ext_BITMAP_HEIGHT][STB_FONT_courier_bold_10_latin_ext_BITMAP_WIDTH],
int height)
{
int i,j;
if (data != 0) {
unsigned int *bits = stb__courier_bold_10_latin_ext_pixels;
unsigned int bitpack = *bits++, numbits = 32;
for (i=0; i < STB_FONT_courier_bold_10_latin_ext_BITMAP_WIDTH*height; ++i)
data[0][i] = 0; // zero entire bitmap
for (j=1; j < STB_FONT_courier_bold_10_latin_ext_BITMAP_HEIGHT-1; ++j) {
for (i=1; i < STB_FONT_courier_bold_10_latin_ext_BITMAP_WIDTH-1; ++i) {
unsigned int value;
if (numbits==0) bitpack = *bits++, numbits=32;
value = bitpack & 1;
bitpack >>= 1, --numbits;
if (value) {
if (numbits < 3) bitpack = *bits++, numbits = 32;
data[j][i] = (bitpack & 7) * 0x20 + 0x1f;
bitpack >>= 3, numbits -= 3;
} else {
data[j][i] = 0;
}
}
}
}
// build font description
if (font != 0) {
float recip_width = 1.0f / STB_FONT_courier_bold_10_latin_ext_BITMAP_WIDTH;
float recip_height = 1.0f / height;
for (i=0; i < STB_FONT_courier_bold_10_latin_ext_NUM_CHARS; ++i) {
// pad characters so they bilerp from empty space around each character
font[i].s0 = (stb__courier_bold_10_latin_ext_s[i]) * recip_width;
font[i].t0 = (stb__courier_bold_10_latin_ext_t[i]) * recip_height;
font[i].s1 = (stb__courier_bold_10_latin_ext_s[i] + stb__courier_bold_10_latin_ext_w[i]) * recip_width;
font[i].t1 = (stb__courier_bold_10_latin_ext_t[i] + stb__courier_bold_10_latin_ext_h[i]) * recip_height;
font[i].x0 = stb__courier_bold_10_latin_ext_x[i];
font[i].y0 = stb__courier_bold_10_latin_ext_y[i];
font[i].x1 = stb__courier_bold_10_latin_ext_x[i] + stb__courier_bold_10_latin_ext_w[i];
font[i].y1 = stb__courier_bold_10_latin_ext_y[i] + stb__courier_bold_10_latin_ext_h[i];
font[i].advance_int = (stb__courier_bold_10_latin_ext_a[i]+8)>>4;
font[i].s0f = (stb__courier_bold_10_latin_ext_s[i] - 0.5f) * recip_width;
font[i].t0f = (stb__courier_bold_10_latin_ext_t[i] - 0.5f) * recip_height;
font[i].s1f = (stb__courier_bold_10_latin_ext_s[i] + stb__courier_bold_10_latin_ext_w[i] + 0.5f) * recip_width;
font[i].t1f = (stb__courier_bold_10_latin_ext_t[i] + stb__courier_bold_10_latin_ext_h[i] + 0.5f) * recip_height;
font[i].x0f = stb__courier_bold_10_latin_ext_x[i] - 0.5f;
font[i].y0f = stb__courier_bold_10_latin_ext_y[i] - 0.5f;
font[i].x1f = stb__courier_bold_10_latin_ext_x[i] + stb__courier_bold_10_latin_ext_w[i] + 0.5f;
font[i].y1f = stb__courier_bold_10_latin_ext_y[i] + stb__courier_bold_10_latin_ext_h[i] + 0.5f;
font[i].advance = stb__courier_bold_10_latin_ext_a[i]/16.0f;
}
}
}
#ifndef STB_SOMEFONT_CREATE
#define STB_SOMEFONT_CREATE stb_font_courier_bold_10_latin_ext
#define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_courier_bold_10_latin_ext_BITMAP_WIDTH
#define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_courier_bold_10_latin_ext_BITMAP_HEIGHT
#define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_courier_bold_10_latin_ext_BITMAP_HEIGHT_POW2
#define STB_SOMEFONT_FIRST_CHAR STB_FONT_courier_bold_10_latin_ext_FIRST_CHAR
#define STB_SOMEFONT_NUM_CHARS STB_FONT_courier_bold_10_latin_ext_NUM_CHARS
#define STB_SOMEFONT_LINE_SPACING STB_FONT_courier_bold_10_latin_ext_LINE_SPACING
#endif
|
#include <Interpreters/InterpreterSelectQuery.h>
#include <Interpreters/InterpreterSelectWithUnionQuery.h>
#include <Interpreters/Context.h>
#include <Parsers/ASTCreateQuery.h>
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Storages/StorageView.h>
#include <Storages/StorageFactory.h>
#include <Storages/SelectQueryDescription.h>
#include <Common/typeid_cast.h>
#include <Processors/Pipe.h>
#include <Processors/Transforms/MaterializingTransform.h>
#include <Processors/Transforms/ConvertingTransform.h>
namespace DB
{
namespace ErrorCodes
{
extern const int INCORRECT_QUERY;
extern const int LOGICAL_ERROR;
}
StorageView::StorageView(
const StorageID & table_id_,
const ASTCreateQuery & query,
const ColumnsDescription & columns_)
: IStorage(table_id_)
{
StorageInMemoryMetadata storage_metadata;
storage_metadata.setColumns(columns_);
if (!query.select)
throw Exception("SELECT query is not specified for " + getName(), ErrorCodes::INCORRECT_QUERY);
SelectQueryDescription description;
description.inner_query = query.select->ptr();
storage_metadata.setSelectQuery(description);
setInMemoryMetadata(storage_metadata);
}
Pipe StorageView::read(
const Names & column_names,
const StorageMetadataPtr & metadata_snapshot,
SelectQueryInfo & query_info,
const Context & context,
QueryProcessingStage::Enum /*processed_stage*/,
const size_t /*max_block_size*/,
const unsigned /*num_streams*/)
{
Pipes pipes;
ASTPtr current_inner_query = metadata_snapshot->getSelectQuery().inner_query;
if (query_info.view_query)
{
if (!query_info.view_query->as<ASTSelectWithUnionQuery>())
throw Exception("Unexpected optimized VIEW query", ErrorCodes::LOGICAL_ERROR);
current_inner_query = query_info.view_query->clone();
}
InterpreterSelectWithUnionQuery interpreter(current_inner_query, context, {}, column_names);
auto pipeline = interpreter.execute().pipeline;
/// It's expected that the columns read from storage are not constant.
/// Because method 'getSampleBlockForColumns' is used to obtain a structure of result in InterpreterSelectQuery.
pipeline.addSimpleTransform([](const Block & header)
{
return std::make_shared<MaterializingTransform>(header);
});
/// And also convert to expected structure.
pipeline.addSimpleTransform([&](const Block & header)
{
return std::make_shared<ConvertingTransform>(
header, metadata_snapshot->getSampleBlockForColumns(
column_names, getVirtuals(), getStorageID()), ConvertingTransform::MatchColumnsMode::Name);
});
return QueryPipeline::getPipe(std::move(pipeline));
}
static ASTTableExpression * getFirstTableExpression(ASTSelectQuery & select_query)
{
auto * select_element = select_query.tables()->children[0]->as<ASTTablesInSelectQueryElement>();
if (!select_element->table_expression)
throw Exception("Logical error: incorrect table expression", ErrorCodes::LOGICAL_ERROR);
return select_element->table_expression->as<ASTTableExpression>();
}
void StorageView::replaceWithSubquery(ASTSelectQuery & outer_query, ASTPtr view_query, ASTPtr & view_name)
{
ASTTableExpression * table_expression = getFirstTableExpression(outer_query);
if (!table_expression->database_and_table_name)
{
// If it's a view table function, add a fake db.table name.
if (table_expression->table_function && table_expression->table_function->as<ASTFunction>()->name == "view")
table_expression->database_and_table_name = std::make_shared<ASTIdentifier>("__view");
else
throw Exception("Logical error: incorrect table expression", ErrorCodes::LOGICAL_ERROR);
}
DatabaseAndTableWithAlias db_table(table_expression->database_and_table_name);
String alias = db_table.alias.empty() ? db_table.table : db_table.alias;
view_name = table_expression->database_and_table_name;
table_expression->database_and_table_name = {};
table_expression->subquery = std::make_shared<ASTSubquery>();
table_expression->subquery->children.push_back(view_query);
table_expression->subquery->setAlias(alias);
for (auto & child : table_expression->children)
if (child.get() == view_name.get())
child = view_query;
}
ASTPtr StorageView::restoreViewName(ASTSelectQuery & select_query, const ASTPtr & view_name)
{
ASTTableExpression * table_expression = getFirstTableExpression(select_query);
if (!table_expression->subquery)
throw Exception("Logical error: incorrect table expression", ErrorCodes::LOGICAL_ERROR);
ASTPtr subquery = table_expression->subquery;
table_expression->subquery = {};
table_expression->database_and_table_name = view_name;
for (auto & child : table_expression->children)
if (child.get() == subquery.get())
child = view_name;
return subquery->children[0];
}
void registerStorageView(StorageFactory & factory)
{
factory.registerStorage("View", [](const StorageFactory::Arguments & args)
{
if (args.query.storage)
throw Exception("Specifying ENGINE is not allowed for a View", ErrorCodes::INCORRECT_QUERY);
return StorageView::create(args.table_id, args.query, args.columns);
});
}
}
|
// Copyright (c) 2008-2018 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#define BOOST_TEST_MODULE ResourceManagerClientTest
#include <boost/test/included/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <ResourceManagerClient.h>
#include <atomic>
#include <sstream>
#include <unistd.h>
#include <thread>
using namespace boost::unit_test::framework;
#define INDEXED_RESOURCE "VDEC"
// NB: assuming that system has exactly 2 resource units of the kind
#define ANONYMOUS_RESOURCE "ADEC"
struct ResourceManagerClientMock {
// resource ownership info
// assuming that client owns only 1 resource of a type
struct ROI {
ROI() : indexed(false), anonymous(-1) {}
std::atomic<bool> indexed;
std::atomic<size_t> anonymous;
};
ResourceManagerClientMock()
: deny_policy_action(false)
, hang_in_policy_action(false) {
BOOST_REQUIRE(client.registerPipeline("ref"));
client.registerPolicyActionHandler(
[this](const char *, const char * res,
const char *, const char *, const char *)->bool {
while(hang_in_policy_action){ usleep(500); }
if (deny_policy_action) {
deny_policy_action = false;
return false;
}
using namespace boost::property_tree;
std::string resources = (res + 1);
resources.erase(resources.length() - 1);
std::stringstream resources_stream(resources);
ptree json;
read_json(resources_stream, json);
return release(json.get<std::string>("resource") == INDEXED_RESOURCE);
});
}
~ResourceManagerClientMock() {
BOOST_REQUIRE(client.unregisterPipeline());
}
bool tryAcquire(bool indexed = true) {
std::string response;
if (indexed)
return owned_resources.indexed =
client.tryAcquire(indexed_request, response);
using boost::format;
using namespace boost::property_tree;
// shouldn't try to acquire if already owns
BOOST_REQUIRE_EQUAL(owned_resources.anonymous, -1);
std::stringstream request;
request << format(anonymous_request) % -1;
if (client.tryAcquire(request.str(), response)) {
std::stringstream response_stream(response);
ptree json;
read_json(response_stream, json);
owned_resources.anonymous = json.get<size_t>("resources..index");
return true;
}
return false;
}
bool acquire(bool indexed = true) {
std::string response;
if (indexed)
return owned_resources.indexed = client.acquire(indexed_request, response);
using boost::format;
using namespace boost::property_tree;
// shouldn't try to acquire if already owns
BOOST_REQUIRE_EQUAL(owned_resources.anonymous, -1);
std::stringstream request;
request << format(anonymous_request) % -1;
if (client.acquire(request.str(), response)) {
std::stringstream response_stream(response);
ptree json;
read_json(response_stream, json);
owned_resources.anonymous = json.get<size_t>("resources..index");
return true;
}
return false;
}
bool release(bool indexed = true) {
if (indexed) {
owned_resources.indexed = false;
return client.release(indexed_request);
}
using boost::format;
// shouldn't try to release not owned resource
BOOST_REQUIRE_PREDICATE(std::not_equal_to<size_t>(), (owned_resources.anonymous)(-1));
std::stringstream request;
request << format(anonymous_request) % owned_resources.anonymous;
owned_resources.anonymous = -1;
if (client.release(request.str())) {
return true;
}
return false;
}
bool notifyActivity() {
return client.notifyActivity();
}
void denyPolicyAction() {
deny_policy_action = true;
}
void hangInPolicyAction( bool hang = true ) {
hang_in_policy_action = hang;
}
// detail
static const std::string indexed_request;
static const std::string anonymous_request;
uMediaServer::ResourceManagerClient client;
ROI owned_resources;
bool deny_policy_action;
bool hang_in_policy_action;
};
#define NUM_CLIENTS 3
#define NUM_COLORS 6
struct ResourceManagerClientFixture {
ResourceManagerClientFixture()
: test_counter(max_test_runs), test_runs(max_test_runs)
, test_color(colors[fixture_counter++ % NUM_COLORS]) {
try {
test_counter = test_runs = boost::lexical_cast<size_t>
(master_test_suite().argv[master_test_suite().argc - 1]);
} catch (...) {}
}
bool tryAcquire(size_t c = 0, bool indexed = true) {
auto & client = clients[c % NUM_CLIENTS];
return client.tryAcquire(indexed);
}
bool acquire(size_t c = 0, bool indexed = true) {
auto & client = clients[c % NUM_CLIENTS];
return client.acquire(indexed);
}
bool release(size_t c = 0, bool indexed = true) {
auto & client = clients[c % NUM_CLIENTS];
return client.release(indexed);
}
size_t owner(bool anonymous = false, size_t index = 0) {
size_t owner = -1;
auto is_owner = [] (const ResourceManagerClientMock & client,
bool anon, size_t idx)->bool {
return (( anon && client.owned_resources.anonymous == idx) ||
(!anon && client.owned_resources.indexed ));
};
for (size_t i = 0; i < NUM_CLIENTS; ++i) {
if (is_owner(clients[i], anonymous, index))
owner = owner == -1 ? i : -1;
}
return owner;
}
const ResourceManagerClientMock::ROI & roi(size_t c = 0) {
return clients[c % NUM_CLIENTS].owned_resources;
}
bool notifyActivity(size_t c = 0) {
return clients[c % NUM_CLIENTS].notifyActivity();
}
void denyPolicyAction(size_t c = 0) {
clients[c % NUM_CLIENTS].denyPolicyAction();
}
void hangInPolicyAction(size_t c = 0, bool hang = true) {
clients[c % NUM_CLIENTS].hangInPolicyAction(hang);
}
void report() {
std::cerr << "\033[1;3" << test_color << "mrunning "
<< boost::unit_test::framework::current_test_case().p_name
<< " # " << (test_runs - test_counter)
<< " of " << test_runs << "...\033[0m" << std::endl;
}
// static data
static const size_t max_test_runs = 100;
static size_t fixture_counter;
static const std::string request;
static const char colors[NUM_COLORS];
// internals
ResourceManagerClientMock clients[NUM_CLIENTS];
size_t test_counter;
size_t test_runs;
const char test_color;
};
const std::string ResourceManagerClientMock::indexed_request =
"[{\"resource\":\"" INDEXED_RESOURCE "\",\"qty\":1,\"index\":0}]";
const std::string ResourceManagerClientMock::anonymous_request =
"[{\"resource\":\"" ANONYMOUS_RESOURCE "\",\"qty\":1,\"index\":%1%}]";
const char ResourceManagerClientFixture::colors[] = {'1','2','3','4','5','6'};
size_t ResourceManagerClientFixture::fixture_counter = 0;
BOOST_FIXTURE_TEST_CASE(acquire_release, ResourceManagerClientFixture) {
while(test_counter--) {
report();
BOOST_CHECK(acquire());
BOOST_CHECK(release());
// anonymous resource case
BOOST_CHECK(acquire(0, false));
BOOST_CHECK(release(0, false));
}
}
BOOST_FIXTURE_TEST_CASE(try_acquire, ResourceManagerClientFixture) {
while(test_counter--) {
report();
// indexed resource
BOOST_CHECK(tryAcquire(0));
// second request should fail
BOOST_CHECK(!tryAcquire(1));
// client # 0 holds resource
BOOST_CHECK(roi(0).indexed);
// client # 1 has no resource
BOOST_CHECK(!roi(1).indexed);
// anonymous resource
BOOST_CHECK(tryAcquire(0, false));
BOOST_CHECK(tryAcquire(1, false));
// third request should fail
BOOST_CHECK(!tryAcquire(2, false));
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (roi(0).anonymous)(-1));
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (roi(1).anonymous)(-1));
BOOST_CHECK_EQUAL(roi(2).anonymous, -1);
// release resources to restore state
BOOST_CHECK(release(0));
BOOST_CHECK(release(0, false));
BOOST_CHECK(release(1, false));
}
}
#include <unistd.h>
BOOST_FIXTURE_TEST_CASE(resource_cycling, ResourceManagerClientFixture) {
BOOST_CHECK(notifyActivity(NUM_CLIENTS - 1));
BOOST_CHECK(acquire(NUM_CLIENTS - 1));
BOOST_CHECK_EQUAL(owner(), NUM_CLIENTS - 1);
while(test_counter--) {
report();
for (size_t i = 0; i < NUM_CLIENTS; ++i) {
BOOST_CHECK(notifyActivity(i));
BOOST_CHECK(acquire(i));
BOOST_CHECK_EQUAL(owner(), i);
}
}
}
BOOST_FIXTURE_TEST_CASE(full_lifecycle, ResourceManagerClientFixture) {
while(test_counter--) {
report();
ResourceManagerClientMock rmc;
BOOST_CHECK(rmc.acquire());
BOOST_CHECK(rmc.release());
}
}
BOOST_FIXTURE_TEST_CASE(keep_alive, ResourceManagerClientFixture) {
while(test_counter--) {
report();
// resource conflict w/o notifyActivity
BOOST_CHECK(notifyActivity(0));
BOOST_CHECK(acquire(0, false));
// grab indexed resource for sync
BOOST_CHECK(notifyActivity(1));
BOOST_CHECK(acquire(1));
BOOST_CHECK(acquire(1, false));
BOOST_CHECK(notifyActivity(2));
BOOST_CHECK(acquire(2, false));
// client # 0 should give up resource
BOOST_CHECK_EQUAL(roi(0).anonymous, -1);
// resource conflict with notifyActivity
BOOST_CHECK(notifyActivity(1));
// invoke policy action on client # 1 with indexed resource
// this should sync notifyActivity with consequental acquire
usleep(200);
BOOST_CHECK(notifyActivity(0));
BOOST_CHECK(acquire(0));
BOOST_CHECK(acquire(0, false));
// client # 2 should give up resource
BOOST_CHECK_EQUAL(roi(2).anonymous, -1);
// client # 1 should preserve resource
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (roi(1).anonymous)(-1));
// free acquired resources to restore state
BOOST_CHECK(release(0, false));
BOOST_CHECK(release(1, false));
BOOST_CHECK(release(0));
}
}
BOOST_FIXTURE_TEST_CASE(multiple_select, ResourceManagerClientFixture) {
while(test_counter--) {
report();
BOOST_CHECK(acquire(0, false));
BOOST_CHECK(acquire(1, false));
// setting policy action deny to client # 0
denyPolicyAction(0);
BOOST_CHECK(acquire(2, false));
// client # 1 should give up resource
BOOST_CHECK_EQUAL(roi(1).anonymous, -1);
// client # 0 should preserve resource
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (roi(0).anonymous)(-1));
// deny all
denyPolicyAction(0);
denyPolicyAction(2);
BOOST_CHECK(!acquire(1, false));
BOOST_CHECK_EQUAL(roi(1).anonymous, -1);
// free acquired resources to restore state
BOOST_CHECK(release(0, false));
BOOST_CHECK(release(2, false));
}
}
BOOST_FIXTURE_TEST_CASE(selected_flag, ResourceManagerClientFixture) {
while(test_counter--) {
report();
BOOST_CHECK(notifyActivity(0));
BOOST_CHECK(acquire(0, false));
BOOST_CHECK(notifyActivity(1));
BOOST_CHECK(acquire(1, false));
// as the result client # 1 should go to selected list
BOOST_CHECK(notifyActivity(2));
BOOST_CHECK(acquire(2, false));
// client # 0 should give up resource
BOOST_CHECK_EQUAL(roi(0).anonymous, -1);
// client # 1 should preserve resource
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (roi(1).anonymous)(-1));
// now client # 1 should give up
BOOST_CHECK(notifyActivity(0));
BOOST_CHECK(acquire(0, false));
// client # 1 should give up resource
BOOST_CHECK_EQUAL(roi(1).anonymous, -1);
// client # 2 should preserve resource
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (roi(2).anonymous)(-1));
// free acquired resources to restore state
BOOST_CHECK(release(0, false));
BOOST_CHECK(release(2, false));
}
}
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bloom.h"
#include "base58.h"
#include "clientversion.h"
#include "key.h"
#include "merkleblock.h"
#include "random.h"
#include "serialize.h"
#include "streams.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_crowdcoin.h"
#include <vector>
#include <boost/test/unit_test.hpp>
#include <boost/tuple/tuple.hpp>
BOOST_FIXTURE_TEST_SUITE(bloom_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize)
{
CBloomFilter filter(3, 0.01, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8"));
BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "Bloom filter doesn't contain just-inserted object!");
// One bit different in first byte
BOOST_CHECK_MESSAGE(!filter.contains(ParseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8")), "Bloom filter contains something it shouldn't!");
filter.insert(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"));
BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")), "Bloom filter doesn't contain just-inserted object (2)!");
filter.insert(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5"));
BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")), "Bloom filter doesn't contain just-inserted object (3)!");
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << filter;
std::vector<unsigned char> vch = ParseHex("03614e9b050000000000000001");
std::vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end());
BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "Bloom filter doesn't contain just-inserted object!");
filter.clear();
BOOST_CHECK_MESSAGE( !filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "Bloom filter should be empty!");
}
BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize_with_tweak)
{
// Same test as bloom_create_insert_serialize, but we add a nTweak of 100
CBloomFilter filter(3, 0.01, 2147483649UL, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8"));
BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "Bloom filter doesn't contain just-inserted object!");
// One bit different in first byte
BOOST_CHECK_MESSAGE(!filter.contains(ParseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8")), "Bloom filter contains something it shouldn't!");
filter.insert(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"));
BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")), "Bloom filter doesn't contain just-inserted object (2)!");
filter.insert(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5"));
BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")), "Bloom filter doesn't contain just-inserted object (3)!");
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << filter;
std::vector<unsigned char> vch = ParseHex("03ce4299050000000100008001");
std::vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(bloom_create_insert_key)
{
std::string strSecret = std::string("7sQb6QHALg4XyHsJHsSNXnEHGhZfzTTUPJXJqaqK7CavQkiL9Ms");
CBitcoinSecret vchSecret;
BOOST_CHECK(vchSecret.SetString(strSecret));
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
std::vector<unsigned char> vchPubKey(pubkey.begin(), pubkey.end());
CBloomFilter filter(2, 0.001, 0, BLOOM_UPDATE_ALL);
filter.insert(vchPubKey);
uint160 hash = pubkey.GetID();
filter.insert(std::vector<unsigned char>(hash.begin(), hash.end()));
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << filter;
std::vector<unsigned char> vch = ParseHex("038fc16b080000000000000001");
std::vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(bloom_match)
{
// Random real transaction (b4749f017444b051c44dfd2720e88f314ff94f3dd6d56d40ef65854fcd7fff6b)
CDataStream stream(ParseHex("01000000010b26e9b7735eb6aabdf358bab62f9816a21ba9ebdb719d5299e88607d722c190000000008b4830450220070aca44506c5cef3a16ed519d7c3c39f8aab192c4e1c90d065f37b8a4af6141022100a8e160b856c2d43d27d8fba71e5aef6405b8643ac4cb7cb3c462aced7f14711a0141046d11fee51b0e60666d5049a9101a72741df480b96ee26488a4d3466b95c9a40ac5eeef87e10a5cd336c19a84565f80fa6c547957b7700ff4dfbdefe76036c339ffffffff021bff3d11000000001976a91404943fdd508053c75000106d3bc6e2754dbcff1988ac2f15de00000000001976a914a266436d2965547608b9e15d9032a7b9d64fa43188ac00000000"), SER_DISK, CLIENT_VERSION);
CTransaction tx(deserialize, stream);
// and one which spends it (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00};
std::vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
CDataStream spendStream(vch, SER_DISK, CLIENT_VERSION);
CTransaction spendingTx(deserialize, spendStream);
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(uint256S("0xb4749f017444b051c44dfd2720e88f314ff94f3dd6d56d40ef65854fcd7fff6b"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match tx hash");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// byte-reversed tx hash
filter.insert(ParseHex("6bff7fcd4f8565ef406dd5d63d4ff94f318fe82027fd4dc451b04474019f74b4"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match manually serialized tx hash");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("30450220070aca44506c5cef3a16ed519d7c3c39f8aab192c4e1c90d065f37b8a4af6141022100a8e160b856c2d43d27d8fba71e5aef6405b8643ac4cb7cb3c462aced7f14711a01"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match input signature");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("046d11fee51b0e60666d5049a9101a72741df480b96ee26488a4d3466b95c9a40ac5eeef87e10a5cd336c19a84565f80fa6c547957b7700ff4dfbdefe76036c339"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match input pub key");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("04943fdd508053c75000106d3bc6e2754dbcff19"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match output address");
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(spendingTx), "Simple Bloom filter didn't add output");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("a266436d2965547608b9e15d9032a7b9d64fa431"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match output address");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(COutPoint(uint256S("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match COutPoint");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
COutPoint prevOutPoint(uint256S("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0);
{
std::vector<unsigned char> data(32 + sizeof(unsigned int));
memcpy(&data[0], prevOutPoint.hash.begin(), 32);
memcpy(&data[32], &prevOutPoint.n, sizeof(unsigned int));
filter.insert(data);
}
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match manually serialized COutPoint");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(uint256S("00000009e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436"));
BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched random tx hash");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("0000006d2965547608b9e15d9032a7b9d64fa431"));
BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched random address");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(COutPoint(uint256S("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 1));
BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched COutPoint for an output we didn't care about");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(COutPoint(uint256S("0x000000d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0));
BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched COutPoint for an output we didn't care about");
}
BOOST_AUTO_TEST_CASE(merkle_block_1)
{
// Random real block (0000000000013b8ab2cd513b0261a14096412195a72a0c4827d229dcc7e0f7af)
// With 9 txes
CBlock block;
CDataStream stream(ParseHex("0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// Match the last transaction
filter.insert(uint256S("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 8);
std::vector<uint256> vMatched;
std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
// Also match the 8th transaction
filter.insert(uint256S("0xdd1fd2a6fc16404faf339881a90adbde7f4f728691ac62e8f168809cdfae1053"));
merkleBlock = CMerkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 2);
BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0xdd1fd2a6fc16404faf339881a90adbde7f4f728691ac62e8f168809cdfae1053"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 7);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
}
BOOST_AUTO_TEST_CASE(merkle_block_2)
{
// Random real block (000000005a4ded781e667e06ceefafb71410b511fe0d5adc3e5a27ecbec34ae6)
// With 4 txes
CBlock block;
CDataStream stream(ParseHex("0100000075616236cc2126035fadb38deb65b9102cc2c41c09cdf29fc051906800000000fe7d5e12ef0ff901f6050211249919b1c0653771832b3a80c66cea42847f0ae1d4d26e49ffff001d00f0a4410401000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0804ffff001d029105ffffffff0100f2052a010000004341046d8709a041d34357697dfcb30a9d05900a6294078012bf3bb09c6f9b525f1d16d5503d7905db1ada9501446ea00728668fc5719aa80be2fdfc8a858a4dbdd4fbac00000000010000000255605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d28350000000049483045022100aa46504baa86df8a33b1192b1b9367b4d729dc41e389f2c04f3e5c7f0559aae702205e82253a54bf5c4f65b7428551554b2045167d6d206dfe6a2e198127d3f7df1501ffffffff55605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d2835010000004847304402202329484c35fa9d6bb32a55a70c0982f606ce0e3634b69006138683bcd12cbb6602200c28feb1e2555c3210f1dddb299738b4ff8bbe9667b68cb8764b5ac17b7adf0001ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac0000000001000000025f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028000000004847304402205d6058484157235b06028c30736c15613a28bdb768ee628094ca8b0030d4d6eb0220328789c9a2ec27ddaec0ad5ef58efded42e6ea17c2e1ce838f3d6913f5e95db601ffffffff5f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028010000004a493046022100c45af050d3cea806cedd0ab22520c53ebe63b987b8954146cdca42487b84bdd6022100b9b027716a6b59e640da50a864d6dd8a0ef24c76ce62391fa3eabaf4d2886d2d01ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac000000000100000002e2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b0000000048473044022016e7a727a061ea2254a6c358376aaa617ac537eb836c77d646ebda4c748aac8b0220192ce28bf9f2c06a6467e6531e27648d2b3e2e2bae85159c9242939840295ba501ffffffffe2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b010000004a493046022100b7a1a755588d4190118936e15cd217d133b0e4a53c3c15924010d5648d8925c9022100aaef031874db2114f2d869ac2de4ae53908fbfea5b2b1862e181626bb9005c9f01ffffffff0200e1f505000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// Match the first transaction
filter.insert(uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
std::vector<uint256> vMatched;
std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
// Match an output from the second transaction (the pubkey for address 1DZTzaBHUDM7T3QvUKBz4qXMRpkg8jsfB5)
// This should match the third transaction because it spends the output matched
// It also matches the fourth transaction, which spends to the pubkey again
filter.insert(ParseHex("044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45af"));
merkleBlock = CMerkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 4);
BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]);
BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == uint256S("0x28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f"));
BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == uint256S("0x6b0f8a73a56c04b519f1883e8aafda643ba61a30bd1439969df21bea5f4e27e2"));
BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 2);
BOOST_CHECK(merkleBlock.vMatchedTxn[3].second == uint256S("0x3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007663ace63cddb23"));
BOOST_CHECK(merkleBlock.vMatchedTxn[3].first == 3);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
}
BOOST_AUTO_TEST_CASE(merkle_block_2_with_update_none)
{
// Random real block (000000005a4ded781e667e06ceefafb71410b511fe0d5adc3e5a27ecbec34ae6)
// With 4 txes
CBlock block;
CDataStream stream(ParseHex("0100000075616236cc2126035fadb38deb65b9102cc2c41c09cdf29fc051906800000000fe7d5e12ef0ff901f6050211249919b1c0653771832b3a80c66cea42847f0ae1d4d26e49ffff001d00f0a4410401000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0804ffff001d029105ffffffff0100f2052a010000004341046d8709a041d34357697dfcb30a9d05900a6294078012bf3bb09c6f9b525f1d16d5503d7905db1ada9501446ea00728668fc5719aa80be2fdfc8a858a4dbdd4fbac00000000010000000255605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d28350000000049483045022100aa46504baa86df8a33b1192b1b9367b4d729dc41e389f2c04f3e5c7f0559aae702205e82253a54bf5c4f65b7428551554b2045167d6d206dfe6a2e198127d3f7df1501ffffffff55605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d2835010000004847304402202329484c35fa9d6bb32a55a70c0982f606ce0e3634b69006138683bcd12cbb6602200c28feb1e2555c3210f1dddb299738b4ff8bbe9667b68cb8764b5ac17b7adf0001ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac0000000001000000025f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028000000004847304402205d6058484157235b06028c30736c15613a28bdb768ee628094ca8b0030d4d6eb0220328789c9a2ec27ddaec0ad5ef58efded42e6ea17c2e1ce838f3d6913f5e95db601ffffffff5f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028010000004a493046022100c45af050d3cea806cedd0ab22520c53ebe63b987b8954146cdca42487b84bdd6022100b9b027716a6b59e640da50a864d6dd8a0ef24c76ce62391fa3eabaf4d2886d2d01ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac000000000100000002e2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b0000000048473044022016e7a727a061ea2254a6c358376aaa617ac537eb836c77d646ebda4c748aac8b0220192ce28bf9f2c06a6467e6531e27648d2b3e2e2bae85159c9242939840295ba501ffffffffe2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b010000004a493046022100b7a1a755588d4190118936e15cd217d133b0e4a53c3c15924010d5648d8925c9022100aaef031874db2114f2d869ac2de4ae53908fbfea5b2b1862e181626bb9005c9f01ffffffff0200e1f505000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_NONE);
// Match the first transaction
filter.insert(uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
std::vector<uint256> vMatched;
std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
// Match an output from the second transaction (the pubkey for address 1DZTzaBHUDM7T3QvUKBz4qXMRpkg8jsfB5)
// This should not match the third transaction though it spends the output matched
// It will match the fourth transaction, which has another pay-to-pubkey output to the same address
filter.insert(ParseHex("044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45af"));
merkleBlock = CMerkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 3);
BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]);
BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == uint256S("0x28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f"));
BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == uint256S("0x3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007663ace63cddb23"));
BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 3);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
}
BOOST_AUTO_TEST_CASE(merkle_block_3_and_serialize)
{
// Random real block (000000000000dab0130bbcc991d3d7ae6b81aa6f50a798888dfe62337458dc45)
// With one tx
CBlock block;
CDataStream stream(ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff08044c86041b020a02ffffffff0100f2052a01000000434104ecd3229b0571c3be876feaac0442a9f13c5a572742927af1dc623353ecf8c202225f64868137a18cdd85cbbb4c74fbccfd4f49639cf1bdc94a5672bb15ad5d4cac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// Match the only transaction
filter.insert(uint256S("0x63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
std::vector<uint256> vMatched;
std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
CDataStream merkleStream(SER_NETWORK, PROTOCOL_VERSION);
merkleStream << merkleBlock;
std::vector<unsigned char> vch = ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101");
std::vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), merkleStream.begin(), merkleStream.end());
}
BOOST_AUTO_TEST_CASE(merkle_block_4)
{
// Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4)
// With 7 txes
CBlock block;
CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// Match the last transaction
filter.insert(uint256S("0x0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
std::pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 6);
std::vector<uint256> vMatched;
std::vector<unsigned int> vIndex;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
// Also match the 4th transaction
filter.insert(uint256S("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"));
merkleBlock = CMerkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 2);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 3);
BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched, vIndex) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
}
BOOST_AUTO_TEST_CASE(merkle_block_4_test_p2pubkey_only)
{
// Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4)
// With 7 txes
CBlock block;
CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_P2PUBKEY_ONLY);
// Match the generation pubkey
filter.insert(ParseHex("04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91"));
// ...and the output address of the 4th transaction
filter.insert(ParseHex("b6efd80d99179f4f4ff6f4dd0a007d018c385d21"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
// We should match the generation outpoint
BOOST_CHECK(filter.contains(COutPoint(uint256S("0x147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"), 0)));
// ... but not the 4th transaction's output (its not pay-2-pubkey)
BOOST_CHECK(!filter.contains(COutPoint(uint256S("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"), 0)));
}
BOOST_AUTO_TEST_CASE(merkle_block_4_test_update_none)
{
// Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4)
// With 7 txes
CBlock block;
CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_NONE);
// Match the generation pubkey
filter.insert(ParseHex("04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91"));
// ...and the output address of the 4th transaction
filter.insert(ParseHex("b6efd80d99179f4f4ff6f4dd0a007d018c385d21"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
// We shouldn't match any outpoints (UPDATE_NONE)
BOOST_CHECK(!filter.contains(COutPoint(uint256S("0x147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"), 0)));
BOOST_CHECK(!filter.contains(COutPoint(uint256S("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"), 0)));
}
static std::vector<unsigned char> RandomData()
{
uint256 r = GetRandHash();
return std::vector<unsigned char>(r.begin(), r.end());
}
BOOST_AUTO_TEST_CASE(rolling_bloom)
{
// last-100-entry, 1% false positive:
CRollingBloomFilter rb1(100, 0.01);
// Overfill:
static const int DATASIZE=399;
std::vector<unsigned char> data[DATASIZE];
for (int i = 0; i < DATASIZE; i++) {
data[i] = RandomData();
rb1.insert(data[i]);
}
// Last 100 guaranteed to be remembered:
for (int i = 299; i < DATASIZE; i++) {
BOOST_CHECK(rb1.contains(data[i]));
}
// false positive rate is 1%, so we should get about 100 hits if
// testing 10,000 random keys. We get worst-case false positive
// behavior when the filter is as full as possible, which is
// when we've inserted one minus an integer multiple of nElement*2.
unsigned int nHits = 0;
for (int i = 0; i < 10000; i++) {
if (rb1.contains(RandomData()))
++nHits;
}
// Run test_crowdcoin with --log_level=message to see BOOST_TEST_MESSAGEs:
BOOST_TEST_MESSAGE("RollingBloomFilter got " << nHits << " false positives (~100 expected)");
// Insanely unlikely to get a fp count outside this range:
BOOST_CHECK(nHits > 25);
BOOST_CHECK(nHits < 175);
BOOST_CHECK(rb1.contains(data[DATASIZE-1]));
rb1.reset();
BOOST_CHECK(!rb1.contains(data[DATASIZE-1]));
// Now roll through data, make sure last 100 entries
// are always remembered:
for (int i = 0; i < DATASIZE; i++) {
if (i >= 100)
BOOST_CHECK(rb1.contains(data[i-100]));
rb1.insert(data[i]);
BOOST_CHECK(rb1.contains(data[i]));
}
// Insert 999 more random entries:
for (int i = 0; i < 999; i++) {
std::vector<unsigned char> d = RandomData();
rb1.insert(d);
BOOST_CHECK(rb1.contains(d));
}
// Sanity check to make sure the filter isn't just filling up:
nHits = 0;
for (int i = 0; i < DATASIZE; i++) {
if (rb1.contains(data[i]))
++nHits;
}
// Expect about 5 false positives, more than 100 means
// something is definitely broken.
BOOST_TEST_MESSAGE("RollingBloomFilter got " << nHits << " false positives (~5 expected)");
BOOST_CHECK(nHits < 100);
// last-1000-entry, 0.01% false positive:
CRollingBloomFilter rb2(1000, 0.001);
for (int i = 0; i < DATASIZE; i++) {
rb2.insert(data[i]);
}
// ... room for all of them:
for (int i = 0; i < DATASIZE; i++) {
BOOST_CHECK(rb2.contains(data[i]));
}
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <common/toolkit/StringTk.h>
#include "Config.h"
#include <sys/stat.h>
#define CONFIG_DEFAULT_CFGFILENAME "/etc/congfs/congfs-mon.conf"
Config::Config(int argc, char** argv): AbstractConfig(argc, argv)
{
initConfig(argc, argv, true);
// check mandatory value
if(getSysMgmtdHost().empty())
throw InvalidConfigException("Management host undefined.");
}
void Config::loadDefaults(bool addDashes)
{
AbstractConfig::loadDefaults();
// re-definitions
configMapRedefine("cfgFile", "");
configMapRedefine("connUseRDMA", "false");
// own definitions
configMapRedefine("connInterfacesFile", "");
configMapRedefine("tuneNumWorkers", "4");
configMapRedefine("runDaemonized", "false");
configMapRedefine("pidFile", "");
configMapRedefine("dbType", "influxdb");
configMapRedefine("dbHostName", "localhost");
configMapRedefine("dbHostPort", "8086");
configMapRedefine("dbDatabase", "congfs_mon");
// those are used by influxdb only but are kept like this for compatibility
configMapRedefine("dbMaxPointsPerRequest", "5000");
configMapRedefine("dbSetRetentionPolicy", "true");
configMapRedefine("dbRetentionDuration", "1d");
configMapRedefine("cassandraMaxInsertsPerBatch","25");
configMapRedefine("cassandraTTLSecs", "86400");
configMapRedefine("collectClientOpsByNode", "true");
configMapRedefine("collectClientOpsByUser", "true");
configMapRedefine("httpTimeoutMSecs", "1000");
configMapRedefine("statsRequestIntervalSecs", "5");
configMapRedefine("nodelistRequestIntervalSecs","30");
configMapRedefine("curlCheckSSLCertificates", "true");
}
void Config::applyConfigMap(bool enableException, bool addDashes)
{
AbstractConfig::applyConfigMap(false);
for (StringMapIter iter = configMap.begin(); iter != configMap.end(); )
{
bool unknownElement = false;
if (iter->first == std::string("logType"))
{
if (iter->second == "syslog")
{
logType = LogType_SYSLOG;
}
else if (iter->second == "logfile")
{
logType = LogType_LOGFILE;
}
else
{
throw InvalidConfigException("The value of config argument logType is invalid:"
" Must be syslog or logfile.");
}
}
else if (iter->first == std::string("connInterfacesFile"))
connInterfacesFile = iter->second;
else
if (iter->first == std::string("tuneNumWorkers"))
tuneNumWorkers = StringTk::strToUInt(iter->second);
else
if (iter->first == std::string("runDaemonized"))
runDaemonized = StringTk::strToBool(iter->second);
else
if (iter->first == std::string("pidFile"))
pidFile = iter->second;
else
if (iter->first == std::string("dbType"))
{
if (iter->second == "influxdb")
dbType = DbTypes::INFLUXDB;
else if (iter->second == "cassandra")
dbType = DbTypes::CASSANDRA;
else
throw InvalidConfigException("The value of config argument dbType is invalid:"
" Must be influxdb or cassandra.");
}
else
if (iter->first == std::string("dbHostName"))
dbHostName = iter->second;
else
if (iter->first == std::string("dbHostPort"))
dbHostPort = StringTk::strToUInt(iter->second);
else
if (iter->first == std::string("dbDatabase"))
dbDatabase = iter->second;
else
// those are used by influxdb only but are kept like this for compatibility
if (iter->first == std::string("dbMaxPointsPerRequest"))
influxdbMaxPointsPerRequest = StringTk::strToUInt(iter->second);
else
if (iter->first == std::string("dbSetRetentionPolicy"))
influxdbSetRetentionPolicy = StringTk::strToBool(iter->second);
else
if (iter->first == std::string("dbRetentionDuration"))
influxdbRetentionDuration = iter->second;
else
if (iter->first == std::string("cassandraMaxInsertsPerBatch"))
cassandraMaxInsertsPerBatch = StringTk::strToUInt(iter->second);
else
if (iter->first == std::string("cassandraTTLSecs"))
cassandraTTLSecs = StringTk::strToUInt(iter->second);
else
if (iter->first == std::string("collectClientOpsByNode"))
collectClientOpsByNode = StringTk::strToBool(iter->second);
else
if (iter->first == std::string("collectClientOpsByUser"))
collectClientOpsByUser = StringTk::strToBool(iter->second);
else
if (iter->first == std::string("httpTimeoutMSecs"))
httpTimeout = std::chrono::milliseconds(StringTk::strToUInt(iter->second));
else
if (iter->first == std::string("statsRequestIntervalSecs"))
statsRequestInterval = std::chrono::seconds(StringTk::strToUInt(iter->second));
else
if (iter->first == std::string("nodelistRequestIntervalSecs"))
nodelistRequestInterval = std::chrono::seconds(StringTk::strToUInt(iter->second));
else
if (iter->first == std::string("curlCheckSSLCertificates"))
curlCheckSSLCertificates = StringTk::strToBool(iter->second);
else
{
unknownElement = true;
if (enableException)
{
throw InvalidConfigException(std::string("The config argument '")
+ iter->first + std::string("' is invalid.") );
}
}
if (unknownElement)
{
iter++;
}
else
{
iter = eraseFromConfigMap(iter);
}
}
}
void Config::initImplicitVals()
{
AbstractConfig::initConnAuthHash(connAuthFile, &connAuthHash);
}
|
#include <iostream>
#define Log(x) std::cout << x << std::endl
#define wait std::cin.get()
template <class T>
class stack
{
private:
int top;
int size;
T *array;
public:
stack(int);
void push(T);
void multi_push(int, T *);
T pop();
T *multi_pop(int);
bool is_empty();
bool is_full();
T top_element();
void clear();
int no_of_elements();
void display();
};
template <class T>
stack<T>::stack(int size) : size(size)
{
top = -1;
array = new T[size];
}
template <class T>
void stack<T>::push(T element)
{
if (top < (size - 1))
array[++top] = element;
else
Log("overflow...");
return;
}
template <class T>
void stack<T>::multi_push(int k, T *data)
{
for (int i = 0; i < k; i++)
push(data[i]);
}
template <class T>
T stack<T>::pop()
{
if (top != (-1))
return array[top--];
else
Log("stack is empty...");
}
template <class T>
T *stack<T>::multi_pop(int k)
{
T *temp = new T[k];
for (int i = 0; i < k; i++)
temp[i] = pop();
return temp;
}
template <class T>
bool stack<T>::is_empty()
{
return (top == (-1));
}
template <class T>
bool stack<T>::is_full()
{
return (top == (size - 1));
}
template <class T>
T stack<T>::top_element()
{
if (top != (-1))
return array[top];
else
Log("No top element stack is empty...");
}
template <class T>
void stack<T>::clear()
{
top = -1;
return;
}
template <class T>
int stack<T>::no_of_elements()
{
return top + 1;
}
template <class T>
void stack<T>::display()
{
Log("");
for (int i = top; i > -1; i--)
Log(array[i]);
return;
}
void object_creator(auto type, auto element_type, int size)
{
decltype(type) stack_obj(size);
startLabel:
Log("==========MENU==========");
Log("1. push");
Log("2. pop");
Log("3. multi push (program crashes , under construction)");
Log("4. multi pop (program crashes , under construction)");
Log("5. is full");
Log("6. is empty");
Log("7. top element");
Log("8. total element");
Log("9. clear");
Log("10. Display");
Log("Enter your choice: ");
int choice;
std::cin >> choice;
switch (choice)
{
case 1:
{
Log("Enter element to be pushed : ");
decltype(element_type) element;
std::cin >> element;
stack_obj.push(element);
}
break;
case 2:
{
decltype(element_type) var;
var = stack_obj.pop();
Log("poped element is :: ");
Log(var);
}
break;
case 3:
{
Log("Enter no of element to be pushed : ");
int count;
decltype(element_type) arr[count];
for (int i = 0; i < count; i++)
std::cin >> arr[i];
stack_obj.multi_push(count, arr);
}
break;
case 4:
{
Log("Enter no of element to be poped : ");
int count;
decltype(element_type) *arr;
arr = stack_obj.multi_pop(count);
for (int i = 0; i < count; i++)
Log(arr[i]);
}
break;
case 5:
stack_obj.is_full() ? Log("stack is full") : Log("stack is not full");
break;
case 6:
stack_obj.is_empty() ? Log("stack is empty") : Log("stack is not empty");
break;
case 7:
{
Log("top element is ");
Log(stack_obj.top_element());
}
break;
case 8:
{
Log("total no of elements : ");
Log(stack_obj.no_of_elements());
}
break;
case 9:
{
stack_obj.clear();
Log("cleared the stack ");
}
break;
case 10:
stack_obj.display();
break;
default:
Log("Inavlid option...");
}
Log("\nPress 0 to exit : ");
std::cin >> choice;
if (choice != 0)
goto startLabel;
return;
}
int main()
{
Log("Enter the size of stack : ");
int size;
std::cin >> size;
Log("Enter type of data you want to enter : ");
Log("==========MENU==========");
Log("1. Boolean ");
Log("2. Short ");
Log("3. Integer ");
Log("4. Unsigned Integer");
Log("5. Long ");
Log("6. Float ");
Log("7. Double ");
Log("8. Character ");
Log("9. String ");
Log("10. Object ");
Log("Enter your choice: ");
int type_data;
std::cin >> type_data;
switch (type_data)
{
case 1:
{
stack<bool> bool_obj(size);
object_creator(bool_obj, true, size);
}
break;
case 2:
{
stack<short> short_obj(size);
object_creator(short_obj, (short)1, size);
}
break;
case 3:
{
stack<int> int_obj(size);
object_creator(int_obj, 1, size);
}
break;
case 4:
{
stack<unsigned int> uint_obj(size);
object_creator(uint_obj, 1U, size);
}
break;
case 5:
{
stack<long> long_obj(size);
object_creator(long_obj, 1l, size);
}
break;
case 6:
{
stack<float> float_obj(size);
object_creator(float_obj, 1.1f, size);
}
break;
case 7:
{
stack<double> double_obj(size);
object_creator(double_obj, 1.1, size);
}
break;
case 8:
{
stack<char> char_obj(size);
object_creator(char_obj, 'a', size);
}
break;
default:
Log("invalid option...");
break;
}
wait;
return 0;
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "examples/example_compiler_gym_service/service/ExampleService.h"
#include "compiler_gym/service/proto/compiler_gym_service.pb.h"
#include "compiler_gym/util/GrpcStatusMacros.h"
#include "compiler_gym/util/Version.h"
namespace compiler_gym::example_service {
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
namespace fs = boost::filesystem;
namespace {
template <typename T>
[[nodiscard]] inline Status rangeCheck(const T& value, const T& minValue, const T& maxValue) {
if (value < minValue || value > maxValue) {
return Status(StatusCode::INVALID_ARGUMENT, "Out-of-range");
}
return Status::OK;
}
} // namespace
std::vector<std::string> getBenchmarks() { return {"foo", "bar"}; }
std::vector<ActionSpace> getActionSpaces() {
ActionSpace space;
space.set_name("default");
space.add_action("a");
space.add_action("b");
space.add_action("c");
return {space};
}
std::vector<ObservationSpace> getObservationSpaces() {
ObservationSpace ir;
ir.set_name("ir");
ScalarRange irSizeRange;
irSizeRange.mutable_min()->set_value(0);
*ir.mutable_string_size_range() = irSizeRange;
ObservationSpace features;
features.set_name("features");
for (int i = 0; i < 3; ++i) {
ScalarRange* featureSizeRange = features.mutable_int64_range_list()->add_range();
featureSizeRange->mutable_min()->set_value(-100);
featureSizeRange->mutable_max()->set_value(100);
}
ObservationSpace codesize;
codesize.set_name("codesize");
ScalarRange codesizeRange;
codesizeRange.mutable_min()->set_value(0);
*codesize.mutable_scalar_int64_range() = codesizeRange;
return {ir, features, codesize};
}
ExampleService::ExampleService(const fs::path& workingDirectory)
: workingDirectory_(workingDirectory), nextSessionId_(0) {}
Status ExampleService::GetVersion(ServerContext* /* unused */,
const GetVersionRequest* /* unused */, GetVersionReply* reply) {
reply->set_service_version(COMPILER_GYM_VERSION);
reply->set_compiler_version("1.0.0");
return Status::OK;
}
Status ExampleService::GetSpaces(ServerContext* /* unused*/, const GetSpacesRequest* /* unused */,
GetSpacesReply* reply) {
const auto actionSpaces = getActionSpaces();
const auto observationSpaces = getObservationSpaces();
*reply->mutable_action_space_list() = {actionSpaces.begin(), actionSpaces.end()};
*reply->mutable_observation_space_list() = {observationSpaces.begin(), observationSpaces.end()};
return Status::OK;
}
Status ExampleService::StartSession(ServerContext* /* unused*/, const StartSessionRequest* request,
StartSessionReply* reply) {
const std::lock_guard<std::mutex> lock(sessionsMutex_);
// Determine the benchmark to use.
std::string benchmark = request->benchmark();
const auto benchmarks = getBenchmarks();
if (!benchmark.empty() &&
std::find(benchmarks.begin(), benchmarks.end(), benchmark) == benchmarks.end()) {
return Status(StatusCode::INVALID_ARGUMENT, "Unknown program name");
} else {
// If no benchmark was requested, choose one.
benchmark = "foo";
}
reply->set_benchmark(benchmark);
// Determine the action space.
const auto actionSpaces = getActionSpaces();
RETURN_IF_ERROR(
rangeCheck(request->action_space(), 0, static_cast<int32_t>(actionSpaces.size()) - 1));
const auto actionSpace = actionSpaces[request->action_space()];
// Create the new compilation session given.
reply->set_session_id(nextSessionId_);
sessions_[nextSessionId_] = std::make_unique<ExampleCompilationSession>(benchmark, actionSpace);
++nextSessionId_;
return Status::OK;
}
Status ExampleService::EndSession(ServerContext* /* unused*/, const EndSessionRequest* request,
EndSessionReply* /* unused */) {
const std::lock_guard<std::mutex> lock(sessionsMutex_);
auto session = sessions_.find(request->session_id());
// De-allocate the session.
if (session != sessions_.end()) {
sessions_.erase(session);
}
return Status::OK;
}
Status ExampleService::Step(ServerContext* /* unused*/, const StepRequest* request,
StepReply* reply) {
ExampleCompilationSession* sess;
RETURN_IF_ERROR(session(request->session_id(), &sess));
return sess->Step(request, reply);
}
Status ExampleService::GetBenchmarks(grpc::ServerContext* /*unused*/,
const GetBenchmarksRequest* /*unused*/,
GetBenchmarksReply* reply) {
const auto benchmarks = getBenchmarks();
*reply->mutable_benchmark() = {benchmarks.begin(), benchmarks.end()};
return Status::OK;
}
Status ExampleService::session(uint64_t id, ExampleCompilationSession** sess) {
auto it = sessions_.find(id);
if (it == sessions_.end()) {
return Status(StatusCode::INVALID_ARGUMENT, "Session ID not found");
}
*sess = it->second.get();
return Status::OK;
}
ExampleCompilationSession::ExampleCompilationSession(const std::string& benchmark,
ActionSpace actionSpace)
: benchmark_(benchmark), actionSpace_(actionSpace) {}
Status ExampleCompilationSession::Step(const StepRequest* request, StepReply* reply) {
for (int i = 0; i < request->action_size(); ++i) {
const auto action = request->action(i);
// Run the actual action. Here we just range check.
RETURN_IF_ERROR(rangeCheck(action, 0, static_cast<int32_t>(actionSpace_.action_size() - 1)));
}
// Generate observations.
for (int i = 0; i < request->observation_space_size(); ++i) {
RETURN_IF_ERROR(rangeCheck(request->observation_space(i), 0,
static_cast<int32_t>(getObservationSpaces().size()) - 1));
auto observation = reply->add_observation();
RETURN_IF_ERROR(getObservation(request->observation_space(i), observation));
}
return Status::OK;
}
Status ExampleCompilationSession::getObservation(int32_t observationSpace,
Observation* observation) {
const auto observationSpaces = getObservationSpaces();
RETURN_IF_ERROR(
rangeCheck(observationSpace, 0, static_cast<int32_t>(observationSpaces.size()) - 1));
switch (observationSpace) {
case 0: // IR
observation->set_string_value("Hello, world!");
break;
case 1: // Features
for (int i = 0; i < 3; ++i) {
observation->mutable_int64_list()->add_value(0);
}
break;
case 2: // Codesize
observation->set_scalar_int64(0);
default:
break;
}
return Status::OK;
}
} // namespace compiler_gym::example_service
|
#pragma once
#include <LuminoEditor/Plugin.hpp>
#include "UIExtension.hpp"
class NavigatorManager;
class AssetBrowserNavigator;
class Navigator
: public ln::Object
{
public:
Navigator() {}
virtual ln::UIElement* getNavigationMenuItem() = 0;
virtual ln::UIElement* getNavigationPane() = 0;
// View 部分の作成。必要になったときに作成する遅延実行にしたいので、Navigator のサブクラスとはしない。
// インスタンスは実装側で保持が必要。
// TOOD: name。エディタ状態復元などで、前回どれを開いていたかを識別したい
protected:
private:
};
class NavigationBarItem : public ln::UICollectionItem
{
public:
void init(NavigatorManager* manager, Navigator* navigator);
void addIcon(const ln::StringView& iconName);
Navigator* navigator() const { return m_navigator; }
protected:
virtual const ln::String& elementName() const override { static ln::String name = _TT("NavigationBarItem"); return name; }
virtual void onSelected(ln::UIEventArgs* e) override;
virtual void onUnselected(ln::UIEventArgs* e) override;
private:
NavigatorManager* m_navigatorManager;
Navigator* m_navigator;
};
class NavigationBar : public ln::UIItemsControl
{
public:
static const int ItemSize = 60;
void init(NavigatorManager* manager);
void addNavigator(Navigator* navigator);
void removeNavigator(Navigator* navigator);
protected:
private:
NavigatorManager* m_navigatorManager;
ln::List<Ref<NavigationBarItem>> m_navigatorContainers;
};
class NavigatorContentPane
: public ln::UIControl
{
public:
void onUpdateStyle(const ln::UIStyleContext* styleContext, const ln::detail::UIStyleInstance* finalStyle) override;
};
class NavigatorManager
: public ln::UIControl
{
public:
std::function<void()> navigationViewOpen;
std::function<void()> navigationViewClose;
NavigatorManager();
void init();
void resetNavigators();
void addNavigator(Navigator* navigator);
void removeNavigator(Navigator* navigator);
void unloadAdditionalNavigators();
void setCurrent(Navigator* navigator);
const Ref<NavigationBar>& navigationBar() const { return m_navigationBar; }
protected:
private:
Ref<ln::UIBoxLayout> m_layout;
Ref<ln::UISwitchLayout> m_switchLayout;
Ref<NavigationBar> m_navigationBar;
ln::List<Navigator*> m_navigators;
// default navi
//Ref<AssetBrowserNavigator> m_assetBrowserNavigator;
//float m_viewExpandingSize;
};
|
#include "FaceRecognition/FaceRecognition.h"
using namespace face_recognition;
FaceRecognition::FaceRecognition(std::string weight, std::string config, std::string recog, std::string dataset, std::string webcam){
img_result = cv::Mat::zeros(cv::Size(640, 480), CV_64FC1);
std::string weight_file = "../model/opencv_face_detector_uint8.pb";
std::string config_file = "../model/opencv_face_detector.pbtxt";
std::string recog_file = "../model/openface.nn4.small2.v1.t7";
device = "/dev/video0";
dataset_dir = "../../dataset";
if (weight != "") weight_file = weight;
if (config != "") config_file = config;
if (webcam != "") device = webcam;
if (recog != "") recog_file = recog;
if (dataset != "") dataset_dir = dataset;
net = cv::dnn::readNetFromTensorflow(weight_file, config_file);
net_recog = cv::dnn::readNetFromTorch(recog_file);
dataset_preprocessing();
}
FaceRecognition::~FaceRecognition(){
}
void FaceRecognition::dataset_preprocessing(){
std::vector<std::string> filenames;
std::string dir = "";
int found = dataset_dir.find_last_of("/\\");
int end = dataset_dir.size()-1;
if(found == end) dir = std::string(dataset_dir) + std::string("*.jpg");
else dir = std::string(dataset_dir) + std::string("/*.jpg");
cv::glob(dir, filenames);
for (auto name : filenames)
{
cv::Mat im = cv::imread(name);
cv::Mat inputBlobRecog = cv::dnn::blobFromImage(im, 1.0/255.0, cv::Size(96.0, 96.0), cv::Scalar(0, 0, 0, 0), true, false);
net_recog.setInput(inputBlobRecog);
cv::Mat recognition = net_recog.forward();
std::size_t found = name.find_last_of("/\\");
name = name.substr(found+1);
found = name.find_last_of(".\\");
name = name.substr(0, found);
name_list.push_back(name);
face_encoding[name] = recognition.clone();
}
}
std::string FaceRecognition::compare_face(cv::Mat encoding){
std::string who_am_i = "Unknown";
auto best_score = 0.6;
for(auto name : name_list){
double score = 0.0;
double mag_known = 0.0;
double mag_new = 0.0;
for(int col = 0; col < face_encoding[name].cols; col++){
auto val_known = face_encoding[name].at<float>(0, col);
auto val_new = encoding.at<float>(0, col);
mag_known += std::pow(val_known, 2.0);
mag_new += std::pow(val_new, 2.0);
}
mag_known = std::sqrt(mag_known);
mag_new = std::sqrt(mag_new);
for(int col = 0; col < encoding.cols; col++){
auto val_known = face_encoding[name].at<float>(0, col);
auto val_new = encoding.at<float>(0, col);
score += val_known * val_new;
}
score /= (mag_known * mag_new);
if(score > best_score){
best_score = score;
who_am_i = name;
}
}
return who_am_i;
}
void FaceRecognition::start(){
run = true;
thread = std::thread(&FaceRecognition::loop, this);
}
void FaceRecognition::loop(){
cv::VideoCapture cap(device);
if (!cap.isOpened())
{
run = false;
std::cout << "Cannot open the video cam" << std::endl;
return;
}
double dWidth = cap.get(cv::CAP_PROP_FRAME_WIDTH);
double dHeight = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
std::cout << "Frame Size: " << dWidth << "x" << dHeight << std::endl;
cv::Mat frame;
double fps, t, T;
while(run){
cap >> frame;
if (frame.empty())
{
std::cout << "Cannot read a frame video stream" << std::endl;
run = false;
break;
}
t = cv::getTickCount();
process(frame);
T = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
fps = 1/T;
putText(frame, cv::format("FPS = %.2f",fps), cv::Point(10, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255), 4);
img_result = frame.clone();
}
}
void FaceRecognition::process(cv::Mat &frame)
{
int frameHeight = frame.rows;
int frameWidth = frame.cols;
std::string name = "Unknown";
cv::Mat inputBlob = cv::dnn::blobFromImage(frame, 1.0, cv::Size(300.0, 300.0), cv::Scalar(104.0, 177.0, 123.0), true, false);
net.setInput(inputBlob, "data");
cv::Mat detection = net.forward("detection_out");
cv::Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
for(int i = 0; i < detectionMat.rows; i++)
{
float confidence = detectionMat.at<float>(i, 2);
if(confidence > 0.7)
{
int x1 = static_cast<int>(detectionMat.at<float>(i, 3) * frameWidth);
int y1 = static_cast<int>(detectionMat.at<float>(i, 4) * frameHeight);
int x2 = static_cast<int>(detectionMat.at<float>(i, 5) * frameWidth);
int y2 = static_cast<int>(detectionMat.at<float>(i, 6) * frameHeight);
cv::rectangle(frame, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0),2, 4);
cv::rectangle(frame, cv::Point(x1, y2 - 35), cv::Point(x2, y2), cv::Scalar(0, 255, 0), cv::FILLED);
auto font = cv::FONT_HERSHEY_DUPLEX;
if((x1 >= 0) && (y1 >= 0) && (x2 >= 0) && (y2 >= 0) && (x1 < frame.cols) && (y1 < frame.rows) && (x2 < frame.cols) && (y2 < frame.rows)){
cv::Mat frame_clone = frame.clone();
auto x_top = (x1 - 30 >= 0)? x1 - 30 : x1;
auto y_top = (y1 - 30 >= 0)? y1 - 30 : y1;
auto x_bottom = (x2 + 30 < frame.cols)? x2 + 30 : x2;
auto y_bottom = (y2 + 30 < frame.rows)? y2 + 30 : y2;
cv::Rect myROI(x_top, y_top, (x_bottom - x_top), (y_bottom -y_top));
frame_clone = frame_clone(myROI);
cv::Mat inputBlobRecog = cv::dnn::blobFromImage(frame_clone, 1.0/255.0, cv::Size(96.0, 96.0), cv::Scalar(0, 0, 0, 0), true, false);
net_recog.setInput(inputBlobRecog);
cv::Mat recognition = net_recog.forward();
name = compare_face(recognition);
}
cv::putText(frame, name, cv::Point(x1 + 6, y2 - 6), font, 0.8, cv::Scalar(255, 255, 255), 1);
}
}
}
|
#include "global_include.h"
#include "log.h"
#include "curl_wrapper.h"
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
namespace mavsdk {
CurlWrapper::CurlWrapper() {}
CurlWrapper::~CurlWrapper() {}
// converts curl output to string
// taken from
// https://stackoverflow.com/questions/9786150/save-curl-content-result-into-a-string-in-c
static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp)
{
reinterpret_cast<std::string *>(userp)->append(reinterpret_cast<char *>(contents),
size * nmemb);
return size * nmemb;
}
bool CurlWrapper::download_text(const std::string &url, std::string &content)
{
auto curl = std::shared_ptr<CURL>(curl_easy_init(), curl_easy_cleanup);
std::string readBuffer;
if (nullptr != curl) {
CURLcode res;
curl_easy_setopt(curl.get(), CURLOPT_CONNECTTIMEOUT, 5L);
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl.get());
content = readBuffer;
if (res == CURLcode::CURLE_OK) {
return true;
} else {
LogErr() << "Error while downloading text, curl error code: "
<< curl_easy_strerror(res);
return false;
}
} else {
LogErr() << "Error: cannot start uploading because of curl initialization error. ";
return false;
}
}
static int
upload_progress_update(void *p, double dltotal, double dlnow, double ultotal, double ulnow)
{
UNUSED(dltotal);
UNUSED(dlnow);
struct dl_up_progress *myp = reinterpret_cast<struct dl_up_progress *>(p);
if (myp->progress_callback == nullptr) {
return 0;
}
if (ultotal == 0 || ulnow == 0) {
return myp->progress_callback(0, Status::Idle, CURLcode::CURLE_OK);
}
int percentage = static_cast<int>(100.0 / ultotal * ulnow);
if (percentage > myp->progress_in_percentage) {
myp->progress_in_percentage = percentage;
return myp->progress_callback(percentage, Status::Uploading, CURLcode::CURLE_OK);
}
return 0;
}
size_t get_file_size(const std::string &path)
{
std::streampos begin, end;
std::ifstream myfile(path.c_str(), std::ios::binary);
begin = myfile.tellg();
myfile.seekg(0, std::ios::end);
end = myfile.tellg();
myfile.close();
return ((end - begin) > 0) ? (end - begin) : 0;
}
template<typename T> std::string to_string(T value)
{
std::ostringstream os;
os << value;
return os.str();
}
bool CurlWrapper::upload_file(const std::string &url,
const std::string &path,
const progress_callback_t &progress_callback)
{
auto curl = std::shared_ptr<CURL>(curl_easy_init(), curl_easy_cleanup);
CURLcode res;
if (nullptr != curl) {
struct dl_up_progress prog;
prog.progress_callback = progress_callback;
curl_httppost *post = NULL;
curl_httppost *last = NULL;
struct curl_slist *chunk = NULL;
// avoid sending 'Expect: 100-Continue' header, required by some server implementations
chunk = curl_slist_append(chunk, "Expect:");
// disable chunked upload
chunk = curl_slist_append(chunk, "Content-Encoding: ");
// to allow efficient file upload, we need to add the file size to the header
std::string filesize_header = "File-Size: " + to_string(get_file_size(path));
chunk = curl_slist_append(chunk, filesize_header.c_str());
curl_formadd(
&post, &last, CURLFORM_COPYNAME, "file", CURLFORM_FILE, path.c_str(), CURLFORM_END);
curl_easy_setopt(curl.get(), CURLOPT_CONNECTTIMEOUT, 5L);
curl_easy_setopt(curl.get(), CURLOPT_PROGRESSFUNCTION, upload_progress_update);
curl_easy_setopt(curl.get(), CURLOPT_PROGRESSDATA, &prog);
curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_HTTPPOST, post);
curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
res = curl_easy_perform(curl.get());
curl_slist_free_all(chunk);
curl_formfree(post);
if (res == CURLcode::CURLE_OK) {
if (nullptr != progress_callback) {
progress_callback(100, Status::Finished, CURLcode::CURLE_OK);
}
return true;
} else {
if (nullptr != progress_callback) {
progress_callback(0, Status::Error, res);
}
LogErr() << "Error while uploading file, curl error code: " << curl_easy_strerror(res);
return false;
}
} else {
LogErr() << "Error: cannot start uploading because of curl initialization error.";
return false;
}
}
static int
download_progress_update(void *p, double dltotal, double dlnow, double ultotal, double ulnow)
{
UNUSED(ultotal);
UNUSED(ulnow);
struct dl_up_progress *myp = reinterpret_cast<struct dl_up_progress *>(p);
if (myp->progress_callback == nullptr) {
return 0;
}
if (dltotal == 0 || dlnow == 0) {
return myp->progress_callback(0, Status::Idle, CURLcode::CURLE_OK);
}
int percentage = static_cast<int>(100 / dltotal * dlnow);
if (percentage > myp->progress_in_percentage) {
myp->progress_in_percentage = percentage;
return myp->progress_callback(percentage, Status::Downloading, CURLcode::CURLE_OK);
}
return 0;
}
bool CurlWrapper::download_file_to_path(const std::string &url,
const std::string &path,
const progress_callback_t &progress_callback)
{
auto curl = std::shared_ptr<CURL>(curl_easy_init(), curl_easy_cleanup);
FILE *fp;
if (nullptr != curl) {
CURLcode res;
struct dl_up_progress prog;
prog.progress_callback = progress_callback;
fp = fopen(path.c_str(), "wb");
curl_easy_setopt(curl.get(), CURLOPT_CONNECTTIMEOUT, 5L);
curl_easy_setopt(curl.get(), CURLOPT_PROGRESSFUNCTION, download_progress_update);
curl_easy_setopt(curl.get(), CURLOPT_PROGRESSDATA, &prog);
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
res = curl_easy_perform(curl.get());
fclose(fp);
if (res == CURLcode::CURLE_OK) {
if (nullptr != progress_callback) {
progress_callback(100, Status::Finished, res);
}
return true;
} else {
if (nullptr != progress_callback) {
progress_callback(0, Status::Error, res);
}
remove(path.c_str());
LogErr() << "Error while downloading file, curl error code: "
<< curl_easy_strerror(res);
return false;
}
} else {
LogErr() << "Error: cannot start downloading file because of curl initialization error. ";
return false;
}
}
} // namespace mavsdk
|
#include "target_classifier.h"
#include <catboost/libs/helpers/vector_helpers.h>
#include <library/grid_creator/binarization.h>
#include <util/generic/algorithm.h>
static TVector<float> GetMultiClassBorders(int cnt) {
TVector<float> borders(cnt);
for (int i = 0; i < cnt; ++i) {
borders[i] = 0.5 + i;
}
return borders;
}
static TVector<float> SelectBorders(TConstArrayRef<float> target,
int targetBorderCount,
EBorderSelectionType targetBorderType,
bool allowConstLabel) {
TVector<float> learnTarget(target.begin(), target.end());
THashSet<float> borderSet = BestSplit(learnTarget, targetBorderCount, targetBorderType);
TVector<float> borders(borderSet.begin(), borderSet.end());
CB_ENSURE((borders.ysize() > 0) || allowConstLabel, "0 target borders");
if (borders.empty()) {
borders.push_back(target.front());
}
Sort(borders.begin(), borders.end());
return borders;
}
TTargetClassifier BuildTargetClassifier(TConstArrayRef<float> target,
ELossFunction loss,
const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,
int targetBorderCount,
EBorderSelectionType targetBorderType,
bool allowConstLabel) {
if (targetBorderCount == 0) {
return TTargetClassifier();
}
CB_ENSURE(!target.empty(), "train target should not be empty");
TMinMax<float> targetBounds = CalcMinMax<float>(target);
CB_ENSURE((targetBounds.Min != targetBounds.Max) || allowConstLabel, "target in train should not be constant");
switch (loss) {
case ELossFunction::RMSE:
case ELossFunction::Quantile:
case ELossFunction::Lq:
case ELossFunction::LogLinQuantile:
case ELossFunction::Poisson:
case ELossFunction::MAE:
case ELossFunction::MAPE:
case ELossFunction::PairLogit:
case ELossFunction::PairLogitPairwise:
case ELossFunction::QueryRMSE:
case ELossFunction::QuerySoftMax:
case ELossFunction::YetiRank:
case ELossFunction::YetiRankPairwise:
case ELossFunction::StochasticFilter:
case ELossFunction::Logloss:
case ELossFunction::CrossEntropy:
case ELossFunction::UserPerObjMetric:
case ELossFunction::UserQuerywiseMetric:
return TTargetClassifier(SelectBorders(
target,
targetBorderCount,
targetBorderType,
allowConstLabel));
case ELossFunction::MultiClass:
case ELossFunction::MultiClassOneVsAll:
return TTargetClassifier(GetMultiClassBorders(targetBorderCount));
case ELossFunction::PythonUserDefinedPerObject: {
Y_ASSERT(objectiveDescriptor.Defined());
return TTargetClassifier(SelectBorders(
target,
targetBorderCount,
targetBorderType,
allowConstLabel));
}
default:
CB_ENSURE(false, "provided error function is not supported");
}
}
|
#ifndef YOLONODEJS_LIST_H
#define YOLONODEJS_LIST_H
#include <node_api.h>
extern "C" {
#include "darknet.h"
#include "list.h"
}
#include "../utils/common.h"
#include "../helpers/common.h"
using namespace std;
/**
* @description: print matrix
* @param m: <matrix>
*/
static napi_value yolo_make_list(napi_env env, napi_callback_info info){
list* l = make_list();
return NULL;
}
#endif //YOLONODEJS_LIST_H
|
/*
Copyright (c) 2005-2022, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
#ifndef _TESTNEUMANNSTIMULUS_HPP_
#define _TESTNEUMANNSTIMULUS_HPP_
#include <cxxtest/TestSuite.h>
#include <vector>
#include "MonodomainProblem.hpp"
#include "BidomainProblem.hpp"
#include "AbstractCardiacCellFactory.hpp"
#include "LuoRudy1991.hpp"
#include "ReplicatableVector.hpp"
#include "SimpleStimulus.hpp"
#include "StimulusBoundaryCondition.hpp"
#include "ConstBoundaryCondition.hpp"
#include "ZeroStimulusCellFactory.hpp"
#include "PetscSetupAndFinalize.hpp"
/* HOW_TO_TAG Cardiac/Problem definition
* Use a genuinely Neumann intracellular stimulus, rather than default volume stimulus
*/
class TestNeumannStimulus : public CxxTest::TestSuite
{
public:
void tearDown()
{
HeartConfig::Reset();
}
// Solve on a 1D string of cells, 1mm long with a space step of 0.1mm.
void TestMonodomainConstantStimulus()
{
// this parameters are a bit arbitrary, and chosen to get a good spread of voltages
HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(1.75));
HeartConfig::Instance()->SetSimulationDuration(2); //ms
HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements");
HeartConfig::Instance()->SetOutputDirectory("MonoNeumannConst");
HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d");
ZeroStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory;
MonodomainProblem<1> monodomain_problem( &cell_factory );
monodomain_problem.Initialise();
HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1*1.75/0.0005);
// create boundary conditions container
boost::shared_ptr<BoundaryConditionsContainer<1,1,1> > p_bcc(new BoundaryConditionsContainer<1,1,1>);
ConstBoundaryCondition<1>* p_bc_stim = new ConstBoundaryCondition<1>(2*1.75/0.0005);
// get mesh
AbstractTetrahedralMesh<1,1> &mesh = monodomain_problem.rGetMesh();
// loop over boundary elements
AbstractTetrahedralMesh<1, 1>::BoundaryElementIterator iter;
iter = mesh.GetBoundaryElementIteratorBegin();
while (iter != mesh.GetBoundaryElementIteratorEnd())
{
// if the element is on the left of the mesh, add a stimulus to the bcc
if (((*iter)->GetNodeLocation(0))[0]==0.0)
{
p_bcc->AddNeumannBoundaryCondition(*iter, p_bc_stim);
}
iter++;
}
// pass the bcc to the monodomain problem
monodomain_problem.SetBoundaryConditionsContainer(p_bcc);
monodomain_problem.Solve();
// check some voltages
ReplicatableVector voltage_replicated(monodomain_problem.GetSolution());
double atol=5e-3;
TS_ASSERT_DELTA(voltage_replicated[1], 94.6426, atol);
TS_ASSERT_DELTA(voltage_replicated[3], 49.7867, atol);
TS_ASSERT_DELTA(voltage_replicated[5], 30.5954, atol);
TS_ASSERT_DELTA(voltage_replicated[7], 21.6782, atol);
TS_ASSERT_DELTA(voltage_replicated[9], -33.9983, atol);
TS_ASSERT_DELTA(voltage_replicated[10], -52.2396, atol);
}
void TestMonodomainSquareWaveStimulus()
{
// this parameters are a bit arbitrary, and chosen to get a good spread of voltages
HeartConfig::Instance()->SetIntracellularConductivities(Create_c_vector(1.75));
HeartConfig::Instance()->SetSimulationDuration(2); //ms
HeartConfig::Instance()->SetMeshFileName("mesh/test/data/1D_0_to_1mm_10_elements");
HeartConfig::Instance()->SetOutputDirectory("MonoNeumannSquare");
HeartConfig::Instance()->SetOutputFilenamePrefix("MonodomainLR91_1d");
ZeroStimulusCellFactory<CellLuoRudy1991FromCellML, 1> cell_factory;
MonodomainProblem<1> monodomain_problem( &cell_factory );
monodomain_problem.Initialise();
HeartConfig::Instance()->SetSurfaceAreaToVolumeRatio(1*1.75/0.0005);
// create boundary conditions container
boost::shared_ptr<BoundaryConditionsContainer<1,1,1> > p_bcc(new BoundaryConditionsContainer<1,1,1>);
SimpleStimulus stim(4*1.75/0.0005, 0.5);
StimulusBoundaryCondition<1>* p_bc_stim = new StimulusBoundaryCondition<1>(&stim);
// get mesh
AbstractTetrahedralMesh<1,1> &mesh = monodomain_problem.rGetMesh();
// loop over boundary elements
AbstractTetrahedralMesh<1, 1>::BoundaryElementIterator iter;
iter = mesh.GetBoundaryElementIteratorBegin();
while (iter != mesh.GetBoundaryElementIteratorEnd())
{
// if the element is on the left of the mesh, add a stimulus to the bcc
if (((*iter)->GetNodeLocation(0))[0]==0.0)
{
p_bcc->AddNeumannBoundaryCondition(*iter, p_bc_stim);
}
iter++;
}
// pass the bcc to the monodomain problem
monodomain_problem.SetBoundaryConditionsContainer(p_bcc);
monodomain_problem.Solve();
// check some voltages
ReplicatableVector voltage_replicated(monodomain_problem.GetSolution());
double atol=8e-3;
TS_ASSERT_DELTA(voltage_replicated[1], 22.4940, atol);
TS_ASSERT_DELTA(voltage_replicated[3], 22.6008, atol);
TS_ASSERT_DELTA(voltage_replicated[5], 23.3054, atol);
TS_ASSERT_DELTA(voltage_replicated[7], 24.4932, atol);
TS_ASSERT_DELTA(voltage_replicated[9], 14.5184, atol);
TS_ASSERT_DELTA(voltage_replicated[10],3.7081, atol);
}
/// Note: Neumann intracellular stimuli won't work with bidomain (no solution to PDEs) (unless nodes are grounded)
};
#endif //_TESTNEUMANNSTIMULUS_HPP_
|
#include "org_semux_evmc_jni_Native.h"
#include <evmc/evmc.h>
#include <evmjit.h>
#include <cstdint>
#include <cstdlib>
#include <cstring>
/**
* Encodes a 32-bit integer in its BE format.
*/
inline void encode_int(int32_t num, jbyte *dest) {
dest[0] = (num >> 24) & 0xff;
dest[1] = (num >> 16) & 0xff;
dest[2] = (num >> 8) & 0xff;
dest[3] = num & 0xff;
}
/**
* Decodes a 32-bit integer.
*/
inline int32_t decode_int(jbyte *dest) {
return ((int32_t) dest[0] << 24) | ((int32_t) dest[1] << 16)
| ((int32_t) dest[2] << 8) | ((int32_t) dest[3]);
}
/**
* Encodes a 64-bit integer in its BE format.
*/
inline void encode_long(int64_t num, jbyte *dest) {
encode_int(num >> 32, dest);
encode_int(num & 0xffffffff, dest + 4);
}
/**
* Decodes a 64-bit integer.
*/
inline int64_t decode_long(jbyte *dest) {
return ((int64_t) decode_int(dest) << 32) | (int64_t) decode_int(dest + 4);
}
/**
* Encodes an byte array: size + raw bytes.
*/
inline void encode_bytes(const uint8_t *bytes, size_t size, jbyte *dest) {
encode_int(size, dest);
memcpy(dest += 4, bytes, size);
}
/**
* Encodes an instance object.
*/
jbyteArray encode_instance(JNIEnv *env, struct evmc_instance *instance) {
int name_size = strlen(instance->name);
int version_size = strlen(instance->version);
int size = 8 + 4 + name_size + 4 + version_size + 4;
jbyte *buf = (jbyte *) malloc(size);
jbyte *ptr = buf;
// encode
encode_long((int64_t) instance, ptr);
encode_int(instance->abi_version, ptr + 8);
encode_bytes((const uint8_t *) instance->name, name_size, ptr += 4);
encode_bytes((const uint8_t *) instance->version, version_size, ptr +=
name_size);
// copy back
jbyteArray bytes = env->NewByteArray(size);
env->SetByteArrayRegion(bytes, 0, size, buf);
free(buf);
return bytes;
}
JNIEXPORT jbyteArray JNICALL Java_org_semux_evmc_jni_Native_create_1evmjit(
JNIEnv *env, jclass cls) {
struct evmc_instance *instance = evmjit_create();
if (instance == nullptr) {
return nullptr;
} else {
return encode_instance(env, instance);
}
}
JNIEXPORT void JNICALL Java_org_semux_evmc_jni_Native_set_1option(JNIEnv *env,
jclass cls, jlong p, jbyteArray name, jbyteArray value) {
struct evmc_instance *instance = (struct evmc_instance *) p;
// retrieve data
int name_size = env->GetArrayLength(name);
int value_size = env->GetArrayLength(value);
jbyte *name_buf = (jbyte *) malloc(name_size);
jbyte *value_buf = (jbyte *) malloc(value_size);
env->GetByteArrayRegion(name, 0, name_size, name_buf);
env->GetByteArrayRegion(value, 0, value_size, value_buf);
// set option
instance->set_option(instance, (const char*) name_buf,
(const char*) value_buf);
// release buffer
free(name_buf);
free(value_buf);
}
JNIEXPORT jbyteArray JNICALL Java_org_semux_evmc_jni_Native_execute(JNIEnv *env,
jclass cls, jlong p, jobject ctx, jint rev, jbyteArray msg,
jbyteArray code) {
return nullptr;
}
JNIEXPORT void JNICALL Java_org_semux_evmc_jni_Native_destroy(JNIEnv *env,
jclass cls, jlong p) {
struct evmc_instance *instance = (struct evmc_instance *) p;
instance->destroy(instance);
}
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/kernels/lstm_eval.h"
#include <algorithm>
#include <cstdint>
#include "tensorflow/lite/kernels/internal/compatibility.h"
#ifdef GEMMLOWP_PROFILING
#include "profiling/profiler.h"
#endif
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/c_api_internal.h"
#include "tensorflow/lite/kernels/internal/kernel_utils.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/internal/tensor_utils.h"
#include "tensorflow/lite/kernels/op_macros.h"
namespace tflite {
namespace ops {
namespace builtin {
namespace lstm_eval {
namespace {
// Small float to avoid divergence during calculation of deviation for layer
// norm lstm.
const float kLayerNormEpsilon = 1e-8;
// Performs an LSTM batch inference step for input specified by input_ptr_batch.
// The LSTM cell is specified by the pointers to its weights (*_weights_ptr) and
// biases (*_bias_ptr), and buffers (*_scratch), along with additional
// parameters:
// - params: various LSTM params including activation, clipping, etc.,
// - n_batch: size of batch,
// - n_cell: number of cells (or units),
// - n_input: the input size,
// - n_aux_input: the auxiliary input size.
// - n_output: the output size.
// - output_batch_leading_dim: the leading dimension of the output buffer.
//
// LSTM weights:
// Input weights of size 'n_cell * n_input':
// input_to_input_weights - optional (can be nullptr)
// input_to_forget_weights
// input_to_cell_weights
// input_to_output_weights
// Auxiliary input weights of size 'n_cell * n_aux_input':
// aux_input_to_input_weights - optional
// aux_input_to_forget_weights - optional
// aux_input_to_cell_weights - optional
// aux_input_to_output_weights - optional
// Recurrent weights of size 'n_cell * n_output':
// recurrent_to_input_weights - optional
// recurrent_to_forget_weights
// recurrent_to_cell_weights
// recurrent_to_input_weights
// Peephole weights of size 'n_cell', representing diagonal matrices.
// cell_to_input_weights - optional
// cell_to_cell_weights - optional
// cell_to_output_weights - optional
// Projection weights of size 'n_output * n_cell'
// projection_weights_ptr - optional
// Gate biases of size 'n_cell':
// input_gate_bias_ptr - optional
// forget_gate_bias_ptr
// cell_gate_bias_ptr
// output_gate_bias_ptr
//
// Layer norm coefficients of size 'n_cell', representing diagonal matrices.
// input_layer_norm_coefficients_ptr - optional
// forget_layer_norm_coefficients_ptr - optional
// cell_layer_norm_coefficients_ptr - optional
// output_layer_norm_coefficients_ptr - optional
//
// The pointers to the cell and output state and the output are updated.
//
// The pointers with the suffix "_batch" point to data aligned in batch_major
// order, and each step processes batch_size many inputs from input_ptr_batch,
// and updates batch_size many cell and output states.
//
// The output_batch_dim is output.shape[-1], i.e. the outermost dimension of the
// output tensor, and in most cases will be equal to n_output. It is usually not
// when we want to store the LSTM output into a slice of the output tensor, e.g.
// for bidirectional LSTMs with merge_outputs. In this case, the batched
// operations cannot be used since they assume that the batched outputs are
// contiguous, and we manually loop over the batched outputs.
inline void LstmStepWithAuxInput(
const float* input_ptr_batch, const float* input_to_input_weights_ptr,
const float* input_to_forget_weights_ptr,
const float* input_to_cell_weights_ptr,
const float* input_to_output_weights_ptr, const float* aux_input_ptr_batch,
const float* aux_input_to_input_weights_ptr,
const float* aux_input_to_forget_weights_ptr,
const float* aux_input_to_cell_weights_ptr,
const float* aux_input_to_output_weights_ptr,
const float* recurrent_to_input_weights_ptr,
const float* recurrent_to_forget_weights_ptr,
const float* recurrent_to_cell_weights_ptr,
const float* recurrent_to_output_weights_ptr,
const float* cell_to_input_weights_ptr,
const float* cell_to_forget_weights_ptr,
const float* cell_to_output_weights_ptr,
const float* input_layer_norm_coefficients_ptr,
const float* forget_layer_norm_coefficients_ptr,
const float* cell_layer_norm_coefficients_ptr,
const float* output_layer_norm_coefficients_ptr,
const float* input_gate_bias_ptr, const float* forget_gate_bias_ptr,
const float* cell_bias_ptr, const float* output_gate_bias_ptr,
const float* projection_weights_ptr, const float* projection_bias_ptr,
const TfLiteLSTMParams* params, int n_batch, int n_cell, int n_input,
int n_aux_input, int n_output, int output_batch_leading_dim,
float* output_state_ptr, float* cell_state_ptr, float* input_gate_scratch,
float* forget_gate_scratch, float* cell_scratch, float* output_gate_scratch,
float* output_ptr_batch) {
#ifdef GEMMLOWP_PROFILING
gemmlowp::ScopedProfilingLabel label("LstmStepWithAuxInputFloat");
#endif
// Since we have already checked that weights are all there or none, we can
// check the existence of only one to the get the condition.
const bool use_cifg = (input_to_input_weights_ptr == nullptr);
const bool use_peephole = (cell_to_output_weights_ptr != nullptr);
const bool is_layer_norm_lstm =
(forget_layer_norm_coefficients_ptr != nullptr);
// Initialize scratch buffers with bias for regular lstm or initialize with
// zero for layer norm lstm.
if (is_layer_norm_lstm) {
if (!use_cifg) {
std::fill_n(input_gate_scratch, n_cell * n_batch, 0.0f);
}
std::fill_n(forget_gate_scratch, n_cell * n_batch, 0.0f);
std::fill_n(cell_scratch, n_cell * n_batch, 0.0f);
std::fill_n(output_gate_scratch, n_cell * n_batch, 0.0f);
} else {
if (!use_cifg) {
tensor_utils::VectorBatchVectorAssign(input_gate_bias_ptr, n_cell,
n_batch, input_gate_scratch);
}
tensor_utils::VectorBatchVectorAssign(forget_gate_bias_ptr, n_cell, n_batch,
forget_gate_scratch);
tensor_utils::VectorBatchVectorAssign(cell_bias_ptr, n_cell, n_batch,
cell_scratch);
tensor_utils::VectorBatchVectorAssign(output_gate_bias_ptr, n_cell, n_batch,
output_gate_scratch);
}
// For each batch and cell: compute input_weight * input.
if (!use_cifg) {
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_to_input_weights_ptr, n_cell, n_input, input_ptr_batch, n_batch,
input_gate_scratch, /*result_stride=*/1);
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_to_forget_weights_ptr, n_cell, n_input, input_ptr_batch, n_batch,
forget_gate_scratch, /*result_stride=*/1);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_to_cell_weights_ptr, n_cell, n_input, input_ptr_batch, n_batch,
cell_scratch, /*result_stride=*/1);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_to_output_weights_ptr, n_cell, n_input, input_ptr_batch, n_batch,
output_gate_scratch, /*result_stride=*/1);
// If auxiliary input is available then compute aux_input_weight * aux_input
if (aux_input_ptr_batch != nullptr) {
if (!use_cifg) {
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
aux_input_to_input_weights_ptr, n_cell, n_aux_input,
aux_input_ptr_batch, n_batch, input_gate_scratch,
/*result_stride=*/1);
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
aux_input_to_forget_weights_ptr, n_cell, n_aux_input,
aux_input_ptr_batch, n_batch, forget_gate_scratch, /*result_stride=*/1);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
aux_input_to_cell_weights_ptr, n_cell, n_aux_input, aux_input_ptr_batch,
n_batch, cell_scratch, /*result_stride=*/1);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
aux_input_to_output_weights_ptr, n_cell, n_aux_input,
aux_input_ptr_batch, n_batch, output_gate_scratch, /*result_stride=*/1);
}
// For each batch and cell: compute recurrent_weight * output_state.
if (!use_cifg) {
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
recurrent_to_input_weights_ptr, n_cell, n_output, output_state_ptr,
n_batch, input_gate_scratch, /*result_stride=*/1);
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
recurrent_to_forget_weights_ptr, n_cell, n_output, output_state_ptr,
n_batch, forget_gate_scratch,
/*result_stride=*/1);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
recurrent_to_cell_weights_ptr, n_cell, n_output, output_state_ptr,
n_batch, cell_scratch, /*result_stride=*/1);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
recurrent_to_output_weights_ptr, n_cell, n_output, output_state_ptr,
n_batch, output_gate_scratch,
/*result_stride=*/1);
// For each batch and cell: update input gate.
if (!use_cifg) {
if (use_peephole) {
tensor_utils::VectorBatchVectorCwiseProductAccumulate(
cell_to_input_weights_ptr, n_cell, cell_state_ptr, n_batch,
input_gate_scratch);
}
if (is_layer_norm_lstm) {
tensor_utils::MeanStddevNormalization(input_gate_scratch,
input_gate_scratch, n_cell, n_batch,
kLayerNormEpsilon);
tensor_utils::VectorBatchVectorCwiseProduct(
input_layer_norm_coefficients_ptr, n_cell, input_gate_scratch,
n_batch, input_gate_scratch);
tensor_utils::VectorBatchVectorAdd(input_gate_bias_ptr, n_cell, n_batch,
input_gate_scratch);
}
tensor_utils::ApplySigmoidToVector(input_gate_scratch, n_cell * n_batch,
input_gate_scratch);
}
// For each batch and cell: update forget gate.
if (use_peephole) {
tensor_utils::VectorBatchVectorCwiseProductAccumulate(
cell_to_forget_weights_ptr, n_cell, cell_state_ptr, n_batch,
forget_gate_scratch);
}
if (is_layer_norm_lstm) {
tensor_utils::MeanStddevNormalization(forget_gate_scratch,
forget_gate_scratch, n_cell, n_batch,
kLayerNormEpsilon);
tensor_utils::VectorBatchVectorCwiseProduct(
forget_layer_norm_coefficients_ptr, n_cell, forget_gate_scratch,
n_batch, forget_gate_scratch);
tensor_utils::VectorBatchVectorAdd(forget_gate_bias_ptr, n_cell, n_batch,
forget_gate_scratch);
}
tensor_utils::ApplySigmoidToVector(forget_gate_scratch, n_cell * n_batch,
forget_gate_scratch);
// For each batch and cell: update the cell.
tensor_utils::VectorVectorCwiseProduct(forget_gate_scratch, cell_state_ptr,
n_batch * n_cell, cell_state_ptr);
if (is_layer_norm_lstm) {
tensor_utils::MeanStddevNormalization(cell_scratch, cell_scratch, n_cell,
n_batch, kLayerNormEpsilon);
tensor_utils::VectorBatchVectorCwiseProduct(
cell_layer_norm_coefficients_ptr, n_cell, cell_scratch, n_batch,
cell_scratch);
tensor_utils::VectorBatchVectorAdd(cell_bias_ptr, n_cell, n_batch,
cell_scratch);
}
tensor_utils::ApplyActivationToVector(cell_scratch, n_batch * n_cell,
params->activation, cell_scratch);
if (use_cifg) {
tensor_utils::Sub1Vector(forget_gate_scratch, n_batch * n_cell,
forget_gate_scratch);
tensor_utils::VectorVectorCwiseProductAccumulate(
cell_scratch, forget_gate_scratch, n_batch * n_cell, cell_state_ptr);
} else {
tensor_utils::VectorVectorCwiseProductAccumulate(
cell_scratch, input_gate_scratch, n_batch * n_cell, cell_state_ptr);
}
if (params->cell_clip > 0.0) {
tensor_utils::ClipVector(cell_state_ptr, n_batch * n_cell,
params->cell_clip, cell_state_ptr);
}
// For each batch and cell: update the output gate.
if (use_peephole) {
tensor_utils::VectorBatchVectorCwiseProductAccumulate(
cell_to_output_weights_ptr, n_cell, cell_state_ptr, n_batch,
output_gate_scratch);
}
if (is_layer_norm_lstm) {
tensor_utils::MeanStddevNormalization(output_gate_scratch,
output_gate_scratch, n_cell, n_batch,
kLayerNormEpsilon);
tensor_utils::VectorBatchVectorCwiseProduct(
output_layer_norm_coefficients_ptr, n_cell, output_gate_scratch,
n_batch, output_gate_scratch);
tensor_utils::VectorBatchVectorAdd(output_gate_bias_ptr, n_cell, n_batch,
output_gate_scratch);
}
tensor_utils::ApplySigmoidToVector(output_gate_scratch, n_batch * n_cell,
output_gate_scratch);
tensor_utils::ApplyActivationToVector(cell_state_ptr, n_batch * n_cell,
params->activation, cell_scratch);
tensor_utils::VectorVectorCwiseProduct(output_gate_scratch, cell_scratch,
n_batch * n_cell, output_gate_scratch);
const bool use_projection_weight = (projection_weights_ptr != nullptr);
const bool use_projection_bias = (projection_bias_ptr != nullptr);
// For each batch: update the projection and output_state. Note that since
// the output batch rows may not be contiguous (output_batch_leading_dim !=
// n_output), we unroll the batched operations where this is the case.
if (output_batch_leading_dim == n_output) {
if (use_projection_weight) {
if (use_projection_bias) {
tensor_utils::VectorBatchVectorAssign(projection_bias_ptr, n_output,
n_batch, output_ptr_batch);
} else {
std::fill_n(output_ptr_batch, n_batch * n_output, 0.0f);
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
projection_weights_ptr, n_output, n_cell, output_gate_scratch,
n_batch, output_ptr_batch, /*result_stride=*/1);
if (params->proj_clip > 0.0) {
tensor_utils::ClipVector(output_ptr_batch, n_batch * n_output,
params->proj_clip, output_ptr_batch);
}
} else {
std::copy_n(output_gate_scratch, n_batch * n_output, output_ptr_batch);
}
std::copy_n(output_ptr_batch, n_batch * n_output, output_state_ptr);
} else {
if (use_projection_weight) {
if (use_projection_bias) {
for (int k = 0; k < n_batch; k++) {
std::copy_n(projection_bias_ptr, n_output,
output_ptr_batch + k * output_batch_leading_dim);
}
} else {
for (int k = 0; k < n_batch; k++) {
std::fill_n(output_ptr_batch + k * output_batch_leading_dim, n_output,
0.0f);
}
}
for (int k = 0; k < n_batch; k++) {
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
projection_weights_ptr, n_output, n_cell,
output_gate_scratch + k * n_cell,
/*n_batch=*/1, output_ptr_batch + k * output_batch_leading_dim,
/*result_stride=*/1);
if (params->proj_clip > 0.0) {
tensor_utils::ClipVector(
output_ptr_batch + k * output_batch_leading_dim, n_output,
params->proj_clip,
output_ptr_batch + k * output_batch_leading_dim);
}
}
} else {
for (int k = 0; k < n_batch; k++) {
std::copy_n(output_gate_scratch + k * n_output, n_output,
output_ptr_batch + k * output_batch_leading_dim);
}
}
for (int k = 0; k < n_batch; k++) {
std::copy_n(output_ptr_batch + k * output_batch_leading_dim, n_output,
output_state_ptr + k * n_output);
}
}
}
void ApplyActivationsToVector(float* input, int input_size,
TfLiteFusedActivation activation_type,
float* output) {
using VectorMap = Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, 1>>;
VectorMap input_map(input, input_size, 1);
VectorMap output_map(output, input_size, 1);
switch (activation_type) {
case kTfLiteActSigmoid: {
output_map.array() = input_map.array().logistic();
break;
}
case kTfLiteActTanh: {
output_map.array() = input_map.array().tanh();
break;
}
default: {
tensor_utils::ApplyActivationToVector(input, input_size, activation_type,
output);
}
}
}
// Same as above but with quantized weight matrices. In detail:
// Input of size 'n_batch * n_input':
// input_ptr_batch
//
// LSTM weights:
// Quantized input weights of size 'n_cell * n_input':
// input_to_input_weights - optional (can be nullptr)
// input_to_forget_weights
// input_to_cell_weights
// input_to_input_weights
// Quantized auxiliary input weights of size 'n_cell * n_aux_input':
// aux_input_to_input_weights - optional
// aux_input_to_forget_weights - optional
// aux_input_to_cell_weights - optional
// aux_input_to_output_weights - optional
// Quantized recurrent weights of size 'n_cell * n_output':
// recurrent_to_input_weights - optional
// recurrent_to_forget_weights
// recurrent_to_cell_weights
// recurrent_to_input_weights
// Quantized peephole weights of size 'n_cell', representing diagonal matrices.
// cell_to_input_weights - optional
// cell_to_cell_weights - optional
// cell_to_output_weights - optional
// Quantized projection weights of size 'n_output * n_cell'
// projection_weights_ptr - optional
// Weight scales (scalars) for each of the weights above.
// input_to_input_weights_scale - optional
// input_to_forget_weights_scale
// input_to_cell_weights_scale
// input_to_output_weights_scale
// aux_input_to_input_weights_scale - optional
// aux_input_to_forget_weights_scale - optional
// aux_input_to_cell_weights_scale - optional
// aux_input_to_output_weights_scale - optional
// recurrent_to_input_weights_scale - optional
// recurrent_to_forget_weights_scale
// recurrent_to_cell_weights_scale
// recurrent_to_output_weights_scale
// cell_to_input_weights_scale,
// cell_to_forget_weights_scale,
// cell_to_output_weights_scale,
// projection_weights_scale - optional
// Gate biases of size 'n_cell':
// input_gate_bias_ptr - optional
// forget_gate_bias_ptr
// cell_gate_bias_ptr
// output_gate_bias_ptr
//
// Layer norm coefficients of size 'n_cell', representing diagonal matrices.
// input_layer_norm_coefficients_ptr - optional
// forget_layer_norm_coefficients_ptr - optional
// cell_layer_norm_coefficients_ptr - optional
// output_layer_norm_coefficients_ptr - optional
//
// Temporary pre-allocated storage for quantized values:
// quantized_input_ptr_batch (same size as input_ptr_batch)
// quantized_output_state_ptr (same size as output_state_ptr)
// quantized_cell_state_ptr (same size as cell_state_ptr)
// Temporary pre-allocated storage for recovered values:
// recovered_cell_weights (same size as cell_to_*_weights)
//
// Outputs:
// output_state_ptr - size 'n_batch * n_output'
// cell_state_ptr - size 'n_batch * n_cell'
// output_ptr_batch - size 'n_batch * output_batch_leading_dim'
inline void LstmStepWithAuxInput(
const float* input_ptr_batch, const int8_t* input_to_input_weights_ptr,
float input_to_input_weights_scale,
const int8_t* input_to_forget_weights_ptr,
float input_to_forget_weights_scale,
const int8_t* input_to_cell_weights_ptr, float input_to_cell_weights_scale,
const int8_t* input_to_output_weights_ptr,
float input_to_output_weights_scale, const float* aux_input_ptr_batch,
const int8_t* aux_input_to_input_weights_ptr,
float aux_input_to_input_weights_scale,
const int8_t* aux_input_to_forget_weights_ptr,
float aux_input_to_forget_weights_scale,
const int8_t* aux_input_to_cell_weights_ptr,
float aux_input_to_cell_weights_scale,
const int8_t* aux_input_to_output_weights_ptr,
float aux_input_to_output_weights_scale,
const int8_t* recurrent_to_input_weights_ptr,
float recurrent_to_input_weights_scale,
const int8_t* recurrent_to_forget_weights_ptr,
float recurrent_to_forget_weights_scale,
const int8_t* recurrent_to_cell_weights_ptr,
float recurrent_to_cell_weights_scale,
const int8_t* recurrent_to_output_weights_ptr,
float recurrent_to_output_weights_scale,
const int8_t* cell_to_input_weights_ptr, float cell_to_input_weights_scale,
const int8_t* cell_to_forget_weights_ptr,
float cell_to_forget_weights_scale,
const int8_t* cell_to_output_weights_ptr,
float cell_to_output_weights_scale,
const float* input_layer_norm_coefficients_ptr,
const float* forget_layer_norm_coefficients_ptr,
const float* cell_layer_norm_coefficients_ptr,
const float* output_layer_norm_coefficients_ptr,
const float* input_gate_bias_ptr, const float* forget_gate_bias_ptr,
const float* cell_bias_ptr, const float* output_gate_bias_ptr,
const int8_t* projection_weights_ptr, float projection_weights_scale,
const float* projection_bias_ptr, const TfLiteLSTMParams* params,
int n_batch, int n_cell, int n_input, int n_aux_input, int n_output,
int output_batch_leading_dim, float* input_gate_scratch,
float* forget_gate_scratch, float* cell_scratch, float* output_gate_scratch,
float* scaling_factors, float* product_scaling_factors,
float* recovered_cell_weights, int8_t* quantized_input_ptr_batch,
int8_t* quantized_aux_input_ptr_batch, int8_t* quantized_output_state_ptr,
int8_t* quantized_cell_state_ptr, float* output_state_ptr,
float* cell_state_ptr, float* output_ptr_batch) {
#ifdef GEMMLOWP_PROFILING
gemmlowp::ScopedProfilingLabel label("LstmStepWithAuxInputHybrid");
#endif
// Since we have already checked that weights are all there or none, we
// can check the existence of only one to the get the condition.
const bool use_cifg = (input_to_input_weights_ptr == nullptr);
const bool use_peephole = (cell_to_output_weights_ptr != nullptr);
const bool is_layer_norm_lstm =
(forget_layer_norm_coefficients_ptr != nullptr);
// Initialize scratch buffers with bias.
if (is_layer_norm_lstm) {
if (!use_cifg) {
std::fill_n(input_gate_scratch, n_cell * n_batch, 0.0f);
}
std::fill_n(forget_gate_scratch, n_cell * n_batch, 0.0f);
std::fill_n(cell_scratch, n_cell * n_batch, 0.0f);
std::fill_n(output_gate_scratch, n_cell * n_batch, 0.0f);
} else {
if (!use_cifg) {
tensor_utils::VectorBatchVectorAssign(input_gate_bias_ptr, n_cell,
n_batch, input_gate_scratch);
}
tensor_utils::VectorBatchVectorAssign(forget_gate_bias_ptr, n_cell, n_batch,
forget_gate_scratch);
tensor_utils::VectorBatchVectorAssign(cell_bias_ptr, n_cell, n_batch,
cell_scratch);
tensor_utils::VectorBatchVectorAssign(output_gate_bias_ptr, n_cell, n_batch,
output_gate_scratch);
}
if (!tensor_utils::IsZeroVector(input_ptr_batch, n_batch * n_input)) {
// Save quantization and matmul computation for all zero input.
float unused_min, unused_max;
for (int b = 0; b < n_batch; ++b) {
const int offset = b * n_input;
tensor_utils::SymmetricQuantizeFloats(
input_ptr_batch + offset, n_input, quantized_input_ptr_batch + offset,
&unused_min, &unused_max, &scaling_factors[b]);
}
// For each batch and cell: compute input_weight * input.
if (!use_cifg) {
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * input_to_input_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_to_input_weights_ptr, n_cell, n_input,
quantized_input_ptr_batch, product_scaling_factors, n_batch,
input_gate_scratch, /*result_stride=*/1);
}
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * input_to_forget_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_to_forget_weights_ptr, n_cell, n_input, quantized_input_ptr_batch,
product_scaling_factors, n_batch, forget_gate_scratch,
/*result_stride=*/1);
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * input_to_cell_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_to_cell_weights_ptr, n_cell, n_input, quantized_input_ptr_batch,
product_scaling_factors, n_batch, cell_scratch, /*result_stride=*/1);
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * input_to_output_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_to_output_weights_ptr, n_cell, n_input, quantized_input_ptr_batch,
product_scaling_factors, n_batch, output_gate_scratch,
/*result_stride=*/1);
}
if (aux_input_ptr_batch != nullptr &&
!tensor_utils::IsZeroVector(aux_input_ptr_batch, n_batch * n_input)) {
// Save quantization and matmul computation for all zero input.
float unused_min, unused_max;
for (int b = 0; b < n_batch; ++b) {
const int offset = b * n_input;
tensor_utils::SymmetricQuantizeFloats(
aux_input_ptr_batch + offset, n_input,
quantized_aux_input_ptr_batch + offset, &unused_min, &unused_max,
&scaling_factors[b]);
}
// For each batch and cell: compute input_weight * input.
if (!use_cifg) {
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * aux_input_to_input_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
aux_input_to_input_weights_ptr, n_cell, n_input,
quantized_aux_input_ptr_batch, product_scaling_factors, n_batch,
input_gate_scratch, /*result_stride=*/1);
}
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * aux_input_to_forget_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
aux_input_to_forget_weights_ptr, n_cell, n_input,
quantized_aux_input_ptr_batch, product_scaling_factors, n_batch,
forget_gate_scratch, /*result_stride=*/1);
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * aux_input_to_cell_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
aux_input_to_cell_weights_ptr, n_cell, n_input,
quantized_aux_input_ptr_batch, product_scaling_factors, n_batch,
cell_scratch, /*result_stride=*/1);
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * aux_input_to_output_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
aux_input_to_output_weights_ptr, n_cell, n_input,
quantized_aux_input_ptr_batch, product_scaling_factors, n_batch,
output_gate_scratch, /*result_stride=*/1);
}
if (!tensor_utils::IsZeroVector(output_state_ptr, n_batch * n_output)) {
// Save quantization and matmul computation for all zero input.
float unused_min, unused_max;
for (int b = 0; b < n_batch; ++b) {
const int offset = b * n_output;
tensor_utils::SymmetricQuantizeFloats(output_state_ptr + offset, n_output,
quantized_output_state_ptr + offset,
&unused_min, &unused_max,
&scaling_factors[b]);
}
// For each batch and cell: compute recurrent_weight * output_state.
if (!use_cifg) {
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * recurrent_to_input_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
recurrent_to_input_weights_ptr, n_cell, n_output,
quantized_output_state_ptr, product_scaling_factors, n_batch,
input_gate_scratch, /*result_stride=*/1);
}
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * recurrent_to_forget_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
recurrent_to_forget_weights_ptr, n_cell, n_output,
quantized_output_state_ptr, product_scaling_factors, n_batch,
forget_gate_scratch, /*result_stride=*/1);
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * recurrent_to_cell_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
recurrent_to_cell_weights_ptr, n_cell, n_output,
quantized_output_state_ptr, product_scaling_factors, n_batch,
cell_scratch, /*result_stride=*/1);
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * recurrent_to_output_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
recurrent_to_output_weights_ptr, n_cell, n_output,
quantized_output_state_ptr, product_scaling_factors, n_batch,
output_gate_scratch, /*result_stride=*/1);
}
// Save quantization and matmul computation for all zero input.
bool is_cell_state_all_zeros =
tensor_utils::IsZeroVector(cell_state_ptr, n_batch * n_cell);
// For each batch and cell: update input gate.
if (!use_cifg) {
if (use_peephole && !is_cell_state_all_zeros) {
tensor_utils::VectorScalarMultiply(cell_to_input_weights_ptr, n_cell,
cell_to_input_weights_scale,
recovered_cell_weights);
tensor_utils::VectorBatchVectorCwiseProductAccumulate(
recovered_cell_weights, n_cell, cell_state_ptr, n_batch,
input_gate_scratch);
}
if (is_layer_norm_lstm) {
tensor_utils::MeanStddevNormalization(input_gate_scratch,
input_gate_scratch, n_cell, n_batch,
kLayerNormEpsilon);
tensor_utils::VectorBatchVectorCwiseProduct(
input_layer_norm_coefficients_ptr, n_cell, input_gate_scratch,
n_batch, input_gate_scratch);
tensor_utils::VectorBatchVectorAdd(input_gate_bias_ptr, n_cell, n_batch,
input_gate_scratch);
}
ApplyActivationsToVector(input_gate_scratch, n_cell * n_batch,
kTfLiteActSigmoid, input_gate_scratch);
}
// For each batch and cell: update forget gate.
if (use_peephole && !is_cell_state_all_zeros) {
tensor_utils::VectorScalarMultiply(cell_to_forget_weights_ptr, n_cell,
cell_to_forget_weights_scale,
recovered_cell_weights);
tensor_utils::VectorBatchVectorCwiseProductAccumulate(
recovered_cell_weights, n_cell, cell_state_ptr, n_batch,
forget_gate_scratch);
}
if (is_layer_norm_lstm) {
tensor_utils::MeanStddevNormalization(forget_gate_scratch,
forget_gate_scratch, n_cell, n_batch,
kLayerNormEpsilon);
tensor_utils::VectorBatchVectorCwiseProduct(
forget_layer_norm_coefficients_ptr, n_cell, forget_gate_scratch,
n_batch, forget_gate_scratch);
tensor_utils::VectorBatchVectorAdd(forget_gate_bias_ptr, n_cell, n_batch,
forget_gate_scratch);
}
ApplyActivationsToVector(forget_gate_scratch, n_cell * n_batch,
kTfLiteActSigmoid, forget_gate_scratch);
// For each batch and cell: update the cell.
tensor_utils::VectorVectorCwiseProduct(forget_gate_scratch, cell_state_ptr,
n_batch * n_cell, cell_state_ptr);
if (is_layer_norm_lstm) {
tensor_utils::MeanStddevNormalization(cell_scratch, cell_scratch, n_cell,
n_batch, kLayerNormEpsilon);
tensor_utils::VectorBatchVectorCwiseProduct(
cell_layer_norm_coefficients_ptr, n_cell, cell_scratch, n_batch,
cell_scratch);
tensor_utils::VectorBatchVectorAdd(cell_bias_ptr, n_cell, n_batch,
cell_scratch);
}
ApplyActivationsToVector(cell_scratch, n_batch * n_cell, params->activation,
cell_scratch);
if (use_cifg) {
tensor_utils::Sub1Vector(forget_gate_scratch, n_batch * n_cell,
forget_gate_scratch);
tensor_utils::VectorVectorCwiseProductAccumulate(
cell_scratch, forget_gate_scratch, n_batch * n_cell, cell_state_ptr);
} else {
tensor_utils::VectorVectorCwiseProductAccumulate(
cell_scratch, input_gate_scratch, n_batch * n_cell, cell_state_ptr);
}
if (params->cell_clip > 0.0) {
tensor_utils::ClipVector(cell_state_ptr, n_batch * n_cell,
params->cell_clip, cell_state_ptr);
}
is_cell_state_all_zeros =
tensor_utils::IsZeroVector(cell_state_ptr, n_batch * n_cell);
// For each batch and cell: update the output gate.
if (use_peephole && !is_cell_state_all_zeros) {
tensor_utils::VectorScalarMultiply(cell_to_output_weights_ptr, n_cell,
cell_to_output_weights_scale,
recovered_cell_weights);
tensor_utils::VectorBatchVectorCwiseProductAccumulate(
recovered_cell_weights, n_cell, cell_state_ptr, n_batch,
output_gate_scratch);
}
if (is_layer_norm_lstm) {
tensor_utils::MeanStddevNormalization(output_gate_scratch,
output_gate_scratch, n_cell, n_batch,
kLayerNormEpsilon);
tensor_utils::VectorBatchVectorCwiseProduct(
output_layer_norm_coefficients_ptr, n_cell, output_gate_scratch,
n_batch, output_gate_scratch);
tensor_utils::VectorBatchVectorAdd(output_gate_bias_ptr, n_cell, n_batch,
output_gate_scratch);
}
ApplyActivationsToVector(output_gate_scratch, n_batch * n_cell,
kTfLiteActSigmoid, output_gate_scratch);
ApplyActivationsToVector(cell_state_ptr, n_batch * n_cell, params->activation,
cell_scratch);
tensor_utils::VectorVectorCwiseProduct(output_gate_scratch, cell_scratch,
n_batch * n_cell, output_gate_scratch);
const bool use_projection_weight = (projection_weights_ptr != nullptr);
const bool use_projection_bias = (projection_bias_ptr != nullptr);
// For each batch: update the projection and output_state. Note that since
// the output batch rows may not be contiguous (output_batch_leading_dim !=
// n_output), we unroll the batched operations where this is the case.
if (output_batch_leading_dim == n_output) {
if (use_projection_weight) {
if (use_projection_bias) {
tensor_utils::VectorBatchVectorAssign(projection_bias_ptr, n_output,
n_batch, output_ptr_batch);
} else {
std::fill_n(output_ptr_batch, n_batch * n_output, 0.0f);
}
if (!tensor_utils::IsZeroVector(output_gate_scratch, n_batch * n_cell)) {
// Save quantization and matmul computation for all zero input.
float unused_min, unused_max;
for (int b = 0; b < n_batch; ++b) {
const int offset = b * n_cell;
tensor_utils::SymmetricQuantizeFloats(
output_gate_scratch + offset, n_cell,
quantized_cell_state_ptr + offset, &unused_min, &unused_max,
&scaling_factors[b]);
}
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * projection_weights_scale;
}
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
projection_weights_ptr, n_output, n_cell, quantized_cell_state_ptr,
product_scaling_factors, n_batch, output_ptr_batch,
/*result_stride=*/1);
}
if (params->proj_clip > 0.0) {
tensor_utils::ClipVector(output_ptr_batch, n_batch * n_output,
params->proj_clip, output_ptr_batch);
}
} else {
std::copy_n(output_gate_scratch, n_batch * n_output, output_ptr_batch);
}
std::copy_n(output_ptr_batch, n_batch * n_output, output_state_ptr);
} else {
if (use_projection_weight) {
if (use_projection_bias) {
for (int k = 0; k < n_batch; k++) {
std::copy_n(projection_bias_ptr, n_output,
output_ptr_batch + k * output_batch_leading_dim);
}
} else {
for (int k = 0; k < n_batch; k++) {
std::fill_n(output_ptr_batch + k * output_batch_leading_dim, n_output,
0.0f);
}
}
if (!tensor_utils::IsZeroVector(output_gate_scratch, n_batch * n_cell)) {
// Save quantization and matmul computation for all zero input.
float unused_min, unused_max;
for (int b = 0; b < n_batch; ++b) {
const int offset = b * n_cell;
tensor_utils::SymmetricQuantizeFloats(
output_gate_scratch + offset, n_cell,
quantized_cell_state_ptr + offset, &unused_min, &unused_max,
&scaling_factors[b]);
}
for (int b = 0; b < n_batch; ++b) {
product_scaling_factors[b] =
scaling_factors[b] * projection_weights_scale;
}
for (int k = 0; k < n_batch; k++) {
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
projection_weights_ptr, n_output, n_cell,
quantized_cell_state_ptr + k * n_cell,
&product_scaling_factors[k],
/*n_batch=*/1, output_ptr_batch + k * output_batch_leading_dim,
/*result_stride=*/1);
}
}
if (params->proj_clip > 0.0) {
for (int k = 0; k < n_batch; k++) {
tensor_utils::ClipVector(
output_ptr_batch + k * output_batch_leading_dim, n_output,
params->proj_clip,
output_ptr_batch + k * output_batch_leading_dim);
}
}
} else {
for (int k = 0; k < n_batch; k++) {
std::copy_n(output_gate_scratch + k * n_output, n_output,
output_ptr_batch + k * output_batch_leading_dim);
}
}
for (int k = 0; k < n_batch; k++) {
std::copy_n(output_ptr_batch + k * output_batch_leading_dim, n_output,
output_state_ptr + k * n_output);
}
}
}
// Fully quantized lstm kernel. Currently supports both cifg and non-cifg.
//
// Input activatoin of size n_batch * n_input:
// input_ptr
//
// LSTM weights:
// Quantized input weights of size 'n_cell * n_input':
// input_to_input_weight_ptr - optional
// input_to_forget_weight_ptr - optional
// input_to_cell_weight_ptr - optional
// input_to_output_weight_ptr - optional
//
// Quantized recurrent weights of size 'n_cell * n_output':
// recurrent_to_input_weight_ptr - optional
// recurrent_to_forget_weights_ptr
// recurrent_to_cell_weights_ptr
// recurrent_to_input_weights_ptr
//
// Quantized peephole weights of size 'n_cell', representing diagonal matrices.
// cell_to_input_weights - optional
// cell_to_cell_weights - optional
// cell_to_output_weights - optional
//
// Quantized projection weights of size 'n_output * n_cell'
// proj_weight_ptr - optional
//
// Weight scales (scalars) for each of the weights above.
// effective_input_to_input_scale_a - optional
// effective_input_to_input_scale_b - optional
// effective_input_to_forget_scale_a
// effective_input_to_forget_scale_b
// effective_input_to_cell_scale_a
// effective_input_to_cell_scale_b
// effective_input_to_output_scale_a
// effective_input_to_output_scale_b
// effective_recurrent_to_input_scale_a - optional
// effective_recurrent_to_input_scale_b - optional
// effective_recurrent_to_forget_scale_a
// effective_recurrent_to_forget_scale_b
// effective_recurrent_to_cell_scale_a
// effective_recurrent_to_cell_scale_b
// effective_recurrent_to_output_scale_a
// effective_recurrent_to_output_scale_b
// effective_proj_scale_a - optional
// effective_proj_scale_b - optional
//
// Gate biases of size 'n_cell':
// input_bias_ptr - optional
// forget_bias_ptr
// cell_bias_ptr
// output_bias_ptr
//
// Layer norm coefficients of size 'n_cell', representing diagonal matrices.
// layer_norm_input_weight_ptr - optional
// layer_norm_forput_weight_ptr - optional
// layer_norm_cell_weight_ptr - optional
// layer_norm_output_weight_ptr - optional
//
// Layer norm scales of size 'n_cell'.
// layer_norm_input_scale_a - optional
// layer_norm_input_scale_b - optional
// layer_norm_forget_scale_a - optional
// layer_norm_forget_scale_b - optional
// layer_norm_cell_scale_a - optional
// layer_norm_cell_scale_b - optional
// layer_norm_output_scale_a - optional
// layer_norm_output_scale_b - optional
//
// Scalar values:
// quantized_cell_clip: quantized clip value for cell.
// quantized_proj_clip: quantized clip value for projection.
// cell_scale: the POT scale for cell state.
//
// Zero points:
// activation_zp: zero point of activation
// hidden_zp: zero point for hidden state.
//
// Temporary pre-allocated storage for the calculation. Each is of size n_cell *
// n_batch.
// scratch_0:
// scratch_1
// scratch_2
// scratch_3
// scratch_4
// scratch_5: this scratch buffer is created purely for optimizing the
// MatrixBatchVectorMultiplyAccumulate.
//
// Outputs:
// output_state_ptr - size 'n_batch * n_output'
// cell_state_ptr - size 'n_batch * n_cell'
// output_ptr - size 'n_batch * n_output'
inline void LstmStepQuantized(
const int8_t* input_ptr, const int8_t* input_to_input_weight_ptr,
int32_t effective_input_to_input_scale_a,
int32_t effective_input_to_input_scale_b,
const int8_t* input_to_forget_weight_ptr,
int32_t effective_input_to_forget_scale_a,
int32_t effective_input_to_forget_scale_b,
const int8_t* input_to_cell_weight_ptr,
int32_t effective_input_to_cell_scale_a,
int32_t effective_input_to_cell_scale_b,
const int8_t* input_to_output_weight_ptr,
int32_t effective_input_to_output_scale_a,
int32_t effective_input_to_output_scale_b,
const int8_t* recurrent_to_input_weight_ptr,
int32_t effective_recurrent_to_input_scale_a,
int32_t effective_recurrent_to_input_scale_b,
const int8_t* recurrent_to_forget_weight_ptr,
int32_t effective_recurrent_to_forget_scale_a,
int32_t effective_recurrent_to_forget_scale_b,
const int8_t* recurrent_to_cell_weight_ptr,
int32_t effective_recurrent_to_cell_scale_a,
int32_t effective_recurrent_to_cell_scale_b,
const int8_t* recurrent_to_output_weight_ptr,
int32_t effective_recurrent_to_output_scale_a,
int32_t effective_recurrent_to_output_scale_b,
const int8_t* cell_to_input_weight_ptr,
int32_t effective_cell_to_input_scale_a,
int32_t effective_cell_to_input_scale_b,
const int8_t* cell_to_forget_weight_ptr,
int32_t effective_cell_to_forget_scale_a,
int32_t effective_cell_to_forget_scale_b,
const int8_t* cell_to_output_weight_ptr,
int32_t effective_cell_to_output_scale_a,
int32_t effective_cell_to_output_scale_b, const int8_t* proj_weight_ptr,
int32_t effective_proj_scale_a, int32_t effective_proj_scale_b,
int32_t hidden_zp, int32_t effective_hidden_scale_a,
int32_t effective_hidden_scale_b,
const int16_t* layer_norm_input_weight_ptr,
int32_t layer_norm_input_scale_a, int32_t layer_norm_input_scale_b,
const int16_t* layer_norm_forget_weight_ptr,
int32_t layer_norm_forget_scale_a, int32_t layer_norm_forget_scale_b,
const int16_t* layer_norm_cell_weight_ptr, int32_t layer_norm_cell_scale_a,
int32_t layer_norm_cell_scale_b,
const int16_t* layer_norm_output_weight_ptr,
int32_t layer_norm_output_scale_a, int32_t layer_norm_output_scale_b,
const int32_t* input_bias_ptr, const int32_t* forget_bias_ptr,
const int32_t* cell_bias_ptr, const int32_t* output_bias_ptr,
int16_t quantized_cell_clip, int8_t quantized_proj_clip, int32_t cell_scale,
const int32_t* inv_large_value,
const int32_t* input_to_forget_effective_bias,
const int32_t* recurrent_to_forget_effective_bias,
const int32_t* input_to_cell_effective_bias,
const int32_t* recurrent_to_cell_effective_bias,
const int32_t* input_to_output_effective_bias,
const int32_t* recurrent_to_output_effective_bias,
const int32_t* input_to_input_effective_bias,
const int32_t* recurrent_to_input_effective_bias,
const int32_t* projection_effective_bias, int32 n_batch, int32 n_cell,
int32 n_input, int32 n_output, int32 output_batch_leading_dim,
int8_t* activation_ptr, int32_t activation_zp, int16_t* cell_ptr,
int8_t* output_ptr, int16_t* scratch_0_ptr, int16_t* scratch_1_ptr,
int16_t* scratch_2_ptr, int16_t* scratch_3_ptr, int8_t* scratch_4_ptr,
int32_t* scratch_5_ptr) {
TFLITE_DCHECK(input_to_forget_effective_bias);
TFLITE_DCHECK(recurrent_to_forget_effective_bias);
TFLITE_DCHECK(input_to_cell_effective_bias);
TFLITE_DCHECK(recurrent_to_cell_effective_bias);
TFLITE_DCHECK(input_to_output_effective_bias);
TFLITE_DCHECK(recurrent_to_output_effective_bias);
TFLITE_DCHECK(input_to_input_effective_bias);
TFLITE_DCHECK(recurrent_to_input_effective_bias);
TFLITE_DCHECK(projection_effective_bias);
const bool use_cifg = (input_to_input_weight_ptr == nullptr);
// TODO(renjieliu): Handle optional arguments processing here:
// case cifg: input_to_input_weights should be nullptr
// recurrent_to_input_weight should be nullptr
// input_bias should be nullptr
// case not peephole: cell_to_forget_weight should be nullptr
// cell_to_output_weight should be nullptr
// cifg: cell_to_input_weight should be nullptr
// Set scratch to 0.
memset(scratch_0_ptr, 0, n_batch * n_cell * sizeof(int16_t));
memset(scratch_1_ptr, 0, n_batch * n_cell * sizeof(int16_t));
memset(scratch_2_ptr, 0, n_batch * n_cell * sizeof(int16_t));
memset(scratch_3_ptr, 0, n_batch * n_cell * sizeof(int16_t));
// Forget gate.
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_ptr, input_to_forget_effective_bias, input_to_forget_weight_ptr,
effective_input_to_forget_scale_a, effective_input_to_forget_scale_b,
n_batch, n_input, n_cell, 0, scratch_5_ptr, scratch_1_ptr);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
activation_ptr, recurrent_to_forget_effective_bias,
recurrent_to_forget_weight_ptr, effective_recurrent_to_forget_scale_a,
effective_recurrent_to_forget_scale_b, n_batch, n_output, n_cell, 0,
scratch_5_ptr, scratch_1_ptr);
if (layer_norm_forget_weight_ptr != nullptr) {
tensor_utils::ApplyLayerNorm(scratch_1_ptr, layer_norm_forget_weight_ptr,
forget_bias_ptr, layer_norm_forget_scale_a,
layer_norm_forget_scale_b, inv_large_value[1],
n_batch, n_cell, scratch_1_ptr);
}
tensor_utils::ApplySigmoid(scratch_1_ptr, n_batch, n_cell, scratch_1_ptr);
// Modulation gate.
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_ptr, input_to_cell_effective_bias, input_to_cell_weight_ptr,
effective_input_to_cell_scale_a, effective_input_to_cell_scale_b, n_batch,
n_input, n_cell, 0, scratch_5_ptr, scratch_2_ptr);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
activation_ptr, recurrent_to_cell_effective_bias,
recurrent_to_cell_weight_ptr, effective_recurrent_to_cell_scale_a,
effective_recurrent_to_cell_scale_b, n_batch, n_output, n_cell, 0,
scratch_5_ptr, scratch_2_ptr);
if (layer_norm_cell_weight_ptr != nullptr) {
tensor_utils::ApplyLayerNorm(scratch_2_ptr, layer_norm_cell_weight_ptr,
cell_bias_ptr, layer_norm_cell_scale_a,
layer_norm_cell_scale_b, inv_large_value[2],
n_batch, n_cell, scratch_2_ptr);
}
tensor_utils::ApplyTanh3(scratch_2_ptr, n_batch, n_cell, scratch_2_ptr);
// Ouptut gate.
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_ptr, input_to_output_effective_bias, input_to_output_weight_ptr,
effective_input_to_output_scale_a, effective_input_to_output_scale_b,
n_batch, n_input, n_cell, 0, scratch_5_ptr, scratch_3_ptr);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
activation_ptr, recurrent_to_output_effective_bias,
recurrent_to_output_weight_ptr, effective_recurrent_to_output_scale_a,
effective_recurrent_to_output_scale_b, n_batch, n_output, n_cell, 0,
scratch_5_ptr, scratch_3_ptr);
if (layer_norm_output_weight_ptr != nullptr) {
tensor_utils::ApplyLayerNorm(scratch_3_ptr, layer_norm_output_weight_ptr,
output_bias_ptr, layer_norm_output_scale_a,
layer_norm_output_scale_b, inv_large_value[3],
n_batch, n_cell, scratch_3_ptr);
}
tensor_utils::ApplySigmoid(scratch_3_ptr, n_batch, n_cell, scratch_3_ptr);
// Input gate.
if (use_cifg) {
tensor_utils::Sub1Vector(scratch_1_ptr, n_batch * n_cell, scratch_0_ptr);
} else {
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
input_ptr, input_to_input_effective_bias, input_to_input_weight_ptr,
effective_input_to_input_scale_a, effective_input_to_input_scale_b,
n_batch, n_input, n_cell, 0, scratch_5_ptr, scratch_0_ptr);
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
activation_ptr, recurrent_to_input_effective_bias,
recurrent_to_input_weight_ptr, effective_recurrent_to_input_scale_a,
effective_recurrent_to_input_scale_b, n_batch, n_output, n_cell, 0,
scratch_5_ptr, scratch_0_ptr);
if (layer_norm_input_weight_ptr != nullptr) {
tensor_utils::ApplyLayerNorm(scratch_0_ptr, layer_norm_input_weight_ptr,
input_bias_ptr, layer_norm_input_scale_a,
layer_norm_input_scale_b, inv_large_value[0],
n_batch, n_cell, scratch_0_ptr);
}
tensor_utils::ApplySigmoid(scratch_0_ptr, n_batch, n_cell, scratch_0_ptr);
}
// Cell and hidden.
tensor_utils::CwiseMul(scratch_1_ptr, cell_ptr, n_batch, n_cell, 15,
scratch_1_ptr);
tensor_utils::CwiseMul(scratch_0_ptr, scratch_2_ptr, n_batch, n_cell,
30 + cell_scale, scratch_2_ptr);
tensor_utils::CwiseAdd(scratch_1_ptr, scratch_2_ptr, n_batch, n_cell,
cell_ptr);
if (quantized_cell_clip > 0) {
tensor_utils::CwiseClipping(cell_ptr, quantized_cell_clip, n_batch, n_cell);
}
// TODO(jianlijianli): swtich to a tempalte.
if (cell_scale == -11) {
tensor_utils::ApplyTanh4(cell_ptr, n_batch, n_cell, scratch_0_ptr);
} else if (cell_scale == -15) {
tensor_utils::ApplyTanh0(cell_ptr, n_batch, n_cell, scratch_0_ptr);
}
tensor_utils::CwiseMul(scratch_3_ptr, scratch_0_ptr, effective_hidden_scale_a,
effective_hidden_scale_b, n_batch, n_cell, hidden_zp,
scratch_4_ptr);
// Projection.
if (proj_weight_ptr != nullptr) {
memset(output_ptr, 0, n_batch * n_output * sizeof(int8_t));
tensor_utils::MatrixBatchVectorMultiplyAccumulate(
scratch_4_ptr, projection_effective_bias, proj_weight_ptr,
effective_proj_scale_a, effective_proj_scale_b, n_batch, n_cell,
n_output, activation_zp, scratch_5_ptr, output_ptr);
}
if (quantized_proj_clip > 0) {
tensor_utils::CwiseClipping(output_ptr, quantized_proj_clip, n_batch,
n_output);
}
memcpy(activation_ptr, output_ptr, n_batch * n_output * sizeof(int8_t));
}
} // namespace
TfLiteStatus EvalFloat(
const TfLiteTensor* input, const TfLiteTensor* input_to_input_weights,
const TfLiteTensor* input_to_forget_weights,
const TfLiteTensor* input_to_cell_weights,
const TfLiteTensor* input_to_output_weights,
const TfLiteTensor* recurrent_to_input_weights,
const TfLiteTensor* recurrent_to_forget_weights,
const TfLiteTensor* recurrent_to_cell_weights,
const TfLiteTensor* recurrent_to_output_weights,
const TfLiteTensor* cell_to_input_weights,
const TfLiteTensor* cell_to_forget_weights,
const TfLiteTensor* cell_to_output_weights,
const TfLiteTensor* input_layer_norm_coefficients,
const TfLiteTensor* forget_layer_norm_coefficients,
const TfLiteTensor* cell_layer_norm_coefficients,
const TfLiteTensor* output_layer_norm_coefficients,
const TfLiteTensor* aux_input,
const TfLiteTensor* aux_input_to_input_weights,
const TfLiteTensor* aux_input_to_forget_weights,
const TfLiteTensor* aux_input_to_cell_weights,
const TfLiteTensor* aux_input_to_output_weights,
const TfLiteTensor* input_gate_bias, const TfLiteTensor* forget_gate_bias,
const TfLiteTensor* cell_bias, const TfLiteTensor* output_gate_bias,
const TfLiteTensor* projection_weights, const TfLiteTensor* projection_bias,
const TfLiteLSTMParams* params, bool forward_sequence, bool time_major,
int output_offset, TfLiteTensor* scratch_buffer,
TfLiteTensor* activation_state, TfLiteTensor* cell_state,
TfLiteTensor* output) {
TF_LITE_ASSERT(input->dims->size >= 2 && input->dims->size <= 3);
int max_time, n_batch;
if (input->dims->size == 3) {
max_time = (time_major) ? input->dims->data[0] : input->dims->data[1];
n_batch = (time_major) ? input->dims->data[1] : input->dims->data[0];
} else {
max_time = 1;
n_batch = input->dims->data[0];
}
const int n_input = input->dims->data[input->dims->size - 1];
const int aux_input_size =
(aux_input) ? aux_input->dims->data[aux_input->dims->size - 1] : 0;
// n_cell and n_output will be the same size when there is no projection.
const int n_cell = input_to_output_weights->dims->data[0];
const int n_output = recurrent_to_output_weights->dims->data[1];
// Since we have already checked that weights are all there or none, we can
// check the existence of only one to the get the condition.
const bool use_cifg = (input_to_input_weights == nullptr);
const bool use_peephole = (cell_to_output_weights != nullptr);
const bool is_layer_norm_lstm = (forget_layer_norm_coefficients != nullptr);
// Index the scratch buffers pointers to the global scratch buffer.
float* input_gate_scratch = nullptr;
float* cell_scratch = nullptr;
float* forget_gate_scratch = nullptr;
float* output_gate_scratch = nullptr;
if (use_cifg) {
cell_scratch = GetTensorData<float>(scratch_buffer);
forget_gate_scratch =
GetTensorData<float>(scratch_buffer) + n_cell * n_batch;
output_gate_scratch =
GetTensorData<float>(scratch_buffer) + 2 * n_cell * n_batch;
} else {
input_gate_scratch = GetTensorData<float>(scratch_buffer);
cell_scratch = GetTensorData<float>(scratch_buffer) + n_cell * n_batch;
forget_gate_scratch =
GetTensorData<float>(scratch_buffer) + 2 * n_cell * n_batch;
output_gate_scratch =
GetTensorData<float>(scratch_buffer) + 3 * n_cell * n_batch;
}
// Check optional tensors, the respective pointers can be null.
const float* input_to_input_weights_ptr =
(use_cifg) ? nullptr : GetTensorData<float>(input_to_input_weights);
const float* recurrent_to_input_weights_ptr =
(use_cifg) ? nullptr : GetTensorData<float>(recurrent_to_input_weights);
const float* input_gate_bias_ptr =
(use_cifg) ? nullptr : GetTensorData<float>(input_gate_bias);
const float* cell_to_input_weights_ptr =
(use_peephole && !use_cifg) ? GetTensorData<float>(cell_to_input_weights)
: nullptr;
const float* cell_to_forget_weights_ptr =
(use_peephole) ? GetTensorData<float>(cell_to_forget_weights) : nullptr;
const float* cell_to_output_weights_ptr =
(use_peephole) ? GetTensorData<float>(cell_to_output_weights) : nullptr;
const float* input_layer_norm_coefficients_ptr =
(is_layer_norm_lstm && !use_cifg)
? GetTensorData<float>(input_layer_norm_coefficients)
: nullptr;
const float* forget_layer_norm_coefficients_ptr =
is_layer_norm_lstm ? GetTensorData<float>(forget_layer_norm_coefficients)
: nullptr;
const float* cell_layer_norm_coefficients_ptr =
is_layer_norm_lstm ? GetTensorData<float>(cell_layer_norm_coefficients)
: nullptr;
const float* output_layer_norm_coefficients_ptr =
is_layer_norm_lstm ? GetTensorData<float>(output_layer_norm_coefficients)
: nullptr;
const float* projection_weights_ptr =
(projection_weights == nullptr)
? nullptr
: GetTensorData<float>(projection_weights);
const float* projection_bias_ptr =
(projection_bias == nullptr) ? nullptr
: GetTensorData<float>(projection_bias);
const float* aux_input_ptr = nullptr;
const float* aux_input_to_input_weights_ptr = nullptr;
const float* aux_input_to_forget_weights_ptr = nullptr;
const float* aux_input_to_cell_weights_ptr = nullptr;
const float* aux_input_to_output_weights_ptr = nullptr;
if (aux_input_size > 0) {
if (!use_cifg) {
aux_input_to_input_weights_ptr =
GetTensorData<float>(aux_input_to_input_weights);
}
aux_input_to_forget_weights_ptr =
GetTensorData<float>(aux_input_to_forget_weights);
aux_input_to_cell_weights_ptr =
GetTensorData<float>(aux_input_to_cell_weights);
aux_input_to_output_weights_ptr =
GetTensorData<float>(aux_input_to_output_weights);
}
const int output_batch_leading_dim =
output->dims->data[output->dims->size - 1];
if (time_major) {
// Loop through the sequence.
const int input_step = n_batch * n_input;
const int output_step = n_batch * output_batch_leading_dim;
for (int t = 0; t < max_time; t++) {
// If this is the forward_sequence, step forward, otherwise step
// backwards.
const int t_rel = forward_sequence ? t : max_time - t - 1;
const float* input_ptr_batch =
GetTensorData<float>(input) + t_rel * input_step;
if (aux_input) {
aux_input_ptr = GetTensorData<float>(aux_input) + t_rel * input_step;
}
float* output_ptr_time =
GetTensorData<float>(output) + t_rel * output_step + output_offset;
LstmStepWithAuxInput(
input_ptr_batch, input_to_input_weights_ptr,
GetTensorData<float>(input_to_forget_weights),
GetTensorData<float>(input_to_cell_weights),
GetTensorData<float>(input_to_output_weights), aux_input_ptr,
aux_input_to_input_weights_ptr, aux_input_to_forget_weights_ptr,
aux_input_to_cell_weights_ptr, aux_input_to_output_weights_ptr,
recurrent_to_input_weights_ptr,
GetTensorData<float>(recurrent_to_forget_weights),
GetTensorData<float>(recurrent_to_cell_weights),
GetTensorData<float>(recurrent_to_output_weights),
cell_to_input_weights_ptr, cell_to_forget_weights_ptr,
cell_to_output_weights_ptr, input_layer_norm_coefficients_ptr,
forget_layer_norm_coefficients_ptr, cell_layer_norm_coefficients_ptr,
output_layer_norm_coefficients_ptr, input_gate_bias_ptr,
GetTensorData<float>(forget_gate_bias),
GetTensorData<float>(cell_bias),
GetTensorData<float>(output_gate_bias), projection_weights_ptr,
projection_bias_ptr, params, n_batch, n_cell, n_input, aux_input_size,
n_output, output_batch_leading_dim,
GetTensorData<float>(activation_state),
GetTensorData<float>(cell_state), input_gate_scratch,
forget_gate_scratch, cell_scratch, output_gate_scratch,
output_ptr_time);
}
} else {
for (int b = 0; b < n_batch; b++) {
const int input_step = n_input;
const int output_step = output_batch_leading_dim;
for (int t = 0; t < max_time; t++) {
// If this is the forward_sequence, step forward, otherwise step
// backwards.
const int t_rel = forward_sequence ? t : max_time - t - 1;
const int time_offset = b * max_time + t_rel;
const float* input_ptr =
GetTensorData<float>(input) + time_offset * input_step;
if (aux_input) {
aux_input_ptr =
GetTensorData<float>(aux_input) + time_offset * input_step;
}
float* output_ptr = GetTensorData<float>(output) +
time_offset * output_step + output_offset;
// Offset the {activation,cell}_state pointers to the right batch.
float* activation_state_ptr = GetTensorData<float>(activation_state) +
b * output_batch_leading_dim;
float* cell_state_ptr = GetTensorData<float>(cell_state) + b * n_cell;
// Offset the scratch pointers to the right batch.
float* input_gate_scratch_ptr =
input_gate_scratch ? input_gate_scratch + b * n_cell : nullptr;
float* forget_gate_scratch_ptr = forget_gate_scratch + b * n_cell;
float* cell_scratch_ptr = cell_scratch + b * n_cell;
float* output_gate_scratch_ptr = output_gate_scratch + b * n_cell;
LstmStepWithAuxInput(
input_ptr, input_to_input_weights_ptr,
GetTensorData<float>(input_to_forget_weights),
GetTensorData<float>(input_to_cell_weights),
GetTensorData<float>(input_to_output_weights), aux_input_ptr,
aux_input_to_input_weights_ptr, aux_input_to_forget_weights_ptr,
aux_input_to_cell_weights_ptr, aux_input_to_output_weights_ptr,
recurrent_to_input_weights_ptr,
GetTensorData<float>(recurrent_to_forget_weights),
GetTensorData<float>(recurrent_to_cell_weights),
GetTensorData<float>(recurrent_to_output_weights),
cell_to_input_weights_ptr, cell_to_forget_weights_ptr,
cell_to_output_weights_ptr, input_layer_norm_coefficients_ptr,
forget_layer_norm_coefficients_ptr,
cell_layer_norm_coefficients_ptr,
output_layer_norm_coefficients_ptr, input_gate_bias_ptr,
GetTensorData<float>(forget_gate_bias),
GetTensorData<float>(cell_bias),
GetTensorData<float>(output_gate_bias), projection_weights_ptr,
projection_bias_ptr, params, /*n_batch=*/1, n_cell, n_input,
aux_input_size, n_output, output_batch_leading_dim,
activation_state_ptr, cell_state_ptr, input_gate_scratch_ptr,
forget_gate_scratch_ptr, cell_scratch_ptr, output_gate_scratch_ptr,
output_ptr);
}
}
}
return kTfLiteOk;
}
TfLiteStatus EvalHybrid(
const TfLiteTensor* input, const TfLiteTensor* input_to_input_weights,
const TfLiteTensor* input_to_forget_weights,
const TfLiteTensor* input_to_cell_weights,
const TfLiteTensor* input_to_output_weights,
const TfLiteTensor* recurrent_to_input_weights,
const TfLiteTensor* recurrent_to_forget_weights,
const TfLiteTensor* recurrent_to_cell_weights,
const TfLiteTensor* recurrent_to_output_weights,
const TfLiteTensor* cell_to_input_weights,
const TfLiteTensor* cell_to_forget_weights,
const TfLiteTensor* cell_to_output_weights,
const TfLiteTensor* input_layer_norm_coefficients,
const TfLiteTensor* forget_layer_norm_coefficients,
const TfLiteTensor* cell_layer_norm_coefficients,
const TfLiteTensor* output_layer_norm_coefficients,
const TfLiteTensor* aux_input,
const TfLiteTensor* aux_input_to_input_weights,
const TfLiteTensor* aux_input_to_forget_weights,
const TfLiteTensor* aux_input_to_cell_weights,
const TfLiteTensor* aux_input_to_output_weights,
const TfLiteTensor* input_gate_bias, const TfLiteTensor* forget_gate_bias,
const TfLiteTensor* cell_bias, const TfLiteTensor* output_gate_bias,
const TfLiteTensor* projection_weights, const TfLiteTensor* projection_bias,
const TfLiteLSTMParams* params, bool forward_sequence, bool time_major,
int output_offset, TfLiteTensor* scratch_buffer,
TfLiteTensor* scaling_factors, TfLiteTensor* prod_scaling_factors,
TfLiteTensor* recovered_cell_weights, TfLiteTensor* input_quantized,
TfLiteTensor* aux_input_quantized, TfLiteTensor* output_state_quantized,
TfLiteTensor* cell_state_quantized, TfLiteTensor* output_state,
TfLiteTensor* cell_state, TfLiteTensor* output) {
TF_LITE_ASSERT(input->dims->size >= 2 && input->dims->size <= 3);
const int n_input = input->dims->data[input->dims->size - 1];
int max_time, n_batch;
if (input->dims->size == 2) {
max_time = 1;
n_batch = input->dims->data[0];
} else {
max_time = (time_major) ? input->dims->data[0] : input->dims->data[1];
n_batch = (time_major) ? input->dims->data[1] : input->dims->data[0];
}
const int aux_input_size =
(aux_input) ? aux_input->dims->data[aux_input->dims->size - 1] : 0;
// n_cell and n_output will be the same size when there is no projection.
const int n_cell = input_to_output_weights->dims->data[0];
const int n_output = recurrent_to_output_weights->dims->data[1];
// Since we have already checked that weights are all there or none, we can
// check the existence of only one to get the condition.
const bool use_cifg = (input_to_input_weights == nullptr);
const bool use_peephole = (cell_to_output_weights != nullptr);
const bool is_layer_norm_lstm = (forget_layer_norm_coefficients != nullptr);
float* input_gate_scratch = nullptr;
float* cell_scratch = nullptr;
float* forget_gate_scratch = nullptr;
float* output_gate_scratch = nullptr;
if (use_cifg) {
cell_scratch = GetTensorData<float>(scratch_buffer);
forget_gate_scratch =
GetTensorData<float>(scratch_buffer) + n_cell * n_batch;
output_gate_scratch =
GetTensorData<float>(scratch_buffer) + 2 * n_cell * n_batch;
} else {
input_gate_scratch = GetTensorData<float>(scratch_buffer);
cell_scratch = GetTensorData<float>(scratch_buffer) + n_cell * n_batch;
forget_gate_scratch =
GetTensorData<float>(scratch_buffer) + 2 * n_cell * n_batch;
output_gate_scratch =
GetTensorData<float>(scratch_buffer) + 3 * n_cell * n_batch;
}
// Check optional tensors, the respective pointers can be null.
const int8_t* input_to_input_weights_ptr = nullptr;
float input_to_input_weights_scale = 1.0f;
const int8_t* recurrent_to_input_weights_ptr = nullptr;
float recurrent_to_input_weights_scale = 1.0f;
const float* input_gate_bias_ptr = nullptr;
if (!use_cifg) {
input_to_input_weights_ptr = GetTensorData<int8_t>(input_to_input_weights);
recurrent_to_input_weights_ptr =
GetTensorData<int8_t>(recurrent_to_input_weights);
input_gate_bias_ptr = GetTensorData<float>(input_gate_bias);
input_to_input_weights_scale = input_to_input_weights->params.scale;
recurrent_to_input_weights_scale = recurrent_to_input_weights->params.scale;
}
const int8_t* cell_to_input_weights_ptr = nullptr;
const int8_t* cell_to_forget_weights_ptr = nullptr;
const int8_t* cell_to_output_weights_ptr = nullptr;
float cell_to_input_weights_scale = 1.0f;
float cell_to_forget_weights_scale = 1.0f;
float cell_to_output_weights_scale = 1.0f;
if (use_peephole) {
if (!use_cifg) {
cell_to_input_weights_ptr = GetTensorData<int8_t>(cell_to_input_weights);
cell_to_input_weights_scale = cell_to_input_weights->params.scale;
}
cell_to_forget_weights_ptr = GetTensorData<int8_t>(cell_to_forget_weights);
cell_to_output_weights_ptr = GetTensorData<int8_t>(cell_to_output_weights);
cell_to_forget_weights_scale = cell_to_forget_weights->params.scale;
cell_to_output_weights_scale = cell_to_output_weights->params.scale;
}
const float* input_layer_norm_coefficients_ptr =
(is_layer_norm_lstm && !use_cifg)
? GetTensorData<float>(input_layer_norm_coefficients)
: nullptr;
const float* forget_layer_norm_coefficients_ptr =
is_layer_norm_lstm ? GetTensorData<float>(forget_layer_norm_coefficients)
: nullptr;
const float* cell_layer_norm_coefficients_ptr =
is_layer_norm_lstm ? GetTensorData<float>(cell_layer_norm_coefficients)
: nullptr;
const float* output_layer_norm_coefficients_ptr =
is_layer_norm_lstm ? GetTensorData<float>(output_layer_norm_coefficients)
: nullptr;
const int8_t* projection_weights_ptr =
(projection_weights == nullptr)
? nullptr
: GetTensorData<int8_t>(projection_weights);
const float projection_weights_scale =
(projection_weights == nullptr) ? 1.0f : projection_weights->params.scale;
const float* projection_bias_ptr =
(projection_bias == nullptr) ? nullptr
: GetTensorData<float>(projection_bias);
// Required tensors, pointers are non-null.
const int8_t* input_to_forget_weights_ptr =
GetTensorData<int8_t>(input_to_forget_weights);
const float input_to_forget_weights_scale =
input_to_forget_weights->params.scale;
const int8_t* input_to_cell_weights_ptr =
GetTensorData<int8_t>(input_to_cell_weights);
const float input_to_cell_weights_scale = input_to_cell_weights->params.scale;
const int8_t* input_to_output_weights_ptr =
GetTensorData<int8_t>(input_to_output_weights);
const float input_to_output_weights_scale =
input_to_output_weights->params.scale;
const int8_t* recurrent_to_forget_weights_ptr =
GetTensorData<int8_t>(recurrent_to_forget_weights);
const float recurrent_to_forget_weights_scale =
recurrent_to_forget_weights->params.scale;
const int8_t* recurrent_to_cell_weights_ptr =
GetTensorData<int8_t>(recurrent_to_cell_weights);
const float recurrent_to_cell_weights_scale =
recurrent_to_cell_weights->params.scale;
const int8_t* recurrent_to_output_weights_ptr =
GetTensorData<int8_t>(recurrent_to_output_weights);
const float recurrent_to_output_weights_scale =
recurrent_to_output_weights->params.scale;
const float* forget_gate_bias_ptr = GetTensorData<float>(forget_gate_bias);
const float* cell_bias_ptr = GetTensorData<float>(cell_bias);
const float* output_gate_bias_ptr = GetTensorData<float>(output_gate_bias);
// Temporary storage for quantized values and scaling factors.
int8_t* quantized_input_ptr = GetTensorData<int8_t>(input_quantized);
int8_t* quantized_aux_input_ptr =
(aux_input_quantized == nullptr)
? nullptr
: GetTensorData<int8_t>(aux_input_quantized);
int8_t* quantized_output_state_ptr =
GetTensorData<int8_t>(output_state_quantized);
int8_t* quantized_cell_state_ptr =
GetTensorData<int8_t>(cell_state_quantized);
float* scaling_factors_ptr = GetTensorData<float>(scaling_factors);
float* prod_scaling_factors_ptr = GetTensorData<float>(prod_scaling_factors);
float* recovered_cell_weights_ptr =
GetTensorData<float>(recovered_cell_weights);
// Auxiliary input and weights.
const float* aux_input_ptr = nullptr;
const int8_t* aux_input_to_input_weights_ptr = nullptr;
const int8_t* aux_input_to_forget_weights_ptr = nullptr;
const int8_t* aux_input_to_cell_weights_ptr = nullptr;
const int8_t* aux_input_to_output_weights_ptr = nullptr;
float aux_input_to_input_weights_scale = 0.0f;
float aux_input_to_forget_weights_scale = 0.0f;
float aux_input_to_cell_weights_scale = 0.0f;
float aux_input_to_output_weights_scale = 0.0f;
if (aux_input_size > 0) {
if (!use_cifg) {
aux_input_to_input_weights_ptr =
GetTensorData<int8_t>(aux_input_to_input_weights);
}
aux_input_to_forget_weights_ptr =
GetTensorData<int8_t>(aux_input_to_forget_weights);
aux_input_to_cell_weights_ptr =
GetTensorData<int8_t>(aux_input_to_cell_weights);
aux_input_to_output_weights_ptr =
GetTensorData<int8_t>(aux_input_to_output_weights);
if (!use_cifg) {
aux_input_to_input_weights_scale =
aux_input_to_input_weights->params.scale;
}
aux_input_to_forget_weights_scale =
aux_input_to_forget_weights->params.scale;
aux_input_to_cell_weights_scale = aux_input_to_cell_weights->params.scale;
aux_input_to_output_weights_scale =
aux_input_to_output_weights->params.scale;
}
const int output_batch_leading_dim =
output->dims->data[output->dims->size - 1];
if (time_major) {
// Feed the sequence into the LSTM step-by-step.
const int input_step = n_batch * n_input;
const int output_step = n_batch * output_batch_leading_dim;
for (int t = 0; t < max_time; t++) {
// If this is the forward_sequence, step forward, otherwise step
// backwards.
const int t_rel = forward_sequence ? t : max_time - t - 1;
const float* input_ptr_batch =
GetTensorData<float>(input) + t_rel * input_step;
if (aux_input) {
aux_input_ptr = GetTensorData<float>(aux_input) + t_rel * input_step;
}
float* output_ptr_batch =
GetTensorData<float>(output) + t_rel * output_step + output_offset;
LstmStepWithAuxInput(
input_ptr_batch, input_to_input_weights_ptr,
input_to_input_weights_scale, input_to_forget_weights_ptr,
input_to_forget_weights_scale, input_to_cell_weights_ptr,
input_to_cell_weights_scale, input_to_output_weights_ptr,
input_to_output_weights_scale, aux_input_ptr,
aux_input_to_input_weights_ptr, aux_input_to_input_weights_scale,
aux_input_to_forget_weights_ptr, aux_input_to_forget_weights_scale,
aux_input_to_cell_weights_ptr, aux_input_to_cell_weights_scale,
aux_input_to_output_weights_ptr, aux_input_to_output_weights_scale,
recurrent_to_input_weights_ptr, recurrent_to_input_weights_scale,
recurrent_to_forget_weights_ptr, recurrent_to_forget_weights_scale,
recurrent_to_cell_weights_ptr, recurrent_to_cell_weights_scale,
recurrent_to_output_weights_ptr, recurrent_to_output_weights_scale,
cell_to_input_weights_ptr, cell_to_input_weights_scale,
cell_to_forget_weights_ptr, cell_to_forget_weights_scale,
cell_to_output_weights_ptr, cell_to_output_weights_scale,
input_layer_norm_coefficients_ptr, forget_layer_norm_coefficients_ptr,
cell_layer_norm_coefficients_ptr, output_layer_norm_coefficients_ptr,
input_gate_bias_ptr, forget_gate_bias_ptr, cell_bias_ptr,
output_gate_bias_ptr, projection_weights_ptr,
projection_weights_scale, projection_bias_ptr, params, n_batch,
n_cell, n_input, aux_input_size, n_output, output_batch_leading_dim,
input_gate_scratch, forget_gate_scratch, cell_scratch,
output_gate_scratch, scaling_factors_ptr, prod_scaling_factors_ptr,
recovered_cell_weights_ptr, quantized_input_ptr,
quantized_aux_input_ptr, quantized_output_state_ptr,
quantized_cell_state_ptr, GetTensorData<float>(output_state),
GetTensorData<float>(cell_state), output_ptr_batch);
}
} else {
for (int b = 0; b < n_batch; b++) {
const int input_step = n_input;
const int output_step = output_batch_leading_dim;
for (int t = 0; t < max_time; t++) {
// If this is the forward_sequence, step forward, otherwise step
// backwards.
const int t_rel = forward_sequence ? t : max_time - t - 1;
const int time_offset = b * max_time + t_rel;
const float* input_ptr =
GetTensorData<float>(input) + time_offset * input_step;
if (aux_input) {
aux_input_ptr =
GetTensorData<float>(aux_input) + time_offset * input_step;
}
float* output_ptr = GetTensorData<float>(output) +
time_offset * output_step + output_offset;
// Offset the {output,cell}_state pointers to the right batch.
float* output_state_ptr =
GetTensorData<float>(output_state) + b * output_batch_leading_dim;
float* cell_state_ptr = GetTensorData<float>(cell_state) + b * n_cell;
// Offset the scratch pointers to the right batch.
float* input_gate_scratch_ptr =
input_gate_scratch ? input_gate_scratch + b * n_cell : nullptr;
float* forget_gate_scratch_ptr = forget_gate_scratch + b * n_cell;
float* cell_scratch_ptr = cell_scratch + b * n_cell;
float* output_gate_scratch_ptr = output_gate_scratch + b * n_cell;
LstmStepWithAuxInput(
input_ptr, input_to_input_weights_ptr, input_to_input_weights_scale,
input_to_forget_weights_ptr, input_to_forget_weights_scale,
input_to_cell_weights_ptr, input_to_cell_weights_scale,
input_to_output_weights_ptr, input_to_output_weights_scale,
aux_input_ptr, aux_input_to_input_weights_ptr,
aux_input_to_input_weights_scale, aux_input_to_forget_weights_ptr,
aux_input_to_forget_weights_scale, aux_input_to_cell_weights_ptr,
aux_input_to_cell_weights_scale, aux_input_to_output_weights_ptr,
aux_input_to_output_weights_scale, recurrent_to_input_weights_ptr,
recurrent_to_input_weights_scale, recurrent_to_forget_weights_ptr,
recurrent_to_forget_weights_scale, recurrent_to_cell_weights_ptr,
recurrent_to_cell_weights_scale, recurrent_to_output_weights_ptr,
recurrent_to_output_weights_scale, cell_to_input_weights_ptr,
cell_to_input_weights_scale, cell_to_forget_weights_ptr,
cell_to_forget_weights_scale, cell_to_output_weights_ptr,
cell_to_output_weights_scale, input_layer_norm_coefficients_ptr,
forget_layer_norm_coefficients_ptr,
cell_layer_norm_coefficients_ptr,
output_layer_norm_coefficients_ptr, input_gate_bias_ptr,
forget_gate_bias_ptr, cell_bias_ptr, output_gate_bias_ptr,
projection_weights_ptr, projection_weights_scale,
projection_bias_ptr, params,
/*n_batch=*/1, n_cell, n_input, aux_input_size, n_output,
output_batch_leading_dim, input_gate_scratch_ptr,
forget_gate_scratch_ptr, cell_scratch_ptr, output_gate_scratch_ptr,
scaling_factors_ptr, prod_scaling_factors_ptr,
recovered_cell_weights_ptr, quantized_input_ptr,
quantized_aux_input_ptr, quantized_output_state_ptr,
quantized_cell_state_ptr, output_state_ptr, cell_state_ptr,
output_ptr);
}
}
}
return kTfLiteOk;
}
TfLiteStatus EvalQuantized(
const TfLiteTensor* input, const TfLiteTensor* input_to_input_weights,
const TfLiteTensor* input_to_forget_weights,
const TfLiteTensor* input_to_cell_weights,
const TfLiteTensor* input_to_output_weights,
const TfLiteTensor* recurrent_to_input_weights,
const TfLiteTensor* recurrent_to_forget_weights,
const TfLiteTensor* recurrent_to_cell_weights,
const TfLiteTensor* recurrent_to_output_weights,
const TfLiteTensor* cell_to_input_weights,
const TfLiteTensor* cell_to_forget_weights,
const TfLiteTensor* cell_to_output_weights,
const TfLiteTensor* input_layer_norm_coefficients,
const TfLiteTensor* forget_layer_norm_coefficients,
const TfLiteTensor* cell_layer_norm_coefficients,
const TfLiteTensor* output_layer_norm_coefficients,
const TfLiteTensor* input_gate_bias, const TfLiteTensor* forget_gate_bias,
const TfLiteTensor* cell_bias, const TfLiteTensor* output_gate_bias,
const TfLiteTensor* projection_weights, const TfLiteTensor* projection_bias,
const TfLiteLSTMParams* params,
const lstm_eval::QuantizedLstmParameter* quantized_lstm_param,
TfLiteTensor* activation_state, TfLiteTensor* cell_state,
TfLiteTensor* output, TfLiteTensor* scratch0, TfLiteTensor* scratch1,
TfLiteTensor* scratch2, TfLiteTensor* scratch3, TfLiteTensor* scratch4,
TfLiteTensor* scratch5) {
TF_LITE_ASSERT(input->dims->size >= 2 && input->dims->size <= 3);
const int n_input = input->dims->data[input->dims->size - 1];
int max_time, n_batch;
if (input->dims->size == 2) {
max_time = 1;
n_batch = input->dims->data[0];
} else {
max_time = input->dims->data[0];
n_batch = input->dims->data[1];
}
// n_cell and n_output will be the same size when there is no projection.
const int n_cell = input_to_output_weights->dims->data[0];
const int n_output = recurrent_to_output_weights->dims->data[1];
// Weights and states.
const int8_t* input_to_input_weight_ptr =
GetTensorData<int8_t>(input_to_input_weights);
const int8_t* recurrent_to_input_weight_ptr =
GetTensorData<int8_t>(recurrent_to_input_weights);
const int8_t* cell_to_input_weight_ptr =
GetTensorData<int8_t>(cell_to_input_weights);
const int8_t* input_to_forget_weight_ptr =
GetTensorData<int8_t>(input_to_forget_weights);
const int8_t* recurrent_to_forget_weight_ptr =
GetTensorData<int8_t>(recurrent_to_forget_weights);
const int8_t* cell_to_forget_weight_ptr =
GetTensorData<int8_t>(cell_to_forget_weights);
const int8_t* input_to_cell_weight_ptr =
GetTensorData<int8_t>(input_to_cell_weights);
const int8_t* recurrent_to_cell_weight_ptr =
GetTensorData<int8_t>(recurrent_to_cell_weights);
const int8_t* input_to_output_weight_ptr =
GetTensorData<int8_t>(input_to_output_weights);
const int8_t* recurrent_to_output_weight_ptr =
GetTensorData<int8_t>(recurrent_to_output_weights);
const int8_t* cell_to_output_weight_ptr =
GetTensorData<int8_t>(cell_to_output_weights);
const int8_t* proj_weight_ptr = GetTensorData<int8_t>(projection_weights);
const int16_t* layer_norm_input_weight_ptr =
GetTensorData<int16_t>(input_layer_norm_coefficients);
const int16_t* layer_norm_forget_weight_ptr =
GetTensorData<int16_t>(forget_layer_norm_coefficients);
const int16_t* layer_norm_cell_weight_ptr =
GetTensorData<int16_t>(cell_layer_norm_coefficients);
const int16_t* layer_norm_output_weight_ptr =
GetTensorData<int16_t>(output_layer_norm_coefficients);
const int32_t* input_bias_ptr = GetTensorData<int32_t>(input_gate_bias);
const int32_t* forget_bias_ptr = GetTensorData<int32_t>(forget_gate_bias);
const int32_t* cell_bias_ptr = GetTensorData<int32_t>(cell_bias);
const int32_t* output_bias_ptr = GetTensorData<int32_t>(output_gate_bias);
int16_t* cell_ptr = GetTensorData<int16_t>(cell_state);
int8_t* activation_ptr = GetTensorData<int8_t>(activation_state);
int8_t* output_ptr = GetTensorData<int8_t>(output);
// Zero points
int input_zp = 0;
int activation_zp = 0;
input_zp = input->params.zero_point;
activation_zp = activation_state->params.zero_point;
// Get params for time/batch/sequence.
const int output_batch_leading_dim =
output->dims->data[output->dims->size - 1];
const int input_step = n_batch * n_input;
const int output_step = n_batch * output_batch_leading_dim;
for (int t = 0; t < max_time; t++) {
const int t_rel = t;
output_ptr = output_ptr + t_rel * output_step;
// Input can be int8 asymmetric or int16 symmetric.
const int8_t* input_ptr = GetTensorData<int8_t>(input) + t_rel * input_step;
LstmStepQuantized(
input_ptr, input_to_input_weight_ptr,
quantized_lstm_param->effective_input_to_input_scale_a,
quantized_lstm_param->effective_input_to_input_scale_b,
input_to_forget_weight_ptr,
quantized_lstm_param->effective_input_to_forget_scale_a,
quantized_lstm_param->effective_input_to_forget_scale_b,
input_to_cell_weight_ptr,
quantized_lstm_param->effective_input_to_cell_scale_a,
quantized_lstm_param->effective_input_to_cell_scale_b,
input_to_output_weight_ptr,
quantized_lstm_param->effective_input_to_output_scale_a,
quantized_lstm_param->effective_input_to_output_scale_b,
recurrent_to_input_weight_ptr,
quantized_lstm_param->effective_recurrent_to_input_scale_a,
quantized_lstm_param->effective_recurrent_to_input_scale_b,
recurrent_to_forget_weight_ptr,
quantized_lstm_param->effective_recurrent_to_forget_scale_a,
quantized_lstm_param->effective_recurrent_to_forget_scale_b,
recurrent_to_cell_weight_ptr,
quantized_lstm_param->effective_recurrent_to_cell_scale_a,
quantized_lstm_param->effective_recurrent_to_cell_scale_b,
recurrent_to_output_weight_ptr,
quantized_lstm_param->effective_recurrent_to_output_scale_a,
quantized_lstm_param->effective_recurrent_to_output_scale_b,
cell_to_input_weight_ptr,
quantized_lstm_param->effective_cell_to_input_scale_a,
quantized_lstm_param->effective_cell_to_input_scale_b,
cell_to_forget_weight_ptr,
quantized_lstm_param->effective_cell_to_forget_scale_a,
quantized_lstm_param->effective_cell_to_forget_scale_b,
cell_to_output_weight_ptr,
quantized_lstm_param->effective_cell_to_output_scale_a,
quantized_lstm_param->effective_cell_to_output_scale_b, proj_weight_ptr,
quantized_lstm_param->effective_proj_scale_a,
quantized_lstm_param->effective_proj_scale_b,
quantized_lstm_param->hidden_zp,
quantized_lstm_param->effective_hidden_scale_a,
quantized_lstm_param->effective_hidden_scale_b,
layer_norm_input_weight_ptr,
quantized_lstm_param->layer_norm_input_scale_a,
quantized_lstm_param->layer_norm_input_scale_b,
layer_norm_forget_weight_ptr,
quantized_lstm_param->layer_norm_forget_scale_a,
quantized_lstm_param->layer_norm_forget_scale_b,
layer_norm_cell_weight_ptr,
quantized_lstm_param->layer_norm_cell_scale_a,
quantized_lstm_param->layer_norm_cell_scale_b,
layer_norm_output_weight_ptr,
quantized_lstm_param->layer_norm_output_scale_a,
quantized_lstm_param->layer_norm_output_scale_b, input_bias_ptr,
forget_bias_ptr, cell_bias_ptr, output_bias_ptr,
quantized_lstm_param->quantized_cell_clip,
quantized_lstm_param->quantized_proj_clip,
quantized_lstm_param->cell_scale,
quantized_lstm_param->inv_large_value.data(),
quantized_lstm_param->input_to_forget_effective_bias.get(),
quantized_lstm_param->recurrent_to_forget_effective_bias.get(),
quantized_lstm_param->input_to_cell_effective_bias.get(),
quantized_lstm_param->recurrent_to_cell_effective_bias.get(),
quantized_lstm_param->input_to_output_effective_bias.get(),
quantized_lstm_param->recurrent_to_output_effective_bias.get(),
quantized_lstm_param->input_to_input_effective_bias.get(),
quantized_lstm_param->recurrent_to_input_effective_bias.get(),
quantized_lstm_param->projection_effective_bias.get(), n_batch, n_cell,
n_input, n_output, output_batch_leading_dim, activation_ptr,
activation_zp, cell_ptr, output_ptr, GetTensorData<int16_t>(scratch0),
GetTensorData<int16_t>(scratch1), GetTensorData<int16_t>(scratch2),
GetTensorData<int16_t>(scratch3), GetTensorData<int8_t>(scratch4),
GetTensorData<int32_t>(scratch5));
}
return kTfLiteOk;
}
} // namespace lstm_eval
} // namespace builtin
} // namespace ops
} // namespace tflite
|
#include <math.h>
#include <tradingcore2/ctrlcondition/indicatorsvaread.h>
#include <tradingcore2/ctrlconditionmgr.h>
#include <tradingcore2/indicatormap.h>
#include <functional>
CR2BEGIN
// 因为是单值模式,需要判断当前值和配置值之间的关系
void CCIndicatorSVAreaD::regCtrlConditionHelper() {
CtrlConditionMgr::getSingleton()->regCtrlCondition("indicatorsvaread",
new CCIndicatorSVAreaD());
}
void CCIndicatorSVAreaD::getIndicators(std::set<std::string>& indicators,
const tradingpb::CtrlCondition& cc) {
indicators.insert(cc.strvals(0));
}
bool CCIndicatorSVAreaD::isValid(const tradingpb::CtrlCondition& cc,
CtrlType ct) {
if (cc.operators_size() == 1) {
if (cc.operators(0) == "==") {
return cc.vals_size() == 1 && cc.strvals_size() == 1;
}
} else if (cc.operators_size() == 3) {
if (cc.operators(2) == "up" || cc.operators(2) == "down") {
if (cc.operators(0) == ">" || cc.operators(0) == ">=" ||
cc.operators(0) == "<" || cc.operators(0) == "<=") {
if (cc.operators(1) == ">" || cc.operators(1) == ">=" ||
cc.operators(1) == "<" || cc.operators(1) == "<=") {
return cc.vals_size() == 2 && cc.strvals_size() == 1;
}
}
}
}
return false;
}
bool CCIndicatorSVAreaD::canCtrl(const Exchange& exchange, const Wallet& wallet,
const IndicatorMap& mapIndicators,
const tradingpb::CtrlCondition& cc, bool issim,
CtrlType ct, TimeStamp ts, int index,
CandleData& cd, Assets& assets, void* pData) {
auto pIndicator = mapIndicators.getIndicator(cc.strvals(0).c_str());
if (pIndicator != NULL) {
if (index <= 0) {
return false;
}
auto lv = pIndicator->getSingleValue(index - 1);
if (lv == NULL) {
return false;
}
auto cv = pIndicator->getSingleValue(index);
assert(cv != NULL);
bool canctrl = false;
if (cc.operators_size() == 1) {
if (cv->value == cc.vals(0)) {
canctrl = true;
}
} else {
assert(cc.operators_size() == 3);
if (cc.operators(2) == "up") {
if (cv->value <= lv->value) {
return false;
}
} else if (cc.operators(2) == "down") {
if (cv->value >= lv->value) {
return false;
}
}
if (cc.operators(0) == ">") {
if (cv->value > cc.vals(0)) {
canctrl = true;
}
} else if (cc.operators(0) == ">=") {
if (cv->value >= cc.vals(0)) {
canctrl = true;
}
} else if (cc.operators(0) == "<") {
if (cv->value < cc.vals(0)) {
canctrl = true;
}
} else if (cc.operators(0) == "<=") {
if (cv->value <= cc.vals(0)) {
canctrl = true;
}
}
if (canctrl) {
canctrl = false;
if (cc.operators(1) == ">") {
if (cv->value > cc.vals(1)) {
canctrl = true;
}
} else if (cc.operators(1) == ">=") {
if (cv->value >= cc.vals(1)) {
canctrl = true;
}
} else if (cc.operators(1) == "<") {
if (cv->value < cc.vals(1)) {
canctrl = true;
}
} else if (cc.operators(1) == "<=") {
if (cv->value <= cc.vals(1)) {
canctrl = true;
}
}
}
}
return canctrl;
} else {
LOG(INFO) << "no indicator " << cc.strvals(0);
}
return false;
}
CR2END
|
/*!
* \copy
* Copyright (c) 2009-2013, Cisco Systems
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER 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.
*
*
* \file au_parser.c
*
* \brief Interfaces introduced in Access Unit level based parser
*
* \date 03/10/2009 Created
*
*************************************************************************************
*/
#include "codec_def.h"
#include "au_parser.h"
#include "decoder.h"
#include "error_code.h"
#include "memmgr_nal_unit.h"
#include "decoder_core.h"
#include "bit_stream.h"
#include "memory_align.h"
#define _PARSE_NALHRD_VCLHRD_PARAMS_ 1
namespace WelsDec {
/*!
*************************************************************************************
* \brief Start Code Prefix (0x 00 00 00 01) detection
*
* \param pBuf bitstream payload buffer
* \param pOffset offset between NAL rbsp and original bitsteam that
* start code prefix is seperated from.
* \param iBufSize count size of buffer
*
* \return RBSP buffer of start code prefix exclusive
*
* \note N/A
*************************************************************************************
*/
uint8_t* DetectStartCodePrefix (const uint8_t* kpBuf, int32_t* pOffset, int32_t iBufSize) {
uint8_t* pBits = (uint8_t*)kpBuf;
do {
int32_t iIdx = 0;
while ((iIdx < iBufSize) && (! (*pBits))) {
++ pBits;
++ iIdx;
}
if (iIdx >= iBufSize) break;
++ iIdx;
++ pBits;
if ((iIdx >= 3) && ((* (pBits - 1)) == 0x1)) {
*pOffset = (int32_t) (((uintptr_t)pBits) - ((uintptr_t)kpBuf));
return pBits;
}
iBufSize -= iIdx;
} while (1);
return NULL;
}
/*!
*************************************************************************************
* \brief to parse nal unit
*
* \param pCtx decoder context
* \param pNalUnitHeader parsed result of NAL Unit Header to output
* \param pSrcRbsp bitstream buffer to input
* \param iSrcRbspLen length size of bitstream buffer payload
* \param pSrcNal
* \param iSrcNalLen
* \param pConsumedBytes consumed bytes during parsing
*
* \return decoded bytes payload, might be (pSrcRbsp+1) if no escapes
*
* \note N/A
*************************************************************************************
*/
uint8_t* ParseNalHeader (PWelsDecoderContext pCtx, SNalUnitHeader* pNalUnitHeader, uint8_t* pSrcRbsp,
int32_t iSrcRbspLen, uint8_t* pSrcNal, int32_t iSrcNalLen, int32_t* pConsumedBytes) {
PNalUnit pCurNal = NULL;
uint8_t* pNal = pSrcRbsp;
int32_t iNalSize = iSrcRbspLen;
PBitStringAux pBs = NULL;
bool bExtensionFlag = false;
int32_t iErr = ERR_NONE;
int32_t iBitSize = 0;
SDataBuffer* pSavedData = &pCtx->sSavedData;
SLogContext* pLogCtx = & (pCtx->sLogCtx);
pNalUnitHeader->eNalUnitType = NAL_UNIT_UNSPEC_0;//SHOULD init it. because pCtx->sCurNalHead is common variable.
//remove the consecutive ZERO at the end of current NAL in the reverse order.--2011.6.1
{
int32_t iIndex = iSrcRbspLen - 1;
uint8_t uiBsZero = 0;
while (iIndex >= 0) {
uiBsZero = pSrcRbsp[iIndex];
if (0 == uiBsZero) {
--iNalSize;
++ (*pConsumedBytes);
--iIndex;
} else {
break;
}
}
}
pNalUnitHeader->uiForbiddenZeroBit = (uint8_t) (pNal[0] >> 7); // uiForbiddenZeroBit
if (pNalUnitHeader->uiForbiddenZeroBit) { //2010.4.14
pCtx->iErrorCode |= dsBitstreamError;
return NULL; //uiForbiddenZeroBit should always equal to 0
}
pNalUnitHeader->uiNalRefIdc = (uint8_t) (pNal[0] >> 5); // uiNalRefIdc
pNalUnitHeader->eNalUnitType = (EWelsNalUnitType) (pNal[0] & 0x1f); // eNalUnitType
++pNal;
--iNalSize;
++ (*pConsumedBytes);
if (! (IS_SEI_NAL (pNalUnitHeader->eNalUnitType) || IS_SPS_NAL (pNalUnitHeader->eNalUnitType)
|| IS_AU_DELIMITER_NAL (pNalUnitHeader->eNalUnitType) || pCtx->bSpsExistAheadFlag)) {
if (pCtx->bPrintFrameErrorTraceFlag && pCtx->iSpsErrorIgnored == 0) {
WelsLog (pLogCtx, WELS_LOG_WARNING,
"parse_nal(), no exist Sequence Parameter Sets ahead of sequence when try to decode NAL(type:%d).",
pNalUnitHeader->eNalUnitType);
} else {
pCtx->iSpsErrorIgnored++;
}
pCtx->sDecoderStatistics.iSpsNoExistNalNum++;
pCtx->iErrorCode = dsNoParamSets;
return NULL;
}
pCtx->iSpsErrorIgnored = 0;
if (! (IS_SEI_NAL (pNalUnitHeader->eNalUnitType) || IS_PARAM_SETS_NALS (pNalUnitHeader->eNalUnitType)
|| IS_AU_DELIMITER_NAL (pNalUnitHeader->eNalUnitType) || pCtx->bPpsExistAheadFlag)) {
if (pCtx->bPrintFrameErrorTraceFlag && pCtx->iPpsErrorIgnored == 0) {
WelsLog (pLogCtx, WELS_LOG_WARNING,
"parse_nal(), no exist Picture Parameter Sets ahead of sequence when try to decode NAL(type:%d).",
pNalUnitHeader->eNalUnitType);
} else {
pCtx->iPpsErrorIgnored++;
}
pCtx->sDecoderStatistics.iPpsNoExistNalNum++;
pCtx->iErrorCode = dsNoParamSets;
return NULL;
}
pCtx->iPpsErrorIgnored = 0;
if ((IS_VCL_NAL_AVC_BASE (pNalUnitHeader->eNalUnitType) && ! (pCtx->bSpsExistAheadFlag || pCtx->bPpsExistAheadFlag)) ||
(IS_NEW_INTRODUCED_SVC_NAL (pNalUnitHeader->eNalUnitType) && ! (pCtx->bSpsExistAheadFlag || pCtx->bSubspsExistAheadFlag
|| pCtx->bPpsExistAheadFlag))) {
if (pCtx->bPrintFrameErrorTraceFlag && pCtx->iSubSpsErrorIgnored == 0) {
WelsLog (pLogCtx, WELS_LOG_WARNING,
"ParseNalHeader(), no exist Parameter Sets ahead of sequence when try to decode slice(type:%d).",
pNalUnitHeader->eNalUnitType);
} else {
pCtx->iSubSpsErrorIgnored++;
}
pCtx->sDecoderStatistics.iSubSpsNoExistNalNum++;
pCtx->iErrorCode |= dsNoParamSets;
return NULL;
}
pCtx->iSubSpsErrorIgnored = 0;
switch (pNalUnitHeader->eNalUnitType) {
case NAL_UNIT_AU_DELIMITER:
case NAL_UNIT_SEI:
if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
pCtx->pAccessUnitList->uiEndPos = pCtx->pAccessUnitList->uiAvailUnitsNum - 1;
pCtx->bAuReadyFlag = true;
}
break;
case NAL_UNIT_PREFIX:
pCurNal = &pCtx->sPrefixNal;
pCurNal->uiTimeStamp = pCtx->uiTimeStamp;
if (iNalSize < NAL_UNIT_HEADER_EXT_SIZE) {
PAccessUnit pCurAu = pCtx->pAccessUnitList;
uint32_t uiAvailNalNum = pCurAu->uiAvailUnitsNum;
if (uiAvailNalNum > 0) {
pCurAu->uiEndPos = uiAvailNalNum - 1;
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
pCtx->bAuReadyFlag = true;
}
}
pCurNal->sNalData.sPrefixNal.bPrefixNalCorrectFlag = false;
pCtx->iErrorCode |= dsBitstreamError;
return NULL;
}
DecodeNalHeaderExt (pCurNal, pNal);
if ((pCurNal->sNalHeaderExt.uiQualityId != 0) || (pCurNal->sNalHeaderExt.bUseRefBasePicFlag != 0)) {
WelsLog (pLogCtx, WELS_LOG_WARNING,
"ParseNalHeader() in Prefix Nal Unit:uiQualityId (%d) != 0, bUseRefBasePicFlag (%d) != 0, not supported!",
pCurNal->sNalHeaderExt.uiQualityId, pCurNal->sNalHeaderExt.bUseRefBasePicFlag);
PAccessUnit pCurAu = pCtx->pAccessUnitList;
uint32_t uiAvailNalNum = pCurAu->uiAvailUnitsNum;
if (uiAvailNalNum > 0) {
pCurAu->uiEndPos = uiAvailNalNum - 1;
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
pCtx->bAuReadyFlag = true;
}
}
pCurNal->sNalData.sPrefixNal.bPrefixNalCorrectFlag = false;
pCtx->iErrorCode |= dsBitstreamError;
return NULL;
}
pNal += NAL_UNIT_HEADER_EXT_SIZE;
iNalSize -= NAL_UNIT_HEADER_EXT_SIZE;
*pConsumedBytes += NAL_UNIT_HEADER_EXT_SIZE;
pCurNal->sNalHeaderExt.sNalUnitHeader.uiForbiddenZeroBit = pNalUnitHeader->uiForbiddenZeroBit;
pCurNal->sNalHeaderExt.sNalUnitHeader.uiNalRefIdc = pNalUnitHeader->uiNalRefIdc;
pCurNal->sNalHeaderExt.sNalUnitHeader.eNalUnitType = pNalUnitHeader->eNalUnitType;
if (pNalUnitHeader->uiNalRefIdc != 0) {
pBs = &pCtx->sBs;
iBitSize = (iNalSize << 3) - BsGetTrailingBits (pNal + iNalSize - 1); // convert into bit
iErr = DecInitBits (pBs, pNal, iBitSize);
if (iErr) {
WelsLog (pLogCtx, WELS_LOG_ERROR, "NAL_UNIT_PREFIX: DecInitBits() fail due invalid access.");
pCtx->iErrorCode |= dsBitstreamError;
return NULL;
}
ParsePrefixNalUnit (pCtx, pBs);
}
pCurNal->sNalData.sPrefixNal.bPrefixNalCorrectFlag = true;
break;
case NAL_UNIT_CODED_SLICE_EXT:
bExtensionFlag = true;
case NAL_UNIT_CODED_SLICE:
case NAL_UNIT_CODED_SLICE_IDR: {
PAccessUnit pCurAu = NULL;
uint32_t uiAvailNalNum;
pCurNal = MemGetNextNal (&pCtx->pAccessUnitList, pCtx->pMemAlign);
if (NULL == pCurNal) {
WelsLog (pLogCtx, WELS_LOG_ERROR, "MemGetNextNal() fail due out of memory.");
pCtx->iErrorCode |= dsOutOfMemory;
return NULL;
}
pCurNal->uiTimeStamp = pCtx->uiTimeStamp;
pCurNal->sNalHeaderExt.sNalUnitHeader.uiForbiddenZeroBit = pNalUnitHeader->uiForbiddenZeroBit;
pCurNal->sNalHeaderExt.sNalUnitHeader.uiNalRefIdc = pNalUnitHeader->uiNalRefIdc;
pCurNal->sNalHeaderExt.sNalUnitHeader.eNalUnitType = pNalUnitHeader->eNalUnitType;
pCurAu = pCtx->pAccessUnitList;
uiAvailNalNum = pCurAu->uiAvailUnitsNum;
if (pNalUnitHeader->eNalUnitType == NAL_UNIT_CODED_SLICE_EXT) {
if (iNalSize < NAL_UNIT_HEADER_EXT_SIZE) {
ForceClearCurrentNal (pCurAu);
if (uiAvailNalNum > 1) {
pCurAu->uiEndPos = uiAvailNalNum - 2;
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
pCtx->bAuReadyFlag = true;
}
}
pCtx->iErrorCode |= dsBitstreamError;
return NULL;
}
DecodeNalHeaderExt (pCurNal, pNal);
if (pCurNal->sNalHeaderExt.uiQualityId != 0 ||
pCurNal->sNalHeaderExt.bUseRefBasePicFlag) {
if (pCurNal->sNalHeaderExt.uiQualityId != 0)
WelsLog (pLogCtx, WELS_LOG_WARNING, "ParseNalHeader():uiQualityId (%d) != 0, MGS not supported!",
pCurNal->sNalHeaderExt.uiQualityId);
if (pCurNal->sNalHeaderExt.bUseRefBasePicFlag != 0)
WelsLog (pLogCtx, WELS_LOG_WARNING, "ParseNalHeader():bUseRefBasePicFlag (%d) != 0, MGS not supported!",
pCurNal->sNalHeaderExt.bUseRefBasePicFlag);
ForceClearCurrentNal (pCurAu);
if (uiAvailNalNum > 1) {
pCurAu->uiEndPos = uiAvailNalNum - 2;
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
pCtx->bAuReadyFlag = true;
}
}
pCtx->iErrorCode |= dsBitstreamError;
return NULL;
}
pNal += NAL_UNIT_HEADER_EXT_SIZE;
iNalSize -= NAL_UNIT_HEADER_EXT_SIZE;
*pConsumedBytes += NAL_UNIT_HEADER_EXT_SIZE;
if (pCtx->pParam->bParseOnly) {
pCurNal->sNalData.sVclNal.pNalPos = pSavedData->pCurPos;
int32_t iTrailingZeroByte = 0;
while (pSrcNal[iSrcNalLen - iTrailingZeroByte - 1] == 0x0) //remove final trailing 0 bytes
iTrailingZeroByte++;
int32_t iActualLen = iSrcNalLen - iTrailingZeroByte;
pCurNal->sNalData.sVclNal.iNalLength = iActualLen - NAL_UNIT_HEADER_EXT_SIZE;
//unify start code as 0x0001
int32_t iCurrStartByte = 4; //4 for 0x0001, 3 for 0x001
if (pSrcNal[0] == 0x0 && pSrcNal[1] == 0x0 && pSrcNal[2] == 0x1) { //if 0x001
iCurrStartByte = 3;
pCurNal->sNalData.sVclNal.iNalLength++;
}
if (pCurNal->sNalHeaderExt.bIdrFlag) {
* (pSrcNal + iCurrStartByte) &= 0xE0;
* (pSrcNal + iCurrStartByte) |= 0x05;
} else {
* (pSrcNal + iCurrStartByte) &= 0xE0;
* (pSrcNal + iCurrStartByte) |= 0x01;
}
pSavedData->pCurPos[0] = pSavedData->pCurPos[1] = pSavedData->pCurPos[2] = 0x0;
pSavedData->pCurPos[3] = 0x1;
pSavedData->pCurPos[4] = * (pSrcNal + iCurrStartByte);
pSavedData->pCurPos += 5;
int32_t iOffset = iCurrStartByte + 1 + NAL_UNIT_HEADER_EXT_SIZE;
memcpy (pSavedData->pCurPos, pSrcNal + iOffset, iActualLen - iOffset);
pSavedData->pCurPos += iActualLen - iOffset;
}
} else {
if (pCtx->pParam->bParseOnly) {
pCurNal->sNalData.sVclNal.pNalPos = pSavedData->pCurPos;
int32_t iTrailingZeroByte = 0;
while (pSrcNal[iSrcNalLen - iTrailingZeroByte - 1] == 0x0) //remove final trailing 0 bytes
iTrailingZeroByte++;
int32_t iActualLen = iSrcNalLen - iTrailingZeroByte;
pCurNal->sNalData.sVclNal.iNalLength = iActualLen;
//unify start code as 0x0001
int32_t iStartDeltaByte = 0; //0 for 0x0001, 1 for 0x001
if (pSrcNal[0] == 0x0 && pSrcNal[1] == 0x0 && pSrcNal[2] == 0x1) { //if 0x001
pSavedData->pCurPos[0] = 0x0;
iStartDeltaByte = 1;
pCurNal->sNalData.sVclNal.iNalLength++;
}
memcpy (pSavedData->pCurPos + iStartDeltaByte, pSrcNal, iActualLen);
pSavedData->pCurPos += iStartDeltaByte + iActualLen;
}
if (NAL_UNIT_PREFIX == pCtx->sPrefixNal.sNalHeaderExt.sNalUnitHeader.eNalUnitType) {
if (pCtx->sPrefixNal.sNalData.sPrefixNal.bPrefixNalCorrectFlag) {
PrefetchNalHeaderExtSyntax (pCtx, pCurNal, &pCtx->sPrefixNal);
}
}
pCurNal->sNalHeaderExt.bIdrFlag = (NAL_UNIT_CODED_SLICE_IDR == pNalUnitHeader->eNalUnitType) ? true :
false; //SHOULD update this flag for AVC if no prefix NAL
pCurNal->sNalHeaderExt.iNoInterLayerPredFlag = 1;
}
pBs = &pCurAu->pNalUnitsList[uiAvailNalNum - 1]->sNalData.sVclNal.sSliceBitsRead;
iBitSize = (iNalSize << 3) - BsGetTrailingBits (pNal + iNalSize - 1); // convert into bit
iErr = DecInitBits (pBs, pNal, iBitSize);
if (iErr) {
ForceClearCurrentNal (pCurAu);
if (uiAvailNalNum > 1) {
pCurAu->uiEndPos = uiAvailNalNum - 2;
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
pCtx->bAuReadyFlag = true;
}
}
WelsLog (pLogCtx, WELS_LOG_ERROR, "NAL_UNIT_CODED_SLICE: DecInitBits() fail due invalid access.");
pCtx->iErrorCode |= dsBitstreamError;
return NULL;
}
iErr = ParseSliceHeaderSyntaxs (pCtx, pBs, bExtensionFlag);
if (iErr != ERR_NONE) {
if ((uiAvailNalNum == 1) && (pCurNal->sNalHeaderExt.bIdrFlag)) { //IDR parse error
ResetActiveSPSForEachLayer (pCtx);
}
//if current NAL occur error when parsing, should clean it from pNalUnitsList
//otherwise, when Next good NAL decoding, this corrupt NAL is considered as normal NAL and lead to decoder crash
ForceClearCurrentNal (pCurAu);
if (uiAvailNalNum > 1) {
pCurAu->uiEndPos = uiAvailNalNum - 2;
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE) {
pCtx->bAuReadyFlag = true;
}
}
pCtx->iErrorCode |= dsBitstreamError;
return NULL;
}
if ((uiAvailNalNum == 1)
&& CheckNextAuNewSeq (pCtx, pCurNal, pCurNal->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps)) {
ResetActiveSPSForEachLayer (pCtx);
}
if ((uiAvailNalNum > 1) &&
CheckAccessUnitBoundary (pCtx, pCurAu->pNalUnitsList[uiAvailNalNum - 1], pCurAu->pNalUnitsList[uiAvailNalNum - 2],
pCurAu->pNalUnitsList[uiAvailNalNum - 1]->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps)) {
pCurAu->uiEndPos = uiAvailNalNum - 2;
pCtx->bAuReadyFlag = true;
pCtx->bNextNewSeqBegin = CheckNextAuNewSeq (pCtx, pCurNal, pCurNal->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps);
}
}
break;
default:
break;
}
return pNal;
}
bool CheckAccessUnitBoundaryExt (PNalUnitHeaderExt pLastNalHdrExt, PNalUnitHeaderExt pCurNalHeaderExt,
PSliceHeader pLastSliceHeader, PSliceHeader pCurSliceHeader) {
const PSps kpSps = pCurSliceHeader->pSps;
//Sub-clause 7.1.4.1.1 temporal_id
if (pLastNalHdrExt->uiTemporalId != pCurNalHeaderExt->uiTemporalId) {
return true;
}
// Subclause 7.4.1.2.5
if (pLastSliceHeader->iRedundantPicCnt > pCurSliceHeader->iRedundantPicCnt)
return true;
// Subclause G7.4.1.2.4
if (pLastNalHdrExt->uiDependencyId > pCurNalHeaderExt->uiDependencyId)
return true;
if (pLastNalHdrExt->uiQualityId > pCurNalHeaderExt->uiQualityId)
return true;
// Subclause 7.4.1.2.4
if (pLastSliceHeader->iFrameNum != pCurSliceHeader->iFrameNum)
return true;
if (pLastSliceHeader->iPpsId != pCurSliceHeader->iPpsId)
return true;
if (pLastSliceHeader->pSps->iSpsId != pCurSliceHeader->pSps->iSpsId)
return true;
if (pLastSliceHeader->bFieldPicFlag != pCurSliceHeader->bFieldPicFlag)
return true;
if (pLastSliceHeader->bBottomFiledFlag != pCurSliceHeader->bBottomFiledFlag)
return true;
if ((pLastNalHdrExt->sNalUnitHeader.uiNalRefIdc != NRI_PRI_LOWEST) != (pCurNalHeaderExt->sNalUnitHeader.uiNalRefIdc !=
NRI_PRI_LOWEST))
return true;
if (pLastNalHdrExt->bIdrFlag != pCurNalHeaderExt->bIdrFlag)
return true;
if (pCurNalHeaderExt->bIdrFlag) {
if (pLastSliceHeader->uiIdrPicId != pCurSliceHeader->uiIdrPicId)
return true;
}
if (kpSps->uiPocType == 0) {
if (pLastSliceHeader->iPicOrderCntLsb != pCurSliceHeader->iPicOrderCntLsb)
return true;
if (pLastSliceHeader->iDeltaPicOrderCntBottom != pCurSliceHeader->iDeltaPicOrderCntBottom)
return true;
} else if (kpSps->uiPocType == 1) {
if (pLastSliceHeader->iDeltaPicOrderCnt[0] != pCurSliceHeader->iDeltaPicOrderCnt[0])
return true;
if (pLastSliceHeader->iDeltaPicOrderCnt[1] != pCurSliceHeader->iDeltaPicOrderCnt[1])
return true;
}
if (memcmp (pLastSliceHeader->pPps, pCurSliceHeader->pPps, sizeof (SPps)) != 0
|| memcmp (pLastSliceHeader->pSps, pCurSliceHeader->pSps, sizeof (SSps)) != 0) {
return true;
}
return false;
}
bool CheckAccessUnitBoundary (PWelsDecoderContext pCtx, const PNalUnit kpCurNal, const PNalUnit kpLastNal,
const PSps kpSps) {
const PNalUnitHeaderExt kpLastNalHeaderExt = &kpLastNal->sNalHeaderExt;
const PNalUnitHeaderExt kpCurNalHeaderExt = &kpCurNal->sNalHeaderExt;
const SSliceHeader* kpLastSliceHeader = &kpLastNal->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader;
const SSliceHeader* kpCurSliceHeader = &kpCurNal->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader;
if (pCtx->pActiveLayerSps[kpCurNalHeaderExt->uiDependencyId] != NULL
&& pCtx->pActiveLayerSps[kpCurNalHeaderExt->uiDependencyId] != kpSps) {
return true; // the active sps changed, new sequence begins, so the current au is ready
}
//Sub-clause 7.1.4.1.1 temporal_id
if (kpLastNalHeaderExt->uiTemporalId != kpCurNalHeaderExt->uiTemporalId) {
return true;
}
if (kpLastSliceHeader->iFrameNum != kpCurSliceHeader->iFrameNum)
return true;
// Subclause 7.4.1.2.5
if (kpLastSliceHeader->iRedundantPicCnt > kpCurSliceHeader->iRedundantPicCnt)
return true;
// Subclause G7.4.1.2.4
if (kpLastNalHeaderExt->uiDependencyId > kpCurNalHeaderExt->uiDependencyId)
return true;
// Subclause 7.4.1.2.4
if (kpLastNalHeaderExt->uiDependencyId == kpCurNalHeaderExt->uiDependencyId
&& kpLastSliceHeader->iPpsId != kpCurSliceHeader->iPpsId)
return true;
if (kpLastSliceHeader->bFieldPicFlag != kpCurSliceHeader->bFieldPicFlag)
return true;
if (kpLastSliceHeader->bBottomFiledFlag != kpCurSliceHeader->bBottomFiledFlag)
return true;
if ((kpLastNalHeaderExt->sNalUnitHeader.uiNalRefIdc != NRI_PRI_LOWEST) != (kpCurNalHeaderExt->sNalUnitHeader.uiNalRefIdc
!= NRI_PRI_LOWEST))
return true;
if (kpLastNalHeaderExt->bIdrFlag != kpCurNalHeaderExt->bIdrFlag)
return true;
if (kpCurNalHeaderExt->bIdrFlag) {
if (kpLastSliceHeader->uiIdrPicId != kpCurSliceHeader->uiIdrPicId)
return true;
}
if (kpSps->uiPocType == 0) {
if (kpLastSliceHeader->iPicOrderCntLsb != kpCurSliceHeader->iPicOrderCntLsb)
return true;
if (kpLastSliceHeader->iDeltaPicOrderCntBottom != kpCurSliceHeader->iDeltaPicOrderCntBottom)
return true;
} else if (kpSps->uiPocType == 1) {
if (kpLastSliceHeader->iDeltaPicOrderCnt[0] != kpCurSliceHeader->iDeltaPicOrderCnt[0])
return true;
if (kpLastSliceHeader->iDeltaPicOrderCnt[1] != kpCurSliceHeader->iDeltaPicOrderCnt[1])
return true;
}
return false;
}
bool CheckNextAuNewSeq (PWelsDecoderContext pCtx, const PNalUnit kpCurNal, const PSps kpSps) {
const PNalUnitHeaderExt kpCurNalHeaderExt = &kpCurNal->sNalHeaderExt;
if (pCtx->pActiveLayerSps[kpCurNalHeaderExt->uiDependencyId] != NULL
&& pCtx->pActiveLayerSps[kpCurNalHeaderExt->uiDependencyId] != kpSps)
return true;
if (kpCurNalHeaderExt->bIdrFlag)
return true;
return false;
}
/*!
*************************************************************************************
* \brief to parse NON VCL NAL Units
*
* \param pCtx decoder context
* \param rbsp rbsp buffer of NAL Unit
* \param src_len length of rbsp buffer
*
* \return 0 - successed
* 1 - failed
*
*************************************************************************************
*/
int32_t ParseNonVclNal (PWelsDecoderContext pCtx, uint8_t* pRbsp, const int32_t kiSrcLen, uint8_t* pSrcNal,
const int32_t kSrcNalLen) {
PBitStringAux pBs = NULL;
EWelsNalUnitType eNalType = NAL_UNIT_UNSPEC_0; // make initial value as unspecified
int32_t iPicWidth = 0;
int32_t iPicHeight = 0;
int32_t iBitSize = 0;
int32_t iErr = ERR_NONE;
if (kiSrcLen <= 0)
return iErr;
pBs = &pCtx->sBs; // SBitStringAux instance for non VCL NALs decoding
iBitSize = (kiSrcLen << 3) - BsGetTrailingBits (pRbsp + kiSrcLen - 1); // convert into bit
eNalType = pCtx->sCurNalHead.eNalUnitType;
switch (eNalType) {
case NAL_UNIT_SPS:
case NAL_UNIT_SUBSET_SPS:
if (iBitSize > 0) {
iErr = DecInitBits (pBs, pRbsp, iBitSize);
if (ERR_NONE != iErr) {
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE)
pCtx->iErrorCode |= dsNoParamSets;
else
pCtx->iErrorCode |= dsBitstreamError;
return iErr;
}
}
iErr = ParseSps (pCtx, pBs, &iPicWidth, &iPicHeight, pSrcNal, kSrcNalLen);
if (ERR_NONE != iErr) { // modified for pSps/pSubsetSps invalid, 12/1/2009
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE)
pCtx->iErrorCode |= dsNoParamSets;
else
pCtx->iErrorCode |= dsBitstreamError;
return iErr;
}
break;
case NAL_UNIT_PPS:
if (iBitSize > 0) {
iErr = DecInitBits (pBs, pRbsp, iBitSize);
if (ERR_NONE != iErr) {
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE)
pCtx->iErrorCode |= dsNoParamSets;
else
pCtx->iErrorCode |= dsBitstreamError;
return iErr;
}
}
iErr = ParsePps (pCtx, &pCtx->sPpsBuffer[0], pBs, pSrcNal, kSrcNalLen);
if (ERR_NONE != iErr) { // modified for pps invalid, 12/1/2009
if (pCtx->pParam->eEcActiveIdc == ERROR_CON_DISABLE)
pCtx->iErrorCode |= dsNoParamSets;
else
pCtx->iErrorCode |= dsBitstreamError;
return iErr;
}
pCtx->bPpsExistAheadFlag = true;
break;
case NAL_UNIT_SEI:
break;
case NAL_UNIT_PREFIX:
break;
case NAL_UNIT_CODED_SLICE_DPA:
case NAL_UNIT_CODED_SLICE_DPB:
case NAL_UNIT_CODED_SLICE_DPC:
break;
default:
break;
}
return iErr;
}
int32_t ParseRefBasePicMarking (PBitStringAux pBs, PRefBasePicMarking pRefBasePicMarking) {
uint32_t uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //adaptive_ref_base_pic_marking_mode_flag
const bool kbAdaptiveMarkingModeFlag = !!uiCode;
pRefBasePicMarking->bAdaptiveRefBasePicMarkingModeFlag = kbAdaptiveMarkingModeFlag;
if (kbAdaptiveMarkingModeFlag) {
int32_t iIdx = 0;
do {
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //MMCO_base
const uint32_t kuiMmco = uiCode;
pRefBasePicMarking->mmco_base[iIdx].uiMmcoType = kuiMmco;
if (kuiMmco == MMCO_END)
break;
if (kuiMmco == MMCO_SHORT2UNUSED) {
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //difference_of_base_pic_nums_minus1
pRefBasePicMarking->mmco_base[iIdx].uiDiffOfPicNums = 1 + uiCode;
pRefBasePicMarking->mmco_base[iIdx].iShortFrameNum = 0;
} else if (kuiMmco == MMCO_LONG2UNUSED) {
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //long_term_base_pic_num
pRefBasePicMarking->mmco_base[iIdx].uiLongTermPicNum = uiCode;
}
++ iIdx;
} while (iIdx < MAX_MMCO_COUNT);
}
return ERR_NONE;
}
int32_t ParsePrefixNalUnit (PWelsDecoderContext pCtx, PBitStringAux pBs) {
PNalUnit pCurNal = &pCtx->sPrefixNal;
uint32_t uiCode;
if (pCurNal->sNalHeaderExt.sNalUnitHeader.uiNalRefIdc != 0) {
PNalUnitHeaderExt head_ext = &pCurNal->sNalHeaderExt;
PPrefixNalUnit sPrefixNal = &pCurNal->sNalData.sPrefixNal;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //store_ref_base_pic_flag
sPrefixNal->bStoreRefBasePicFlag = !!uiCode;
if ((head_ext->bUseRefBasePicFlag || sPrefixNal->bStoreRefBasePicFlag) && !head_ext->bIdrFlag) {
WELS_READ_VERIFY (ParseRefBasePicMarking (pBs, &sPrefixNal->sRefPicBaseMarking));
}
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //additional_prefix_nal_unit_extension_flag
sPrefixNal->bPrefixNalUnitAdditionalExtFlag = !!uiCode;
if (sPrefixNal->bPrefixNalUnitAdditionalExtFlag) {
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //additional_prefix_nal_unit_extension_data_flag
sPrefixNal->bPrefixNalUnitExtFlag = !!uiCode;
}
}
return ERR_NONE;
}
#define SUBSET_SPS_SEQ_SCALED_REF_LAYER_LEFT_OFFSET_MIN -32768
#define SUBSET_SPS_SEQ_SCALED_REF_LAYER_LEFT_OFFSET_MAX 32767
#define SUBSET_SPS_SEQ_SCALED_REF_LAYER_TOP_OFFSET_MIN -32768
#define SUBSET_SPS_SEQ_SCALED_REF_LAYER_TOP_OFFSET_MAX 32767
#define SUBSET_SPS_SEQ_SCALED_REF_LAYER_RIGHT_OFFSET_MIN -32768
#define SUBSET_SPS_SEQ_SCALED_REF_LAYER_RIGHT_OFFSET_MAX 32767
#define SUBSET_SPS_SEQ_SCALED_REF_LAYER_BOTTOM_OFFSET_MIN -32768
#define SUBSET_SPS_SEQ_SCALED_REF_LAYER_BOTTOM_OFFSET_MAX 32767
int32_t DecodeSpsSvcExt (PWelsDecoderContext pCtx, PSubsetSps pSpsExt, PBitStringAux pBs) {
PSpsSvcExt pExt = NULL;
uint32_t uiCode;
int32_t iCode;
pExt = &pSpsExt->sSpsSvcExt;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //inter_layer_deblocking_filter_control_present_flag
pExt->bInterLayerDeblockingFilterCtrlPresentFlag = !!uiCode;
WELS_READ_VERIFY (BsGetBits (pBs, 2, &uiCode)); //extended_spatial_scalability_idc
pExt->uiExtendedSpatialScalability = uiCode;
if (pExt->uiExtendedSpatialScalability > 2) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING,
"DecodeSpsSvcExt():extended_spatial_scalability (%d) != 0, ESS not supported!",
pExt->uiExtendedSpatialScalability);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_ESS);
}
pExt->uiChromaPhaseXPlus1Flag =
0; // FIXME: Incoherent with JVT X201 standard (= 1), but conformance to JSVM (= 0) implementation.
pExt->uiChromaPhaseYPlus1 = 1;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //chroma_phase_x_plus1_flag
pExt->uiChromaPhaseXPlus1Flag = uiCode;
WELS_READ_VERIFY (BsGetBits (pBs, 2, &uiCode)); //chroma_phase_y_plus1
pExt->uiChromaPhaseYPlus1 = uiCode;
pExt->uiSeqRefLayerChromaPhaseXPlus1Flag = pExt->uiChromaPhaseXPlus1Flag;
pExt->uiSeqRefLayerChromaPhaseYPlus1 = pExt->uiChromaPhaseYPlus1;
memset (&pExt->sSeqScaledRefLayer, 0, sizeof (SPosOffset));
if (pExt->uiExtendedSpatialScalability == 1) {
SPosOffset* const kpPos = &pExt->sSeqScaledRefLayer;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //seq_ref_layer_chroma_phase_x_plus1_flag
pExt->uiSeqRefLayerChromaPhaseXPlus1Flag = uiCode;
WELS_READ_VERIFY (BsGetBits (pBs, 2, &uiCode)); //seq_ref_layer_chroma_phase_y_plus1
pExt->uiSeqRefLayerChromaPhaseYPlus1 = uiCode;
WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //seq_scaled_ref_layer_left_offset
kpPos->iLeftOffset = iCode;
WELS_CHECK_SE_BOTH_WARNING (kpPos->iLeftOffset, SUBSET_SPS_SEQ_SCALED_REF_LAYER_LEFT_OFFSET_MIN,
SUBSET_SPS_SEQ_SCALED_REF_LAYER_LEFT_OFFSET_MAX, "seq_scaled_ref_layer_left_offset");
WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //seq_scaled_ref_layer_top_offset
kpPos->iTopOffset = iCode;
WELS_CHECK_SE_BOTH_WARNING (kpPos->iTopOffset, SUBSET_SPS_SEQ_SCALED_REF_LAYER_TOP_OFFSET_MIN,
SUBSET_SPS_SEQ_SCALED_REF_LAYER_TOP_OFFSET_MAX, "seq_scaled_ref_layer_top_offset");
WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //seq_scaled_ref_layer_right_offset
kpPos->iRightOffset = iCode;
WELS_CHECK_SE_BOTH_WARNING (kpPos->iRightOffset, SUBSET_SPS_SEQ_SCALED_REF_LAYER_RIGHT_OFFSET_MIN,
SUBSET_SPS_SEQ_SCALED_REF_LAYER_RIGHT_OFFSET_MAX, "seq_scaled_ref_layer_right_offset");
WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //seq_scaled_ref_layer_bottom_offset
kpPos->iBottomOffset = iCode;
WELS_CHECK_SE_BOTH_WARNING (kpPos->iBottomOffset, SUBSET_SPS_SEQ_SCALED_REF_LAYER_BOTTOM_OFFSET_MIN,
SUBSET_SPS_SEQ_SCALED_REF_LAYER_BOTTOM_OFFSET_MAX, "seq_scaled_ref_layer_bottom_offset");
}
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //seq_tcoeff_level_prediction_flag
pExt->bSeqTCoeffLevelPredFlag = !!uiCode;
pExt->bAdaptiveTCoeffLevelPredFlag = false;
if (pExt->bSeqTCoeffLevelPredFlag) {
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //adaptive_tcoeff_level_prediction_flag
pExt->bAdaptiveTCoeffLevelPredFlag = !!uiCode;
}
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //slice_header_restriction_flag
pExt->bSliceHeaderRestrictionFlag = !!uiCode;
return ERR_NONE;
}
const SLevelLimits* GetLevelLimits (int32_t iLevelIdx, bool bConstraint3) {
switch (iLevelIdx) {
case 9:
return &g_ksLevelLimits[1];
case 10:
return &g_ksLevelLimits[0];
case 11:
if (bConstraint3)
return &g_ksLevelLimits[1];
else
return &g_ksLevelLimits[2];
case 12:
return &g_ksLevelLimits[3];
case 13:
return &g_ksLevelLimits[4];
case 20:
return &g_ksLevelLimits[5];
case 21:
return &g_ksLevelLimits[6];
case 22:
return &g_ksLevelLimits[7];
case 30:
return &g_ksLevelLimits[8];
case 31:
return &g_ksLevelLimits[9];
case 32:
return &g_ksLevelLimits[10];
case 40:
return &g_ksLevelLimits[11];
case 41:
return &g_ksLevelLimits[12];
case 42:
return &g_ksLevelLimits[13];
case 50:
return &g_ksLevelLimits[14];
case 51:
return &g_ksLevelLimits[15];
case 52:
return &g_ksLevelLimits[16];
default:
return NULL;
}
return NULL;
}
bool CheckSpsActive (PWelsDecoderContext pCtx, PSps pSps, bool bUseSubsetFlag) {
for (int i = 0; i < MAX_LAYER_NUM; i++) {
if (pCtx->pActiveLayerSps[i] == pSps)
return true;
}
// Pre-active, will be used soon
if (bUseSubsetFlag) {
if (pSps->iMbWidth > 0 && pSps->iMbHeight > 0 && pCtx->bSubspsAvailFlags[pSps->iSpsId]) {
if (pCtx->iTotalNumMbRec > 0) {
return true;
}
if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
int i = 0, iNum = (int32_t) pCtx->pAccessUnitList->uiAvailUnitsNum;
while (i < iNum) {
PNalUnit pNalUnit = pCtx->pAccessUnitList->pNalUnitsList[i];
if (pNalUnit->sNalData.sVclNal.bSliceHeaderExtFlag) { //ext data
PSps pNextUsedSps = pNalUnit->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps;
if (pNextUsedSps->iSpsId == pSps->iSpsId)
return true;
}
++i;
}
}
}
} else {
if (pSps->iMbWidth > 0 && pSps->iMbHeight > 0 && pCtx->bSpsAvailFlags[pSps->iSpsId]) {
if (pCtx->iTotalNumMbRec > 0) {
return true;
}
if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
int i = 0, iNum = (int32_t) pCtx->pAccessUnitList->uiAvailUnitsNum;
while (i < iNum) {
PNalUnit pNalUnit = pCtx->pAccessUnitList->pNalUnitsList[i];
if (!pNalUnit->sNalData.sVclNal.bSliceHeaderExtFlag) { //non-ext data
PSps pNextUsedSps = pNalUnit->sNalData.sVclNal.sSliceHeaderExt.sSliceHeader.pSps;
if (pNextUsedSps->iSpsId == pSps->iSpsId)
return true;
}
++i;
}
}
}
}
return false;
}
#define SPS_LOG2_MAX_FRAME_NUM_MINUS4_MAX 12
#define SPS_LOG2_MAX_PIC_ORDER_CNT_LSB_MINUS4_MAX 12
#define SPS_NUM_REF_FRAMES_IN_PIC_ORDER_CNT_CYCLE_MAX 255
#define SPS_MAX_NUM_REF_FRAMES_MAX 16
#define PPS_PIC_INIT_QP_QS_MIN 0
#define PPS_PIC_INIT_QP_QS_MAX 51
#define PPS_CHROMA_QP_INDEX_OFFSET_MIN -12
#define PPS_CHROMA_QP_INDEX_OFFSET_MAX 12
#define SCALING_LIST_DELTA_SCALE_MAX 127
#define SCALING_LIST_DELTA_SCALE_MIN -128
/*!
*************************************************************************************
* \brief to parse Sequence Parameter Set (SPS)
*
* \param pCtx Decoder context
* \param pBsAux bitstream reader auxiliary
* \param pPicWidth picture width current Sps represented
* \param pPicHeight picture height current Sps represented
*
* \return 0 - successed
* 1 - failed
*
* \note Call it in case eNalUnitType is SPS.
*************************************************************************************
*/
int32_t ParseSps (PWelsDecoderContext pCtx, PBitStringAux pBsAux, int32_t* pPicWidth, int32_t* pPicHeight,
uint8_t* pSrcNal, const int32_t kSrcNalLen) {
PBitStringAux pBs = pBsAux;
SSubsetSps sTempSubsetSps;
PSps pSps = NULL;
PSubsetSps pSubsetSps = NULL;
SNalUnitHeader* pNalHead = &pCtx->sCurNalHead;
ProfileIdc uiProfileIdc;
uint8_t uiLevelIdc;
int32_t iSpsId;
uint32_t uiCode;
int32_t iCode;
int32_t iRet = ERR_NONE;
bool bConstraintSetFlags[6] = { false };
const bool kbUseSubsetFlag = IS_SUBSET_SPS_NAL (pNalHead->eNalUnitType);
WELS_READ_VERIFY (BsGetBits (pBs, 8, &uiCode)); //profile_idc
uiProfileIdc = uiCode;
if (uiProfileIdc != PRO_BASELINE && uiProfileIdc != PRO_MAIN && uiProfileIdc != PRO_SCALABLE_BASELINE
&& uiProfileIdc != PRO_SCALABLE_HIGH
&& uiProfileIdc != PRO_EXTENDED && uiProfileIdc != PRO_HIGH) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "SPS ID can not be supported!\n");
return false;
}
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set0_flag
bConstraintSetFlags[0] = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set1_flag
bConstraintSetFlags[1] = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set2_flag
bConstraintSetFlags[2] = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set3_flag
bConstraintSetFlags[3] = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set4_flag
bConstraintSetFlags[4] = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //constraint_set5_flag
bConstraintSetFlags[5] = !!uiCode;
WELS_READ_VERIFY (BsGetBits (pBs, 2, &uiCode)); // reserved_zero_2bits, equal to 0
WELS_READ_VERIFY (BsGetBits (pBs, 8, &uiCode)); // level_idc
uiLevelIdc = uiCode;
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //seq_parameter_set_id
if (uiCode >= MAX_SPS_COUNT) { // Modified to check invalid negative iSpsId, 12/1/2009
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, " iSpsId is out of range! \n");
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_SPS_ID_OVERFLOW);
}
iSpsId = uiCode;
pSubsetSps = &sTempSubsetSps;
pSps = &sTempSubsetSps.sSps;
memset (pSubsetSps, 0, sizeof (SSubsetSps));
// Use the level 5.2 for compatibility
const SLevelLimits* pSMaxLevelLimits = GetLevelLimits (52, false);
const SLevelLimits* pSLevelLimits = GetLevelLimits (uiLevelIdc, bConstraintSetFlags[3]);
if (NULL == pSLevelLimits) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): level_idx (%d).\n", uiLevelIdc);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
} else pSps->pSLevelLimits = pSLevelLimits;
// syntax elements in default
pSps->uiChromaFormatIdc = 1;
pSps->uiChromaArrayType = 1;
pSps->uiProfileIdc = uiProfileIdc;
pSps->uiLevelIdc = uiLevelIdc;
pSps->iSpsId = iSpsId;
if (PRO_SCALABLE_BASELINE == uiProfileIdc || PRO_SCALABLE_HIGH == uiProfileIdc ||
PRO_HIGH == uiProfileIdc || PRO_HIGH10 == uiProfileIdc ||
PRO_HIGH422 == uiProfileIdc || PRO_HIGH444 == uiProfileIdc ||
PRO_CAVLC444 == uiProfileIdc || 44 == uiProfileIdc) {
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //chroma_format_idc
pSps->uiChromaFormatIdc = uiCode;
// if (pSps->uiChromaFormatIdc != 1) {
// WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): chroma_format_idc (%d) = 1 supported.",
// pSps->uiChromaFormatIdc);
// return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
// }
if (pSps->uiChromaFormatIdc > 1) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): chroma_format_idc (%d) <=1 supported.",
pSps->uiChromaFormatIdc);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
}// To support 4:0:0; 4:2:0
pSps->uiChromaArrayType = pSps->uiChromaFormatIdc;
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //bit_depth_luma_minus8
if (uiCode != 0) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): bit_depth_luma (%d) Only 8 bit supported.", 8 + uiCode);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
}
pSps->uiBitDepthLuma = 8;
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //bit_depth_chroma_minus8
if (uiCode != 0) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): bit_depth_chroma (%d). Only 8 bit supported.", 8 + uiCode);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_NON_BASELINE);
}
pSps->uiBitDepthChroma = 8;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //qpprime_y_zero_transform_bypass_flag
pSps->bQpPrimeYZeroTransfBypassFlag = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //seq_scaling_matrix_present_flag
pSps->bSeqScalingMatrixPresentFlag = !!uiCode;
if (pSps->bSeqScalingMatrixPresentFlag) {
WELS_READ_VERIFY (ParseScalingList (pSps, pBs, 0, 0, pSps->bSeqScalingListPresentFlag, pSps->iScalingList4x4,
pSps->iScalingList8x8));
}
}
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //log2_max_frame_num_minus4
WELS_CHECK_SE_UPPER_ERROR (uiCode, SPS_LOG2_MAX_FRAME_NUM_MINUS4_MAX, "log2_max_frame_num_minus4",
GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_LOG2_MAX_FRAME_NUM_MINUS4));
pSps->uiLog2MaxFrameNum = LOG2_MAX_FRAME_NUM_OFFSET + uiCode;
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //pic_order_cnt_type
pSps->uiPocType = uiCode;
if (0 == pSps->uiPocType) {
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //log2_max_pic_order_cnt_lsb_minus4
// log2_max_pic_order_cnt_lsb_minus4 should be in range 0 to 12, inclusive. (sec. 7.4.3)
WELS_CHECK_SE_UPPER_ERROR (uiCode, SPS_LOG2_MAX_PIC_ORDER_CNT_LSB_MINUS4_MAX, "log2_max_pic_order_cnt_lsb_minus4",
GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_LOG2_MAX_PIC_ORDER_CNT_LSB_MINUS4));
pSps->iLog2MaxPocLsb = LOG2_MAX_PIC_ORDER_CNT_LSB_OFFSET + uiCode; // log2_max_pic_order_cnt_lsb_minus4
} else if (1 == pSps->uiPocType) {
int32_t i;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //delta_pic_order_always_zero_flag
pSps->bDeltaPicOrderAlwaysZeroFlag = !!uiCode;
WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //offset_for_non_ref_pic
pSps->iOffsetForNonRefPic = iCode;
WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //offset_for_top_to_bottom_field
pSps->iOffsetForTopToBottomField = iCode;
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //num_ref_frames_in_pic_order_cnt_cycle
WELS_CHECK_SE_UPPER_ERROR (uiCode, SPS_NUM_REF_FRAMES_IN_PIC_ORDER_CNT_CYCLE_MAX,
"num_ref_frames_in_pic_order_cnt_cycle", GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS,
ERR_INFO_INVALID_NUM_REF_FRAME_IN_PIC_ORDER_CNT_CYCLE));
pSps->iNumRefFramesInPocCycle = uiCode;
for (i = 0; i < pSps->iNumRefFramesInPocCycle; i++) {
WELS_READ_VERIFY (BsGetSe (pBs, &iCode)); //offset_for_ref_frame[ i ]
pSps->iOffsetForRefFrame[ i ] = iCode;
}
}
if (pSps->uiPocType > 2) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, " illegal pic_order_cnt_type: %d ! ", pSps->uiPocType);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_POC_TYPE);
}
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //max_num_ref_frames
pSps->iNumRefFrames = uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //gaps_in_frame_num_value_allowed_flag
pSps->bGapsInFrameNumValueAllowedFlag = !!uiCode;
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //pic_width_in_mbs_minus1
pSps->iMbWidth = PIC_WIDTH_IN_MBS_OFFSET + uiCode;
if (pSps->iMbWidth > MAX_MB_SIZE || pSps->iMbWidth == 0) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "pic_width_in_mbs(%d) invalid!", pSps->iMbWidth);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
}
if (((uint64_t)pSps->iMbWidth * (uint64_t)pSps->iMbWidth) > (uint64_t) (8 * pSLevelLimits->uiMaxFS)) {
if (((uint64_t)pSps->iMbWidth * (uint64_t)pSps->iMbWidth) > (uint64_t) (8 * pSMaxLevelLimits->uiMaxFS)) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "the pic_width_in_mbs exceeds the level limits!");
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
} else {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "the pic_width_in_mbs exceeds the level limits!");
}
}
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //pic_height_in_map_units_minus1
pSps->iMbHeight = PIC_HEIGHT_IN_MAP_UNITS_OFFSET + uiCode;
if (pSps->iMbHeight > MAX_MB_SIZE || pSps->iMbHeight == 0) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "pic_height_in_mbs(%d) invalid!", pSps->iMbHeight);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
}
if (((uint64_t)pSps->iMbHeight * (uint64_t)pSps->iMbHeight) > (uint64_t) (8 * pSLevelLimits->uiMaxFS)) {
if (((uint64_t)pSps->iMbHeight * (uint64_t)pSps->iMbHeight) > (uint64_t) (8 * pSMaxLevelLimits->uiMaxFS)) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "the pic_height_in_mbs exceeds the level limits!");
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
} else {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "the pic_height_in_mbs exceeds the level limits!");
}
}
uint64_t uiTmp64 = (uint64_t)pSps->iMbWidth * (uint64_t)pSps->iMbHeight;
if (uiTmp64 > (uint64_t)pSLevelLimits->uiMaxFS) {
if (uiTmp64 > (uint64_t)pSMaxLevelLimits->uiMaxFS) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "the total count of mb exceeds the level limits!");
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_MB_SIZE);
} else {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "the total count of mb exceeds the level limits!");
}
}
pSps->uiTotalMbCount = (uint32_t)uiTmp64;
WELS_CHECK_SE_UPPER_ERROR (pSps->iNumRefFrames, SPS_MAX_NUM_REF_FRAMES_MAX, "max_num_ref_frames",
GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_MAX_NUM_REF_FRAMES));
// here we check max_num_ref_frames
uint32_t uiMaxDpbMbs = pSLevelLimits->uiMaxDPBMbs;
uint32_t uiMaxDpbFrames = uiMaxDpbMbs / pSps->uiTotalMbCount;
if (uiMaxDpbFrames > SPS_MAX_NUM_REF_FRAMES_MAX)
uiMaxDpbFrames = SPS_MAX_NUM_REF_FRAMES_MAX;
if ((uint32_t)pSps->iNumRefFrames > uiMaxDpbFrames) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, " max_num_ref_frames exceeds level limits!");
}
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //frame_mbs_only_flag
pSps->bFrameMbsOnlyFlag = !!uiCode;
if (!pSps->bFrameMbsOnlyFlag) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParseSps(): frame_mbs_only_flag (%d) not supported.",
pSps->bFrameMbsOnlyFlag);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_MBAFF);
}
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //direct_8x8_inference_flag
pSps->bDirect8x8InferenceFlag = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //frame_cropping_flag
pSps->bFrameCroppingFlag = !!uiCode;
if (pSps->bFrameCroppingFlag) {
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //frame_crop_left_offset
pSps->sFrameCrop.iLeftOffset = uiCode;
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //frame_crop_right_offset
pSps->sFrameCrop.iRightOffset = uiCode;
if ((pSps->sFrameCrop.iLeftOffset + pSps->sFrameCrop.iRightOffset) > ((int32_t)pSps->iMbWidth * 16 / 2)) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "frame_crop_left_offset + frame_crop_right_offset exceeds limits!");
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_CROPPING_DATA);
}
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //frame_crop_top_offset
pSps->sFrameCrop.iTopOffset = uiCode;
WELS_READ_VERIFY (BsGetUe (pBs, &uiCode)); //frame_crop_bottom_offset
pSps->sFrameCrop.iBottomOffset = uiCode;
if ((pSps->sFrameCrop.iTopOffset + pSps->sFrameCrop.iBottomOffset) > ((int32_t)pSps->iMbHeight * 16 / 2)) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "frame_crop_top_offset + frame_crop_right_offset exceeds limits!");
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_CROPPING_DATA);
}
} else {
pSps->sFrameCrop.iLeftOffset = 0; // frame_crop_left_offset
pSps->sFrameCrop.iRightOffset = 0; // frame_crop_right_offset
pSps->sFrameCrop.iTopOffset = 0; // frame_crop_top_offset
pSps->sFrameCrop.iBottomOffset = 0; // frame_crop_bottom_offset
}
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //vui_parameters_present_flag
pSps->bVuiParamPresentFlag = !!uiCode;
if (pSps->bVuiParamPresentFlag) {
int iRetVui = ParseVui (pCtx, pSps, pBsAux);
if (iRetVui == GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_VUI_HRD)) {
if (kbUseSubsetFlag) { //Currently do no support VUI with HRD enable in subsetSPS
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "hrd parse in vui of subsetSPS is not supported!");
return iRetVui;
}
} else {
WELS_READ_VERIFY (iRetVui);
}
}
if (pCtx->pParam->bParseOnly) {
if (kSrcNalLen >= SPS_PPS_BS_SIZE - 4) { //sps bs exceeds!
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "sps payload size (%d) too large for parse only (%d), not supported!",
kSrcNalLen, SPS_PPS_BS_SIZE - 4);
pCtx->iErrorCode |= dsBitstreamError;
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_OUT_OF_MEMORY);
}
if (!kbUseSubsetFlag) { //SPS
SSpsBsInfo* pSpsBs = &pCtx->sSpsBsInfo [iSpsId];
pSpsBs->iSpsId = iSpsId;
int32_t iTrailingZeroByte = 0;
while (pSrcNal[kSrcNalLen - iTrailingZeroByte - 1] == 0x0) //remove final trailing 0 bytes
iTrailingZeroByte++;
int32_t iActualLen = kSrcNalLen - iTrailingZeroByte;
pSpsBs->uiSpsBsLen = (uint16_t) iActualLen;
//unify start code as 0x0001
int32_t iStartDeltaByte = 0; //0 for 0x0001, 1 for 0x001
if (pSrcNal[0] == 0x0 && pSrcNal[1] == 0x0 && pSrcNal[2] == 0x1) { //if 0x001
pSpsBs->pSpsBsBuf[0] = 0x0; //add 0 to form 0x0001
iStartDeltaByte++;
pSpsBs->uiSpsBsLen++;
}
memcpy (pSpsBs->pSpsBsBuf + iStartDeltaByte, pSrcNal, iActualLen);
} else { //subset SPS
SSpsBsInfo* pSpsBs = &pCtx->sSubsetSpsBsInfo [iSpsId];
pSpsBs->iSpsId = iSpsId;
pSpsBs->pSpsBsBuf [0] = pSpsBs->pSpsBsBuf [1] = pSpsBs->pSpsBsBuf [2] = 0x00;
pSpsBs->pSpsBsBuf [3] = 0x01;
pSpsBs->pSpsBsBuf [4] = 0x67;
//re-write subset SPS to SPS
SBitStringAux sSubsetSpsBs;
CMemoryAlign* pMa = pCtx->pMemAlign;
uint8_t* pBsBuf = static_cast<uint8_t*> (pMa->WelsMallocz (SPS_PPS_BS_SIZE + 4,
"Temp buffer for parse only usage.")); //to reserve 4 bytes for UVLC writing buffer
if (NULL == pBsBuf) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_ERROR, "sps buffer alloc failed for parse only!");
pCtx->iErrorCode |= dsOutOfMemory;
return pCtx->iErrorCode;
}
InitBits (&sSubsetSpsBs, pBsBuf, (int32_t) (pBs->pEndBuf - pBs->pStartBuf));
BsWriteBits (&sSubsetSpsBs, 8, 77); //profile_idc, forced to Main profile
BsWriteOneBit (&sSubsetSpsBs, pSps->bConstraintSet0Flag); // constraint_set0_flag
BsWriteOneBit (&sSubsetSpsBs, pSps->bConstraintSet1Flag); // constraint_set1_flag
BsWriteOneBit (&sSubsetSpsBs, pSps->bConstraintSet2Flag); // constraint_set2_flag
BsWriteOneBit (&sSubsetSpsBs, pSps->bConstraintSet3Flag); // constraint_set3_flag
BsWriteBits (&sSubsetSpsBs, 4, 0); //constraint_set4_flag, constraint_set5_flag, reserved_zero_2bits
BsWriteBits (&sSubsetSpsBs, 8, pSps->uiLevelIdc); //level_idc
BsWriteUE (&sSubsetSpsBs, pSps->iSpsId); //sps_id
BsWriteUE (&sSubsetSpsBs, pSps->uiLog2MaxFrameNum - 4); //log2_max_frame_num_minus4
BsWriteUE (&sSubsetSpsBs, pSps->uiPocType); //pic_order_cnt_type
if (pSps->uiPocType == 0) {
BsWriteUE (&sSubsetSpsBs, pSps->iLog2MaxPocLsb - 4); //log2_max_pic_order_cnt_lsb_minus4
} else if (pSps->uiPocType == 1) {
BsWriteOneBit (&sSubsetSpsBs, pSps->bDeltaPicOrderAlwaysZeroFlag); //delta_pic_order_always_zero_flag
BsWriteSE (&sSubsetSpsBs, pSps->iOffsetForNonRefPic); //offset_for_no_ref_pic
BsWriteSE (&sSubsetSpsBs, pSps->iOffsetForTopToBottomField); //offset_for_top_to_bottom_field
BsWriteUE (&sSubsetSpsBs, pSps->iNumRefFramesInPocCycle); //num_ref_frames_in_pic_order_cnt_cycle
for (int32_t i = 0; i < pSps->iNumRefFramesInPocCycle; ++i) {
BsWriteSE (&sSubsetSpsBs, pSps->iOffsetForRefFrame[i]); //offset_for_ref_frame[i]
}
}
BsWriteUE (&sSubsetSpsBs, pSps->iNumRefFrames); //max_num_ref_frames
BsWriteOneBit (&sSubsetSpsBs, pSps->bGapsInFrameNumValueAllowedFlag); //gaps_in_frame_num_value_allowed_flag
BsWriteUE (&sSubsetSpsBs, pSps->iMbWidth - 1); //pic_width_in_mbs_minus1
BsWriteUE (&sSubsetSpsBs, pSps->iMbHeight - 1); //pic_height_in_map_units_minus1
BsWriteOneBit (&sSubsetSpsBs, pSps->bFrameMbsOnlyFlag); //frame_mbs_only_flag
if (!pSps->bFrameMbsOnlyFlag) {
BsWriteOneBit (&sSubsetSpsBs, pSps->bMbaffFlag); //mb_adaptive_frame_field_flag
}
BsWriteOneBit (&sSubsetSpsBs, pSps->bDirect8x8InferenceFlag); //direct_8x8_inference_flag
BsWriteOneBit (&sSubsetSpsBs, pSps->bFrameCroppingFlag); //frame_cropping_flag
if (pSps->bFrameCroppingFlag) {
BsWriteUE (&sSubsetSpsBs, pSps->sFrameCrop.iLeftOffset); //frame_crop_left_offset
BsWriteUE (&sSubsetSpsBs, pSps->sFrameCrop.iRightOffset); //frame_crop_right_offset
BsWriteUE (&sSubsetSpsBs, pSps->sFrameCrop.iTopOffset); //frame_crop_top_offset
BsWriteUE (&sSubsetSpsBs, pSps->sFrameCrop.iBottomOffset); //frame_crop_bottom_offset
}
BsWriteOneBit (&sSubsetSpsBs, 0); //vui_parameters_present_flag
BsRbspTrailingBits (&sSubsetSpsBs); //finished, rbsp trailing bit
int32_t iRbspSize = (int32_t) (sSubsetSpsBs.pCurBuf - sSubsetSpsBs.pStartBuf);
RBSP2EBSP (pSpsBs->pSpsBsBuf + 5, sSubsetSpsBs.pStartBuf, iRbspSize);
pSpsBs->uiSpsBsLen = (uint16_t) (sSubsetSpsBs.pCurBuf - sSubsetSpsBs.pStartBuf + 5);
if (pBsBuf) {
pMa->WelsFree (pBsBuf, "pBsBuf for parse only usage");
}
}
}
// Check if SPS SVC extension applicated
if (kbUseSubsetFlag && (PRO_SCALABLE_BASELINE == uiProfileIdc || PRO_SCALABLE_HIGH == uiProfileIdc)) {
if ((iRet = DecodeSpsSvcExt (pCtx, pSubsetSps, pBs)) != ERR_NONE) {
return iRet;
}
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode)); //svc_vui_parameters_present_flag
pSubsetSps->bSvcVuiParamPresentFlag = !!uiCode;
if (pSubsetSps->bSvcVuiParamPresentFlag) {
}
}
if (PRO_SCALABLE_BASELINE == uiProfileIdc || PRO_SCALABLE_HIGH == uiProfileIdc)
pCtx->bAvcBasedFlag = false;
*pPicWidth = pSps->iMbWidth << 4;
*pPicHeight = pSps->iMbHeight << 4;
PSps pTmpSps = NULL;
if (kbUseSubsetFlag) {
pTmpSps = &pCtx->sSubsetSpsBuffer[iSpsId].sSps;
} else {
pTmpSps = &pCtx->sSpsBuffer[iSpsId];
}
if (CheckSpsActive (pCtx, pTmpSps, kbUseSubsetFlag)) {
// we are overwriting the active sps, copy a temp buffer
if (kbUseSubsetFlag) {
if (memcmp (&pCtx->sSubsetSpsBuffer[iSpsId], pSubsetSps, sizeof (SSubsetSps)) != 0) {
if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
memcpy (&pCtx->sSubsetSpsBuffer[MAX_SPS_COUNT], pSubsetSps, sizeof (SSubsetSps));
pCtx->bAuReadyFlag = true;
pCtx->pAccessUnitList->uiEndPos = pCtx->pAccessUnitList->uiAvailUnitsNum - 1;
pCtx->iOverwriteFlags |= OVERWRITE_SUBSETSPS;
} else if ((pCtx->pSps != NULL) && (pCtx->pSps->iSpsId == pSubsetSps->sSps.iSpsId)) {
memcpy (&pCtx->sSubsetSpsBuffer[MAX_SPS_COUNT], pSubsetSps, sizeof (SSubsetSps));
pCtx->iOverwriteFlags |= OVERWRITE_SUBSETSPS;
} else {
memcpy (&pCtx->sSubsetSpsBuffer[iSpsId], pSubsetSps, sizeof (SSubsetSps));
}
}
} else {
if (memcmp (&pCtx->sSpsBuffer[iSpsId], pSps, sizeof (SSps)) != 0) {
if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
memcpy (&pCtx->sSpsBuffer[MAX_SPS_COUNT], pSps, sizeof (SSps));
pCtx->iOverwriteFlags |= OVERWRITE_SPS;
pCtx->bAuReadyFlag = true;
pCtx->pAccessUnitList->uiEndPos = pCtx->pAccessUnitList->uiAvailUnitsNum - 1;
} else if ((pCtx->pSps != NULL) && (pCtx->pSps->iSpsId == pSps->iSpsId)) {
memcpy (&pCtx->sSpsBuffer[MAX_SPS_COUNT], pSps, sizeof (SSps));
pCtx->iOverwriteFlags |= OVERWRITE_SPS;
} else {
memcpy (&pCtx->sSpsBuffer[iSpsId], pSps, sizeof (SSps));
}
}
}
}
// Not overwrite active sps, just copy to final place
else if (kbUseSubsetFlag) {
memcpy (&pCtx->sSubsetSpsBuffer[iSpsId], pSubsetSps, sizeof (SSubsetSps));
pCtx->bSubspsAvailFlags[iSpsId] = true;
pCtx->bSubspsExistAheadFlag = true;
} else {
memcpy (&pCtx->sSpsBuffer[iSpsId], pSps, sizeof (SSps));
pCtx->bSpsAvailFlags[iSpsId] = true;
pCtx->bSpsExistAheadFlag = true;
}
return ERR_NONE;
}
/*!
*************************************************************************************
* \brief to parse Picture Parameter Set (PPS)
*
* \param pCtx Decoder context
* \param pPpsList pps list
* \param pBsAux bitstream reader auxiliary
*
* \return 0 - successed
* 1 - failed
*
* \note Call it in case eNalUnitType is PPS.
*************************************************************************************
*/
int32_t ParsePps (PWelsDecoderContext pCtx, PPps pPpsList, PBitStringAux pBsAux, uint8_t* pSrcNal,
const int32_t kSrcNalLen) {
PPps pPps = NULL;
SPps sTempPps;
uint32_t uiPpsId = 0;
uint32_t iTmp;
uint32_t uiCode;
int32_t iCode;
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //pic_parameter_set_id
uiPpsId = uiCode;
if (uiPpsId >= MAX_PPS_COUNT) {
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_PPS_ID_OVERFLOW);
}
pPps = &sTempPps;
memset (pPps, 0, sizeof (SPps));
pPps->iPpsId = uiPpsId;
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //seq_parameter_set_id
pPps->iSpsId = uiCode;
if (pPps->iSpsId >= MAX_SPS_COUNT) {
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_SPS_ID_OVERFLOW);
}
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //entropy_coding_mode_flag
pPps->bEntropyCodingModeFlag = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //bottom_field_pic_order_in_frame_present_flag
pPps->bPicOrderPresentFlag = !!uiCode;
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //num_slice_groups_minus1
pPps->uiNumSliceGroups = NUM_SLICE_GROUPS_OFFSET + uiCode;
if (pPps->uiNumSliceGroups > MAX_SLICEGROUP_IDS) {
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_SLICEGROUP);
}
if (pPps->uiNumSliceGroups > 1) {
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //slice_group_map_type
pPps->uiSliceGroupMapType = uiCode;
if (pPps->uiSliceGroupMapType > 1) {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "ParsePps(): slice_group_map_type (%d): support only 0,1.",
pPps->uiSliceGroupMapType);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_FMOTYPE);
}
switch (pPps->uiSliceGroupMapType) {
case 0:
for (iTmp = 0; iTmp < pPps->uiNumSliceGroups; iTmp++) {
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //run_length_minus1[ iGroup ]
pPps->uiRunLength[iTmp] = RUN_LENGTH_OFFSET + uiCode;
}
break;
default:
break;
}
}
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //num_ref_idx_l0_default_active_minus1
pPps->uiNumRefIdxL0Active = NUM_REF_IDX_L0_DEFAULT_ACTIVE_OFFSET + uiCode;
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //num_ref_idx_l1_default_active_minus1
pPps->uiNumRefIdxL1Active = NUM_REF_IDX_L1_DEFAULT_ACTIVE_OFFSET + uiCode;
if (pPps->uiNumRefIdxL0Active > MAX_REF_PIC_COUNT ||
pPps->uiNumRefIdxL1Active > MAX_REF_PIC_COUNT) {
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_REF_COUNT_OVERFLOW);
}
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //weighted_pred_flag
pPps->bWeightedPredFlag = !!uiCode;
WELS_READ_VERIFY (BsGetBits (pBsAux, 2, &uiCode)); //weighted_bipred_idc
pPps->uiWeightedBipredIdc = uiCode;
// weighted_bipred_idc > 0 NOT supported now, but no impact when we ignore it
WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode)); //pic_init_qp_minus26
pPps->iPicInitQp = PIC_INIT_QP_OFFSET + iCode;
WELS_CHECK_SE_BOTH_ERROR (pPps->iPicInitQp, PPS_PIC_INIT_QP_QS_MIN, PPS_PIC_INIT_QP_QS_MAX, "pic_init_qp_minus26 + 26",
GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_PIC_INIT_QP));
WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode)); //pic_init_qs_minus26
pPps->iPicInitQs = PIC_INIT_QS_OFFSET + iCode;
WELS_CHECK_SE_BOTH_ERROR (pPps->iPicInitQs, PPS_PIC_INIT_QP_QS_MIN, PPS_PIC_INIT_QP_QS_MAX, "pic_init_qs_minus26 + 26",
GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_PIC_INIT_QS));
WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode)); //chroma_qp_index_offset,cb
pPps->iChromaQpIndexOffset[0] = iCode;
WELS_CHECK_SE_BOTH_ERROR (pPps->iChromaQpIndexOffset[0], PPS_CHROMA_QP_INDEX_OFFSET_MIN, PPS_CHROMA_QP_INDEX_OFFSET_MAX,
"chroma_qp_index_offset", GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_CHROMA_QP_INDEX_OFFSET));
pPps->iChromaQpIndexOffset[1] = pPps->iChromaQpIndexOffset[0];//init cr qp offset
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //deblocking_filter_control_present_flag
pPps->bDeblockingFilterControlPresentFlag = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //constrained_intra_pred_flag
pPps->bConstainedIntraPredFlag = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //redundant_pic_cnt_present_flag
pPps->bRedundantPicCntPresentFlag = !!uiCode;
if (CheckMoreRBSPData (pBsAux)) {
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //transform_8x8_mode_flag
pPps->bTransform8x8ModeFlag = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //pic_scaling_matrix_present_flag
pPps->bPicScalingMatrixPresentFlag = !!uiCode;
if (pPps->bPicScalingMatrixPresentFlag) {
if (pCtx->bSpsAvailFlags[pPps->iSpsId]) {
WELS_READ_VERIFY (ParseScalingList (&pCtx->sSpsBuffer[pPps->iSpsId], pBsAux, 1, pPps->bTransform8x8ModeFlag,
pPps->bPicScalingListPresentFlag, pPps->iScalingList4x4, pPps->iScalingList8x8));
} else {
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING,
"ParsePps(): sps_id (%d) does not exist for scaling_list. This PPS (%d) is marked as invalid.", pPps->iSpsId,
pPps->iPpsId);
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_INVALID_SPS_ID);
}
}
WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode)); //second_chroma_qp_index_offset
pPps->iChromaQpIndexOffset[1] = iCode;
WELS_CHECK_SE_BOTH_ERROR (pPps->iChromaQpIndexOffset[1], PPS_CHROMA_QP_INDEX_OFFSET_MIN,
PPS_CHROMA_QP_INDEX_OFFSET_MAX, "chroma_qp_index_offset", GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS,
ERR_INFO_INVALID_CHROMA_QP_INDEX_OFFSET));
}
if (pCtx->pPps != NULL && pCtx->pPps->iPpsId == pPps->iPpsId) {
if (memcmp (pCtx->pPps, pPps, sizeof (*pPps)) != 0) {
memcpy (&pCtx->sPpsBuffer[MAX_PPS_COUNT], pPps, sizeof (SPps));
pCtx->iOverwriteFlags |= OVERWRITE_PPS;
if (pCtx->pAccessUnitList->uiAvailUnitsNum > 0) {
pCtx->bAuReadyFlag = true;
pCtx->pAccessUnitList->uiEndPos = pCtx->pAccessUnitList->uiAvailUnitsNum - 1;
}
}
} else {
memcpy (&pCtx->sPpsBuffer[uiPpsId], pPps, sizeof (SPps));
pCtx->bPpsAvailFlags[uiPpsId] = true;
}
if (pCtx->pParam->bParseOnly) {
if (kSrcNalLen >= SPS_PPS_BS_SIZE - 4) { //pps bs exceeds
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "pps payload size (%d) too large for parse only (%d), not supported!",
kSrcNalLen, SPS_PPS_BS_SIZE - 4);
pCtx->iErrorCode |= dsBitstreamError;
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_OUT_OF_MEMORY);
}
SPpsBsInfo* pPpsBs = &pCtx->sPpsBsInfo [uiPpsId];
pPpsBs->iPpsId = (int32_t) uiPpsId;
int32_t iTrailingZeroByte = 0;
while (pSrcNal[kSrcNalLen - iTrailingZeroByte - 1] == 0x0) //remove final trailing 0 bytes
iTrailingZeroByte++;
int32_t iActualLen = kSrcNalLen - iTrailingZeroByte;
pPpsBs->uiPpsBsLen = (uint16_t) iActualLen;
//unify start code as 0x0001
int32_t iStartDeltaByte = 0; //0 for 0x0001, 1 for 0x001
if (pSrcNal[0] == 0x0 && pSrcNal[1] == 0x0 && pSrcNal[2] == 0x1) { //if 0x001
pPpsBs->pPpsBsBuf[0] = 0x0; //add 0 to form 0x0001
iStartDeltaByte++;
pPpsBs->uiPpsBsLen++;
}
memcpy (pPpsBs->pPpsBsBuf + iStartDeltaByte, pSrcNal, iActualLen);
}
return ERR_NONE;
}
#define VUI_MAX_CHROMA_LOG_TYPE_TOP_BOTTOM_FIELD_MAX 5
#define VUI_NUM_UNITS_IN_TICK_MIN 1
#define VUI_TIME_SCALE_MIN 1
#define VUI_MAX_BYTES_PER_PIC_DENOM_MAX 16
#define VUI_MAX_BITS_PER_MB_DENOM_MAX 16
#define VUI_LOG2_MAX_MV_LENGTH_HOR_MAX 16
#define VUI_LOG2_MAX_MV_LENGTH_VER_MAX 16
#define VUI_MAX_DEC_FRAME_BUFFERING_MAX 16
int32_t ParseVui (PWelsDecoderContext pCtx, PSps pSps, PBitStringAux pBsAux) {
uint32_t uiCode;
PVui pVui = &pSps->sVui;
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //aspect_ratio_info_present_flag
pVui->bAspectRatioInfoPresentFlag = !!uiCode;
if (pSps->sVui.bAspectRatioInfoPresentFlag) {
WELS_READ_VERIFY (BsGetBits (pBsAux, 8, &uiCode)); //aspect_ratio_idc
pVui->uiAspectRatioIdc = uiCode;
if (pVui->uiAspectRatioIdc < 17) {
pVui->uiSarWidth = g_ksVuiSampleAspectRatio[pVui->uiAspectRatioIdc].uiWidth;
pVui->uiSarHeight = g_ksVuiSampleAspectRatio[pVui->uiAspectRatioIdc].uiHeight;
} else if (pVui->uiAspectRatioIdc == EXTENDED_SAR) {
WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //sar_width
pVui->uiSarWidth = uiCode;
WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //sar_height
pVui->uiSarHeight = uiCode;
}
}
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //overscan_info_present_flag
pVui->bOverscanInfoPresentFlag = !!uiCode;
if (pVui->bOverscanInfoPresentFlag) {
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //overscan_appropriate_flag
pVui->bOverscanAppropriateFlag = !!uiCode;
}
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //video_signal_type_present_flag
pVui->bVideoSignalTypePresentFlag = !!uiCode;
if (pVui->bVideoSignalTypePresentFlag) {
WELS_READ_VERIFY (BsGetBits (pBsAux, 3, &uiCode)); //video_format
pVui->uiVideoFormat = uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //video_full_range_flag
pVui->bVideoFullRangeFlag = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //colour_description_present_flag
pVui->bColourDescripPresentFlag = !!uiCode;
if (pVui->bColourDescripPresentFlag) {
WELS_READ_VERIFY (BsGetBits (pBsAux, 8, &uiCode)); //colour_primaries
pVui->uiColourPrimaries = uiCode;
WELS_READ_VERIFY (BsGetBits (pBsAux, 8, &uiCode)); //transfer_characteristics
pVui->uiTransferCharacteristics = uiCode;
WELS_READ_VERIFY (BsGetBits (pBsAux, 8, &uiCode)); //matrix_coefficients
pVui->uiMatrixCoeffs = uiCode;
}
}
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //chroma_loc_info_present_flag
pVui->bChromaLocInfoPresentFlag = !!uiCode;
if (pVui->bChromaLocInfoPresentFlag) {
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //chroma_sample_loc_type_top_field
pVui->uiChromaSampleLocTypeTopField = uiCode;
WELS_CHECK_SE_UPPER_WARNING (pVui->uiChromaSampleLocTypeTopField, VUI_MAX_CHROMA_LOG_TYPE_TOP_BOTTOM_FIELD_MAX,
"chroma_sample_loc_type_top_field");
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //chroma_sample_loc_type_bottom_field
pVui->uiChromaSampleLocTypeBottomField = uiCode;
WELS_CHECK_SE_UPPER_WARNING (pVui->uiChromaSampleLocTypeBottomField, VUI_MAX_CHROMA_LOG_TYPE_TOP_BOTTOM_FIELD_MAX,
"chroma_sample_loc_type_bottom_field");
}
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //timing_info_present_flag
pVui->bTimingInfoPresentFlag = !!uiCode;
if (pVui->bTimingInfoPresentFlag) {
uint32_t uiTmp = 0;
WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //num_units_in_tick
uiTmp = (uiCode << 16);
WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //num_units_in_tick
uiTmp |= uiCode;
pVui->uiNumUnitsInTick = uiTmp;
WELS_CHECK_SE_LOWER_WARNING (pVui->uiNumUnitsInTick, VUI_NUM_UNITS_IN_TICK_MIN, "num_units_in_tick");
WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //time_scale
uiTmp = (uiCode << 16);
WELS_READ_VERIFY (BsGetBits (pBsAux, 16, &uiCode)); //time_scale
uiTmp |= uiCode;
pVui->uiTimeScale = uiTmp;
WELS_CHECK_SE_LOWER_WARNING (pVui->uiNumUnitsInTick, VUI_TIME_SCALE_MIN, "time_scale");
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //fixed_frame_rate_flag
pVui->bFixedFrameRateFlag = !!uiCode;
}
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //nal_hrd_parameters_present_flag
pVui->bNalHrdParamPresentFlag = !!uiCode;
if (pVui->bNalHrdParamPresentFlag) { //Add HRD parse. the values are not being used though.
#ifdef _PARSE_NALHRD_VCLHRD_PARAMS_
int32_t cpb_cnt_minus1 = BsGetUe(pBsAux, &uiCode);
/*bit_rate_scale = */BsGetBits(pBsAux, 4, &uiCode);
/*cpb_size_scale = */BsGetBits(pBsAux, 4, &uiCode);
for (int32_t i = 0; i <= cpb_cnt_minus1; i++) {
/*bit_rate_value_minus1[i] = */BsGetUe(pBsAux, &uiCode);
/*cpb_size_value_minus1[i] = */BsGetUe(pBsAux, &uiCode);
/*cbr_flag[i] = */BsGetOneBit(pBsAux, &uiCode);
}
/*initial_cpb_removal_delay_length_minus1 = */BsGetBits(pBsAux, 5, &uiCode);
/*cpb_removal_delay_length_minus1 = */BsGetBits(pBsAux, 5, &uiCode);
/*dpb_output_delay_length_minus1 = */BsGetBits(pBsAux, 5, &uiCode);
/*time_offset_length = */BsGetBits(pBsAux, 5, &uiCode);
#else
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "nal_hrd_parameters_present_flag = 1 not supported.");
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_VUI_HRD);
#endif
}
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //vcl_hrd_parameters_present_flag
pVui->bVclHrdParamPresentFlag = !!uiCode;
if (pVui->bVclHrdParamPresentFlag) {//Add HRD parse. the values are not being used though.
#ifdef _PARSE_NALHRD_VCLHRD_PARAMS_
int32_t cpb_cnt_minus1 = BsGetUe(pBsAux, &uiCode);
/*bit_rate_scale = */BsGetBits(pBsAux, 4, &uiCode);
/*cpb_size_scale = */BsGetBits(pBsAux, 4, &uiCode);
for (int32_t i = 0; i <= cpb_cnt_minus1; i++) {
/*bit_rate_value_minus1[i] = */BsGetUe(pBsAux, &uiCode);
/*cpb_size_value_minus1[i] = */BsGetUe(pBsAux, &uiCode);
/*cbr_flag[i] = */BsGetOneBit(pBsAux, &uiCode);
}
/*initial_cpb_removal_delay_length_minus1 = */BsGetBits(pBsAux, 5, &uiCode);
/*cpb_removal_delay_length_minus1 = */BsGetBits(pBsAux, 5, &uiCode);
/*dpb_output_delay_length_minus1 = */BsGetBits(pBsAux, 5, &uiCode);
/*time_offset_length = */BsGetBits(pBsAux, 5, &uiCode);
#else
WelsLog (& (pCtx->sLogCtx), WELS_LOG_WARNING, "vcl_hrd_parameters_present_flag = 1 not supported.");
return GENERATE_ERROR_NO (ERR_LEVEL_PARAM_SETS, ERR_INFO_UNSUPPORTED_VUI_HRD);
#endif
}
#ifdef _PARSE_NALHRD_VCLHRD_PARAMS_
if (pVui->bNalHrdParamPresentFlag | pVui->bVclHrdParamPresentFlag) {
/*low_delay_hrd_flag = */BsGetOneBit(pBsAux, &uiCode);
}
#endif
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //pic_struct_present_flag
pVui->bPicStructPresentFlag = !!uiCode;
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //bitstream_restriction_flag
pVui->bBitstreamRestrictionFlag = !!uiCode;
if (pVui->bBitstreamRestrictionFlag) {
WELS_READ_VERIFY (BsGetOneBit (pBsAux, &uiCode)); //motion_vectors_over_pic_boundaries_flag
pVui->bMotionVectorsOverPicBoundariesFlag = !!uiCode;
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //max_bytes_per_pic_denom
pVui->uiMaxBytesPerPicDenom = uiCode;
WELS_CHECK_SE_UPPER_WARNING (pVui->uiMaxBytesPerPicDenom, VUI_MAX_BYTES_PER_PIC_DENOM_MAX,
"max_bytes_per_pic_denom");
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //max_bits_per_mb_denom
pVui->uiMaxBitsPerMbDenom = uiCode;
WELS_CHECK_SE_UPPER_WARNING (pVui->uiMaxBitsPerMbDenom, VUI_MAX_BITS_PER_MB_DENOM_MAX,
"max_bits_per_mb_denom");
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //log2_max_mv_length_horizontal
pVui->uiLog2MaxMvLengthHorizontal = uiCode;
WELS_CHECK_SE_UPPER_WARNING (pVui->uiLog2MaxMvLengthHorizontal, VUI_LOG2_MAX_MV_LENGTH_HOR_MAX,
"log2_max_mv_length_horizontal");
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //log2_max_mv_length_vertical
pVui->uiLog2MaxMvLengthVertical = uiCode;
WELS_CHECK_SE_UPPER_WARNING (pVui->uiLog2MaxMvLengthVertical, VUI_LOG2_MAX_MV_LENGTH_VER_MAX,
"log2_max_mv_length_vertical");
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //max_num_reorder_frames
pVui->uiMaxNumReorderFrames = uiCode;
WELS_CHECK_SE_UPPER_WARNING (pVui->uiMaxNumReorderFrames, VUI_MAX_DEC_FRAME_BUFFERING_MAX,
"max_num_reorder_frames");
WELS_READ_VERIFY (BsGetUe (pBsAux, &uiCode)); //max_dec_frame_buffering
pVui->uiMaxDecFrameBuffering = uiCode;
WELS_CHECK_SE_UPPER_WARNING (pVui->uiMaxDecFrameBuffering, VUI_MAX_DEC_FRAME_BUFFERING_MAX,
"max_num_reorder_frames");
}
return ERR_NONE;
}
/*!
*************************************************************************************
* \brief to parse SEI message payload
*
* \param pSei sei message to be parsed output
* \param pBsAux bitstream reader auxiliary
*
* \return 0 - successed
* 1 - failed
*
* \note Call it in case eNalUnitType is NAL_UNIT_SEI.
*************************************************************************************
*/
int32_t ParseSei (void* pSei, PBitStringAux pBsAux) { // reserved Sei_Msg type
return ERR_NONE;
}
/*
*************************************************************************************
* \brief to parse scalinglist message payload
*
* \param pps sps scaling list matrix message to be parsed output
* \param pBsAux bitstream reader auxiliary
*
* \return 0 - successed
* 1 - failed
*
* \note Call it in case scaling list matrix present at sps or pps level
*************************************************************************************
*/
int32_t SetScalingListValue (uint8_t* pScalingList, int iScalingListNum, bool* bUseDefaultScalingMatrixFlag,
PBitStringAux pBsAux) { // reserved Sei_Msg type
int iLastScale = 8;
int iNextScale = 8;
int iDeltaScale;
int32_t iCode;
int32_t iIdx;
for (int j = 0; j < iScalingListNum; j++) {
if (iNextScale != 0) {
WELS_READ_VERIFY (BsGetSe (pBsAux, &iCode));
WELS_CHECK_SE_BOTH_ERROR_NOLOG (iCode, SCALING_LIST_DELTA_SCALE_MIN, SCALING_LIST_DELTA_SCALE_MAX, "DeltaScale",
ERR_SCALING_LIST_DELTA_SCALE);
iDeltaScale = iCode;
iNextScale = (iLastScale + iDeltaScale + 256) % 256;
*bUseDefaultScalingMatrixFlag = (j == 0 && iNextScale == 0);
if (*bUseDefaultScalingMatrixFlag)
break;
}
iIdx = iScalingListNum == 16 ? g_kuiZigzagScan[j] : g_kuiZigzagScan8x8[j];
pScalingList[iIdx] = (iNextScale == 0) ? iLastScale : iNextScale;
iLastScale = pScalingList[iIdx];
}
return ERR_NONE;
}
int32_t ParseScalingList (PSps pSps, PBitStringAux pBs, bool bPPS, const bool kbTrans8x8ModeFlag,
bool* pScalingListPresentFlag, uint8_t (*iScalingList4x4)[16], uint8_t (*iScalingList8x8)[64]) {
uint32_t uiScalingListNum;
uint32_t uiCode;
bool bUseDefaultScalingMatrixFlag4x4 = false;
bool bUseDefaultScalingMatrixFlag8x8 = false;
bool bInit = false;
const uint8_t* defaultScaling[4];
if (!bPPS) { //sps scaling_list
uiScalingListNum = (pSps->uiChromaFormatIdc != 3) ? 8 : 12;
} else { //pps scaling_list
uiScalingListNum = 6 + (int32_t) kbTrans8x8ModeFlag * ((pSps->uiChromaFormatIdc != 3) ? 2 : 6);
bInit = pSps->bSeqScalingMatrixPresentFlag;
}
//Init default_scaling_list value for sps or pps
defaultScaling[0] = bInit ? pSps->iScalingList4x4[0] : g_kuiDequantScaling4x4Default[0];
defaultScaling[1] = bInit ? pSps->iScalingList4x4[3] : g_kuiDequantScaling4x4Default[1];
defaultScaling[2] = bInit ? pSps->iScalingList8x8[0] : g_kuiDequantScaling8x8Default[0];
defaultScaling[3] = bInit ? pSps->iScalingList8x8[1] : g_kuiDequantScaling8x8Default[1];
for (unsigned int i = 0; i < uiScalingListNum; i++) {
WELS_READ_VERIFY (BsGetOneBit (pBs, &uiCode));
pScalingListPresentFlag[i] = !!uiCode;
if (!!uiCode) {
if (i < 6) {//4x4 scaling list
WELS_READ_VERIFY (SetScalingListValue (iScalingList4x4[i], 16, &bUseDefaultScalingMatrixFlag4x4, pBs));
if (bUseDefaultScalingMatrixFlag4x4) {
bUseDefaultScalingMatrixFlag4x4 = false;
memcpy (iScalingList4x4[i], g_kuiDequantScaling4x4Default[i / 3], sizeof (uint8_t) * 16);
}
} else {
WELS_READ_VERIFY (SetScalingListValue (iScalingList8x8[i - 6], 64, &bUseDefaultScalingMatrixFlag8x8, pBs));
if (bUseDefaultScalingMatrixFlag8x8) {
bUseDefaultScalingMatrixFlag8x8 = false;
memcpy (iScalingList8x8[i - 6], g_kuiDequantScaling8x8Default[ (i - 6) & 1], sizeof (uint8_t) * 64);
}
}
} else {
if (i < 6) {
if ((i != 0) && (i != 3))
memcpy (iScalingList4x4[i], iScalingList4x4[i - 1], sizeof (uint8_t) * 16);
else
memcpy (iScalingList4x4[i], defaultScaling[i / 3], sizeof (uint8_t) * 16);
} else {
if ((i == 6) || (i == 7))
memcpy (iScalingList8x8[i - 6], defaultScaling[ (i & 1) + 2], sizeof (uint8_t) * 64);
else
memcpy (iScalingList8x8[i - 6], iScalingList8x8[i - 8], sizeof (uint8_t) * 64);
}
}
}
return ERR_NONE;
}
/*!
*************************************************************************************
* \brief reset fmo list due to got Sps now
*
* \param pCtx decoder context
*
* \return count number of fmo context units are reset
*************************************************************************************
*/
int32_t ResetFmoList (PWelsDecoderContext pCtx) {
int32_t iCountNum = 0;
if (NULL != pCtx) {
// Fixed memory leak due to PPS_ID might not be continuous sometimes, 1/5/2010
UninitFmoList (&pCtx->sFmoList[0], MAX_PPS_COUNT, pCtx->iActiveFmoNum, pCtx->pMemAlign);
iCountNum = pCtx->iActiveFmoNum;
pCtx->iActiveFmoNum = 0;
}
return iCountNum;
}
} // namespace WelsDec
|
#pragma once
#include "types.hpp"
#include <memory>
#include <vector>
#include <map>
#include <set>
#include <queue>
namespace randpa_finality {
using std::vector;
using std::shared_ptr;
using std::weak_ptr;
using std::pair;
using std::make_pair;
using std::set;
using std::map;
template <typename ConfType>
class prefix_node {
public:
using conf_type = ConfType;
private:
using node_type = prefix_node<conf_type>;
using node_ptr = shared_ptr<node_type>;
public:
block_id_type block_id;
std::map<public_key_type, shared_ptr<conf_type>> confirmation_data;
vector<node_ptr> adjacent_nodes;
weak_ptr<node_type> parent;
public_key_type creator_key;
set<public_key_type> active_bp_keys;
size_t confirmation_number() const {
return confirmation_data.size();
}
node_ptr get_matching_node(block_id_type block_id) {
for (const auto& node : adjacent_nodes) {
if (node->block_id == block_id) {
return node;
}
}
return nullptr;
}
bool has_confirmation(const public_key_type& pub_key ) {
return confirmation_data.find(pub_key) != confirmation_data.end();
}
};
struct chain_type {
block_id_type base_block;
vector<block_id_type> blocks;
};
class NodeNotFoundError : public std::exception {};
template <typename NodeType>
class prefix_chain_tree {
private:
using node_ptr = shared_ptr<NodeType>;
using node_weak_ptr = weak_ptr<NodeType>;
using conf_ptr = shared_ptr<typename NodeType::conf_type>;
struct node_info {
node_ptr node;
size_t height;
};
public:
explicit prefix_chain_tree(node_ptr&& root_): root(std::move(root_)) {}
prefix_chain_tree() = delete;
prefix_chain_tree(const prefix_chain_tree&) = delete;
auto find(const block_id_type& block_id) const {
return find_node(block_id, root);
}
node_ptr add_confirmations(const chain_type& chain, const public_key_type& sender_key, const conf_ptr& conf) {
node_ptr node = nullptr;
vector<block_id_type> blocks;
std::tie(node, blocks) = get_tree_node(chain);
if (!node) {
return nullptr;
}
return _add_confirmations(node, blocks, sender_key, conf);
}
void remove_confirmations() {
_remove_confirmations(root);
}
void insert(const chain_type& chain, const public_key_type& creator_key, const set<public_key_type>& active_bp_keys) {
node_ptr node = nullptr;
vector<block_id_type> blocks;
std::tie(node, blocks) = get_tree_node(chain);
if (!node) {
throw NodeNotFoundError();
}
insert_blocks(node, blocks, creator_key, active_bp_keys);
}
auto get_final_chain_head(size_t confirmation_number) const {
auto head = get_chain_head(root, confirmation_number, 0).node;
return head != root ? head : nullptr;
}
auto get_root() const {
return root;
}
auto set_root(const node_ptr& new_root) {
root = new_root;
root->parent.reset();
}
auto get_head() const {
if (!head_block.lock()) {
return root;
}
return head_block.lock();
}
node_ptr get_last_inserted_block(const public_key_type& pub_key) {
auto iterator = last_inserted_block.find(pub_key);
if (iterator != last_inserted_block.end()) {
auto node = iterator->second;
return node.lock();
}
return nullptr;
}
chain_type get_branch(const block_id_type& head_block_id) const {
auto last_node = find(head_block_id);
chain_type chain { root->block_id, {} };
while (last_node != root) {
chain.blocks.push_back(last_node->block_id);
FC_ASSERT(!last_node->parent.expired(), "parent should be exists");
last_node = last_node->parent.lock();
}
std::reverse(chain.blocks.begin(), chain.blocks.end());
return chain;
}
private:
node_ptr root;
map<public_key_type, node_weak_ptr> last_inserted_block;
node_weak_ptr head_block;
pair<node_ptr, vector<block_id_type> > get_tree_node(const chain_type& chain) {
auto node = find(chain.base_block);
const auto& blocks = chain.blocks;
if (node) {
return {node, std::move(chain.blocks)};
}
auto block_itr = std::find_if(blocks.begin(), blocks.end(), [&](const auto& block) {
return (bool) find(block);
});
if (block_itr != blocks.end()) {
return { find(*block_itr), vector<block_id_type>(block_itr + 1, blocks.end()) };
}
return {nullptr, {} };
}
node_info get_chain_head(const node_ptr& node, size_t confirmation_number, size_t depth) const {
auto result = node_info{node, depth};
for (const auto& adjacent_node : node->adjacent_nodes) {
if (adjacent_node->confirmation_number() < confirmation_number) {
continue;
}
const auto head_node = get_chain_head(adjacent_node, confirmation_number, depth + 1);
if (head_node.height > result.height) {
result = head_node;
}
}
return result;
}
node_ptr find_node(const block_id_type& block_id, node_ptr node) const {
std::queue<node_ptr> queue {{ node }};
while (queue.size()) {
auto top_node = queue.front();
queue.pop();
if (top_node->block_id == block_id) {
return top_node;
}
for (auto&& adj_node: top_node->adjacent_nodes) {
queue.push(adj_node);
}
}
return nullptr;
}
void insert_blocks(node_ptr node, const vector<block_id_type>& blocks, const public_key_type& creator_key,
const set<public_key_type>& active_bp_keys) {
for (const auto& block_id : blocks) {
auto next_node = node->get_matching_node(block_id);
if (!next_node) {
next_node = std::make_shared<NodeType>(NodeType{block_id,
{},
{},
node,
creator_key,
active_bp_keys});
node->adjacent_nodes.push_back(next_node);
}
node = next_node;
}
last_inserted_block[creator_key] = node;
if (get_block_num(node->block_id) > get_block_num(get_head()->block_id)) {
head_block = node;
}
}
node_ptr _add_confirmations(node_ptr node, const vector<block_id_type>& blocks, const public_key_type& sender_key,
const conf_ptr& conf) {
auto max_conf_node = node;
node->confirmation_data[sender_key] = conf;
for (const auto& block_id : blocks) {
node = node->get_matching_node(block_id);
if (!node) {
break;
}
node->confirmation_data[sender_key] = conf;
if (max_conf_node->confirmation_data.size() <= node->confirmation_data.size()) {
max_conf_node = node;
}
}
return max_conf_node;
}
void _remove_confirmations(node_ptr root) {
if (!root) {
return;
}
root->confirmation_data.clear();
for (const auto& node : root->adjacent_nodes) {
_remove_confirmations(node);
}
}
};
} //namespace randpa_finality
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/log/net_log_values.h"
#include "base/base64.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "net/base/escape.h"
namespace net {
namespace {
// IEEE 64-bit doubles have a 52-bit mantissa, and can therefore represent
// 53-bits worth of precision (see also documentation for JavaScript's
// Number.MAX_SAFE_INTEGER for more discussion on this).
//
// If the number can be represented with an int or double use that. Otherwise
// fallback to encoding it as a string.
template <typename T>
base::Value NetLogNumberValueHelper(T num) {
// Fits in a (32-bit) int: [-2^31, 2^31 - 1]
if ((!std::is_signed<T>::value || (num >= static_cast<T>(-2147483648))) &&
(num <= static_cast<T>(2147483647))) {
return base::Value(static_cast<int>(num));
}
// Fits in a double: (-2^53, 2^53)
if ((!std::is_signed<T>::value ||
(num >= static_cast<T>(-9007199254740991))) &&
(num <= static_cast<T>(9007199254740991))) {
return base::Value(static_cast<double>(num));
}
// Otherwise format as a string.
return base::Value(base::NumberToString(num));
}
} // namespace
base::Value NetLogStringValue(base::StringPiece raw) {
// The common case is that |raw| is ASCII. Represent this directly.
if (base::IsStringASCII(raw))
return base::Value(raw);
// For everything else (including valid UTF-8) percent-escape |raw|, and add a
// prefix that "tags" the value as being a percent-escaped representation.
//
// Note that the sequence E2 80 8B is U+200B (zero-width space) in UTF-8. It
// is added so the escaped string is not itself also ASCII (otherwise there
// would be ambiguity for consumers as to when the value needs to be
// unescaped).
return base::Value("%ESCAPED:\xE2\x80\x8B " + EscapeNonASCIIAndPercent(raw));
}
base::Value NetLogBinaryValue(base::span<const uint8_t> bytes) {
return NetLogBinaryValue(bytes.data(), bytes.size());
}
base::Value NetLogBinaryValue(const void* bytes, size_t length) {
std::string b64;
base::Base64Encode(
base::StringPiece(reinterpret_cast<const char*>(bytes), length), &b64);
return base::Value(std::move(b64));
}
base::Value NetLogNumberValue(int64_t num) {
return NetLogNumberValueHelper(num);
}
base::Value NetLogNumberValue(uint64_t num) {
return NetLogNumberValueHelper(num);
}
base::Value NetLogNumberValue(uint32_t num) {
return NetLogNumberValueHelper(num);
}
base::Value NetLogParamsWithInt(base::StringPiece name, int value) {
base::Value params(base::Value::Type::DICTIONARY);
params.SetIntKey(name, value);
return params;
}
base::Value NetLogParamsWithInt64(base::StringPiece name, int64_t value) {
base::Value params(base::Value::Type::DICTIONARY);
params.SetKey(name, NetLogNumberValue(value));
return params;
}
base::Value NetLogParamsWithBool(base::StringPiece name, bool value) {
base::Value params(base::Value::Type::DICTIONARY);
params.SetBoolKey(name, value);
return params;
}
base::Value NetLogParamsWithString(base::StringPiece name,
base::StringPiece value) {
base::Value params(base::Value::Type::DICTIONARY);
params.SetStringKey(name, value);
return params;
}
} // namespace net
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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 <es-log/trace-log.h>
#include <Interface/Modules/Render/OsprayViewerDialog.h>
#include <Core/Algorithms/Visualization/OsprayRenderAlgorithm.h>
#include <Interface/Modules/Render/ViewOspraySceneConfig.h>
#include <Modules/Render/ViewScene.h>
#include <Core/Datatypes/Color.h>
#include <Modules/Render/OsprayViewer.h>
#include <Core/Logging/Log.h>
#include <boost/algorithm/string/predicate.hpp>
#ifdef WITH_OSPRAY
#include <Interface/Modules/Render/Ospray/VolumeViewer.h>
#include <ospray/version.h>
#endif
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Render;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
#ifdef WITH_OSPRAY
namespace
{
//float dt = 0.0f; //EXPOSE
//std::vector<std::string> plyFilenames;
//float rotationRate = 0.0f; //EXPOSE
//std::vector<std::string> sliceFilenames;
//std::string transferFunctionFilename;
//int benchmarkWarmUpFrames = 0;
//int benchmarkFrames = 0;
//std::string benchmarkFilename;
//int viewSizeWidth = 0; //EXPOSE
//int viewSizeHeight = 0; //EXPOSE
//ospcommon::vec3f viewUp(0.f);
//ospcommon::vec3f viewAt(0.f), viewFrom(0.f);
//std::string writeFramesFilename; //EXPOSE
//bool usePlane = true;
void setupViewer(VolumeViewer* viewer)
{
float ambientLightIntensity = 0.1f;
float directionalLightIntensity = 1.0f;
float directionalLightAzimuth = 80;
float directionalLightElevation = 65;
float samplingRate = .125f;
float maxSamplingRate = 2.f;
int spp = 1;
bool noshadows = false;
int aoSamples = 1;
bool preIntegration = true;
bool gradientShading = true;
bool adaptiveSampling = true;
viewer->setModel(0);
viewer->getLightEditor()->setAmbientLightIntensity(ambientLightIntensity);
viewer->getLightEditor()->setDirectionalLightIntensity(directionalLightIntensity);
viewer->getLightEditor()->setDirectionalLightAzimuth(directionalLightAzimuth);
viewer->getLightEditor()->setDirectionalLightElevation(directionalLightElevation);
viewer->setSamplingRate(samplingRate);
viewer->setAdaptiveMaxSamplingRate(maxSamplingRate);
viewer->setAdaptiveSampling(adaptiveSampling);
viewer->setSPP(spp);
viewer->setShadows(!noshadows);
viewer->setAOSamples(aoSamples);
viewer->setPreIntegration(preIntegration);
viewer->setGradientShadingEnabled(gradientShading);
}
OSPGeometry duplicatedCodeFromAlgorithm(OsprayGeometryObjectHandle obj)
{
const auto& fieldData = obj->data;
const auto& vertex = fieldData.vertex;
const auto& vertex_normal = fieldData.vertex_normal;
const auto& color = fieldData.color;
const auto& index = fieldData.index;
const auto& radius = obj->radius;
const auto& geom_type = obj->GeomType;
SCIRun::LOG_DEBUG("geom_type");
// create and setup model and mesh
if (boost::iequals(geom_type, "TriSurface"))
{
SCIRun::LOG_DEBUG("adding TriSurface");
OSPGeometry mesh = ospNewGeometry("triangles");
OSPData data = ospNewData(vertex.size() / 4, OSP_FLOAT3A, &vertex[0]); // OSP_FLOAT3 format is also supported for vertex positions
ospCommit(data);
ospSetData(mesh, "vertex", data);
data = ospNewData(color.size() / 4, OSP_FLOAT4, &color[0]);
ospCommit(data);
ospSetData(mesh, "vertex.color", data);
data = ospNewData(index.size() / 3, OSP_INT3, &index[0]); // OSP_INT4 format is also supported for triangle indices
ospCommit(data);
ospSetData(mesh, "index", data);
if (vertex_normal.size()==vertex.size())
{
data = ospNewData(vertex_normal.size() / 4, OSP_FLOAT3A, &vertex_normal[0]);
ospCommit(data);
ospSetData(mesh, "vertex.normal", data);
}
return mesh;
}
else if (boost::iequals(geom_type, "QuadSurface"))
{
SCIRun::LOG_DEBUG("adding QuadSurface");
OSPGeometry mesh = ospNewGeometry("quads");
OSPData data = ospNewData(vertex.size() / 4, OSP_FLOAT3A, &vertex[0]); // OSP_FLOAT3 format is also supported for vertex positions
ospCommit(data);
ospSetData(mesh, "vertex", data);
data = ospNewData(color.size() / 4, OSP_FLOAT4, &color[0]);
ospCommit(data);
ospSetData(mesh, "vertex.color", data);
data = ospNewData(index.size() / 4, OSP_INT4, &index[0]);
ospCommit(data);
ospSetData(mesh, "index", data);
data = ospNewData(vertex_normal.size() / 4, OSP_FLOAT3A, &vertex_normal[0]);
ospCommit(data);
ospSetData(mesh, "vertex.normal", data);
SCIRun::LOG_DEBUG("finish adding QuadSurface");
return mesh;
}else if (boost::iequals(geom_type, "Volume"))
{
SCIRun::LOG_DEBUG("adding Volume wrong place");
//OSPVolume vol = ospNewVolume("shared_structured_volume");
/*OSPTransferFunction tfn =
ospTestingNewTransferFunction(test_data.voxelRange, "jet");
ospSetObject(test_data.volume, "transferFunction", tfn);
ospCommit(test_data.volume);*/
//return mesh;
}
else if (boost::iequals(geom_type, "Spheres"))
{
SCIRun::LOG_DEBUG("adding spheres");
OSPGeometry mesh = ospNewGeometry("spheres");
OSPData data = ospNewData(vertex.size() / 4, OSP_FLOAT3A, &vertex[0]); // OSP_FLOAT3 format is also supported for vertex positions
ospCommit(data);
ospSetData(mesh, "spheres", data);
data = ospNewData(color.size() / 4, OSP_FLOAT4, &color[0]);
ospCommit(data);
ospSetData(mesh, "color", data);
ospSet1f(mesh, "radius", radius);
return mesh;
}
else if (boost::iequals(geom_type, "Cylinder"))
{
SCIRun::LOG_DEBUG("adding Cylinders");
OSPGeometry mesh = ospNewGeometry("cylinders");
OSPData data = ospNewData(vertex.size() / 4, OSP_FLOAT3A, &vertex[0]); // OSP_FLOAT3 format is also supported for vertex positions
ospCommit(data);
ospSetData(mesh, "cylinders", data);
data = ospNewData(color.size() / 4, OSP_FLOAT4, &color[0]);
ospCommit(data);
ospSetData(mesh, "color", data);
ospSet1f(mesh, "radius", radius);
return mesh;
}
else if (boost::iequals(geom_type, "Streamlines"))
{
SCIRun::LOG_DEBUG("adding streamlines");
OSPGeometry mesh = ospNewGeometry("streamlines");
OSPData data = ospNewData(vertex.size() / 4, OSP_FLOAT3A, &vertex[0]); // OSP_FLOAT3 format is also supported for vertex positions
ospCommit(data);
ospSetData(mesh, "vertex", data);
data = ospNewData(color.size() / 4, OSP_FLOAT4, &color[0]);
ospCommit(data);
ospSetData(mesh, "vertex.color", data);
data = ospNewData(index.size(), OSP_INT, &index[0]);
ospCommit(data);
ospSetData(mesh, "index", data);
ospSet1f(mesh, "radius", radius);
return mesh;
}
else
{
SCIRun::LOG_DEBUG("something went wrong. File type not supported");
return {};
}
}
OSPVolume duplicatedCodeFromAlgorithm_vol(OsprayGeometryObjectHandle obj, ospcommon::range1f& voxelRange, ospcommon::box3f& bounds){
const auto& fieldData = obj->data;
const auto& vertex = fieldData.vertex;
const auto& vertex_normal = fieldData.vertex_normal;
const auto& color = fieldData.color;
const auto& index = fieldData.index;
const auto& radius = obj->radius;
const auto& geom_type = obj->GeomType;
const auto& func = obj->tfn;
OSPTransferFunction transferFunction = ospNewTransferFunction("piecewise_linear");
OSPData cData = ospNewData(func.colors.size()/3, OSP_FLOAT3, func.colors.data());
OSPData oData = ospNewData(func.opacities.size(), OSP_FLOAT, func.opacities.data());
ospSetData(transferFunction, "colors", cData);
ospSetData(transferFunction, "opacities", oData);
if (boost::iequals(geom_type, "structVol"))
{
SCIRun::LOG_DEBUG("adding Volume");
OSPVolume vol = ospNewVolume("shared_structured_volume");
int numVoxels = obj->data.color.size();
OSPData voxelData = ospNewData(numVoxels, OSP_FLOAT, obj->data.color.data());
ospSetObject(vol, "voxelData", voxelData);
ospRelease(voxelData);
SCIRun::LOG_DEBUG(std::to_string(numVoxels));
ospSetString(vol, "voxelType", "float");
ospSet3i(vol, "dimensions", obj->data.dim_x, obj->data.dim_y, obj->data.dim_z);
ospSet3f(vol, "gridSpacing", fieldData.spacing_x, fieldData.spacing_y, fieldData.spacing_z);
ospSet3f(vol, "gridOrigin", fieldData.origin_x, fieldData.origin_y, fieldData.origin_z);
std::for_each(obj->data.color.begin(), obj->data.color.end(), [&](float &v) {
if (!std::isnan(v))
voxelRange.extend(v);
//SCIRun::LOG_DEBUG(std::to_string(v));
});
for(int i=0;i<vertex.size();i+=3){
ospcommon::vec3f v = ospcommon::vec3f(vertex[i], vertex[i+1], vertex[i+2]);
bounds.extend(v);
}
ospSet2f(transferFunction, "valueRange", voxelRange.lower, voxelRange.upper);
ospCommit(transferFunction);
ospSetObject(vol, "transferFunction", transferFunction);
ospRelease(transferFunction);
return vol;
}else if (boost::iequals(geom_type, "unstructVol")){
SCIRun::LOG_DEBUG("adding unstructured Volume");
OSPVolume vol = ospNewVolume("unstructured_volume");
//int numVoxels = obj->data.color.size();
OSPData vertexData = ospNewData(vertex.size()/3, OSP_FLOAT3, vertex.data());
OSPData fieldsData = ospNewData(color.size(), OSP_FLOAT, color.data());
OSPData indicesData = ospNewData(index.size()/4, OSP_INT4, index.data());
ospSetObject(vol, "vertices", vertexData);
ospSetData(vol, "field", fieldsData);
ospSetData(vol, "indices", indicesData);
ospRelease(vertexData);
ospRelease(fieldsData);
ospRelease(indicesData);
std::for_each(obj->data.color.begin(), obj->data.color.end(), [&](float &v) {
if (!std::isnan(v))
voxelRange.extend(v);
//SCIRun::LOG_DEBUG(std::to_string(v));
});
for(int i=0;i<vertex.size();i+=3){
ospcommon::vec3f v = ospcommon::vec3f(vertex[i], vertex[i+1], vertex[i+2]);
bounds.extend(v);
}
ospSet2f(transferFunction, "valueRange", voxelRange.lower, voxelRange.upper);
ospCommit(transferFunction);
ospSetObject(vol, "transferFunction", transferFunction);
ospRelease(transferFunction);
return vol;
}
}
ospcommon::box3f toOsprayBox(const BBox& box)
{
auto min = box.get_min();
auto max = box.get_max();
return {
{ static_cast<float>(min.x()),
static_cast<float>(min.y()),
static_cast<float>(min.z())},
{ static_cast<float>(max.x()),
static_cast<float>(max.y()),
static_cast<float>(max.z())}
};
}
}
class OsprayObjectImpl
{
public:
std::vector<OSPGeometry> geoms_;
};
#else
class OsprayObjectImpl
{
};
#endif
OsprayViewerDialog::OsprayViewerDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent),
impl_(new OsprayObjectImpl)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
SCIRun::Core::Algorithms::Visualization::OsprayRenderAlgorithm algo; // for ospray init
state->connectSpecificStateChanged(Parameters::GeomData, [this]() { Q_EMIT newGeometryValueForwarder(); });
connect(this, SIGNAL(newGeometryValueForwarder()), this, SLOT(newGeometryValue()));
addConfigurationDialog();
addToolBar();
setMinimumSize(200, 200);
addCheckBoxManager(configDialog_->showPlaneCheckBox_, Parameters::ShowPlane);
addCheckBoxManager(configDialog_->shadowsCheckBox_, Parameters::ShowShadows);
addCheckBoxManager(configDialog_->renderAnnotationsCheckBox_, Parameters::ShowRenderAnnotations);
addCheckBoxManager(configDialog_->subsampleCheckBox_, Parameters::SubsampleDuringInteraction);
addCheckBoxManager(configDialog_->showFrameRateCheckBox_, Parameters::ShowFrameRate);
addCheckBoxManager(configDialog_->separateModelPerObjectCheckBox_, Parameters::SeparateModelPerObject);
addCheckBoxManager(configDialog_->ambientVisibleCheckBox_, Parameters::ShowAmbientLight);
addCheckBoxManager(configDialog_->directionalVisibleCheckBox_, Parameters::ShowDirectionalLight);
addDoubleSpinBoxManager(configDialog_->autoRotationRateDoubleSpinBox_, Parameters::AutoRotationRate);
addDoubleSpinBoxManager(configDialog_->cameraViewAtXDoubleSpinBox_, Parameters::CameraViewAtX);
addDoubleSpinBoxManager(configDialog_->cameraViewAtYDoubleSpinBox_, Parameters::CameraViewAtY);
addDoubleSpinBoxManager(configDialog_->cameraViewAtZDoubleSpinBox_, Parameters::CameraViewAtZ);
addDoubleSpinBoxManager(configDialog_->cameraViewFromXDoubleSpinBox_, Parameters::CameraViewFromX);
addDoubleSpinBoxManager(configDialog_->cameraViewFromYDoubleSpinBox_, Parameters::CameraViewFromY);
addDoubleSpinBoxManager(configDialog_->cameraViewFromZDoubleSpinBox_, Parameters::CameraViewFromZ);
addDoubleSpinBoxManager(configDialog_->cameraViewUpXDoubleSpinBox_, Parameters::CameraViewUpX);
addDoubleSpinBoxManager(configDialog_->cameraViewUpYDoubleSpinBox_, Parameters::CameraViewUpY);
addDoubleSpinBoxManager(configDialog_->cameraViewUpZDoubleSpinBox_, Parameters::CameraViewUpZ);
addDoubleSpinBoxManager(configDialog_->directionalLightIntensityDoubleSpinBox_, Parameters::DirectionalLightIntensity);
addDoubleSpinBoxManager(configDialog_->ambientLightIntensityDoubleSpinBox_, Parameters::AmbientLightIntensity);
//?? these lead to weird camera swings
//addSliderManager(configDialog_->directionalLightAzimuthSlider_, Parameters::DirectionalLightAzimuth);
//addSliderManager(configDialog_->directionalLightElevationSlider_, Parameters::DirectionalLightElevation);
addSpinBoxManager(configDialog_->samplesPerPixelSpinBox_, Parameters::SamplesPerPixel);
addSpinBoxManager(configDialog_->viewerHeightSpinBox_, Parameters::ViewerHeight);
addSpinBoxManager(configDialog_->viewerWidthSpinBox_, Parameters::ViewerWidth);
connect(configDialog_->viewerHeightSpinBox_, SIGNAL(valueChanged(int)), this, SLOT(setHeight(int)));
connect(configDialog_->viewerWidthSpinBox_, SIGNAL(valueChanged(int)), this, SLOT(setWidth(int)));
connect(configDialog_->cameraViewAtXDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->cameraViewAtYDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->cameraViewAtZDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->cameraViewFromXDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->cameraViewFromYDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->cameraViewFromZDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->cameraViewUpXDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->cameraViewUpYDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->cameraViewUpZDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setViewportCamera()));
connect(configDialog_->ambientLightColorRDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setLightColor()));
connect(configDialog_->ambientLightColorGDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setLightColor()));
connect(configDialog_->ambientLightColorBDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setLightColor()));
connect(configDialog_->directionalLightColorRDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setLightColor()));
connect(configDialog_->directionalLightColorGDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setLightColor()));
connect(configDialog_->directionalLightColorBDoubleSpinBox_, SIGNAL(valueChanged(double)), this, SLOT(setLightColor()));
statusBar_ = new QStatusBar(this);
statusBar_->setMaximumHeight(20);
#ifdef WITH_OSPRAY
{
std::ostringstream ostr;
ostr << "Ospray version: " << OSPRAY_VERSION_MAJOR << "." << OSPRAY_VERSION_MINOR << "."
<< OSPRAY_VERSION_PATCH;
auto versionLabel = new QLabel(QString::fromStdString(ostr.str()));
versionLabel->setStyleSheet("QToolTip { color: #ffffff; background - color: #2a82da; border: 1px solid white; }");
statusBar_->addPermanentWidget(versionLabel);
}
#endif
}
void OsprayViewerDialog::newGeometryValue()
{
#ifdef WITH_OSPRAY
auto geomDataTransient = state_->getTransientValue(Parameters::GeomData);
if (geomDataTransient && !geomDataTransient->empty())
{
auto geom = transient_value_cast<OsprayGeometryObjectHandle>(geomDataTransient);
if (!geom)
{
logWarning("Logical error: ViewSceneDialog received an empty object.");
return;
}
auto compGeom = boost::dynamic_pointer_cast<CompositeOsprayGeometryObject>(geom);
//TODO
delete viewer_;
createViewer(*compGeom);
}
#endif
}
void OsprayViewerDialog::createViewer(const CompositeOsprayGeometryObject& geom)
{
#ifdef WITH_OSPRAY
bool showFrameRate = state_->getValue(Parameters::ShowFrameRate).toBool();
bool fullScreen = false;
bool ownModelPerObject = state_->getValue(Parameters::SeparateModelPerObject).toBool();
std::string renderer = state_->getValue(Parameters::RendererChoice).toString();
{
OsprayViewerParameters params
{
showFrameRate,
renderer,
ownModelPerObject,
fullScreen,
"",
};
OsprayGUIParameters guiParams
{
1024,
768,
statusBar_,
configDialog_->ambientLightIntensityDoubleSpinBox_,
configDialog_->directionalLightIntensityDoubleSpinBox_,
configDialog_->directionalLightAzimuthSlider_,
configDialog_->directionalLightElevationSlider_
};
impl_->geoms_.clear();
// volumes
std::vector<OSPVolume> vol_list;
std::vector<ospcommon::range1f> voxelRange_list;
std::vector<ospcommon::box3f> bounds_list;
for (const auto& obj : geom.objects()){
if((boost::iequals(obj->GeomType, "structVol"))||(boost::iequals(obj->GeomType, "unstructVol")) ) {
ospcommon::range1f r;
ospcommon::box3f b;
vol_list.push_back(duplicatedCodeFromAlgorithm_vol(obj, r, b));
voxelRange_list.push_back(r);
bounds_list.push_back(b);
}else
impl_->geoms_.push_back(duplicatedCodeFromAlgorithm(obj));
}
viewer_ = new VolumeViewer(params, guiParams, { impl_->geoms_, toOsprayBox(geom.box) }, this);
setupViewer(viewer_);
SCIRun::LOG_DEBUG("num of vol: {}", vol_list.size());
// load volume here
for(int i=0;i<vol_list.size();i++){
viewer_->loadVolume(vol_list[i], voxelRange_list[i].toVec2f(), bounds_list[i]);
}
SCIRun::LOG_DEBUG("init viewer");
osprayLayout->addWidget(viewer_);
osprayLayout->addWidget(statusBar_);
statusBar_->showMessage("Ospray viewer initialized.", 5000);
{
// TODO: need to move this to dialog ctor--create viewer once, and just change state.
connect(configDialog_->autoRotationRateDoubleSpinBox_, SIGNAL(valueChanged(double)),
viewer_, SLOT(setAutoRotationRate(double)));
connect(configDialog_->showPlaneCheckBox_, SIGNAL(toggled(bool)),
viewer_, SLOT(setPlane(bool)));
connect(configDialog_->shadowsCheckBox_, SIGNAL(toggled(bool)),
viewer_, SLOT(setShadows(bool)));
connect(configDialog_->renderAnnotationsCheckBox_, SIGNAL(toggled(bool)),
viewer_, SLOT(setRenderAnnotationsEnabled(bool)));
connect(configDialog_->subsampleCheckBox_, SIGNAL(toggled(bool)),
viewer_, SLOT(setSubsamplingInteractionEnabled(bool)));
connect(configDialog_->samplesPerPixelSpinBox_, SIGNAL(valueChanged(int)),
viewer_, SLOT(setSPP(int)));
connect(configDialog_->showFrameRateCheckBox_, SIGNAL(toggled(bool)),
viewer_, SLOT(setShowFrameRate(bool)));
connect(configDialog_->ambientVisibleCheckBox_, SIGNAL(toggled(bool)),
viewer_, SLOT(setAmbientLightVisible(bool)));
connect(configDialog_->directionalVisibleCheckBox_, SIGNAL(toggled(bool)),
viewer_, SLOT(setDirectionalLightVisible(bool)));
connect(viewer_->getWindow(), SIGNAL(cameraChanged()), this, SLOT(setCameraWidgets()));
}
setBGColor();
setLightColor();
viewer_->show();
}
#endif
}
void OsprayViewerDialog::setHeight(int h)
{
parentWidget()->resize(width(), h);
}
void OsprayViewerDialog::setWidth(int w)
{
parentWidget()->resize(w, height());
}
// code from viewer main.cc
#if 0
// Default values for the optional command line arguments.
if (dt > 0.0f)
volumeViewer->setSamplingRate(dt);
// Load slice(s) from file.
for(unsigned int i=0; i<sliceFilenames.size(); i++)
volumeViewer->addSlice(sliceFilenames[i]);
// Load transfer function from file.
if(transferFunctionFilename.empty() != true)
volumeViewer->getTransferFunctionEditor()->load(transferFunctionFilename);
// Set benchmarking parameters.
volumeViewer->getWindow()->setBenchmarkParameters(benchmarkWarmUpFrames,
benchmarkFrames, benchmarkFilename);
#endif
void OsprayViewerDialog::addToolBar()
{
toolBar_ = new QToolBar(this);
WidgetStyleMixin::toolbarStyle(toolBar_);
addConfigurationButton();
addAutoViewButton();
addAutoRotateButton();
addTimestepButtons();
addScreenshotButton();
osprayLayout->addWidget(toolBar_);
//addViewBar();
//addViewBarButton();
addControlLockButton();
}
void OsprayViewerDialog::adjustToolbar()
{
adjustToolbarForHighResolution(toolBar_);
}
void OsprayViewerDialog::addConfigurationButton()
{
auto configurationButton = new QPushButton();
configurationButton->setToolTip("Open/Close Configuration Menu");
configurationButton->setIcon(QPixmap(":/general/Resources/ViewScene/configure.png"));
configurationButton->setShortcut(Qt::Key_F5);
connect(configurationButton, SIGNAL(clicked()), this, SLOT(configButtonClicked()));
addToolbarButton(configurationButton);
}
void OsprayViewerDialog::configButtonClicked()
{
configDialog_->setVisible(!configDialog_->isVisible());
}
void OsprayViewerDialog::addConfigurationDialog()
{
auto name = windowTitle() + " Configuration";
configDialog_ = new ViewOspraySceneConfigDialog(name, this);
// configDialog_->setSampleColor(bgColor_);
// configDialog_->setScaleBarValues(scaleBar_.visible, scaleBar_.fontSize, scaleBar_.length, scaleBar_.height,
// scaleBar_.multiplier, scaleBar_.numTicks, scaleBar_.visible, QString::fromStdString(scaleBar_.unit));
// setupMaterials();
}
void OsprayViewerDialog::addToolbarButton(QPushButton* button)
{
button->setFixedSize(35,35);
button->setIconSize(QSize(25,25));
toolBar_->addWidget(button);
}
void OsprayViewerDialog::addAutoViewButton()
{
autoViewButton_ = new QPushButton(this);
//TODO
autoViewButton_->setDisabled(true);
autoViewButton_->setToolTip("Auto View");
autoViewButton_->setIcon(QPixmap(":/general/Resources/ViewScene/autoview.png"));
autoViewButton_->setShortcut(Qt::Key_0);
connect(autoViewButton_, SIGNAL(clicked()), this, SLOT(autoViewClicked()));
addToolbarButton(autoViewButton_);
}
void OsprayViewerDialog::addAutoRotateButton()
{
autoRotateButton_ = new QPushButton(this);
autoRotateButton_->setToolTip("Auto Rotate");
autoRotateButton_->setCheckable(true);
autoRotateButton_->setIcon(QPixmap(":/general/Resources/ViewScene/autorotate.png"));
//autoRotateButton->setShortcut(Qt::Key_0);
connect(autoRotateButton_, SIGNAL(clicked()), this, SLOT(autoRotateClicked()));
addToolbarButton(autoRotateButton_);
}
void OsprayViewerDialog::addTimestepButtons()
{
auto nextTimestep = new QPushButton(this);
nextTimestep->setText("Next");
nextTimestep->setToolTip("Next timestep");
//autoRotateButton->setIcon(QPixmap(":/general/Resources/ViewScene/autoview.png"));
//autoRotateButton->setShortcut(Qt::Key_0);
connect(nextTimestep, SIGNAL(clicked()), this, SLOT(nextTimestepClicked()));
addToolbarButton(nextTimestep);
playTimestepsButton_ = new QPushButton(this);
playTimestepsButton_->setText("Play");
playTimestepsButton_->setToolTip("Play timesteps");
playTimestepsButton_->setCheckable(true);
//autoRotateButton->setIcon(QPixmap(":/general/Resources/ViewScene/autoview.png"));
//autoRotateButton->setShortcut(Qt::Key_0);
connect(playTimestepsButton_, SIGNAL(clicked()), this, SLOT(playTimestepsClicked()));
addToolbarButton(playTimestepsButton_);
}
void OsprayViewerDialog::addScreenshotButton()
{
auto screenshotButton = new QPushButton(this);
screenshotButton->setToolTip("Take screenshot");
screenshotButton->setIcon(QPixmap(":/general/Resources/ViewScene/screenshot.png"));
screenshotButton->setShortcut(Qt::Key_F12);
connect(screenshotButton, SIGNAL(clicked()), this, SLOT(screenshotClicked()));
addToolbarButton(screenshotButton);
}
void OsprayViewerDialog::addViewBarButton()
{
auto viewBarBtn = new QPushButton();
viewBarBtn->setToolTip("Show View Options");
viewBarBtn->setIcon(QPixmap(":/general/Resources/ViewScene/views.png"));
connect(viewBarBtn, SIGNAL(clicked()), this, SLOT(viewBarButtonClicked()));
addToolbarButton(viewBarBtn);
}
void OsprayViewerDialog::addControlLockButton()
{
controlLock_ = new QPushButton();
//TODO
controlLock_->setDisabled(true);
#if 0
controlLock_->setToolTip("Lock specific view controls");
controlLock_->setIcon(QPixmap(":/general/Resources/ViewScene/lockView.png"));
auto menu = new QMenu;
lockRotation_ = menu->addAction("Lock Rotation");
lockRotation_->setCheckable(true);
connect(lockRotation_, SIGNAL(triggered()), this, SLOT(lockRotationToggled()));
lockPan_ = menu->addAction("Lock Panning");
lockPan_->setCheckable(true);
connect(lockPan_, SIGNAL(triggered()), this, SLOT(lockPanningToggled()));
lockZoom_ = menu->addAction("Lock Zoom");
lockZoom_->setCheckable(true);
connect(lockZoom_, SIGNAL(triggered()), this, SLOT(lockZoomToggled()));
menu->addSeparator();
auto lockAll = menu->addAction("Lock All");
connect(lockAll, SIGNAL(triggered()), this, SLOT(lockAllTriggered()));
auto unlockAll = menu->addAction("Unlock All");
connect(unlockAll, SIGNAL(triggered()), this, SLOT(unlockAllTriggered()));
controlLock_->setMenu(menu);
addToolbarButton(controlLock_);
controlLock_->setFixedWidth(45);
toggleLockColor(false);
#endif
}
void OsprayViewerDialog::toggleLockColor(bool locked)
{
QString color = locked ? "red" : "rgb(66,66,69)";
controlLock_->setStyleSheet("QPushButton { background-color: " + color + "; }");
//autoViewButton_->setDisabled(locked);
}
void OsprayViewerDialog::autoRotateClicked()
{
#ifdef WITH_OSPRAY
if (viewer_)
viewer_->autoRotate(autoRotateButton_->isChecked());
#endif
}
void OsprayViewerDialog::autoViewClicked()
{
qDebug() << "TODO" << __FUNCTION__;
}
void OsprayViewerDialog::screenshotClicked()
{
#ifdef WITH_OSPRAY
if (viewer_)
viewer_->screenshot();
#endif
}
void OsprayViewerDialog::nextTimestepClicked()
{
#ifdef WITH_OSPRAY
if (viewer_)
viewer_->nextTimeStep();
#endif
}
void OsprayViewerDialog::playTimestepsClicked()
{
#ifdef WITH_OSPRAY
if (viewer_)
viewer_->playTimeSteps(playTimestepsButton_->isChecked());
#endif
}
#if 0
void OsprayViewerDialog::lockRotationToggled()
{
mGLWidget->setLockRotation(lockRotation_->isChecked());
toggleLockColor(lockRotation_->isChecked() || lockPan_->isChecked() || lockZoom_->isChecked());
}
void OsprayViewerDialog::lockPanningToggled()
{
mGLWidget->setLockPanning(lockPan_->isChecked());
toggleLockColor(lockRotation_->isChecked() || lockPan_->isChecked() || lockZoom_->isChecked());
}
void OsprayViewerDialog::lockZoomToggled()
{
mGLWidget->setLockZoom(lockZoom_->isChecked());
toggleLockColor(lockRotation_->isChecked() || lockPan_->isChecked() || lockZoom_->isChecked());
}
void OsprayViewerDialog::lockAllTriggered()
{
lockRotation_->setChecked(true);
mGLWidget->setLockRotation(true);
lockPan_->setChecked(true);
mGLWidget->setLockPanning(true);
lockZoom_->setChecked(true);
mGLWidget->setLockZoom(true);
toggleLockColor(true);
}
void OsprayViewerDialog::unlockAllTriggered()
{
lockRotation_->setChecked(false);
mGLWidget->setLockRotation(false);
lockPan_->setChecked(false);
mGLWidget->setLockPanning(false);
lockZoom_->setChecked(false);
mGLWidget->setLockZoom(false);
toggleLockColor(false);
}
#endif
void OsprayViewerDialog::setViewportCamera()
{
#ifdef WITH_OSPRAY
if (viewer_)
{
ospcommon::vec3f viewAt {
getFloat(Parameters::CameraViewAtX),
getFloat(Parameters::CameraViewAtY),
getFloat(Parameters::CameraViewAtZ)
};
ospcommon::vec3f viewFrom {
getFloat(Parameters::CameraViewFromX),
getFloat(Parameters::CameraViewFromY),
getFloat(Parameters::CameraViewFromZ)
};
if (viewAt != viewFrom)
{
viewer_->getWindow()->getViewport()->at = viewAt;
viewer_->getWindow()->getViewport()->from = viewFrom;
}
ospcommon::vec3f viewUp {
getFloat(Parameters::CameraViewUpX),
getFloat(Parameters::CameraViewUpY),
getFloat(Parameters::CameraViewUpZ)
};
if (viewUp != ospcommon::vec3f(0.f))
{
viewer_->getWindow()->getViewport()->setUp(viewUp);
viewer_->getWindow()->resetAccumulationBuffer();
}
}
#endif
}
float OsprayViewerDialog::getFloat(const Name& name) const
{
return static_cast<float>(state_->getValue(name).toDouble());
}
void OsprayViewerDialog::setCameraWidgets()
{
#ifdef WITH_OSPRAY
if (viewer_)
{
{
ScopedWidgetSignalBlocker x(configDialog_->cameraViewAtXDoubleSpinBox_);
ScopedWidgetSignalBlocker y(configDialog_->cameraViewAtYDoubleSpinBox_);
ScopedWidgetSignalBlocker z(configDialog_->cameraViewAtZDoubleSpinBox_);
auto viewAt = viewer_->getWindow()->getViewport()->at;
configDialog_->cameraViewAtXDoubleSpinBox_->setValue(viewAt.x);
configDialog_->cameraViewAtYDoubleSpinBox_->setValue(viewAt.y);
configDialog_->cameraViewAtZDoubleSpinBox_->setValue(viewAt.z);
}
{
ScopedWidgetSignalBlocker x(configDialog_->cameraViewFromXDoubleSpinBox_);
ScopedWidgetSignalBlocker y(configDialog_->cameraViewFromYDoubleSpinBox_);
ScopedWidgetSignalBlocker z(configDialog_->cameraViewFromZDoubleSpinBox_);
auto viewFrom = viewer_->getWindow()->getViewport()->from;
configDialog_->cameraViewFromXDoubleSpinBox_->setValue(viewFrom.x);
configDialog_->cameraViewFromYDoubleSpinBox_->setValue(viewFrom.y);
configDialog_->cameraViewFromZDoubleSpinBox_->setValue(viewFrom.z);
}
{
ScopedWidgetSignalBlocker x(configDialog_->cameraViewUpXDoubleSpinBox_);
ScopedWidgetSignalBlocker y(configDialog_->cameraViewUpYDoubleSpinBox_);
ScopedWidgetSignalBlocker z(configDialog_->cameraViewUpZDoubleSpinBox_);
auto viewUp = viewer_->getWindow()->getViewport()->up;
configDialog_->cameraViewUpXDoubleSpinBox_->setValue(viewUp.x);
configDialog_->cameraViewUpYDoubleSpinBox_->setValue(viewUp.y);
configDialog_->cameraViewUpZDoubleSpinBox_->setValue(viewUp.z);
}
}
#endif
}
void OsprayViewerDialog::setLightColor()
{
#ifdef WITH_OSPRAY
if (viewer_)
{
auto ambR = configDialog_->ambientLightColorRDoubleSpinBox_->value();
auto ambG = configDialog_->ambientLightColorGDoubleSpinBox_->value();
auto ambB = configDialog_->ambientLightColorBDoubleSpinBox_->value();
viewer_->setAmbientLightColor(ambR, ambG, ambB);
state_->setValue(Parameters::AmbientLightColor, ColorRGB(ambR, ambG, ambB).toString());
auto dirR = configDialog_->directionalLightColorRDoubleSpinBox_->value();
auto dirG = configDialog_->directionalLightColorGDoubleSpinBox_->value();
auto dirB = configDialog_->directionalLightColorBDoubleSpinBox_->value();
viewer_->setDirectionalLightColor(dirR, dirG, dirB);
state_->setValue(Parameters::DirectionalLightColor, ColorRGB(dirR, dirG, dirB).toString());
}
#endif
}
void OsprayViewerDialog::setBGColor()
{
#ifdef WITH_OSPRAY
auto colorStr = state_->getValue(Parameters::BackgroundColor).toString();
ColorRGB color(colorStr);
viewer_->setBackgroundColor(color.r(), color.g(), color.b());
#endif
}
void OsprayViewerDialog::pullSpecial()
{
auto ambient = colorFromState(Parameters::AmbientLightColor);
configDialog_->ambientLightColorRDoubleSpinBox_->setValue(ambient.redF());
configDialog_->ambientLightColorGDoubleSpinBox_->setValue(ambient.greenF());
configDialog_->ambientLightColorBDoubleSpinBox_->setValue(ambient.blueF());
auto directional = colorFromState(Parameters::DirectionalLightColor);
configDialog_->directionalLightColorRDoubleSpinBox_->setValue(directional.redF());
configDialog_->directionalLightColorGDoubleSpinBox_->setValue(directional.greenF());
configDialog_->directionalLightColorBDoubleSpinBox_->setValue(directional.blueF());
}
|
// Copyright (c) 2018, The TurtleCoin Developers
//
// Please see the included LICENSE file for more information.
/////////////////////////////////////
#include <WalletApi/ParseArguments.h>
/////////////////////////////////////
#include <cxxopts.hpp>
#include <config/CliHeader.h>
#include <config/CryptoNoteConfig.h>
#include <config/WalletConfig.h>
#include "version.h"
Config parseArguments(int argc, char **argv)
{
Config config;
cxxopts::Options options(argv[0], CryptoNote::getProjectCLIHeader());
bool help, version;
int logLevel;
options.add_options("Core")
("h,help", "Display this help message", cxxopts::value<bool>(help)->implicit_value("true"))
("v,version", "Output software version information", cxxopts::value<bool>(version)->default_value("false")->implicit_value("true"))
("log-level", "Specify log level", cxxopts::value<int>(logLevel)->default_value(std::to_string(config.logLevel)), "#");
options.add_options("Network")
("p,port", "The port to listen on for http requests",
cxxopts::value<uint16_t>(config.port)->default_value(std::to_string(CryptoNote::SERVICE_DEFAULT_PORT)), "<port>")
("rpc-bind-ip", "Interface IP address for the RPC service",
cxxopts::value<std::string>(config.rpcBindIp)->default_value("127.0.0.1"));
options.add_options("RPC")
("enable-cors", "Adds header 'Access-Control-Allow-Origin' to the RPC responses. Uses the value specified as the domain. Use * for all.",
cxxopts::value<std::string>(config.corsHeader), "<domain>")
("r,rpc-password", "Specify the <password> to access the RPC server.", cxxopts::value<std::string>(config.rpcPassword), "<password>");
try
{
const auto result = options.parse(argc, argv);
/* Rpc password must be specified if not --help or --version */
if (result.count("rpc-password") == 0 && !(help || version))
{
std::cout << "You must specify an rpc-password!" << std::endl;
std::cout << options.help({}) << std::endl;
exit(1);
}
}
catch (const cxxopts::OptionException& e)
{
std::cout << "Error: Unable to parse command line argument options: " << e.what() << std::endl << std::endl;
std::cout << options.help({}) << std::endl;
exit(1);
}
if (help) // Do we want to display the help message?
{
std::cout << options.help({}) << std::endl;
exit(0);
}
else if (version) // Do we want to display the software version?
{
std::cout << CryptoNote::getProjectCLIHeader() << std::endl;
exit(0);
}
if (logLevel < Logger::DISABLED || logLevel > Logger::DEBUG)
{
std::cout << "Log level must be between " << Logger::DISABLED << " and " << Logger::DEBUG << "!" << std::endl;
exit(1);
}
else
{
config.logLevel = static_cast<Logger::LogLevel>(logLevel);
}
return config;
}
|
//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This coordinates the per-module state used while generating code.
//
//===----------------------------------------------------------------------===//
#include "CodeGenModule.h"
#include "CGBlocks.h"
#include "CGCUDARuntime.h"
#include "CGCXXABI.h"
#include "CGCall.h"
#include "CGDebugInfo.h"
#include "CGObjCRuntime.h"
#include "CGOpenCLRuntime.h"
#include "CGOpenMPRuntime.h"
#include "CGOpenMPRuntimeGPU.h"
#include "CodeGenFunction.h"
#include "CodeGenPGO.h"
#include "ConstantEmitter.h"
#include "CoverageMappingGen.h"
#include "TargetInfo.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ProfileSummary.h"
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/X86TargetParser.h"
using namespace clang;
using namespace CodeGen;
static llvm::cl::opt<bool> LimitedCoverage(
"limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
llvm::cl::init(false));
static const char AnnotationSection[] = "llvm.metadata";
static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
switch (CGM.getContext().getCXXABIKind()) {
case TargetCXXABI::AppleARM64:
case TargetCXXABI::Fuchsia:
case TargetCXXABI::GenericAArch64:
case TargetCXXABI::GenericARM:
case TargetCXXABI::iOS:
case TargetCXXABI::WatchOS:
case TargetCXXABI::GenericMIPS:
case TargetCXXABI::GenericItanium:
case TargetCXXABI::WebAssembly:
case TargetCXXABI::XL:
return CreateItaniumCXXABI(CGM);
case TargetCXXABI::Microsoft:
return CreateMicrosoftCXXABI(CGM);
}
llvm_unreachable("invalid C++ ABI kind");
}
CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
const PreprocessorOptions &PPO,
const CodeGenOptions &CGO, llvm::Module &M,
DiagnosticsEngine &diags,
CoverageSourceInfo *CoverageInfo)
: Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
VMContext(M.getContext()), Types(*this), VTables(*this),
SanitizerMD(new SanitizerMetadata(*this)) {
// Initialize the type cache.
llvm::LLVMContext &LLVMContext = M.getContext();
VoidTy = llvm::Type::getVoidTy(LLVMContext);
Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
HalfTy = llvm::Type::getHalfTy(LLVMContext);
BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
FloatTy = llvm::Type::getFloatTy(LLVMContext);
DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
PointerAlignInBytes =
C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
SizeSizeInBytes =
C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
IntAlignInBytes =
C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
CharTy =
llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
IntPtrTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getMaxPointerWidth());
Int8PtrTy = Int8Ty->getPointerTo(0);
Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
const llvm::DataLayout &DL = M.getDataLayout();
AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace());
GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace());
ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
if (LangOpts.ObjC)
createObjCRuntime();
if (LangOpts.OpenCL)
createOpenCLRuntime();
if (LangOpts.OpenMP)
createOpenMPRuntime();
if (LangOpts.CUDA)
createCUDARuntime();
// Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
(!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
getCXXABI().getMangleContext()));
// If debug info or coverage generation is enabled, create the CGDebugInfo
// object.
if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
DebugInfo.reset(new CGDebugInfo(*this));
Block.GlobalUniqueCount = 0;
if (C.getLangOpts().ObjC)
ObjCData.reset(new ObjCEntrypoints());
if (CodeGenOpts.hasProfileClangUse()) {
auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
if (auto E = ReaderOrErr.takeError()) {
unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
"Could not read profile %0: %1");
llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
<< EI.message();
});
} else
PGOReader = std::move(ReaderOrErr.get());
}
// If coverage mapping generation is enabled, create the
// CoverageMappingModuleGen object.
if (CodeGenOpts.CoverageMapping)
CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
// Generate the module name hash here if needed.
if (CodeGenOpts.UniqueInternalLinkageNames &&
!getModule().getSourceFileName().empty()) {
std::string Path = getModule().getSourceFileName();
// Check if a path substitution is needed from the MacroPrefixMap.
for (const auto &Entry : LangOpts.MacroPrefixMap)
if (Path.rfind(Entry.first, 0) != std::string::npos) {
Path = Entry.second + Path.substr(Entry.first.size());
break;
}
llvm::MD5 Md5;
Md5.update(Path);
llvm::MD5::MD5Result R;
Md5.final(R);
SmallString<32> Str;
llvm::MD5::stringifyResult(R, Str);
// Convert MD5hash to Decimal. Demangler suffixes can either contain
// numbers or characters but not both.
llvm::APInt IntHash(128, Str.str(), 16);
// Prepend "__uniq" before the hash for tools like profilers to understand
// that this symbol is of internal linkage type. The "__uniq" is the
// pre-determined prefix that is used to tell tools that this symbol was
// created with -funique-internal-linakge-symbols and the tools can strip or
// keep the prefix as needed.
ModuleNameHash = (Twine(".__uniq.") +
Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str();
}
}
CodeGenModule::~CodeGenModule() {}
void CodeGenModule::createObjCRuntime() {
// This is just isGNUFamily(), but we want to force implementors of
// new ABIs to decide how best to do this.
switch (LangOpts.ObjCRuntime.getKind()) {
case ObjCRuntime::GNUstep:
case ObjCRuntime::GCC:
case ObjCRuntime::ObjFW:
ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
return;
case ObjCRuntime::FragileMacOSX:
case ObjCRuntime::MacOSX:
case ObjCRuntime::iOS:
case ObjCRuntime::WatchOS:
ObjCRuntime.reset(CreateMacObjCRuntime(*this));
return;
}
llvm_unreachable("bad runtime kind");
}
void CodeGenModule::createOpenCLRuntime() {
OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
}
void CodeGenModule::createOpenMPRuntime() {
// Select a specialized code generation class based on the target, if any.
// If it does not exist use the default implementation.
switch (getTriple().getArch()) {
case llvm::Triple::nvptx:
case llvm::Triple::nvptx64:
case llvm::Triple::amdgcn:
assert(getLangOpts().OpenMPIsDevice &&
"OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
break;
default:
if (LangOpts.OpenMPSimd)
OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
else
OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
break;
}
}
void CodeGenModule::createCUDARuntime() {
CUDARuntime.reset(CreateNVCUDARuntime(*this));
}
void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
Replacements[Name] = C;
}
void CodeGenModule::applyReplacements() {
for (auto &I : Replacements) {
StringRef MangledName = I.first();
llvm::Constant *Replacement = I.second;
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (!Entry)
continue;
auto *OldF = cast<llvm::Function>(Entry);
auto *NewF = dyn_cast<llvm::Function>(Replacement);
if (!NewF) {
if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
} else {
auto *CE = cast<llvm::ConstantExpr>(Replacement);
assert(CE->getOpcode() == llvm::Instruction::BitCast ||
CE->getOpcode() == llvm::Instruction::GetElementPtr);
NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
}
}
// Replace old with new, but keep the old order.
OldF->replaceAllUsesWith(Replacement);
if (NewF) {
NewF->removeFromParent();
OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
NewF);
}
OldF->eraseFromParent();
}
}
void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
GlobalValReplacements.push_back(std::make_pair(GV, C));
}
void CodeGenModule::applyGlobalValReplacements() {
for (auto &I : GlobalValReplacements) {
llvm::GlobalValue *GV = I.first;
llvm::Constant *C = I.second;
GV->replaceAllUsesWith(C);
GV->eraseFromParent();
}
}
// This is only used in aliases that we created and we know they have a
// linear structure.
static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
const llvm::Constant *C;
if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
C = GA->getAliasee();
else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
C = GI->getResolver();
else
return GV;
const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
if (!AliaseeGV)
return nullptr;
const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
if (FinalGV == GV)
return nullptr;
return FinalGV;
}
static bool checkAliasedGlobal(DiagnosticsEngine &Diags,
SourceLocation Location, bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV) {
GV = getAliasedGlobal(Alias);
if (!GV) {
Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
return false;
}
if (GV->isDeclaration()) {
Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
return false;
}
if (IsIFunc) {
// Check resolver function type.
const auto *F = dyn_cast<llvm::Function>(GV);
if (!F) {
Diags.Report(Location, diag::err_alias_to_undefined)
<< IsIFunc << IsIFunc;
return false;
}
llvm::FunctionType *FTy = F->getFunctionType();
if (!FTy->getReturnType()->isPointerTy()) {
Diags.Report(Location, diag::err_ifunc_resolver_return);
return false;
}
}
return true;
}
void CodeGenModule::checkAliases() {
// Check if the constructed aliases are well formed. It is really unfortunate
// that we have to do this in CodeGen, but we only construct mangled names
// and aliases during codegen.
bool Error = false;
DiagnosticsEngine &Diags = getDiags();
for (const GlobalDecl &GD : Aliases) {
const auto *D = cast<ValueDecl>(GD.getDecl());
SourceLocation Location;
bool IsIFunc = D->hasAttr<IFuncAttr>();
if (const Attr *A = D->getDefiningAttr())
Location = A->getLocation();
else
llvm_unreachable("Not an alias or ifunc?");
StringRef MangledName = getMangledName(GD);
llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
const llvm::GlobalValue *GV = nullptr;
if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) {
Error = true;
continue;
}
llvm::Constant *Aliasee =
IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
: cast<llvm::GlobalAlias>(Alias)->getAliasee();
llvm::GlobalValue *AliaseeGV;
if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
else
AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
StringRef AliasSection = SA->getName();
if (AliasSection != AliaseeGV->getSection())
Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
<< AliasSection << IsIFunc << IsIFunc;
}
// We have to handle alias to weak aliases in here. LLVM itself disallows
// this since the object semantics would not match the IL one. For
// compatibility with gcc we implement it by just pointing the alias
// to its aliasee's aliasee. We also warn, since the user is probably
// expecting the link to be weak.
if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
if (GA->isInterposable()) {
Diags.Report(Location, diag::warn_alias_to_weak_alias)
<< GV->getName() << GA->getName() << IsIFunc;
Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
GA->getAliasee(), Alias->getType());
if (IsIFunc)
cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
else
cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
}
}
}
if (!Error)
return;
for (const GlobalDecl &GD : Aliases) {
StringRef MangledName = getMangledName(GD);
llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
Alias->eraseFromParent();
}
}
void CodeGenModule::clear() {
DeferredDeclsToEmit.clear();
if (OpenMPRuntime)
OpenMPRuntime->clear();
}
void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
StringRef MainFile) {
if (!hasDiagnostics())
return;
if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
if (MainFile.empty())
MainFile = "<stdin>";
Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
} else {
if (Mismatched > 0)
Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
if (Missing > 0)
Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
}
}
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
llvm::Module &M) {
if (!LO.VisibilityFromDLLStorageClass)
return;
llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
CodeGenModule::GetLLVMVisibility(
LO.getExternDeclNoDLLStorageClassVisibility());
for (llvm::GlobalValue &GV : M.global_values()) {
if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
continue;
// Reset DSO locality before setting the visibility. This removes
// any effects that visibility options and annotations may have
// had on the DSO locality. Setting the visibility will implicitly set
// appropriate globals to DSO Local; however, this will be pessimistic
// w.r.t. to the normal compiler IRGen.
GV.setDSOLocal(false);
if (GV.isDeclarationForLinker()) {
GV.setVisibility(GV.getDLLStorageClass() ==
llvm::GlobalValue::DLLImportStorageClass
? ExternDeclDLLImportVisibility
: ExternDeclNoDLLStorageClassVisibility);
} else {
GV.setVisibility(GV.getDLLStorageClass() ==
llvm::GlobalValue::DLLExportStorageClass
? DLLExportVisibility
: NoDLLStorageClassVisibility);
}
GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
}
}
void CodeGenModule::Release() {
EmitDeferred();
EmitVTablesOpportunistically();
applyGlobalValReplacements();
applyReplacements();
checkAliases();
emitMultiVersionFunctions();
EmitCXXGlobalInitFunc();
EmitCXXGlobalCleanUpFunc();
registerGlobalDtorsWithAtExit();
EmitCXXThreadLocalInitFunc();
if (ObjCRuntime)
if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
AddGlobalCtor(ObjCInitFunction);
if (Context.getLangOpts().CUDA && CUDARuntime) {
if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
AddGlobalCtor(CudaCtorFunction);
}
if (OpenMPRuntime) {
if (llvm::Function *OpenMPRequiresDirectiveRegFun =
OpenMPRuntime->emitRequiresDirectiveRegFun()) {
AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
}
OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
OpenMPRuntime->clear();
}
if (PGOReader) {
getModule().setProfileSummary(
PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
llvm::ProfileSummary::PSK_Instr);
if (PGOStats.hasDiagnostics())
PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
}
EmitCtorList(GlobalCtors, "llvm.global_ctors");
EmitCtorList(GlobalDtors, "llvm.global_dtors");
EmitGlobalAnnotations();
EmitStaticExternCAliases();
EmitDeferredUnusedCoverageMappings();
CodeGenPGO(*this).setValueProfilingFlag(getModule());
if (CoverageMapping)
CoverageMapping->emit();
if (CodeGenOpts.SanitizeCfiCrossDso) {
CodeGenFunction(*this).EmitCfiCheckFail();
CodeGenFunction(*this).EmitCfiCheckStub();
}
emitAtAvailableLinkGuard();
if (Context.getTargetInfo().getTriple().isWasm() &&
!Context.getTargetInfo().getTriple().isOSEmscripten()) {
EmitMainVoidAlias();
}
// Emit reference of __amdgpu_device_library_preserve_asan_functions to
// preserve ASAN functions in bitcode libraries.
if (LangOpts.Sanitize.has(SanitizerKind::Address) && getTriple().isAMDGPU()) {
auto *FT = llvm::FunctionType::get(VoidTy, {});
auto *F = llvm::Function::Create(
FT, llvm::GlobalValue::ExternalLinkage,
"__amdgpu_device_library_preserve_asan_functions", &getModule());
auto *Var = new llvm::GlobalVariable(
getModule(), FT->getPointerTo(),
/*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F,
"__amdgpu_device_library_preserve_asan_functions_ptr", nullptr,
llvm::GlobalVariable::NotThreadLocal);
addCompilerUsedGlobal(Var);
getModule().addModuleFlag(llvm::Module::Override, "amdgpu_hostcall", 1);
}
emitLLVMUsed();
if (SanStats)
SanStats->finish();
if (CodeGenOpts.Autolink &&
(Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
EmitModuleLinkOptions();
}
// On ELF we pass the dependent library specifiers directly to the linker
// without manipulating them. This is in contrast to other platforms where
// they are mapped to a specific linker option by the compiler. This
// difference is a result of the greater variety of ELF linkers and the fact
// that ELF linkers tend to handle libraries in a more complicated fashion
// than on other platforms. This forces us to defer handling the dependent
// libs to the linker.
//
// CUDA/HIP device and host libraries are different. Currently there is no
// way to differentiate dependent libraries for host or device. Existing
// usage of #pragma comment(lib, *) is intended for host libraries on
// Windows. Therefore emit llvm.dependent-libraries only for host.
if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
for (auto *MD : ELFDependentLibraries)
NMD->addOperand(MD);
}
// Record mregparm value now so it is visible through rest of codegen.
if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
CodeGenOpts.NumRegisterParameters);
if (CodeGenOpts.DwarfVersion) {
getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
CodeGenOpts.DwarfVersion);
}
if (CodeGenOpts.Dwarf64)
getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
if (Context.getLangOpts().SemanticInterposition)
// Require various optimization to respect semantic interposition.
getModule().setSemanticInterposition(true);
if (CodeGenOpts.EmitCodeView) {
// Indicate that we want CodeView in the metadata.
getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
}
if (CodeGenOpts.CodeViewGHash) {
getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
}
if (CodeGenOpts.ControlFlowGuard) {
// Function ID tables and checks for Control Flow Guard (cfguard=2).
getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
} else if (CodeGenOpts.ControlFlowGuardNoChecks) {
// Function ID tables for Control Flow Guard (cfguard=1).
getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
}
if (CodeGenOpts.EHContGuard) {
// Function ID tables for EH Continuation Guard.
getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
}
if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
// We don't support LTO with 2 with different StrictVTablePointers
// FIXME: we could support it by stripping all the information introduced
// by StrictVTablePointers.
getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
llvm::Metadata *Ops[2] = {
llvm::MDString::get(VMContext, "StrictVTablePointers"),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
llvm::Type::getInt32Ty(VMContext), 1))};
getModule().addModuleFlag(llvm::Module::Require,
"StrictVTablePointersRequirement",
llvm::MDNode::get(VMContext, Ops));
}
if (getModuleDebugInfo())
// We support a single version in the linked module. The LLVM
// parser will drop debug info with a different version number
// (and warn about it, too).
getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
llvm::DEBUG_METADATA_VERSION);
// We need to record the widths of enums and wchar_t, so that we can generate
// the correct build attributes in the ARM backend. wchar_size is also used by
// TargetLibraryInfo.
uint64_t WCharWidth =
Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
if ( Arch == llvm::Triple::arm
|| Arch == llvm::Triple::armeb
|| Arch == llvm::Triple::thumb
|| Arch == llvm::Triple::thumbeb) {
// The minimum width of an enum in bytes
uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
}
if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
StringRef ABIStr = Target.getABI();
llvm::LLVMContext &Ctx = TheModule.getContext();
getModule().addModuleFlag(llvm::Module::Error, "target-abi",
llvm::MDString::get(Ctx, ABIStr));
}
if (CodeGenOpts.SanitizeCfiCrossDso) {
// Indicate that we want cross-DSO control flow integrity checks.
getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
}
if (CodeGenOpts.WholeProgramVTables) {
// Indicate whether VFE was enabled for this module, so that the
// vcall_visibility metadata added under whole program vtables is handled
// appropriately in the optimizer.
getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
CodeGenOpts.VirtualFunctionElimination);
}
if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
getModule().addModuleFlag(llvm::Module::Override,
"CFI Canonical Jump Tables",
CodeGenOpts.SanitizeCfiCanonicalJumpTables);
}
if (CodeGenOpts.CFProtectionReturn &&
Target.checkCFProtectionReturnSupported(getDiags())) {
// Indicate that we want to instrument return control flow protection.
getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
1);
}
if (CodeGenOpts.CFProtectionBranch &&
Target.checkCFProtectionBranchSupported(getDiags())) {
// Indicate that we want to instrument branch control flow protection.
getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
1);
}
// Add module metadata for return address signing (ignoring
// non-leaf/all) and stack tagging. These are actually turned on by function
// attributes, but we use module metadata to emit build attributes. This is
// needed for LTO, where the function attributes are inside bitcode
// serialised into a global variable by the time build attributes are
// emitted, so we can't access them.
if (Context.getTargetInfo().hasFeature("ptrauth") &&
LangOpts.getSignReturnAddressScope() !=
LangOptions::SignReturnAddressScopeKind::None)
getModule().addModuleFlag(llvm::Module::Override,
"sign-return-address-buildattr", 1);
if (LangOpts.Sanitize.has(SanitizerKind::MemTag))
getModule().addModuleFlag(llvm::Module::Override,
"tag-stack-memory-buildattr", 1);
if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
Arch == llvm::Triple::aarch64_be) {
getModule().addModuleFlag(llvm::Module::Error, "branch-target-enforcement",
LangOpts.BranchTargetEnforcement);
getModule().addModuleFlag(llvm::Module::Error, "sign-return-address",
LangOpts.hasSignReturnAddress());
getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all",
LangOpts.isSignReturnAddressScopeAll());
if (Arch != llvm::Triple::thumb && Arch != llvm::Triple::thumbeb) {
getModule().addModuleFlag(llvm::Module::Error,
"sign-return-address-with-bkey",
!LangOpts.isSignReturnAddressWithAKey());
}
}
if (!CodeGenOpts.MemoryProfileOutput.empty()) {
llvm::LLVMContext &Ctx = TheModule.getContext();
getModule().addModuleFlag(
llvm::Module::Error, "MemProfProfileFilename",
llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
}
if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
// Indicate whether __nvvm_reflect should be configured to flush denormal
// floating point values to 0. (This corresponds to its "__CUDA_FTZ"
// property.)
getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
CodeGenOpts.FP32DenormalMode.Output !=
llvm::DenormalMode::IEEE);
}
if (LangOpts.EHAsynch)
getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
// Indicate whether this Module was compiled with -fopenmp
if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
if (getLangOpts().OpenMPIsDevice)
getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
LangOpts.OpenMP);
// Emit OpenCL specific module metadata: OpenCL/SPIR version.
if (LangOpts.OpenCL) {
EmitOpenCLMetadata();
// Emit SPIR version.
if (getTriple().isSPIR()) {
// SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
// opencl.spir.version named metadata.
// C++ for OpenCL has a distinct mapping for version compatibility with
// OpenCL.
auto Version = LangOpts.getOpenCLCompatibleVersion();
llvm::Metadata *SPIRVerElts[] = {
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int32Ty, Version / 100)),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int32Ty, (Version / 100 > 1) ? 0 : 2))};
llvm::NamedMDNode *SPIRVerMD =
TheModule.getOrInsertNamedMetadata("opencl.spir.version");
llvm::LLVMContext &Ctx = TheModule.getContext();
SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
}
}
if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
assert(PLevel < 3 && "Invalid PIC Level");
getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
if (Context.getLangOpts().PIE)
getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
}
if (getCodeGenOpts().CodeModel.size() > 0) {
unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
.Case("tiny", llvm::CodeModel::Tiny)
.Case("small", llvm::CodeModel::Small)
.Case("kernel", llvm::CodeModel::Kernel)
.Case("medium", llvm::CodeModel::Medium)
.Case("large", llvm::CodeModel::Large)
.Default(~0u);
if (CM != ~0u) {
llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
getModule().setCodeModel(codeModel);
}
}
if (CodeGenOpts.NoPLT)
getModule().setRtLibUseGOT();
if (CodeGenOpts.UnwindTables)
getModule().setUwtable();
switch (CodeGenOpts.getFramePointer()) {
case CodeGenOptions::FramePointerKind::None:
// 0 ("none") is the default.
break;
case CodeGenOptions::FramePointerKind::NonLeaf:
getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
break;
case CodeGenOptions::FramePointerKind::All:
getModule().setFramePointer(llvm::FramePointerKind::All);
break;
}
SimplifyPersonality();
if (getCodeGenOpts().EmitDeclMetadata)
EmitDeclMetadata();
if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
EmitCoverageFile();
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->finalize();
if (getCodeGenOpts().EmitVersionIdentMetadata)
EmitVersionIdentMetadata();
if (!getCodeGenOpts().RecordCommandLine.empty())
EmitCommandLineMetadata();
if (!getCodeGenOpts().StackProtectorGuard.empty())
getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
if (!getCodeGenOpts().StackProtectorGuardReg.empty())
getModule().setStackProtectorGuardReg(
getCodeGenOpts().StackProtectorGuardReg);
if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
getModule().setStackProtectorGuardOffset(
getCodeGenOpts().StackProtectorGuardOffset);
if (getCodeGenOpts().StackAlignment)
getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
if (getCodeGenOpts().SkipRaxSetup)
getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
EmitBackendOptionsMetadata(getCodeGenOpts());
// Set visibility from DLL storage class
// We do this at the end of LLVM IR generation; after any operation
// that might affect the DLL storage class or the visibility, and
// before anything that might act on these.
setVisibilityFromDLLStorageClass(LangOpts, getModule());
}
void CodeGenModule::EmitOpenCLMetadata() {
// SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
// opencl.ocl.version named metadata node.
// C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL.
auto Version = LangOpts.getOpenCLCompatibleVersion();
llvm::Metadata *OCLVerElts[] = {
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int32Ty, Version / 100)),
llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
llvm::NamedMDNode *OCLVerMD =
TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
llvm::LLVMContext &Ctx = TheModule.getContext();
OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
}
void CodeGenModule::EmitBackendOptionsMetadata(
const CodeGenOptions CodeGenOpts) {
switch (getTriple().getArch()) {
default:
break;
case llvm::Triple::riscv32:
case llvm::Triple::riscv64:
getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
CodeGenOpts.SmallDataLimit);
break;
}
}
void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
// Make sure that this type is translated.
Types.UpdateCompletedType(TD);
}
void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
// Make sure that this type is translated.
Types.RefreshTypeCacheForClass(RD);
}
llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
if (!TBAA)
return nullptr;
return TBAA->getTypeInfo(QTy);
}
TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
if (!TBAA)
return TBAAAccessInfo();
if (getLangOpts().CUDAIsDevice) {
// As CUDA builtin surface/texture types are replaced, skip generating TBAA
// access info.
if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
nullptr)
return TBAAAccessInfo();
} else if (AccessType->isCUDADeviceBuiltinTextureType()) {
if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
nullptr)
return TBAAAccessInfo();
}
}
return TBAA->getAccessInfo(AccessType);
}
TBAAAccessInfo
CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->getVTablePtrAccessInfo(VTablePtrType);
}
llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
if (!TBAA)
return nullptr;
return TBAA->getTBAAStructInfo(QTy);
}
llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
if (!TBAA)
return nullptr;
return TBAA->getBaseTypeInfo(QTy);
}
llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
if (!TBAA)
return nullptr;
return TBAA->getAccessTagInfo(Info);
}
TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
TBAAAccessInfo TargetInfo) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
}
TBAAAccessInfo
CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
TBAAAccessInfo InfoB) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
}
TBAAAccessInfo
CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
TBAAAccessInfo SrcInfo) {
if (!TBAA)
return TBAAAccessInfo();
return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
}
void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
TBAAAccessInfo TBAAInfo) {
if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
}
void CodeGenModule::DecorateInstructionWithInvariantGroup(
llvm::Instruction *I, const CXXRecordDecl *RD) {
I->setMetadata(llvm::LLVMContext::MD_invariant_group,
llvm::MDNode::get(getLLVMContext(), {}));
}
void CodeGenModule::Error(SourceLocation loc, StringRef message) {
unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
getDiags().Report(Context.getFullLoc(loc), diagID) << message;
}
/// ErrorUnsupported - Print out an error that codegen doesn't support the
/// specified stmt yet.
void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
"cannot compile this %0 yet");
std::string Msg = Type;
getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
<< Msg << S->getSourceRange();
}
/// ErrorUnsupported - Print out an error that codegen doesn't support the
/// specified decl yet.
void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
"cannot compile this %0 yet");
std::string Msg = Type;
getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
}
llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
return llvm::ConstantInt::get(SizeTy, size.getQuantity());
}
void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
const NamedDecl *D) const {
if (GV->hasDLLImportStorageClass())
return;
// Internal definitions always have default visibility.
if (GV->hasLocalLinkage()) {
GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
return;
}
if (!D)
return;
// Set visibility for definitions, and for declarations if requested globally
// or set explicitly.
LinkageInfo LV = D->getLinkageAndVisibility();
if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
!GV->isDeclarationForLinker())
GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
}
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
llvm::GlobalValue *GV) {
if (GV->hasLocalLinkage())
return true;
if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
return true;
// DLLImport explicitly marks the GV as external.
if (GV->hasDLLImportStorageClass())
return false;
const llvm::Triple &TT = CGM.getTriple();
if (TT.isWindowsGNUEnvironment()) {
// In MinGW, variables without DLLImport can still be automatically
// imported from a DLL by the linker; don't mark variables that
// potentially could come from another DLL as DSO local.
// With EmulatedTLS, TLS variables can be autoimported from other DLLs
// (and this actually happens in the public interface of libstdc++), so
// such variables can't be marked as DSO local. (Native TLS variables
// can't be dllimported at all, though.)
if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
(!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS))
return false;
}
// On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
// remain unresolved in the link, they can be resolved to zero, which is
// outside the current DSO.
if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
return false;
// Every other GV is local on COFF.
// Make an exception for windows OS in the triple: Some firmware builds use
// *-win32-macho triples. This (accidentally?) produced windows relocations
// without GOT tables in older clang versions; Keep this behaviour.
// FIXME: even thread local variables?
if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
return true;
// Only handle COFF and ELF for now.
if (!TT.isOSBinFormatELF())
return false;
// If this is not an executable, don't assume anything is local.
const auto &CGOpts = CGM.getCodeGenOpts();
llvm::Reloc::Model RM = CGOpts.RelocationModel;
const auto &LOpts = CGM.getLangOpts();
if (RM != llvm::Reloc::Static && !LOpts.PIE) {
// On ELF, if -fno-semantic-interposition is specified and the target
// supports local aliases, there will be neither CC1
// -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
// dso_local on the function if using a local alias is preferable (can avoid
// PLT indirection).
if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
return false;
return !(CGM.getLangOpts().SemanticInterposition ||
CGM.getLangOpts().HalfNoSemanticInterposition);
}
// A definition cannot be preempted from an executable.
if (!GV->isDeclarationForLinker())
return true;
// Most PIC code sequences that assume that a symbol is local cannot produce a
// 0 if it turns out the symbol is undefined. While this is ABI and relocation
// depended, it seems worth it to handle it here.
if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
return false;
// PowerPC64 prefers TOC indirection to avoid copy relocations.
if (TT.isPPC64())
return false;
if (CGOpts.DirectAccessExternalData) {
// If -fdirect-access-external-data (default for -fno-pic), set dso_local
// for non-thread-local variables. If the symbol is not defined in the
// executable, a copy relocation will be needed at link time. dso_local is
// excluded for thread-local variables because they generally don't support
// copy relocations.
if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
if (!Var->isThreadLocal())
return true;
// -fno-pic sets dso_local on a function declaration to allow direct
// accesses when taking its address (similar to a data symbol). If the
// function is not defined in the executable, a canonical PLT entry will be
// needed at link time. -fno-direct-access-external-data can avoid the
// canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
// it could just cause trouble without providing perceptible benefits.
if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
return true;
}
// If we can use copy relocations we can assume it is local.
// Otherwise don't assume it is local.
return false;
}
void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
}
void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
GlobalDecl GD) const {
const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
// C++ destructors have a few C++ ABI specific special cases.
if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
return;
}
setDLLImportDLLExport(GV, D);
}
void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
const NamedDecl *D) const {
if (D && D->isExternallyVisible()) {
if (D->hasAttr<DLLImportAttr>())
GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
}
}
void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
GlobalDecl GD) const {
setDLLImportDLLExport(GV, GD);
setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
}
void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
const NamedDecl *D) const {
setDLLImportDLLExport(GV, D);
setGVPropertiesAux(GV, D);
}
void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
const NamedDecl *D) const {
setGlobalVisibility(GV, D);
setDSOLocal(GV);
GV->setPartition(CodeGenOpts.SymbolPartition);
}
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
.Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
.Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
.Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
.Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
}
llvm::GlobalVariable::ThreadLocalMode
CodeGenModule::GetDefaultLLVMTLSModel() const {
switch (CodeGenOpts.getDefaultTLSModel()) {
case CodeGenOptions::GeneralDynamicTLSModel:
return llvm::GlobalVariable::GeneralDynamicTLSModel;
case CodeGenOptions::LocalDynamicTLSModel:
return llvm::GlobalVariable::LocalDynamicTLSModel;
case CodeGenOptions::InitialExecTLSModel:
return llvm::GlobalVariable::InitialExecTLSModel;
case CodeGenOptions::LocalExecTLSModel:
return llvm::GlobalVariable::LocalExecTLSModel;
}
llvm_unreachable("Invalid TLS model!");
}
void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
llvm::GlobalValue::ThreadLocalMode TLM;
TLM = GetDefaultLLVMTLSModel();
// Override the TLS model if it is explicitly specified.
if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
TLM = GetLLVMTLSModel(Attr->getModel());
}
GV->setThreadLocalMode(TLM);
}
static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
StringRef Name) {
const TargetInfo &Target = CGM.getTarget();
return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
}
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
const CPUSpecificAttr *Attr,
unsigned CPUIndex,
raw_ostream &Out) {
// cpu_specific gets the current name, dispatch gets the resolver if IFunc is
// supported.
if (Attr)
Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
else if (CGM.getTarget().supportsIFunc())
Out << ".resolver";
}
static void AppendTargetMangling(const CodeGenModule &CGM,
const TargetAttr *Attr, raw_ostream &Out) {
if (Attr->isDefaultVersion())
return;
Out << '.';
const TargetInfo &Target = CGM.getTarget();
ParsedTargetAttr Info =
Attr->parse([&Target](StringRef LHS, StringRef RHS) {
// Multiversioning doesn't allow "no-${feature}", so we can
// only have "+" prefixes here.
assert(LHS.startswith("+") && RHS.startswith("+") &&
"Features should always have a prefix.");
return Target.multiVersionSortPriority(LHS.substr(1)) >
Target.multiVersionSortPriority(RHS.substr(1));
});
bool IsFirst = true;
if (!Info.Architecture.empty()) {
IsFirst = false;
Out << "arch_" << Info.Architecture;
}
for (StringRef Feat : Info.Features) {
if (!IsFirst)
Out << '_';
IsFirst = false;
Out << Feat.substr(1);
}
}
// Returns true if GD is a function decl with internal linkage and
// needs a unique suffix after the mangled name.
static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
CodeGenModule &CGM) {
const Decl *D = GD.getDecl();
return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
(CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
}
static void AppendTargetClonesMangling(const CodeGenModule &CGM,
const TargetClonesAttr *Attr,
unsigned VersionIndex,
raw_ostream &Out) {
Out << '.';
StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
if (FeatureStr.startswith("arch="))
Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1);
else
Out << FeatureStr;
Out << '.' << Attr->getMangledIndex(VersionIndex);
}
static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
const NamedDecl *ND,
bool OmitMultiVersionMangling = false) {
SmallString<256> Buffer;
llvm::raw_svector_ostream Out(Buffer);
MangleContext &MC = CGM.getCXXABI().getMangleContext();
if (!CGM.getModuleNameHash().empty())
MC.needsUniqueInternalLinkageNames();
bool ShouldMangle = MC.shouldMangleDeclName(ND);
if (ShouldMangle)
MC.mangleName(GD.getWithDecl(ND), Out);
else {
IdentifierInfo *II = ND->getIdentifier();
assert(II && "Attempt to mangle unnamed decl.");
const auto *FD = dyn_cast<FunctionDecl>(ND);
if (FD &&
FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
Out << "__regcall3__" << II->getName();
} else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
Out << "__device_stub__" << II->getName();
} else {
Out << II->getName();
}
}
// Check if the module name hash should be appended for internal linkage
// symbols. This should come before multi-version target suffixes are
// appended. This is to keep the name and module hash suffix of the
// internal linkage function together. The unique suffix should only be
// added when name mangling is done to make sure that the final name can
// be properly demangled. For example, for C functions without prototypes,
// name mangling is not done and the unique suffix should not be appeneded
// then.
if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
"Hash computed when not explicitly requested");
Out << CGM.getModuleNameHash();
}
if (const auto *FD = dyn_cast<FunctionDecl>(ND))
if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
switch (FD->getMultiVersionKind()) {
case MultiVersionKind::CPUDispatch:
case MultiVersionKind::CPUSpecific:
AppendCPUSpecificCPUDispatchMangling(CGM,
FD->getAttr<CPUSpecificAttr>(),
GD.getMultiVersionIndex(), Out);
break;
case MultiVersionKind::Target:
AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
break;
case MultiVersionKind::TargetClones:
AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(),
GD.getMultiVersionIndex(), Out);
break;
case MultiVersionKind::None:
llvm_unreachable("None multiversion type isn't valid here");
}
}
// Make unique name for device side static file-scope variable for HIP.
if (CGM.getContext().shouldExternalizeStaticVar(ND) &&
CGM.getLangOpts().GPURelocatableDeviceCode &&
CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty())
CGM.printPostfixForExternalizedStaticVar(Out);
return std::string(Out.str());
}
void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
const FunctionDecl *FD,
StringRef &CurName) {
if (!FD->isMultiVersion())
return;
// Get the name of what this would be without the 'target' attribute. This
// allows us to lookup the version that was emitted when this wasn't a
// multiversion function.
std::string NonTargetName =
getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
GlobalDecl OtherGD;
if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
assert(OtherGD.getCanonicalDecl()
.getDecl()
->getAsFunction()
->isMultiVersion() &&
"Other GD should now be a multiversioned function");
// OtherFD is the version of this function that was mangled BEFORE
// becoming a MultiVersion function. It potentially needs to be updated.
const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
.getDecl()
->getAsFunction()
->getMostRecentDecl();
std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
// This is so that if the initial version was already the 'default'
// version, we don't try to update it.
if (OtherName != NonTargetName) {
// Remove instead of erase, since others may have stored the StringRef
// to this.
const auto ExistingRecord = Manglings.find(NonTargetName);
if (ExistingRecord != std::end(Manglings))
Manglings.remove(&(*ExistingRecord));
auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
Result.first->first();
// If this is the current decl is being created, make sure we update the name.
if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
CurName = OtherNameRef;
if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
Entry->setName(OtherName);
}
}
}
StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
GlobalDecl CanonicalGD = GD.getCanonicalDecl();
// Some ABIs don't have constructor variants. Make sure that base and
// complete constructors get mangled the same.
if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
if (!getTarget().getCXXABI().hasConstructorVariants()) {
CXXCtorType OrigCtorType = GD.getCtorType();
assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
if (OrigCtorType == Ctor_Base)
CanonicalGD = GlobalDecl(CD, Ctor_Complete);
}
}
// In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
// static device variable depends on whether the variable is referenced by
// a host or device host function. Therefore the mangled name cannot be
// cached.
if (!LangOpts.CUDAIsDevice ||
!getContext().mayExternalizeStaticVar(GD.getDecl())) {
auto FoundName = MangledDeclNames.find(CanonicalGD);
if (FoundName != MangledDeclNames.end())
return FoundName->second;
}
// Keep the first result in the case of a mangling collision.
const auto *ND = cast<NamedDecl>(GD.getDecl());
std::string MangledName = getMangledNameImpl(*this, GD, ND);
// Ensure either we have different ABIs between host and device compilations,
// says host compilation following MSVC ABI but device compilation follows
// Itanium C++ ABI or, if they follow the same ABI, kernel names after
// mangling should be the same after name stubbing. The later checking is
// very important as the device kernel name being mangled in host-compilation
// is used to resolve the device binaries to be executed. Inconsistent naming
// result in undefined behavior. Even though we cannot check that naming
// directly between host- and device-compilations, the host- and
// device-mangling in host compilation could help catching certain ones.
assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
getLangOpts().CUDAIsDevice ||
(getContext().getAuxTargetInfo() &&
(getContext().getAuxTargetInfo()->getCXXABI() !=
getContext().getTargetInfo().getCXXABI())) ||
getCUDARuntime().getDeviceSideName(ND) ==
getMangledNameImpl(
*this,
GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
ND));
auto Result = Manglings.insert(std::make_pair(MangledName, GD));
return MangledDeclNames[CanonicalGD] = Result.first->first();
}
StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
const BlockDecl *BD) {
MangleContext &MangleCtx = getCXXABI().getMangleContext();
const Decl *D = GD.getDecl();
SmallString<256> Buffer;
llvm::raw_svector_ostream Out(Buffer);
if (!D)
MangleCtx.mangleGlobalBlock(BD,
dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
else
MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
return Result.first->first();
}
llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
return getModule().getNamedValue(Name);
}
/// AddGlobalCtor - Add a function to the list that will be called before
/// main() runs.
void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
llvm::Constant *AssociatedData) {
// FIXME: Type coercion of void()* types.
GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
}
/// AddGlobalDtor - Add a function to the list that will be called
/// when the module is unloaded.
void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
bool IsDtorAttrFunc) {
if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
(!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
DtorsUsingAtExit[Priority].push_back(Dtor);
return;
}
// FIXME: Type coercion of void()* types.
GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
}
void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
if (Fns.empty()) return;
// Ctor function type is void()*.
llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
TheModule.getDataLayout().getProgramAddressSpace());
// Get the type of a ctor entry, { i32, void ()*, i8* }.
llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, CtorPFTy, VoidPtrTy);
// Construct the constructor and destructor arrays.
ConstantInitBuilder builder(*this);
auto ctors = builder.beginArray(CtorStructTy);
for (const auto &I : Fns) {
auto ctor = ctors.beginStruct(CtorStructTy);
ctor.addInt(Int32Ty, I.Priority);
ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
if (I.AssociatedData)
ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
else
ctor.addNullPointer(VoidPtrTy);
ctor.finishAndAddTo(ctors);
}
auto list =
ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
/*constant*/ false,
llvm::GlobalValue::AppendingLinkage);
// The LTO linker doesn't seem to like it when we set an alignment
// on appending variables. Take it off as a workaround.
list->setAlignment(llvm::None);
Fns.clear();
}
llvm::GlobalValue::LinkageTypes
CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
const auto *D = cast<FunctionDecl>(GD.getDecl());
GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
if (isa<CXXConstructorDecl>(D) &&
cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
Context.getTargetInfo().getCXXABI().isMicrosoft()) {
// Our approach to inheriting constructors is fundamentally different from
// that used by the MS ABI, so keep our inheriting constructor thunks
// internal rather than trying to pick an unambiguous mangling for them.
return llvm::GlobalValue::InternalLinkage;
}
return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
}
llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
if (!MDS) return nullptr;
return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
}
void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
const CGFunctionInfo &Info,
llvm::Function *F, bool IsThunk) {
unsigned CallingConv;
llvm::AttributeList PAL;
ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
/*AttrOnCallSite=*/false, IsThunk);
F->setAttributes(PAL);
F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
}
static void removeImageAccessQualifier(std::string& TyName) {
std::string ReadOnlyQual("__read_only");
std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
if (ReadOnlyPos != std::string::npos)
// "+ 1" for the space after access qualifier.
TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
else {
std::string WriteOnlyQual("__write_only");
std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
if (WriteOnlyPos != std::string::npos)
TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
else {
std::string ReadWriteQual("__read_write");
std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
if (ReadWritePos != std::string::npos)
TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
}
}
}
// Returns the address space id that should be produced to the
// kernel_arg_addr_space metadata. This is always fixed to the ids
// as specified in the SPIR 2.0 specification in order to differentiate
// for example in clGetKernelArgInfo() implementation between the address
// spaces with targets without unique mapping to the OpenCL address spaces
// (basically all single AS CPUs).
static unsigned ArgInfoAddressSpace(LangAS AS) {
switch (AS) {
case LangAS::opencl_global:
return 1;
case LangAS::opencl_constant:
return 2;
case LangAS::opencl_local:
return 3;
case LangAS::opencl_generic:
return 4; // Not in SPIR 2.0 specs.
case LangAS::opencl_global_device:
return 5;
case LangAS::opencl_global_host:
return 6;
default:
return 0; // Assume private.
}
}
void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
const FunctionDecl *FD,
CodeGenFunction *CGF) {
assert(((FD && CGF) || (!FD && !CGF)) &&
"Incorrect use - FD and CGF should either be both null or not!");
// Create MDNodes that represent the kernel arg metadata.
// Each MDNode is a list in the form of "key", N number of values which is
// the same number of values as their are kernel arguments.
const PrintingPolicy &Policy = Context.getPrintingPolicy();
// MDNode for the kernel argument address space qualifiers.
SmallVector<llvm::Metadata *, 8> addressQuals;
// MDNode for the kernel argument access qualifiers (images only).
SmallVector<llvm::Metadata *, 8> accessQuals;
// MDNode for the kernel argument type names.
SmallVector<llvm::Metadata *, 8> argTypeNames;
// MDNode for the kernel argument base type names.
SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
// MDNode for the kernel argument type qualifiers.
SmallVector<llvm::Metadata *, 8> argTypeQuals;
// MDNode for the kernel argument names.
SmallVector<llvm::Metadata *, 8> argNames;
if (FD && CGF)
for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
const ParmVarDecl *parm = FD->getParamDecl(i);
QualType ty = parm->getType();
std::string typeQuals;
// Get image and pipe access qualifier:
if (ty->isImageType() || ty->isPipeType()) {
const Decl *PDecl = parm;
if (auto *TD = dyn_cast<TypedefType>(ty))
PDecl = TD->getDecl();
const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
if (A && A->isWriteOnly())
accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
else if (A && A->isReadWrite())
accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
else
accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
} else
accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
// Get argument name.
argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
auto getTypeSpelling = [&](QualType Ty) {
auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
if (Ty.isCanonical()) {
StringRef typeNameRef = typeName;
// Turn "unsigned type" to "utype"
if (typeNameRef.consume_front("unsigned "))
return std::string("u") + typeNameRef.str();
if (typeNameRef.consume_front("signed "))
return typeNameRef.str();
}
return typeName;
};
if (ty->isPointerType()) {
QualType pointeeTy = ty->getPointeeType();
// Get address qualifier.
addressQuals.push_back(
llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
// Get argument type name.
std::string typeName = getTypeSpelling(pointeeTy) + "*";
std::string baseTypeName =
getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
argBaseTypeNames.push_back(
llvm::MDString::get(VMContext, baseTypeName));
// Get argument type qualifiers:
if (ty.isRestrictQualified())
typeQuals = "restrict";
if (pointeeTy.isConstQualified() ||
(pointeeTy.getAddressSpace() == LangAS::opencl_constant))
typeQuals += typeQuals.empty() ? "const" : " const";
if (pointeeTy.isVolatileQualified())
typeQuals += typeQuals.empty() ? "volatile" : " volatile";
} else {
uint32_t AddrSpc = 0;
bool isPipe = ty->isPipeType();
if (ty->isImageType() || isPipe)
AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
addressQuals.push_back(
llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
// Get argument type name.
ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
std::string typeName = getTypeSpelling(ty);
std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
// Remove access qualifiers on images
// (as they are inseparable from type in clang implementation,
// but OpenCL spec provides a special query to get access qualifier
// via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
if (ty->isImageType()) {
removeImageAccessQualifier(typeName);
removeImageAccessQualifier(baseTypeName);
}
argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
argBaseTypeNames.push_back(
llvm::MDString::get(VMContext, baseTypeName));
if (isPipe)
typeQuals = "pipe";
}
argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
}
Fn->setMetadata("kernel_arg_addr_space",
llvm::MDNode::get(VMContext, addressQuals));
Fn->setMetadata("kernel_arg_access_qual",
llvm::MDNode::get(VMContext, accessQuals));
Fn->setMetadata("kernel_arg_type",
llvm::MDNode::get(VMContext, argTypeNames));
Fn->setMetadata("kernel_arg_base_type",
llvm::MDNode::get(VMContext, argBaseTypeNames));
Fn->setMetadata("kernel_arg_type_qual",
llvm::MDNode::get(VMContext, argTypeQuals));
if (getCodeGenOpts().EmitOpenCLArgMetadata)
Fn->setMetadata("kernel_arg_name",
llvm::MDNode::get(VMContext, argNames));
}
/// Determines whether the language options require us to model
/// unwind exceptions. We treat -fexceptions as mandating this
/// except under the fragile ObjC ABI with only ObjC exceptions
/// enabled. This means, for example, that C with -fexceptions
/// enables this.
static bool hasUnwindExceptions(const LangOptions &LangOpts) {
// If exceptions are completely disabled, obviously this is false.
if (!LangOpts.Exceptions) return false;
// If C++ exceptions are enabled, this is true.
if (LangOpts.CXXExceptions) return true;
// If ObjC exceptions are enabled, this depends on the ABI.
if (LangOpts.ObjCExceptions) {
return LangOpts.ObjCRuntime.hasUnwindExceptions();
}
return true;
}
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
const CXXMethodDecl *MD) {
// Check that the type metadata can ever actually be used by a call.
if (!CGM.getCodeGenOpts().LTOUnit ||
!CGM.HasHiddenLTOVisibility(MD->getParent()))
return false;
// Only functions whose address can be taken with a member function pointer
// need this sort of type metadata.
return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
!isa<CXXDestructorDecl>(MD);
}
std::vector<const CXXRecordDecl *>
CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
llvm::SetVector<const CXXRecordDecl *> MostBases;
std::function<void (const CXXRecordDecl *)> CollectMostBases;
CollectMostBases = [&](const CXXRecordDecl *RD) {
if (RD->getNumBases() == 0)
MostBases.insert(RD);
for (const CXXBaseSpecifier &B : RD->bases())
CollectMostBases(B.getType()->getAsCXXRecordDecl());
};
CollectMostBases(RD);
return MostBases.takeVector();
}
void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
llvm::Function *F) {
llvm::AttrBuilder B(F->getContext());
if (CodeGenOpts.UnwindTables)
B.addAttribute(llvm::Attribute::UWTable);
if (CodeGenOpts.StackClashProtector)
B.addAttribute("probe-stack", "inline-asm");
if (!hasUnwindExceptions(LangOpts))
B.addAttribute(llvm::Attribute::NoUnwind);
if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
if (LangOpts.getStackProtector() == LangOptions::SSPOn)
B.addAttribute(llvm::Attribute::StackProtect);
else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
B.addAttribute(llvm::Attribute::StackProtectStrong);
else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
B.addAttribute(llvm::Attribute::StackProtectReq);
}
if (!D) {
// If we don't have a declaration to control inlining, the function isn't
// explicitly marked as alwaysinline for semantic reasons, and inlining is
// disabled, mark the function as noinline.
if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
B.addAttribute(llvm::Attribute::NoInline);
F->addFnAttrs(B);
return;
}
// Track whether we need to add the optnone LLVM attribute,
// starting with the default for this optimization level.
bool ShouldAddOptNone =
!CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
// We can't add optnone in the following cases, it won't pass the verifier.
ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
// Add optnone, but do so only if the function isn't always_inline.
if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
B.addAttribute(llvm::Attribute::OptimizeNone);
// OptimizeNone implies noinline; we should not be inlining such functions.
B.addAttribute(llvm::Attribute::NoInline);
// We still need to handle naked functions even though optnone subsumes
// much of their semantics.
if (D->hasAttr<NakedAttr>())
B.addAttribute(llvm::Attribute::Naked);
// OptimizeNone wins over OptimizeForSize and MinSize.
F->removeFnAttr(llvm::Attribute::OptimizeForSize);
F->removeFnAttr(llvm::Attribute::MinSize);
} else if (D->hasAttr<NakedAttr>()) {
// Naked implies noinline: we should not be inlining such functions.
B.addAttribute(llvm::Attribute::Naked);
B.addAttribute(llvm::Attribute::NoInline);
} else if (D->hasAttr<NoDuplicateAttr>()) {
B.addAttribute(llvm::Attribute::NoDuplicate);
} else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
// Add noinline if the function isn't always_inline.
B.addAttribute(llvm::Attribute::NoInline);
} else if (D->hasAttr<AlwaysInlineAttr>() &&
!F->hasFnAttribute(llvm::Attribute::NoInline)) {
// (noinline wins over always_inline, and we can't specify both in IR)
B.addAttribute(llvm::Attribute::AlwaysInline);
} else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
// If we're not inlining, then force everything that isn't always_inline to
// carry an explicit noinline attribute.
if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
B.addAttribute(llvm::Attribute::NoInline);
} else {
// Otherwise, propagate the inline hint attribute and potentially use its
// absence to mark things as noinline.
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
// Search function and template pattern redeclarations for inline.
auto CheckForInline = [](const FunctionDecl *FD) {
auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
return Redecl->isInlineSpecified();
};
if (any_of(FD->redecls(), CheckRedeclForInline))
return true;
const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
if (!Pattern)
return false;
return any_of(Pattern->redecls(), CheckRedeclForInline);
};
if (CheckForInline(FD)) {
B.addAttribute(llvm::Attribute::InlineHint);
} else if (CodeGenOpts.getInlining() ==
CodeGenOptions::OnlyHintInlining &&
!FD->isInlined() &&
!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
B.addAttribute(llvm::Attribute::NoInline);
}
}
}
// Add other optimization related attributes if we are optimizing this
// function.
if (!D->hasAttr<OptimizeNoneAttr>()) {
if (D->hasAttr<ColdAttr>()) {
if (!ShouldAddOptNone)
B.addAttribute(llvm::Attribute::OptimizeForSize);
B.addAttribute(llvm::Attribute::Cold);
}
if (D->hasAttr<HotAttr>())
B.addAttribute(llvm::Attribute::Hot);
if (D->hasAttr<MinSizeAttr>())
B.addAttribute(llvm::Attribute::MinSize);
}
F->addFnAttrs(B);
unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
if (alignment)
F->setAlignment(llvm::Align(alignment));
if (!D->hasAttr<AlignedAttr>())
if (LangOpts.FunctionAlignment)
F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
// Some C++ ABIs require 2-byte alignment for member functions, in order to
// reserve a bit for differentiating between virtual and non-virtual member
// functions. If the current target's C++ ABI requires this and this is a
// member function, set its alignment accordingly.
if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
F->setAlignment(llvm::Align(2));
}
// In the cross-dso CFI mode with canonical jump tables, we want !type
// attributes on definitions only.
if (CodeGenOpts.SanitizeCfiCrossDso &&
CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
// Skip available_externally functions. They won't be codegen'ed in the
// current module anyway.
if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
CreateFunctionTypeMetadataForIcall(FD, F);
}
}
// Emit type metadata on member functions for member function pointer checks.
// These are only ever necessary on definitions; we're guaranteed that the
// definition will be present in the LTO unit as a result of LTO visibility.
auto *MD = dyn_cast<CXXMethodDecl>(D);
if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
llvm::Metadata *Id =
CreateMetadataIdentifierForType(Context.getMemberPointerType(
MD->getType(), Context.getRecordType(Base).getTypePtr()));
F->addTypeMetadata(0, Id);
}
}
}
void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
llvm::Function *F) {
if (D->hasAttr<StrictFPAttr>()) {
llvm::AttrBuilder FuncAttrs(F->getContext());
FuncAttrs.addAttribute("strictfp");
F->addFnAttrs(FuncAttrs);
}
}
void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
const Decl *D = GD.getDecl();
if (isa_and_nonnull<NamedDecl>(D))
setGVProperties(GV, GD);
else
GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
if (D && D->hasAttr<UsedAttr>())
addUsedOrCompilerUsedGlobal(GV);
if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
const auto *VD = cast<VarDecl>(D);
if (VD->getType().isConstQualified() &&
VD->getStorageDuration() == SD_Static)
addUsedOrCompilerUsedGlobal(GV);
}
}
bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
llvm::AttrBuilder &Attrs) {
// Add target-cpu and target-features attributes to functions. If
// we have a decl for the function and it has a target attribute then
// parse that and add it to the feature set.
StringRef TargetCPU = getTarget().getTargetOpts().CPU;
StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
std::vector<std::string> Features;
const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
FD = FD ? FD->getMostRecentDecl() : FD;
const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
bool AddedAttr = false;
if (TD || SD || TC) {
llvm::StringMap<bool> FeatureMap;
getContext().getFunctionFeatureMap(FeatureMap, GD);
// Produce the canonical string for this set of features.
for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
// Now add the target-cpu and target-features to the function.
// While we populated the feature map above, we still need to
// get and parse the target attribute so we can get the cpu for
// the function.
if (TD) {
ParsedTargetAttr ParsedAttr = TD->parse();
if (!ParsedAttr.Architecture.empty() &&
getTarget().isValidCPUName(ParsedAttr.Architecture)) {
TargetCPU = ParsedAttr.Architecture;
TuneCPU = ""; // Clear the tune CPU.
}
if (!ParsedAttr.Tune.empty() &&
getTarget().isValidCPUName(ParsedAttr.Tune))
TuneCPU = ParsedAttr.Tune;
}
} else {
// Otherwise just add the existing target cpu and target features to the
// function.
Features = getTarget().getTargetOpts().Features;
}
if (!TargetCPU.empty()) {
Attrs.addAttribute("target-cpu", TargetCPU);
AddedAttr = true;
}
if (!TuneCPU.empty()) {
Attrs.addAttribute("tune-cpu", TuneCPU);
AddedAttr = true;
}
if (!Features.empty()) {
llvm::sort(Features);
Attrs.addAttribute("target-features", llvm::join(Features, ","));
AddedAttr = true;
}
return AddedAttr;
}
void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
llvm::GlobalObject *GO) {
const Decl *D = GD.getDecl();
SetCommonAttributes(GD, GO);
if (D) {
if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
if (D->hasAttr<RetainAttr>())
addUsedGlobal(GV);
if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
GV->addAttribute("bss-section", SA->getName());
if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
GV->addAttribute("data-section", SA->getName());
if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
GV->addAttribute("rodata-section", SA->getName());
if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
GV->addAttribute("relro-section", SA->getName());
}
if (auto *F = dyn_cast<llvm::Function>(GO)) {
if (D->hasAttr<RetainAttr>())
addUsedGlobal(F);
if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
if (!D->getAttr<SectionAttr>())
F->addFnAttr("implicit-section-name", SA->getName());
llvm::AttrBuilder Attrs(F->getContext());
if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
// We know that GetCPUAndFeaturesAttributes will always have the
// newest set, since it has the newest possible FunctionDecl, so the
// new ones should replace the old.
llvm::AttributeMask RemoveAttrs;
RemoveAttrs.addAttribute("target-cpu");
RemoveAttrs.addAttribute("target-features");
RemoveAttrs.addAttribute("tune-cpu");
F->removeFnAttrs(RemoveAttrs);
F->addFnAttrs(Attrs);
}
}
if (const auto *CSA = D->getAttr<CodeSegAttr>())
GO->setSection(CSA->getName());
else if (const auto *SA = D->getAttr<SectionAttr>())
GO->setSection(SA->getName());
}
getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
}
void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
llvm::Function *F,
const CGFunctionInfo &FI) {
const Decl *D = GD.getDecl();
SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
SetLLVMFunctionAttributesForDefinition(D, F);
F->setLinkage(llvm::Function::InternalLinkage);
setNonAliasAttributes(GD, F);
}
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
// Set linkage and visibility in case we never see a definition.
LinkageInfo LV = ND->getLinkageAndVisibility();
// Don't set internal linkage on declarations.
// "extern_weak" is overloaded in LLVM; we probably should have
// separate linkage types for this.
if (isExternallyVisible(LV.getLinkage()) &&
(ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
}
void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
llvm::Function *F) {
// Only if we are checking indirect calls.
if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
return;
// Non-static class methods are handled via vtable or member function pointer
// checks elsewhere.
if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
return;
llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
F->addTypeMetadata(0, MD);
F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
// Emit a hash-based bit set entry for cross-DSO calls.
if (CodeGenOpts.SanitizeCfiCrossDso)
if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
}
void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
bool IsIncompleteFunction,
bool IsThunk) {
if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
// If this is an intrinsic function, set the function's attributes
// to the intrinsic's attributes.
F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
return;
}
const auto *FD = cast<FunctionDecl>(GD.getDecl());
if (!IsIncompleteFunction)
SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
IsThunk);
// Add the Returned attribute for "this", except for iOS 5 and earlier
// where substantial code, including the libstdc++ dylib, was compiled with
// GCC and does not actually return "this".
if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
!(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
assert(!F->arg_empty() &&
F->arg_begin()->getType()
->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return");
F->addParamAttr(0, llvm::Attribute::Returned);
}
// Only a few attributes are set on declarations; these may later be
// overridden by a definition.
setLinkageForGV(F, FD);
setGVProperties(F, FD);
// Setup target-specific attributes.
if (!IsIncompleteFunction && F->isDeclaration())
getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
if (const auto *CSA = FD->getAttr<CodeSegAttr>())
F->setSection(CSA->getName());
else if (const auto *SA = FD->getAttr<SectionAttr>())
F->setSection(SA->getName());
if (const auto *EA = FD->getAttr<ErrorAttr>()) {
if (EA->isError())
F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
else if (EA->isWarning())
F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
}
// If we plan on emitting this inline builtin, we can't treat it as a builtin.
if (FD->isInlineBuiltinDeclaration()) {
const FunctionDecl *FDBody;
bool HasBody = FD->hasBody(FDBody);
(void)HasBody;
assert(HasBody && "Inline builtin declarations should always have an "
"available body!");
if (shouldEmitFunction(FDBody))
F->addFnAttr(llvm::Attribute::NoBuiltin);
}
if (FD->isReplaceableGlobalAllocationFunction()) {
// A replaceable global allocation function does not act like a builtin by
// default, only if it is invoked by a new-expression or delete-expression.
F->addFnAttr(llvm::Attribute::NoBuiltin);
}
if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
if (MD->isVirtual())
F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
// Don't emit entries for function declarations in the cross-DSO mode. This
// is handled with better precision by the receiving DSO. But if jump tables
// are non-canonical then we need type metadata in order to produce the local
// jump table.
if (!CodeGenOpts.SanitizeCfiCrossDso ||
!CodeGenOpts.SanitizeCfiCanonicalJumpTables)
CreateFunctionTypeMetadataForIcall(FD, F);
if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
if (const auto *CB = FD->getAttr<CallbackAttr>()) {
// Annotate the callback behavior as metadata:
// - The callback callee (as argument number).
// - The callback payloads (as argument numbers).
llvm::LLVMContext &Ctx = F->getContext();
llvm::MDBuilder MDB(Ctx);
// The payload indices are all but the first one in the encoding. The first
// identifies the callback callee.
int CalleeIdx = *CB->encoding_begin();
ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
F->addMetadata(llvm::LLVMContext::MD_callback,
*llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
CalleeIdx, PayloadIndices,
/* VarArgsArePassed */ false)}));
}
}
void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
"Only globals with definition can force usage.");
LLVMUsed.emplace_back(GV);
}
void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
assert(!GV->isDeclaration() &&
"Only globals with definition can force usage.");
LLVMCompilerUsed.emplace_back(GV);
}
void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
"Only globals with definition can force usage.");
if (getTriple().isOSBinFormatELF())
LLVMCompilerUsed.emplace_back(GV);
else
LLVMUsed.emplace_back(GV);
}
static void emitUsed(CodeGenModule &CGM, StringRef Name,
std::vector<llvm::WeakTrackingVH> &List) {
// Don't create llvm.used if there is no need.
if (List.empty())
return;
// Convert List to what ConstantArray needs.
SmallVector<llvm::Constant*, 8> UsedArray;
UsedArray.resize(List.size());
for (unsigned i = 0, e = List.size(); i != e; ++i) {
UsedArray[i] =
llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
}
if (UsedArray.empty())
return;
llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
auto *GV = new llvm::GlobalVariable(
CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(ATy, UsedArray), Name);
GV->setSection("llvm.metadata");
}
void CodeGenModule::emitLLVMUsed() {
emitUsed(*this, "llvm.used", LLVMUsed);
emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
}
void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
}
void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
llvm::SmallString<32> Opt;
getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
if (Opt.empty())
return;
auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
}
void CodeGenModule::AddDependentLib(StringRef Lib) {
auto &C = getLLVMContext();
if (getTarget().getTriple().isOSBinFormatELF()) {
ELFDependentLibraries.push_back(
llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
return;
}
llvm::SmallString<24> Opt;
getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
}
/// Add link options implied by the given module, including modules
/// it depends on, using a postorder walk.
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
SmallVectorImpl<llvm::MDNode *> &Metadata,
llvm::SmallPtrSet<Module *, 16> &Visited) {
// Import this module's parent.
if (Mod->Parent && Visited.insert(Mod->Parent).second) {
addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
}
// Import this module's dependencies.
for (Module *Import : llvm::reverse(Mod->Imports)) {
if (Visited.insert(Import).second)
addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
}
// Add linker options to link against the libraries/frameworks
// described by this module.
llvm::LLVMContext &Context = CGM.getLLVMContext();
bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
// For modules that use export_as for linking, use that module
// name instead.
if (Mod->UseExportAsModuleLinkName)
return;
for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
// Link against a framework. Frameworks are currently Darwin only, so we
// don't to ask TargetCodeGenInfo for the spelling of the linker option.
if (LL.IsFramework) {
llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
llvm::MDString::get(Context, LL.Library)};
Metadata.push_back(llvm::MDNode::get(Context, Args));
continue;
}
// Link against a library.
if (IsELF) {
llvm::Metadata *Args[2] = {
llvm::MDString::get(Context, "lib"),
llvm::MDString::get(Context, LL.Library),
};
Metadata.push_back(llvm::MDNode::get(Context, Args));
} else {
llvm::SmallString<24> Opt;
CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
auto *OptString = llvm::MDString::get(Context, Opt);
Metadata.push_back(llvm::MDNode::get(Context, OptString));
}
}
}
void CodeGenModule::EmitModuleLinkOptions() {
// Collect the set of all of the modules we want to visit to emit link
// options, which is essentially the imported modules and all of their
// non-explicit child modules.
llvm::SetVector<clang::Module *> LinkModules;
llvm::SmallPtrSet<clang::Module *, 16> Visited;
SmallVector<clang::Module *, 16> Stack;
// Seed the stack with imported modules.
for (Module *M : ImportedModules) {
// Do not add any link flags when an implementation TU of a module imports
// a header of that same module.
if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
!getLangOpts().isCompilingModule())
continue;
if (Visited.insert(M).second)
Stack.push_back(M);
}
// Find all of the modules to import, making a little effort to prune
// non-leaf modules.
while (!Stack.empty()) {
clang::Module *Mod = Stack.pop_back_val();
bool AnyChildren = false;
// Visit the submodules of this module.
for (const auto &SM : Mod->submodules()) {
// Skip explicit children; they need to be explicitly imported to be
// linked against.
if (SM->IsExplicit)
continue;
if (Visited.insert(SM).second) {
Stack.push_back(SM);
AnyChildren = true;
}
}
// We didn't find any children, so add this module to the list of
// modules to link against.
if (!AnyChildren) {
LinkModules.insert(Mod);
}
}
// Add link options for all of the imported modules in reverse topological
// order. We don't do anything to try to order import link flags with respect
// to linker options inserted by things like #pragma comment().
SmallVector<llvm::MDNode *, 16> MetadataArgs;
Visited.clear();
for (Module *M : LinkModules)
if (Visited.insert(M).second)
addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
std::reverse(MetadataArgs.begin(), MetadataArgs.end());
LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
// Add the linker options metadata flag.
auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
for (auto *MD : LinkerOptionsMetadata)
NMD->addOperand(MD);
}
void CodeGenModule::EmitDeferred() {
// Emit deferred declare target declarations.
if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
getOpenMPRuntime().emitDeferredTargetDecls();
// Emit code for any potentially referenced deferred decls. Since a
// previously unused static decl may become used during the generation of code
// for a static function, iterate until no changes are made.
if (!DeferredVTables.empty()) {
EmitDeferredVTables();
// Emitting a vtable doesn't directly cause more vtables to
// become deferred, although it can cause functions to be
// emitted that then need those vtables.
assert(DeferredVTables.empty());
}
// Emit CUDA/HIP static device variables referenced by host code only.
// Note we should not clear CUDADeviceVarODRUsedByHost since it is still
// needed for further handling.
if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
for (const auto *V : getContext().CUDADeviceVarODRUsedByHost)
DeferredDeclsToEmit.push_back(V);
// Stop if we're out of both deferred vtables and deferred declarations.
if (DeferredDeclsToEmit.empty())
return;
// Grab the list of decls to emit. If EmitGlobalDefinition schedules more
// work, it will not interfere with this.
std::vector<GlobalDecl> CurDeclsToEmit;
CurDeclsToEmit.swap(DeferredDeclsToEmit);
for (GlobalDecl &D : CurDeclsToEmit) {
// We should call GetAddrOfGlobal with IsForDefinition set to true in order
// to get GlobalValue with exactly the type we need, not something that
// might had been created for another decl with the same mangled name but
// different type.
llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
GetAddrOfGlobal(D, ForDefinition));
// In case of different address spaces, we may still get a cast, even with
// IsForDefinition equal to true. Query mangled names table to get
// GlobalValue.
if (!GV)
GV = GetGlobalValue(getMangledName(D));
// Make sure GetGlobalValue returned non-null.
assert(GV);
// Check to see if we've already emitted this. This is necessary
// for a couple of reasons: first, decls can end up in the
// deferred-decls queue multiple times, and second, decls can end
// up with definitions in unusual ways (e.g. by an extern inline
// function acquiring a strong function redefinition). Just
// ignore these cases.
if (!GV->isDeclaration())
continue;
// If this is OpenMP, check if it is legal to emit this global normally.
if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
continue;
// Otherwise, emit the definition and move on to the next one.
EmitGlobalDefinition(D, GV);
// If we found out that we need to emit more decls, do that recursively.
// This has the advantage that the decls are emitted in a DFS and related
// ones are close together, which is convenient for testing.
if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
EmitDeferred();
assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
}
}
}
void CodeGenModule::EmitVTablesOpportunistically() {
// Try to emit external vtables as available_externally if they have emitted
// all inlined virtual functions. It runs after EmitDeferred() and therefore
// is not allowed to create new references to things that need to be emitted
// lazily. Note that it also uses fact that we eagerly emitting RTTI.
assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
&& "Only emit opportunistic vtables with optimizations");
for (const CXXRecordDecl *RD : OpportunisticVTables) {
assert(getVTables().isVTableExternal(RD) &&
"This queue should only contain external vtables");
if (getCXXABI().canSpeculativelyEmitVTable(RD))
VTables.GenerateClassData(RD);
}
OpportunisticVTables.clear();
}
void CodeGenModule::EmitGlobalAnnotations() {
if (Annotations.empty())
return;
// Create a new global variable for the ConstantStruct in the Module.
llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
Annotations[0]->getType(), Annotations.size()), Annotations);
auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
llvm::GlobalValue::AppendingLinkage,
Array, "llvm.global.annotations");
gv->setSection(AnnotationSection);
}
llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
llvm::Constant *&AStr = AnnotationStrings[Str];
if (AStr)
return AStr;
// Not found yet, create a new global.
llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
auto *gv =
new llvm::GlobalVariable(getModule(), s->getType(), true,
llvm::GlobalValue::PrivateLinkage, s, ".str");
gv->setSection(AnnotationSection);
gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
AStr = gv;
return gv;
}
llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
SourceManager &SM = getContext().getSourceManager();
PresumedLoc PLoc = SM.getPresumedLoc(Loc);
if (PLoc.isValid())
return EmitAnnotationString(PLoc.getFilename());
return EmitAnnotationString(SM.getBufferName(Loc));
}
llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
SourceManager &SM = getContext().getSourceManager();
PresumedLoc PLoc = SM.getPresumedLoc(L);
unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
SM.getExpansionLineNumber(L);
return llvm::ConstantInt::get(Int32Ty, LineNo);
}
llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
if (Exprs.empty())
return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy);
llvm::FoldingSetNodeID ID;
for (Expr *E : Exprs) {
ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
}
llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
if (Lookup)
return Lookup;
llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
LLVMArgs.reserve(Exprs.size());
ConstantEmitter ConstEmiter(*this);
llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
const auto *CE = cast<clang::ConstantExpr>(E);
return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
CE->getType());
});
auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
llvm::GlobalValue::PrivateLinkage, Struct,
".args");
GV->setSection(AnnotationSection);
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
Lookup = Bitcasted;
return Bitcasted;
}
llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
const AnnotateAttr *AA,
SourceLocation L) {
// Get the globals for file name, annotation, and the line number.
llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
*UnitGV = EmitAnnotationUnit(L),
*LineNoCst = EmitAnnotationLineNo(L),
*Args = EmitAnnotationArgs(AA);
llvm::Constant *GVInGlobalsAS = GV;
if (GV->getAddressSpace() !=
getDataLayout().getDefaultGlobalsAddressSpace()) {
GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
GV, GV->getValueType()->getPointerTo(
getDataLayout().getDefaultGlobalsAddressSpace()));
}
// Create the ConstantStruct for the global annotation.
llvm::Constant *Fields[] = {
llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy),
llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy),
LineNoCst,
Args,
};
return llvm::ConstantStruct::getAnon(Fields);
}
void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
llvm::GlobalValue *GV) {
assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
// Get the struct elements for these annotations.
for (const auto *I : D->specific_attrs<AnnotateAttr>())
Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
}
bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
SourceLocation Loc) const {
const auto &NoSanitizeL = getContext().getNoSanitizeList();
// NoSanitize by function name.
if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
return true;
// NoSanitize by location.
if (Loc.isValid())
return NoSanitizeL.containsLocation(Kind, Loc);
// If location is unknown, this may be a compiler-generated function. Assume
// it's located in the main file.
auto &SM = Context.getSourceManager();
if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
return NoSanitizeL.containsFile(Kind, MainFile->getName());
}
return false;
}
bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV,
SourceLocation Loc, QualType Ty,
StringRef Category) const {
// For now globals can be ignored only in ASan and KASan.
const SanitizerMask EnabledAsanMask =
LangOpts.Sanitize.Mask &
(SanitizerKind::Address | SanitizerKind::KernelAddress |
SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
SanitizerKind::MemTag);
if (!EnabledAsanMask)
return false;
const auto &NoSanitizeL = getContext().getNoSanitizeList();
if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category))
return true;
if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category))
return true;
// Check global type.
if (!Ty.isNull()) {
// Drill down the array types: if global variable of a fixed type is
// not sanitized, we also don't instrument arrays of them.
while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
Ty = AT->getElementType();
Ty = Ty.getCanonicalType().getUnqualifiedType();
// Only record types (classes, structs etc.) are ignored.
if (Ty->isRecordType()) {
std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category))
return true;
}
}
return false;
}
bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
StringRef Category) const {
const auto &XRayFilter = getContext().getXRayFilter();
using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
auto Attr = ImbueAttr::NONE;
if (Loc.isValid())
Attr = XRayFilter.shouldImbueLocation(Loc, Category);
if (Attr == ImbueAttr::NONE)
Attr = XRayFilter.shouldImbueFunction(Fn->getName());
switch (Attr) {
case ImbueAttr::NONE:
return false;
case ImbueAttr::ALWAYS:
Fn->addFnAttr("function-instrument", "xray-always");
break;
case ImbueAttr::ALWAYS_ARG1:
Fn->addFnAttr("function-instrument", "xray-always");
Fn->addFnAttr("xray-log-args", "1");
break;
case ImbueAttr::NEVER:
Fn->addFnAttr("function-instrument", "xray-never");
break;
}
return true;
}
bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
SourceLocation Loc) const {
const auto &ProfileList = getContext().getProfileList();
// If the profile list is empty, then instrument everything.
if (ProfileList.isEmpty())
return false;
CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
// First, check the function name.
Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
if (V.hasValue())
return *V;
// Next, check the source location.
if (Loc.isValid()) {
Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
if (V.hasValue())
return *V;
}
// If location is unknown, this may be a compiler-generated function. Assume
// it's located in the main file.
auto &SM = Context.getSourceManager();
if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
if (V.hasValue())
return *V;
}
return ProfileList.getDefault();
}
bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
// Never defer when EmitAllDecls is specified.
if (LangOpts.EmitAllDecls)
return true;
if (CodeGenOpts.KeepStaticConsts) {
const auto *VD = dyn_cast<VarDecl>(Global);
if (VD && VD->getType().isConstQualified() &&
VD->getStorageDuration() == SD_Static)
return true;
}
return getContext().DeclMustBeEmitted(Global);
}
bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
// In OpenMP 5.0 variables and function may be marked as
// device_type(host/nohost) and we should not emit them eagerly unless we sure
// that they must be emitted on the host/device. To be sure we need to have
// seen a declare target with an explicit mentioning of the function, we know
// we have if the level of the declare target attribute is -1. Note that we
// check somewhere else if we should emit this at all.
if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
OMPDeclareTargetDeclAttr::getActiveAttr(Global);
if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
return false;
}
if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
// Implicit template instantiations may change linkage if they are later
// explicitly instantiated, so they should not be emitted eagerly.
return false;
}
if (const auto *VD = dyn_cast<VarDecl>(Global))
if (Context.getInlineVariableDefinitionKind(VD) ==
ASTContext::InlineVariableDefinitionKind::WeakUnknown)
// A definition of an inline constexpr static data member may change
// linkage later if it's redeclared outside the class.
return false;
// If OpenMP is enabled and threadprivates must be generated like TLS, delay
// codegen for global variables, because they may be marked as threadprivate.
if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
!isTypeConstant(Global->getType(), false) &&
!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
return false;
return true;
}
ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
StringRef Name = getMangledName(GD);
// The UUID descriptor should be pointer aligned.
CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
// Look for an existing global.
if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
return ConstantAddress(GV, GV->getValueType(), Alignment);
ConstantEmitter Emitter(*this);
llvm::Constant *Init;
APValue &V = GD->getAsAPValue();
if (!V.isAbsent()) {
// If possible, emit the APValue version of the initializer. In particular,
// this gets the type of the constant right.
Init = Emitter.emitForInitializer(
GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
} else {
// As a fallback, directly construct the constant.
// FIXME: This may get padding wrong under esoteric struct layout rules.
// MSVC appears to create a complete type 'struct __s_GUID' that it
// presumably uses to represent these constants.
MSGuidDecl::Parts Parts = GD->getParts();
llvm::Constant *Fields[4] = {
llvm::ConstantInt::get(Int32Ty, Parts.Part1),
llvm::ConstantInt::get(Int16Ty, Parts.Part2),
llvm::ConstantInt::get(Int16Ty, Parts.Part3),
llvm::ConstantDataArray::getRaw(
StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
Int8Ty)};
Init = llvm::ConstantStruct::getAnon(Fields);
}
auto *GV = new llvm::GlobalVariable(
getModule(), Init->getType(),
/*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
if (supportsCOMDAT())
GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
setDSOLocal(GV);
if (!V.isAbsent()) {
Emitter.finalize(GV);
return ConstantAddress(GV, GV->getValueType(), Alignment);
}
llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
GV, Ty->getPointerTo(GV->getAddressSpace()));
return ConstantAddress(Addr, Ty, Alignment);
}
ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
const TemplateParamObjectDecl *TPO) {
StringRef Name = getMangledName(TPO);
CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
return ConstantAddress(GV, GV->getValueType(), Alignment);
ConstantEmitter Emitter(*this);
llvm::Constant *Init = Emitter.emitForInitializer(
TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
if (!Init) {
ErrorUnsupported(TPO, "template parameter object");
return ConstantAddress::invalid();
}
auto *GV = new llvm::GlobalVariable(
getModule(), Init->getType(),
/*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
if (supportsCOMDAT())
GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Emitter.finalize(GV);
return ConstantAddress(GV, GV->getValueType(), Alignment);
}
ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
const AliasAttr *AA = VD->getAttr<AliasAttr>();
assert(AA && "No alias?");
CharUnits Alignment = getContext().getDeclAlign(VD);
llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
// See if there is already something with the target's name in the module.
llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
if (Entry) {
unsigned AS = getContext().getTargetAddressSpace(VD->getType());
auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
return ConstantAddress(Ptr, DeclTy, Alignment);
}
llvm::Constant *Aliasee;
if (isa<llvm::FunctionType>(DeclTy))
Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
GlobalDecl(cast<FunctionDecl>(VD)),
/*ForVTable=*/false);
else
Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
nullptr);
auto *F = cast<llvm::GlobalValue>(Aliasee);
F->setLinkage(llvm::Function::ExternalWeakLinkage);
WeakRefReferences.insert(F);
return ConstantAddress(Aliasee, DeclTy, Alignment);
}
void CodeGenModule::EmitGlobal(GlobalDecl GD) {
const auto *Global = cast<ValueDecl>(GD.getDecl());
// Weak references don't produce any output by themselves.
if (Global->hasAttr<WeakRefAttr>())
return;
// If this is an alias definition (which otherwise looks like a declaration)
// emit it now.
if (Global->hasAttr<AliasAttr>())
return EmitAliasDefinition(GD);
// IFunc like an alias whose value is resolved at runtime by calling resolver.
if (Global->hasAttr<IFuncAttr>())
return emitIFuncDefinition(GD);
// If this is a cpu_dispatch multiversion function, emit the resolver.
if (Global->hasAttr<CPUDispatchAttr>())
return emitCPUDispatchDefinition(GD);
// If this is CUDA, be selective about which declarations we emit.
if (LangOpts.CUDA) {
if (LangOpts.CUDAIsDevice) {
if (!Global->hasAttr<CUDADeviceAttr>() &&
!Global->hasAttr<CUDAGlobalAttr>() &&
!Global->hasAttr<CUDAConstantAttr>() &&
!Global->hasAttr<CUDASharedAttr>() &&
!Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
!Global->getType()->isCUDADeviceBuiltinTextureType())
return;
} else {
// We need to emit host-side 'shadows' for all global
// device-side variables because the CUDA runtime needs their
// size and host-side address in order to provide access to
// their device-side incarnations.
// So device-only functions are the only things we skip.
if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
Global->hasAttr<CUDADeviceAttr>())
return;
assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
"Expected Variable or Function");
}
}
if (LangOpts.OpenMP) {
// If this is OpenMP, check if it is legal to emit this global normally.
if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
return;
if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
if (MustBeEmitted(Global))
EmitOMPDeclareReduction(DRD);
return;
} else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
if (MustBeEmitted(Global))
EmitOMPDeclareMapper(DMD);
return;
}
}
// Ignore declarations, they will be emitted on their first use.
if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
// Forward declarations are emitted lazily on first use.
if (!FD->doesThisDeclarationHaveABody()) {
if (!FD->doesDeclarationForceExternallyVisibleDefinition())
return;
StringRef MangledName = getMangledName(GD);
// Compute the function info and LLVM type.
const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
llvm::Type *Ty = getTypes().GetFunctionType(FI);
GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
/*DontDefer=*/false);
return;
}
} else {
const auto *VD = cast<VarDecl>(Global);
assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
!Context.isMSStaticDataMemberInlineDefinition(VD)) {
if (LangOpts.OpenMP) {
// Emit declaration of the must-be-emitted declare target variable.
if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
bool UnifiedMemoryEnabled =
getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
!UnifiedMemoryEnabled) {
(void)GetAddrOfGlobalVar(VD);
} else {
assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
(*Res == OMPDeclareTargetDeclAttr::MT_To &&
UnifiedMemoryEnabled)) &&
"Link clause or to clause with unified memory expected.");
(void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
}
return;
}
}
// If this declaration may have caused an inline variable definition to
// change linkage, make sure that it's emitted.
if (Context.getInlineVariableDefinitionKind(VD) ==
ASTContext::InlineVariableDefinitionKind::Strong)
GetAddrOfGlobalVar(VD);
return;
}
}
// Defer code generation to first use when possible, e.g. if this is an inline
// function. If the global must always be emitted, do it eagerly if possible
// to benefit from cache locality.
if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
// Emit the definition if it can't be deferred.
EmitGlobalDefinition(GD);
return;
}
// If we're deferring emission of a C++ variable with an
// initializer, remember the order in which it appeared in the file.
if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
cast<VarDecl>(Global)->hasInit()) {
DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
CXXGlobalInits.push_back(nullptr);
}
StringRef MangledName = getMangledName(GD);
if (GetGlobalValue(MangledName) != nullptr) {
// The value has already been used and should therefore be emitted.
addDeferredDeclToEmit(GD);
} else if (MustBeEmitted(Global)) {
// The value must be emitted, but cannot be emitted eagerly.
assert(!MayBeEmittedEagerly(Global));
addDeferredDeclToEmit(GD);
} else {
// Otherwise, remember that we saw a deferred decl with this name. The
// first use of the mangled name will cause it to move into
// DeferredDeclsToEmit.
DeferredDecls[MangledName] = GD;
}
}
// Check if T is a class type with a destructor that's not dllimport.
static bool HasNonDllImportDtor(QualType T) {
if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
return true;
return false;
}
namespace {
struct FunctionIsDirectlyRecursive
: public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
const StringRef Name;
const Builtin::Context &BI;
FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
: Name(N), BI(C) {}
bool VisitCallExpr(const CallExpr *E) {
const FunctionDecl *FD = E->getDirectCallee();
if (!FD)
return false;
AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
if (Attr && Name == Attr->getLabel())
return true;
unsigned BuiltinID = FD->getBuiltinID();
if (!BuiltinID || !BI.isLibFunction(BuiltinID))
return false;
StringRef BuiltinName = BI.getName(BuiltinID);
if (BuiltinName.startswith("__builtin_") &&
Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
return true;
}
return false;
}
bool VisitStmt(const Stmt *S) {
for (const Stmt *Child : S->children())
if (Child && this->Visit(Child))
return true;
return false;
}
};
// Make sure we're not referencing non-imported vars or functions.
struct DLLImportFunctionVisitor
: public RecursiveASTVisitor<DLLImportFunctionVisitor> {
bool SafeToInline = true;
bool shouldVisitImplicitCode() const { return true; }
bool VisitVarDecl(VarDecl *VD) {
if (VD->getTLSKind()) {
// A thread-local variable cannot be imported.
SafeToInline = false;
return SafeToInline;
}
// A variable definition might imply a destructor call.
if (VD->isThisDeclarationADefinition())
SafeToInline = !HasNonDllImportDtor(VD->getType());
return SafeToInline;
}
bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
if (const auto *D = E->getTemporary()->getDestructor())
SafeToInline = D->hasAttr<DLLImportAttr>();
return SafeToInline;
}
bool VisitDeclRefExpr(DeclRefExpr *E) {
ValueDecl *VD = E->getDecl();
if (isa<FunctionDecl>(VD))
SafeToInline = VD->hasAttr<DLLImportAttr>();
else if (VarDecl *V = dyn_cast<VarDecl>(VD))
SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
return SafeToInline;
}
bool VisitCXXConstructExpr(CXXConstructExpr *E) {
SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
return SafeToInline;
}
bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
CXXMethodDecl *M = E->getMethodDecl();
if (!M) {
// Call through a pointer to member function. This is safe to inline.
SafeToInline = true;
} else {
SafeToInline = M->hasAttr<DLLImportAttr>();
}
return SafeToInline;
}
bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
return SafeToInline;
}
bool VisitCXXNewExpr(CXXNewExpr *E) {
SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
return SafeToInline;
}
};
}
// isTriviallyRecursive - Check if this function calls another
// decl that, because of the asm attribute or the other decl being a builtin,
// ends up pointing to itself.
bool
CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
StringRef Name;
if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
// asm labels are a special kind of mangling we have to support.
AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
if (!Attr)
return false;
Name = Attr->getLabel();
} else {
Name = FD->getName();
}
FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
const Stmt *Body = FD->getBody();
return Body ? Walker.Visit(Body) : false;
}
bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
return true;
const auto *F = cast<FunctionDecl>(GD.getDecl());
if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
return false;
if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
// Check whether it would be safe to inline this dllimport function.
DLLImportFunctionVisitor Visitor;
Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
if (!Visitor.SafeToInline)
return false;
if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
// Implicit destructor invocations aren't captured in the AST, so the
// check above can't see them. Check for them manually here.
for (const Decl *Member : Dtor->getParent()->decls())
if (isa<FieldDecl>(Member))
if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
return false;
for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
if (HasNonDllImportDtor(B.getType()))
return false;
}
}
// Inline builtins declaration must be emitted. They often are fortified
// functions.
if (F->isInlineBuiltinDeclaration())
return true;
// PR9614. Avoid cases where the source code is lying to us. An available
// externally function should have an equivalent function somewhere else,
// but a function that calls itself through asm label/`__builtin_` trickery is
// clearly not equivalent to the real implementation.
// This happens in glibc's btowc and in some configure checks.
return !isTriviallyRecursive(F);
}
bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
return CodeGenOpts.OptimizationLevel > 0;
}
void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
llvm::GlobalValue *GV) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
if (FD->isCPUSpecificMultiVersion()) {
auto *Spec = FD->getAttr<CPUSpecificAttr>();
for (unsigned I = 0; I < Spec->cpus_size(); ++I)
EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
// Requires multiple emits.
} else if (FD->isTargetClonesMultiVersion()) {
auto *Clone = FD->getAttr<TargetClonesAttr>();
for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
if (Clone->isFirstOfVersion(I))
EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
EmitTargetClonesResolver(GD);
} else
EmitGlobalFunctionDefinition(GD, GV);
}
void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
const auto *D = cast<ValueDecl>(GD.getDecl());
PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Context.getSourceManager(),
"Generating code for declaration");
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
// At -O0, don't generate IR for functions with available_externally
// linkage.
if (!shouldEmitFunction(GD))
return;
llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
std::string Name;
llvm::raw_string_ostream OS(Name);
FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
/*Qualified=*/true);
return Name;
});
if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
// Make sure to emit the definition(s) before we emit the thunks.
// This is necessary for the generation of certain thunks.
if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
ABI->emitCXXStructor(GD);
else if (FD->isMultiVersion())
EmitMultiVersionFunctionDefinition(GD, GV);
else
EmitGlobalFunctionDefinition(GD, GV);
if (Method->isVirtual())
getVTables().EmitThunks(GD);
return;
}
if (FD->isMultiVersion())
return EmitMultiVersionFunctionDefinition(GD, GV);
return EmitGlobalFunctionDefinition(GD, GV);
}
if (const auto *VD = dyn_cast<VarDecl>(D))
return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
}
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
llvm::Function *NewFn);
static unsigned
TargetMVPriority(const TargetInfo &TI,
const CodeGenFunction::MultiVersionResolverOption &RO) {
unsigned Priority = 0;
for (StringRef Feat : RO.Conditions.Features)
Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
if (!RO.Conditions.Architecture.empty())
Priority = std::max(
Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
return Priority;
}
// Multiversion functions should be at most 'WeakODRLinkage' so that a different
// TU can forward declare the function without causing problems. Particularly
// in the cases of CPUDispatch, this causes issues. This also makes sure we
// work with internal linkage functions, so that the same function name can be
// used with internal linkage in multiple TUs.
llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
GlobalDecl GD) {
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
if (FD->getFormalLinkage() == InternalLinkage)
return llvm::GlobalValue::InternalLinkage;
return llvm::GlobalValue::WeakODRLinkage;
}
void CodeGenModule::EmitTargetClonesResolver(GlobalDecl GD) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
assert(FD && "Not a FunctionDecl?");
const auto *TC = FD->getAttr<TargetClonesAttr>();
assert(TC && "Not a target_clones Function?");
QualType CanonTy = Context.getCanonicalType(FD->getType());
llvm::Type *DeclTy = getTypes().ConvertType(CanonTy);
if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
DeclTy = getTypes().GetFunctionType(FInfo);
}
llvm::Function *ResolverFunc;
if (getTarget().supportsIFunc()) {
auto *IFunc = cast<llvm::GlobalIFunc>(
GetOrCreateMultiVersionResolver(GD, DeclTy, FD));
ResolverFunc = cast<llvm::Function>(IFunc->getResolver());
} else
ResolverFunc =
cast<llvm::Function>(GetOrCreateMultiVersionResolver(GD, DeclTy, FD));
SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
++VersionIndex) {
if (!TC->isFirstOfVersion(VersionIndex))
continue;
StringRef Version = TC->getFeatureStr(VersionIndex);
StringRef MangledName =
getMangledName(GD.getWithMultiVersionIndex(VersionIndex));
llvm::Constant *Func = GetGlobalValue(MangledName);
assert(Func &&
"Should have already been created before calling resolver emit");
StringRef Architecture;
llvm::SmallVector<StringRef, 1> Feature;
if (Version.startswith("arch="))
Architecture = Version.drop_front(sizeof("arch=") - 1);
else if (Version != "default")
Feature.push_back(Version);
Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
}
const TargetInfo &TI = getTarget();
std::stable_sort(
Options.begin(), Options.end(),
[&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
const CodeGenFunction::MultiVersionResolverOption &RHS) {
return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
});
CodeGenFunction CGF(*this);
CGF.EmitMultiVersionResolver(ResolverFunc, Options);
}
void CodeGenModule::emitMultiVersionFunctions() {
std::vector<GlobalDecl> MVFuncsToEmit;
MultiVersionFuncs.swap(MVFuncsToEmit);
for (GlobalDecl GD : MVFuncsToEmit) {
SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
getContext().forEachMultiversionedFunctionVersion(
FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
GlobalDecl CurGD{
(CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
StringRef MangledName = getMangledName(CurGD);
llvm::Constant *Func = GetGlobalValue(MangledName);
if (!Func) {
if (CurFD->isDefined()) {
EmitGlobalFunctionDefinition(CurGD, nullptr);
Func = GetGlobalValue(MangledName);
} else {
const CGFunctionInfo &FI =
getTypes().arrangeGlobalDeclaration(GD);
llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
/*DontDefer=*/false, ForDefinition);
}
assert(Func && "This should have just been created");
}
const auto *TA = CurFD->getAttr<TargetAttr>();
llvm::SmallVector<StringRef, 8> Feats;
TA->getAddedFeatures(Feats);
Options.emplace_back(cast<llvm::Function>(Func),
TA->getArchitecture(), Feats);
});
llvm::Function *ResolverFunc;
const TargetInfo &TI = getTarget();
if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
ResolverFunc = cast<llvm::Function>(
GetGlobalValue((getMangledName(GD) + ".resolver").str()));
ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
} else {
ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
}
if (supportsCOMDAT())
ResolverFunc->setComdat(
getModule().getOrInsertComdat(ResolverFunc->getName()));
llvm::stable_sort(
Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
const CodeGenFunction::MultiVersionResolverOption &RHS) {
return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
});
CodeGenFunction CGF(*this);
CGF.EmitMultiVersionResolver(ResolverFunc, Options);
}
// Ensure that any additions to the deferred decls list caused by emitting a
// variant are emitted. This can happen when the variant itself is inline and
// calls a function without linkage.
if (!MVFuncsToEmit.empty())
EmitDeferred();
// Ensure that any additions to the multiversion funcs list from either the
// deferred decls or the multiversion functions themselves are emitted.
if (!MultiVersionFuncs.empty())
emitMultiVersionFunctions();
}
void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
assert(FD && "Not a FunctionDecl?");
assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
const auto *DD = FD->getAttr<CPUDispatchAttr>();
assert(DD && "Not a cpu_dispatch Function?");
llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
DeclTy = getTypes().GetFunctionType(FInfo);
}
StringRef ResolverName = getMangledName(GD);
UpdateMultiVersionNames(GD, FD, ResolverName);
llvm::Type *ResolverType;
GlobalDecl ResolverGD;
if (getTarget().supportsIFunc()) {
ResolverType = llvm::FunctionType::get(
llvm::PointerType::get(DeclTy,
Context.getTargetAddressSpace(FD->getType())),
false);
}
else {
ResolverType = DeclTy;
ResolverGD = GD;
}
auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
if (supportsCOMDAT())
ResolverFunc->setComdat(
getModule().getOrInsertComdat(ResolverFunc->getName()));
SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
const TargetInfo &Target = getTarget();
unsigned Index = 0;
for (const IdentifierInfo *II : DD->cpus()) {
// Get the name of the target function so we can look it up/create it.
std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
getCPUSpecificMangling(*this, II->getName());
llvm::Constant *Func = GetGlobalValue(MangledName);
if (!Func) {
GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
if (ExistingDecl.getDecl() &&
ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
Func = GetGlobalValue(MangledName);
} else {
if (!ExistingDecl.getDecl())
ExistingDecl = GD.getWithMultiVersionIndex(Index);
Func = GetOrCreateLLVMFunction(
MangledName, DeclTy, ExistingDecl,
/*ForVTable=*/false, /*DontDefer=*/true,
/*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
}
}
llvm::SmallVector<StringRef, 32> Features;
Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
llvm::transform(Features, Features.begin(),
[](StringRef Str) { return Str.substr(1); });
llvm::erase_if(Features, [&Target](StringRef Feat) {
return !Target.validateCpuSupports(Feat);
});
Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
++Index;
}
llvm::stable_sort(
Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
const CodeGenFunction::MultiVersionResolverOption &RHS) {
return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
});
// If the list contains multiple 'default' versions, such as when it contains
// 'pentium' and 'generic', don't emit the call to the generic one (since we
// always run on at least a 'pentium'). We do this by deleting the 'least
// advanced' (read, lowest mangling letter).
while (Options.size() > 1 &&
llvm::X86::getCpuSupportsMask(
(Options.end() - 2)->Conditions.Features) == 0) {
StringRef LHSName = (Options.end() - 2)->Function->getName();
StringRef RHSName = (Options.end() - 1)->Function->getName();
if (LHSName.compare(RHSName) < 0)
Options.erase(Options.end() - 2);
else
Options.erase(Options.end() - 1);
}
CodeGenFunction CGF(*this);
CGF.EmitMultiVersionResolver(ResolverFunc, Options);
if (getTarget().supportsIFunc()) {
std::string AliasName = getMangledNameImpl(
*this, GD, FD, /*OmitMultiVersionMangling=*/true);
llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
if (!AliasFunc) {
auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
/*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
auto *GA = llvm::GlobalAlias::create(DeclTy, 0,
getMultiversionLinkage(*this, GD),
AliasName, IFunc, &getModule());
SetCommonAttributes(GD, GA);
}
}
}
/// If a dispatcher for the specified mangled name is not in the module, create
/// and return an llvm Function with the specified type.
llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
std::string MangledName =
getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
// Holds the name of the resolver, in ifunc mode this is the ifunc (which has
// a separate resolver).
std::string ResolverName = MangledName;
if (getTarget().supportsIFunc())
ResolverName += ".ifunc";
else if (FD->isTargetMultiVersion())
ResolverName += ".resolver";
// If this already exists, just return that one.
if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
return ResolverGV;
// Since this is the first time we've created this IFunc, make sure
// that we put this multiversioned function into the list to be
// replaced later if necessary (target multiversioning only).
if (FD->isTargetMultiVersion())
MultiVersionFuncs.push_back(GD);
else if (FD->isTargetClonesMultiVersion()) {
// In target_clones multiversioning, make sure we emit this if used.
auto DDI =
DeferredDecls.find(getMangledName(GD.getWithMultiVersionIndex(0)));
if (DDI != DeferredDecls.end()) {
addDeferredDeclToEmit(GD);
DeferredDecls.erase(DDI);
} else {
// Emit the symbol of the 1st variant, so that the deferred decls know we
// need it, otherwise the only global value will be the resolver/ifunc,
// which end up getting broken if we search for them with GetGlobalValue'.
GetOrCreateLLVMFunction(
getMangledName(GD.getWithMultiVersionIndex(0)), DeclTy, FD,
/*ForVTable=*/false, /*DontDefer=*/true,
/*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
}
}
if (getTarget().supportsIFunc()) {
llvm::Type *ResolverType = llvm::FunctionType::get(
llvm::PointerType::get(
DeclTy, getContext().getTargetAddressSpace(FD->getType())),
false);
llvm::Constant *Resolver = GetOrCreateLLVMFunction(
MangledName + ".resolver", ResolverType, GlobalDecl{},
/*ForVTable=*/false);
llvm::GlobalIFunc *GIF =
llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD),
"", Resolver, &getModule());
GIF->setName(ResolverName);
SetCommonAttributes(FD, GIF);
return GIF;
}
llvm::Constant *Resolver = GetOrCreateLLVMFunction(
ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
assert(isa<llvm::GlobalValue>(Resolver) &&
"Resolver should be created for the first time");
SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
return Resolver;
}
/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
/// module, create and return an llvm Function with the specified type. If there
/// is something in the module with the specified name, return it potentially
/// bitcasted to the right type.
///
/// If D is non-null, it specifies a decl that correspond to this. This is used
/// to set the attributes on the function when it is first created.
llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
ForDefinition_t IsForDefinition) {
const Decl *D = GD.getDecl();
// Any attempts to use a MultiVersion function should result in retrieving
// the iFunc instead. Name Mangling will handle the rest of the changes.
if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
// For the device mark the function as one that should be emitted.
if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
!OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
!DontDefer && !IsForDefinition) {
if (const FunctionDecl *FDDef = FD->getDefinition()) {
GlobalDecl GDDef;
if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
GDDef = GlobalDecl(CD, GD.getCtorType());
else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
GDDef = GlobalDecl(DD, GD.getDtorType());
else
GDDef = GlobalDecl(FDDef);
EmitGlobal(GDDef);
}
}
if (FD->isMultiVersion()) {
UpdateMultiVersionNames(GD, FD, MangledName);
if (!IsForDefinition)
return GetOrCreateMultiVersionResolver(GD, Ty, FD);
}
}
// Lookup the entry, lazily creating it if necessary.
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry) {
if (WeakRefReferences.erase(Entry)) {
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
if (FD && !FD->hasAttr<WeakAttr>())
Entry->setLinkage(llvm::Function::ExternalLinkage);
}
// Handle dropped DLL attributes.
if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
setDSOLocal(Entry);
}
// If there are two attempts to define the same mangled name, issue an
// error.
if (IsForDefinition && !Entry->isDeclaration()) {
GlobalDecl OtherGD;
// Check that GD is not yet in DiagnosedConflictingDefinitions is required
// to make sure that we issue an error only once.
if (lookupRepresentativeDecl(MangledName, OtherGD) &&
(GD.getCanonicalDecl().getDecl() !=
OtherGD.getCanonicalDecl().getDecl()) &&
DiagnosedConflictingDefinitions.insert(GD).second) {
getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
<< MangledName;
getDiags().Report(OtherGD.getDecl()->getLocation(),
diag::note_previous_definition);
}
}
if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
(Entry->getValueType() == Ty)) {
return Entry;
}
// Make sure the result is of the correct type.
// (If function is requested for a definition, we always need to create a new
// function, not just return a bitcast.)
if (!IsForDefinition)
return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
}
// This function doesn't have a complete type (for example, the return
// type is an incomplete struct). Use a fake type instead, and make
// sure not to try to set attributes.
bool IsIncompleteFunction = false;
llvm::FunctionType *FTy;
if (isa<llvm::FunctionType>(Ty)) {
FTy = cast<llvm::FunctionType>(Ty);
} else {
FTy = llvm::FunctionType::get(VoidTy, false);
IsIncompleteFunction = true;
}
llvm::Function *F =
llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
Entry ? StringRef() : MangledName, &getModule());
// If we already created a function with the same mangled name (but different
// type) before, take its name and add it to the list of functions to be
// replaced with F at the end of CodeGen.
//
// This happens if there is a prototype for a function (e.g. "int f()") and
// then a definition of a different type (e.g. "int f(int x)").
if (Entry) {
F->takeName(Entry);
// This might be an implementation of a function without a prototype, in
// which case, try to do special replacement of calls which match the new
// prototype. The really key thing here is that we also potentially drop
// arguments from the call site so as to make a direct call, which makes the
// inliner happier and suppresses a number of optimizer warnings (!) about
// dropping arguments.
if (!Entry->use_empty()) {
ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
Entry->removeDeadConstantUsers();
}
llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
F, Entry->getValueType()->getPointerTo());
addGlobalValReplacement(Entry, BC);
}
assert(F->getName() == MangledName && "name was uniqued!");
if (D)
SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
if (ExtraAttrs.hasFnAttrs()) {
llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
F->addFnAttrs(B);
}
if (!DontDefer) {
// All MSVC dtors other than the base dtor are linkonce_odr and delegate to
// each other bottoming out with the base dtor. Therefore we emit non-base
// dtors on usage, even if there is no dtor definition in the TU.
if (D && isa<CXXDestructorDecl>(D) &&
getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
GD.getDtorType()))
addDeferredDeclToEmit(GD);
// This is the first use or definition of a mangled name. If there is a
// deferred decl with this name, remember that we need to emit it at the end
// of the file.
auto DDI = DeferredDecls.find(MangledName);
if (DDI != DeferredDecls.end()) {
// Move the potentially referenced deferred decl to the
// DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
// don't need it anymore).
addDeferredDeclToEmit(DDI->second);
DeferredDecls.erase(DDI);
// Otherwise, there are cases we have to worry about where we're
// using a declaration for which we must emit a definition but where
// we might not find a top-level definition:
// - member functions defined inline in their classes
// - friend functions defined inline in some class
// - special member functions with implicit definitions
// If we ever change our AST traversal to walk into class methods,
// this will be unnecessary.
//
// We also don't emit a definition for a function if it's going to be an
// entry in a vtable, unless it's already marked as used.
} else if (getLangOpts().CPlusPlus && D) {
// Look for a declaration that's lexically in a record.
for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
FD = FD->getPreviousDecl()) {
if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
if (FD->doesThisDeclarationHaveABody()) {
addDeferredDeclToEmit(GD.getWithDecl(FD));
break;
}
}
}
}
}
// Make sure the result is of the requested type.
if (!IsIncompleteFunction) {
assert(F->getFunctionType() == Ty);
return F;
}
llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
return llvm::ConstantExpr::getBitCast(F, PTy);
}
/// GetAddrOfFunction - Return the address of the given function. If Ty is
/// non-null, then this function will use the specified type if it has to
/// create it (this occurs when we see a definition of the function).
llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
llvm::Type *Ty,
bool ForVTable,
bool DontDefer,
ForDefinition_t IsForDefinition) {
assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
"consteval function should never be emitted");
// If there was no specific requested type, just convert it now.
if (!Ty) {
const auto *FD = cast<FunctionDecl>(GD.getDecl());
Ty = getTypes().ConvertType(FD->getType());
}
// Devirtualized destructor calls may come through here instead of via
// getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
// of the complete destructor when necessary.
if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
if (getTarget().getCXXABI().isMicrosoft() &&
GD.getDtorType() == Dtor_Complete &&
DD->getParent()->getNumVBases() == 0)
GD = GlobalDecl(DD, Dtor_Base);
}
StringRef MangledName = getMangledName(GD);
auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
/*IsThunk=*/false, llvm::AttributeList(),
IsForDefinition);
// Returns kernel handle for HIP kernel stub function.
if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
auto *Handle = getCUDARuntime().getKernelHandle(
cast<llvm::Function>(F->stripPointerCasts()), GD);
if (IsForDefinition)
return F;
return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
}
return F;
}
llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
llvm::GlobalValue *F =
cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F),
llvm::Type::getInt8PtrTy(VMContext));
}
static const FunctionDecl *
GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
IdentifierInfo &CII = C.Idents.get(Name);
for (const auto *Result : DC->lookup(&CII))
if (const auto *FD = dyn_cast<FunctionDecl>(Result))
return FD;
if (!C.getLangOpts().CPlusPlus)
return nullptr;
// Demangle the premangled name from getTerminateFn()
IdentifierInfo &CXXII =
(Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
? C.Idents.get("terminate")
: C.Idents.get(Name);
for (const auto &N : {"__cxxabiv1", "std"}) {
IdentifierInfo &NS = C.Idents.get(N);
for (const auto *Result : DC->lookup(&NS)) {
const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
for (const auto *Result : LSD->lookup(&NS))
if ((ND = dyn_cast<NamespaceDecl>(Result)))
break;
if (ND)
for (const auto *Result : ND->lookup(&CXXII))
if (const auto *FD = dyn_cast<FunctionDecl>(Result))
return FD;
}
}
return nullptr;
}
/// CreateRuntimeFunction - Create a new runtime function with the specified
/// type and name.
llvm::FunctionCallee
CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
llvm::AttributeList ExtraAttrs, bool Local,
bool AssumeConvergent) {
if (AssumeConvergent) {
ExtraAttrs =
ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
}
llvm::Constant *C =
GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
/*DontDefer=*/false, /*IsThunk=*/false,
ExtraAttrs);
if (auto *F = dyn_cast<llvm::Function>(C)) {
if (F->empty()) {
F->setCallingConv(getRuntimeCC());
// In Windows Itanium environments, try to mark runtime functions
// dllimport. For Mingw and MSVC, don't. We don't really know if the user
// will link their standard library statically or dynamically. Marking
// functions imported when they are not imported can cause linker errors
// and warnings.
if (!Local && getTriple().isWindowsItaniumEnvironment() &&
!getCodeGenOpts().LTOVisibilityPublicStd) {
const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
if (!FD || FD->hasAttr<DLLImportAttr>()) {
F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
F->setLinkage(llvm::GlobalValue::ExternalLinkage);
}
}
setDSOLocal(F);
}
}
return {FTy, C};
}
/// isTypeConstant - Determine whether an object of this type can be emitted
/// as a constant.
///
/// If ExcludeCtor is true, the duration when the object's constructor runs
/// will not be considered. The caller will need to verify that the object is
/// not written to during its construction.
bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
if (!Ty.isConstant(Context) && !Ty->isReferenceType())
return false;
if (Context.getLangOpts().CPlusPlus) {
if (const CXXRecordDecl *Record
= Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
return ExcludeCtor && !Record->hasMutableFields() &&
Record->hasTrivialDestructor();
}
return true;
}
/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
/// create and return an llvm GlobalVariable with the specified type and address
/// space. If there is something in the module with the specified name, return
/// it potentially bitcasted to the right type.
///
/// If D is non-null, it specifies a decl that correspond to this. This is used
/// to set the attributes on the global when it is first created.
///
/// If IsForDefinition is true, it is guaranteed that an actual global with
/// type Ty will be returned, not conversion of a variable with the same
/// mangled name but some other type.
llvm::Constant *
CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
LangAS AddrSpace, const VarDecl *D,
ForDefinition_t IsForDefinition) {
// Lookup the entry, lazily creating it if necessary.
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
if (Entry) {
if (WeakRefReferences.erase(Entry)) {
if (D && !D->hasAttr<WeakAttr>())
Entry->setLinkage(llvm::Function::ExternalLinkage);
}
// Handle dropped DLL attributes.
if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
return Entry;
// If there are two attempts to define the same mangled name, issue an
// error.
if (IsForDefinition && !Entry->isDeclaration()) {
GlobalDecl OtherGD;
const VarDecl *OtherD;
// Check that D is not yet in DiagnosedConflictingDefinitions is required
// to make sure that we issue an error only once.
if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
(D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
(OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
OtherD->hasInit() &&
DiagnosedConflictingDefinitions.insert(D).second) {
getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
<< MangledName;
getDiags().Report(OtherGD.getDecl()->getLocation(),
diag::note_previous_definition);
}
}
// Make sure the result is of the correct type.
if (Entry->getType()->getAddressSpace() != TargetAS) {
return llvm::ConstantExpr::getAddrSpaceCast(Entry,
Ty->getPointerTo(TargetAS));
}
// (If global is requested for a definition, we always need to create a new
// global, not just return a bitcast.)
if (!IsForDefinition)
return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
}
auto DAddrSpace = GetGlobalVarAddressSpace(D);
auto *GV = new llvm::GlobalVariable(
getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
getContext().getTargetAddressSpace(DAddrSpace));
// If we already created a global with the same mangled name (but different
// type) before, take its name and remove it from its parent.
if (Entry) {
GV->takeName(Entry);
if (!Entry->use_empty()) {
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Entry->replaceAllUsesWith(NewPtrForOldDecl);
}
Entry->eraseFromParent();
}
// This is the first use or definition of a mangled name. If there is a
// deferred decl with this name, remember that we need to emit it at the end
// of the file.
auto DDI = DeferredDecls.find(MangledName);
if (DDI != DeferredDecls.end()) {
// Move the potentially referenced deferred decl to the DeferredDeclsToEmit
// list, and remove it from DeferredDecls (since we don't need it anymore).
addDeferredDeclToEmit(DDI->second);
DeferredDecls.erase(DDI);
}
// Handle things which are present even on external declarations.
if (D) {
if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
// FIXME: This code is overly simple and should be merged with other global
// handling.
GV->setConstant(isTypeConstant(D->getType(), false));
GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
setLinkageForGV(GV, D);
if (D->getTLSKind()) {
if (D->getTLSKind() == VarDecl::TLS_Dynamic)
CXXThreadLocals.push_back(D);
setTLSMode(GV, *D);
}
setGVProperties(GV, D);
// If required by the ABI, treat declarations of static data members with
// inline initializers as definitions.
if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
EmitGlobalVarDefinition(D);
}
// Emit section information for extern variables.
if (D->hasExternalStorage()) {
if (const SectionAttr *SA = D->getAttr<SectionAttr>())
GV->setSection(SA->getName());
}
// Handle XCore specific ABI requirements.
if (getTriple().getArch() == llvm::Triple::xcore &&
D->getLanguageLinkage() == CLanguageLinkage &&
D->getType().isConstant(Context) &&
isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
GV->setSection(".cp.rodata");
// Check if we a have a const declaration with an initializer, we may be
// able to emit it as available_externally to expose it's value to the
// optimizer.
if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
D->getType().isConstQualified() && !GV->hasInitializer() &&
!D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
const auto *Record =
Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
bool HasMutableFields = Record && Record->hasMutableFields();
if (!HasMutableFields) {
const VarDecl *InitDecl;
const Expr *InitExpr = D->getAnyInitializer(InitDecl);
if (InitExpr) {
ConstantEmitter emitter(*this);
llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
if (Init) {
auto *InitType = Init->getType();
if (GV->getValueType() != InitType) {
// The type of the initializer does not match the definition.
// This happens when an initializer has a different type from
// the type of the global (because of padding at the end of a
// structure for instance).
GV->setName(StringRef());
// Make a new global with the correct type, this is now guaranteed
// to work.
auto *NewGV = cast<llvm::GlobalVariable>(
GetAddrOfGlobalVar(D, InitType, IsForDefinition)
->stripPointerCasts());
// Erase the old global, since it is no longer used.
GV->eraseFromParent();
GV = NewGV;
} else {
GV->setInitializer(Init);
GV->setConstant(true);
GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
}
emitter.finalize(GV);
}
}
}
}
}
if (GV->isDeclaration()) {
getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
// External HIP managed variables needed to be recorded for transformation
// in both device and host compilations.
if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
D->hasExternalStorage())
getCUDARuntime().handleVarRegistration(D, *GV);
}
LangAS ExpectedAS =
D ? D->getType().getAddressSpace()
: (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
if (DAddrSpace != ExpectedAS) {
return getTargetCodeGenInfo().performAddrSpaceCast(
*this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
}
return GV;
}
llvm::Constant *
CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
const Decl *D = GD.getDecl();
if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
/*DontDefer=*/false, IsForDefinition);
if (isa<CXXMethodDecl>(D)) {
auto FInfo =
&getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
auto Ty = getTypes().GetFunctionType(*FInfo);
return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
IsForDefinition);
}
if (isa<FunctionDecl>(D)) {
const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
IsForDefinition);
}
return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
}
llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
unsigned Alignment) {
llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
llvm::GlobalVariable *OldGV = nullptr;
if (GV) {
// Check if the variable has the right type.
if (GV->getValueType() == Ty)
return GV;
// Because C++ name mangling, the only way we can end up with an already
// existing global with the same name is if it has been declared extern "C".
assert(GV->isDeclaration() && "Declaration has wrong type!");
OldGV = GV;
}
// Create a new variable.
GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Linkage, nullptr, Name);
if (OldGV) {
// Replace occurrences of the old variable if needed.
GV->takeName(OldGV);
if (!OldGV->use_empty()) {
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
OldGV->replaceAllUsesWith(NewPtrForOldDecl);
}
OldGV->eraseFromParent();
}
if (supportsCOMDAT() && GV->isWeakForLinker() &&
!GV->hasAvailableExternallyLinkage())
GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
GV->setAlignment(llvm::MaybeAlign(Alignment));
return GV;
}
/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
/// given global variable. If Ty is non-null and if the global doesn't exist,
/// then it will be created with the specified type instead of whatever the
/// normal requested type would be. If IsForDefinition is true, it is guaranteed
/// that an actual global with type Ty will be returned, not conversion of a
/// variable with the same mangled name but some other type.
llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
llvm::Type *Ty,
ForDefinition_t IsForDefinition) {
assert(D->hasGlobalStorage() && "Not a global variable");
QualType ASTTy = D->getType();
if (!Ty)
Ty = getTypes().ConvertTypeForMem(ASTTy);
StringRef MangledName = getMangledName(D);
return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
IsForDefinition);
}
/// CreateRuntimeVariable - Create a new runtime global variable with the
/// specified type and name.
llvm::Constant *
CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
StringRef Name) {
LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
: LangAS::Default;
auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
return Ret;
}
void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
assert(!D->getInit() && "Cannot emit definite definitions here!");
StringRef MangledName = getMangledName(D);
llvm::GlobalValue *GV = GetGlobalValue(MangledName);
// We already have a definition, not declaration, with the same mangled name.
// Emitting of declaration is not required (and actually overwrites emitted
// definition).
if (GV && !GV->isDeclaration())
return;
// If we have not seen a reference to this variable yet, place it into the
// deferred declarations table to be emitted if needed later.
if (!MustBeEmitted(D) && !GV) {
DeferredDecls[MangledName] = D;
return;
}
// The tentative definition is the only definition.
EmitGlobalVarDefinition(D);
}
void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
EmitExternalVarDeclaration(D);
}
CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
return Context.toCharUnitsFromBits(
getDataLayout().getTypeStoreSizeInBits(Ty));
}
LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
if (LangOpts.OpenCL) {
LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
assert(AS == LangAS::opencl_global ||
AS == LangAS::opencl_global_device ||
AS == LangAS::opencl_global_host ||
AS == LangAS::opencl_constant ||
AS == LangAS::opencl_local ||
AS >= LangAS::FirstTargetAddressSpace);
return AS;
}
if (LangOpts.SYCLIsDevice &&
(!D || D->getType().getAddressSpace() == LangAS::Default))
return LangAS::sycl_global;
if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
if (D && D->hasAttr<CUDAConstantAttr>())
return LangAS::cuda_constant;
else if (D && D->hasAttr<CUDASharedAttr>())
return LangAS::cuda_shared;
else if (D && D->hasAttr<CUDADeviceAttr>())
return LangAS::cuda_device;
else if (D && D->getType().isConstQualified())
return LangAS::cuda_constant;
else
return LangAS::cuda_device;
}
if (LangOpts.OpenMP) {
LangAS AS;
if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
return AS;
}
return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
}
LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
// OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
if (LangOpts.OpenCL)
return LangAS::opencl_constant;
if (LangOpts.SYCLIsDevice)
return LangAS::sycl_global;
if (auto AS = getTarget().getConstantAddressSpace())
return AS.getValue();
return LangAS::Default;
}
// In address space agnostic languages, string literals are in default address
// space in AST. However, certain targets (e.g. amdgcn) request them to be
// emitted in constant address space in LLVM IR. To be consistent with other
// parts of AST, string literal global variables in constant address space
// need to be casted to default address space before being put into address
// map and referenced by other part of CodeGen.
// In OpenCL, string literals are in constant address space in AST, therefore
// they should not be casted to default address space.
static llvm::Constant *
castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
llvm::GlobalVariable *GV) {
llvm::Constant *Cast = GV;
if (!CGM.getLangOpts().OpenCL) {
auto AS = CGM.GetGlobalConstantAddressSpace();
if (AS != LangAS::Default)
Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
CGM, GV, AS, LangAS::Default,
GV->getValueType()->getPointerTo(
CGM.getContext().getTargetAddressSpace(LangAS::Default)));
}
return Cast;
}
template<typename SomeDecl>
void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
llvm::GlobalValue *GV) {
if (!getLangOpts().CPlusPlus)
return;
// Must have 'used' attribute, or else inline assembly can't rely on
// the name existing.
if (!D->template hasAttr<UsedAttr>())
return;
// Must have internal linkage and an ordinary name.
if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
return;
// Must be in an extern "C" context. Entities declared directly within
// a record are not extern "C" even if the record is in such a context.
const SomeDecl *First = D->getFirstDecl();
if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
return;
// OK, this is an internal linkage entity inside an extern "C" linkage
// specification. Make a note of that so we can give it the "expected"
// mangled name if nothing else is using that name.
std::pair<StaticExternCMap::iterator, bool> R =
StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
// If we have multiple internal linkage entities with the same name
// in extern "C" regions, none of them gets that name.
if (!R.second)
R.first->second = nullptr;
}
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
if (!CGM.supportsCOMDAT())
return false;
if (D.hasAttr<SelectAnyAttr>())
return true;
GVALinkage Linkage;
if (auto *VD = dyn_cast<VarDecl>(&D))
Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
else
Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
switch (Linkage) {
case GVA_Internal:
case GVA_AvailableExternally:
case GVA_StrongExternal:
return false;
case GVA_DiscardableODR:
case GVA_StrongODR:
return true;
}
llvm_unreachable("No such linkage");
}
void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
llvm::GlobalObject &GO) {
if (!shouldBeInCOMDAT(*this, D))
return;
GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
}
/// Pass IsTentative as true if you want to create a tentative definition.
void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
bool IsTentative) {
// OpenCL global variables of sampler type are translated to function calls,
// therefore no need to be translated.
QualType ASTTy = D->getType();
if (getLangOpts().OpenCL && ASTTy->isSamplerT())
return;
// If this is OpenMP device, check if it is legal to emit this global
// normally.
if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
OpenMPRuntime->emitTargetGlobalVariable(D))
return;
llvm::TrackingVH<llvm::Constant> Init;
bool NeedsGlobalCtor = false;
bool NeedsGlobalDtor =
D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
const VarDecl *InitDecl;
const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Optional<ConstantEmitter> emitter;
// CUDA E.2.4.1 "__shared__ variables cannot have an initialization
// as part of their declaration." Sema has already checked for
// error cases, so we just need to set Init to UndefValue.
bool IsCUDASharedVar =
getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
// Shadows of initialized device-side global variables are also left
// undefined.
// Managed Variables should be initialized on both host side and device side.
bool IsCUDAShadowVar =
!getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
(D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
D->hasAttr<CUDASharedAttr>());
bool IsCUDADeviceShadowVar =
getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
(D->getType()->isCUDADeviceBuiltinSurfaceType() ||
D->getType()->isCUDADeviceBuiltinTextureType());
if (getLangOpts().CUDA &&
(IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
else if (D->hasAttr<LoaderUninitializedAttr>())
Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
else if (!InitExpr) {
// This is a tentative definition; tentative definitions are
// implicitly initialized with { 0 }.
//
// Note that tentative definitions are only emitted at the end of
// a translation unit, so they should never have incomplete
// type. In addition, EmitTentativeDefinition makes sure that we
// never attempt to emit a tentative definition if a real one
// exists. A use may still exists, however, so we still may need
// to do a RAUW.
assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Init = EmitNullConstant(D->getType());
} else {
initializedGlobalDecl = GlobalDecl(D);
emitter.emplace(*this);
llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
if (!Initializer) {
QualType T = InitExpr->getType();
if (D->getType()->isReferenceType())
T = D->getType();
if (getLangOpts().CPlusPlus) {
Init = EmitNullConstant(T);
NeedsGlobalCtor = true;
} else {
ErrorUnsupported(D, "static initializer");
Init = llvm::UndefValue::get(getTypes().ConvertType(T));
}
} else {
Init = Initializer;
// We don't need an initializer, so remove the entry for the delayed
// initializer position (just in case this entry was delayed) if we
// also don't need to register a destructor.
if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
DelayedCXXInitPosition.erase(D);
}
}
llvm::Type* InitType = Init->getType();
llvm::Constant *Entry =
GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
// Strip off pointer casts if we got them.
Entry = Entry->stripPointerCasts();
// Entry is now either a Function or GlobalVariable.
auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
// We have a definition after a declaration with the wrong type.
// We must make a new GlobalVariable* and update everything that used OldGV
// (a declaration or tentative definition) with the new GlobalVariable*
// (which will be a definition).
//
// This happens if there is a prototype for a global (e.g.
// "extern int x[];") and then a definition of a different type (e.g.
// "int x[10];"). This also happens when an initializer has a different type
// from the type of the global (this happens with unions).
if (!GV || GV->getValueType() != InitType ||
GV->getType()->getAddressSpace() !=
getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
// Move the old entry aside so that we'll create a new one.
Entry->setName(StringRef());
// Make a new global with the correct type, this is now guaranteed to work.
GV = cast<llvm::GlobalVariable>(
GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
->stripPointerCasts());
// Replace all uses of the old global with the new global
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
Entry->getType());
Entry->replaceAllUsesWith(NewPtrForOldDecl);
// Erase the old global, since it is no longer used.
cast<llvm::GlobalValue>(Entry)->eraseFromParent();
}
MaybeHandleStaticInExternC(D, GV);
if (D->hasAttr<AnnotateAttr>())
AddGlobalAnnotations(D, GV);
// Set the llvm linkage type as appropriate.
llvm::GlobalValue::LinkageTypes Linkage =
getLLVMLinkageVarDefinition(D, GV->isConstant());
// CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
// the device. [...]"
// CUDA B.2.2 "The __constant__ qualifier, optionally used together with
// __device__, declares a variable that: [...]
// Is accessible from all the threads within the grid and from the host
// through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
// / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
if (GV && LangOpts.CUDA) {
if (LangOpts.CUDAIsDevice) {
if (Linkage != llvm::GlobalValue::InternalLinkage &&
(D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
D->getType()->isCUDADeviceBuiltinSurfaceType() ||
D->getType()->isCUDADeviceBuiltinTextureType()))
GV->setExternallyInitialized(true);
} else {
getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
}
getCUDARuntime().handleVarRegistration(D, *GV);
}
GV->setInitializer(Init);
if (emitter)
emitter->finalize(GV);
// If it is safe to mark the global 'constant', do so now.
GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
isTypeConstant(D->getType(), true));
// If it is in a read-only section, mark it 'constant'.
if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
GV->setConstant(true);
}
GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
// On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
// function is only defined alongside the variable, not also alongside
// callers. Normally, all accesses to a thread_local go through the
// thread-wrapper in order to ensure initialization has occurred, underlying
// variable will never be used other than the thread-wrapper, so it can be
// converted to internal linkage.
//
// However, if the variable has the 'constinit' attribute, it _can_ be
// referenced directly, without calling the thread-wrapper, so the linkage
// must not be changed.
//
// Additionally, if the variable isn't plain external linkage, e.g. if it's
// weak or linkonce, the de-duplication semantics are important to preserve,
// so we don't change the linkage.
if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
Linkage == llvm::GlobalValue::ExternalLinkage &&
Context.getTargetInfo().getTriple().isOSDarwin() &&
!D->hasAttr<ConstInitAttr>())
Linkage = llvm::GlobalValue::InternalLinkage;
GV->setLinkage(Linkage);
if (D->hasAttr<DLLImportAttr>())
GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
else if (D->hasAttr<DLLExportAttr>())
GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
else
GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
if (Linkage == llvm::GlobalVariable::CommonLinkage) {
// common vars aren't constant even if declared const.
GV->setConstant(false);
// Tentative definition of global variables may be initialized with
// non-zero null pointers. In this case they should have weak linkage
// since common linkage must have zero initializer and must not have
// explicit section therefore cannot have non-zero initial value.
if (!GV->getInitializer()->isNullValue())
GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
}
setNonAliasAttributes(D, GV);
if (D->getTLSKind() && !GV->isThreadLocal()) {
if (D->getTLSKind() == VarDecl::TLS_Dynamic)
CXXThreadLocals.push_back(D);
setTLSMode(GV, *D);
}
maybeSetTrivialComdat(*D, *GV);
// Emit the initializer function if necessary.
if (NeedsGlobalCtor || NeedsGlobalDtor)
EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
// Emit global variable debug information.
if (CGDebugInfo *DI = getModuleDebugInfo())
if (getCodeGenOpts().hasReducedDebugInfo())
DI->EmitGlobalVariable(GV, D);
}
void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
if (CGDebugInfo *DI = getModuleDebugInfo())
if (getCodeGenOpts().hasReducedDebugInfo()) {
QualType ASTTy = D->getType();
llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
llvm::Constant *GV =
GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
DI->EmitExternalVariable(
cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
}
}
static bool isVarDeclStrongDefinition(const ASTContext &Context,
CodeGenModule &CGM, const VarDecl *D,
bool NoCommon) {
// Don't give variables common linkage if -fno-common was specified unless it
// was overridden by a NoCommon attribute.
if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
return true;
// C11 6.9.2/2:
// A declaration of an identifier for an object that has file scope without
// an initializer, and without a storage-class specifier or with the
// storage-class specifier static, constitutes a tentative definition.
if (D->getInit() || D->hasExternalStorage())
return true;
// A variable cannot be both common and exist in a section.
if (D->hasAttr<SectionAttr>())
return true;
// A variable cannot be both common and exist in a section.
// We don't try to determine which is the right section in the front-end.
// If no specialized section name is applicable, it will resort to default.
if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
D->hasAttr<PragmaClangDataSectionAttr>() ||
D->hasAttr<PragmaClangRelroSectionAttr>() ||
D->hasAttr<PragmaClangRodataSectionAttr>())
return true;
// Thread local vars aren't considered common linkage.
if (D->getTLSKind())
return true;
// Tentative definitions marked with WeakImportAttr are true definitions.
if (D->hasAttr<WeakImportAttr>())
return true;
// A variable cannot be both common and exist in a comdat.
if (shouldBeInCOMDAT(CGM, *D))
return true;
// Declarations with a required alignment do not have common linkage in MSVC
// mode.
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
if (D->hasAttr<AlignedAttr>())
return true;
QualType VarType = D->getType();
if (Context.isAlignmentRequired(VarType))
return true;
if (const auto *RT = VarType->getAs<RecordType>()) {
const RecordDecl *RD = RT->getDecl();
for (const FieldDecl *FD : RD->fields()) {
if (FD->isBitField())
continue;
if (FD->hasAttr<AlignedAttr>())
return true;
if (Context.isAlignmentRequired(FD->getType()))
return true;
}
}
}
// Microsoft's link.exe doesn't support alignments greater than 32 bytes for
// common symbols, so symbols with greater alignment requirements cannot be
// common.
// Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
// alignments for common symbols via the aligncomm directive, so this
// restriction only applies to MSVC environments.
if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
Context.getTypeAlignIfKnown(D->getType()) >
Context.toBits(CharUnits::fromQuantity(32)))
return true;
return false;
}
llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
if (Linkage == GVA_Internal)
return llvm::Function::InternalLinkage;
if (D->hasAttr<WeakAttr>()) {
if (IsConstantVariable)
return llvm::GlobalVariable::WeakODRLinkage;
else
return llvm::GlobalVariable::WeakAnyLinkage;
}
if (const auto *FD = D->getAsFunction())
if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
return llvm::GlobalVariable::LinkOnceAnyLinkage;
// We are guaranteed to have a strong definition somewhere else,
// so we can use available_externally linkage.
if (Linkage == GVA_AvailableExternally)
return llvm::GlobalValue::AvailableExternallyLinkage;
// Note that Apple's kernel linker doesn't support symbol
// coalescing, so we need to avoid linkonce and weak linkages there.
// Normally, this means we just map to internal, but for explicit
// instantiations we'll map to external.
// In C++, the compiler has to emit a definition in every translation unit
// that references the function. We should use linkonce_odr because
// a) if all references in this translation unit are optimized away, we
// don't need to codegen it. b) if the function persists, it needs to be
// merged with other definitions. c) C++ has the ODR, so we know the
// definition is dependable.
if (Linkage == GVA_DiscardableODR)
return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
: llvm::Function::InternalLinkage;
// An explicit instantiation of a template has weak linkage, since
// explicit instantiations can occur in multiple translation units
// and must all be equivalent. However, we are not allowed to
// throw away these explicit instantiations.
//
// CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
// so say that CUDA templates are either external (for kernels) or internal.
// This lets llvm perform aggressive inter-procedural optimizations. For
// -fgpu-rdc case, device function calls across multiple TU's are allowed,
// therefore we need to follow the normal linkage paradigm.
if (Linkage == GVA_StrongODR) {
if (getLangOpts().AppleKext)
return llvm::Function::ExternalLinkage;
if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
!getLangOpts().GPURelocatableDeviceCode)
return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
: llvm::Function::InternalLinkage;
return llvm::Function::WeakODRLinkage;
}
// C++ doesn't have tentative definitions and thus cannot have common
// linkage.
if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
!isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
CodeGenOpts.NoCommon))
return llvm::GlobalVariable::CommonLinkage;
// selectany symbols are externally visible, so use weak instead of
// linkonce. MSVC optimizes away references to const selectany globals, so
// all definitions should be the same and ODR linkage should be used.
// http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
if (D->hasAttr<SelectAnyAttr>())
return llvm::GlobalVariable::WeakODRLinkage;
// Otherwise, we have strong external linkage.
assert(Linkage == GVA_StrongExternal);
return llvm::GlobalVariable::ExternalLinkage;
}
llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
const VarDecl *VD, bool IsConstant) {
GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
}
/// Replace the uses of a function that was declared with a non-proto type.
/// We want to silently drop extra arguments from call sites
static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
llvm::Function *newFn) {
// Fast path.
if (old->use_empty()) return;
llvm::Type *newRetTy = newFn->getReturnType();
SmallVector<llvm::Value*, 4> newArgs;
for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
ui != ue; ) {
llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
llvm::User *user = use->getUser();
// Recognize and replace uses of bitcasts. Most calls to
// unprototyped functions will use bitcasts.
if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
if (bitcast->getOpcode() == llvm::Instruction::BitCast)
replaceUsesOfNonProtoConstant(bitcast, newFn);
continue;
}
// Recognize calls to the function.
llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
if (!callSite) continue;
if (!callSite->isCallee(&*use))
continue;
// If the return types don't match exactly, then we can't
// transform this call unless it's dead.
if (callSite->getType() != newRetTy && !callSite->use_empty())
continue;
// Get the call site's attribute list.
SmallVector<llvm::AttributeSet, 8> newArgAttrs;
llvm::AttributeList oldAttrs = callSite->getAttributes();
// If the function was passed too few arguments, don't transform.
unsigned newNumArgs = newFn->arg_size();
if (callSite->arg_size() < newNumArgs)
continue;
// If extra arguments were passed, we silently drop them.
// If any of the types mismatch, we don't transform.
unsigned argNo = 0;
bool dontTransform = false;
for (llvm::Argument &A : newFn->args()) {
if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
dontTransform = true;
break;
}
// Add any parameter attributes.
newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
argNo++;
}
if (dontTransform)
continue;
// Okay, we can transform this. Create the new call instruction and copy
// over the required information.
newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
// Copy over any operand bundles.
SmallVector<llvm::OperandBundleDef, 1> newBundles;
callSite->getOperandBundlesAsDefs(newBundles);
llvm::CallBase *newCall;
if (isa<llvm::CallInst>(callSite)) {
newCall =
llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
} else {
auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
oldInvoke->getUnwindDest(), newArgs,
newBundles, "", callSite);
}
newArgs.clear(); // for the next iteration
if (!newCall->getType()->isVoidTy())
newCall->takeName(callSite);
newCall->setAttributes(
llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
oldAttrs.getRetAttrs(), newArgAttrs));
newCall->setCallingConv(callSite->getCallingConv());
// Finally, remove the old call, replacing any uses with the new one.
if (!callSite->use_empty())
callSite->replaceAllUsesWith(newCall);
// Copy debug location attached to CI.
if (callSite->getDebugLoc())
newCall->setDebugLoc(callSite->getDebugLoc());
callSite->eraseFromParent();
}
}
/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
/// implement a function with no prototype, e.g. "int foo() {}". If there are
/// existing call uses of the old function in the module, this adjusts them to
/// call the new function directly.
///
/// This is not just a cleanup: the always_inline pass requires direct calls to
/// functions to be able to inline them. If there is a bitcast in the way, it
/// won't inline them. Instcombine normally deletes these calls, but it isn't
/// run at -O0.
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
llvm::Function *NewFn) {
// If we're redefining a global as a function, don't transform it.
if (!isa<llvm::Function>(Old)) return;
replaceUsesOfNonProtoConstant(Old, NewFn);
}
void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
auto DK = VD->isThisDeclarationADefinition();
if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
return;
TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
// If we have a definition, this might be a deferred decl. If the
// instantiation is explicit, make sure we emit it at the end.
if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
GetAddrOfGlobalVar(VD);
EmitTopLevelDecl(VD);
}
void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
llvm::GlobalValue *GV) {
const auto *D = cast<FunctionDecl>(GD.getDecl());
// Compute the function info and LLVM type.
const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
// Get or create the prototype for the function.
if (!GV || (GV->getValueType() != Ty))
GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
/*DontDefer=*/true,
ForDefinition));
// Already emitted.
if (!GV->isDeclaration())
return;
// We need to set linkage and visibility on the function before
// generating code for it because various parts of IR generation
// want to propagate this information down (e.g. to local static
// declarations).
auto *Fn = cast<llvm::Function>(GV);
setFunctionLinkage(GD, Fn);
// FIXME: this is redundant with part of setFunctionDefinitionAttributes
setGVProperties(Fn, GD);
MaybeHandleStaticInExternC(D, Fn);
maybeSetTrivialComdat(*D, *Fn);
// Set CodeGen attributes that represent floating point environment.
setLLVMFunctionFEnvAttributes(D, Fn);
CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
setNonAliasAttributes(GD, Fn);
SetLLVMFunctionAttributesForDefinition(D, Fn);
if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
AddGlobalCtor(Fn, CA->getPriority());
if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
AddGlobalDtor(Fn, DA->getPriority(), true);
if (D->hasAttr<AnnotateAttr>())
AddGlobalAnnotations(D, Fn);
}
void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
const auto *D = cast<ValueDecl>(GD.getDecl());
const AliasAttr *AA = D->getAttr<AliasAttr>();
assert(AA && "Not an alias?");
StringRef MangledName = getMangledName(GD);
if (AA->getAliasee() == MangledName) {
Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
return;
}
// If there is a definition in the module, then it wins over the alias.
// This is dubious, but allow it to be safe. Just ignore the alias.
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry && !Entry->isDeclaration())
return;
Aliases.push_back(GD);
llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
// Create a reference to the named value. This ensures that it is emitted
// if a deferred decl.
llvm::Constant *Aliasee;
llvm::GlobalValue::LinkageTypes LT;
if (isa<llvm::FunctionType>(DeclTy)) {
Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
/*ForVTable=*/false);
LT = getFunctionLinkage(GD);
} else {
Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
/*D=*/nullptr);
if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
else
LT = getFunctionLinkage(GD);
}
// Create the new alias itself, but don't set a name yet.
unsigned AS = Aliasee->getType()->getPointerAddressSpace();
auto *GA =
llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
if (Entry) {
if (GA->getAliasee() == Entry) {
Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
return;
}
assert(Entry->isDeclaration());
// If there is a declaration in the module, then we had an extern followed
// by the alias, as in:
// extern int test6();
// ...
// int test6() __attribute__((alias("test7")));
//
// Remove it and replace uses of it with the alias.
GA->takeName(Entry);
Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Entry->getType()));
Entry->eraseFromParent();
} else {
GA->setName(MangledName);
}
// Set attributes which are particular to an alias; this is a
// specialization of the attributes which may be set on a global
// variable/function.
if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
D->isWeakImported()) {
GA->setLinkage(llvm::Function::WeakAnyLinkage);
}
if (const auto *VD = dyn_cast<VarDecl>(D))
if (VD->getTLSKind())
setTLSMode(GA, *VD);
SetCommonAttributes(GD, GA);
}
void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
const auto *D = cast<ValueDecl>(GD.getDecl());
const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
assert(IFA && "Not an ifunc?");
StringRef MangledName = getMangledName(GD);
if (IFA->getResolver() == MangledName) {
Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
return;
}
// Report an error if some definition overrides ifunc.
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry && !Entry->isDeclaration()) {
GlobalDecl OtherGD;
if (lookupRepresentativeDecl(MangledName, OtherGD) &&
DiagnosedConflictingDefinitions.insert(GD).second) {
Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
<< MangledName;
Diags.Report(OtherGD.getDecl()->getLocation(),
diag::note_previous_definition);
}
return;
}
Aliases.push_back(GD);
llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
llvm::Constant *Resolver =
GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
/*ForVTable=*/false);
llvm::GlobalIFunc *GIF =
llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
"", Resolver, &getModule());
if (Entry) {
if (GIF->getResolver() == Entry) {
Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
return;
}
assert(Entry->isDeclaration());
// If there is a declaration in the module, then we had an extern followed
// by the ifunc, as in:
// extern int test();
// ...
// int test() __attribute__((ifunc("resolver")));
//
// Remove it and replace uses of it with the ifunc.
GIF->takeName(Entry);
Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
Entry->getType()));
Entry->eraseFromParent();
} else
GIF->setName(MangledName);
SetCommonAttributes(GD, GIF);
}
llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
ArrayRef<llvm::Type*> Tys) {
return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Tys);
}
static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
const StringLiteral *Literal, bool TargetIsLSB,
bool &IsUTF16, unsigned &StringLength) {
StringRef String = Literal->getString();
unsigned NumBytes = String.size();
// Check for simple case.
if (!Literal->containsNonAsciiOrNull()) {
StringLength = NumBytes;
return *Map.insert(std::make_pair(String, nullptr)).first;
}
// Otherwise, convert the UTF8 literals into a string of shorts.
IsUTF16 = true;
SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
llvm::UTF16 *ToPtr = &ToBuf[0];
(void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
ToPtr + NumBytes, llvm::strictConversion);
// ConvertUTF8toUTF16 returns the length in ToPtr.
StringLength = ToPtr - &ToBuf[0];
// Add an explicit null.
*ToPtr = 0;
return *Map.insert(std::make_pair(
StringRef(reinterpret_cast<const char *>(ToBuf.data()),
(StringLength + 1) * 2),
nullptr)).first;
}
ConstantAddress
CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
unsigned StringLength = 0;
bool isUTF16 = false;
llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
GetConstantCFStringEntry(CFConstantStringMap, Literal,
getDataLayout().isLittleEndian(), isUTF16,
StringLength);
if (auto *C = Entry.second)
return ConstantAddress(
C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
llvm::Constant *Zeros[] = { Zero, Zero };
const ASTContext &Context = getContext();
const llvm::Triple &Triple = getTriple();
const auto CFRuntime = getLangOpts().CFRuntime;
const bool IsSwiftABI =
static_cast<unsigned>(CFRuntime) >=
static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
// If we don't already have it, get __CFConstantStringClassReference.
if (!CFConstantStringClassRef) {
const char *CFConstantStringClassName = "__CFConstantStringClassReference";
llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Ty = llvm::ArrayType::get(Ty, 0);
switch (CFRuntime) {
default: break;
case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
case LangOptions::CoreFoundationABI::Swift5_0:
CFConstantStringClassName =
Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
: "$s10Foundation19_NSCFConstantStringCN";
Ty = IntPtrTy;
break;
case LangOptions::CoreFoundationABI::Swift4_2:
CFConstantStringClassName =
Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
: "$S10Foundation19_NSCFConstantStringCN";
Ty = IntPtrTy;
break;
case LangOptions::CoreFoundationABI::Swift4_1:
CFConstantStringClassName =
Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
: "__T010Foundation19_NSCFConstantStringCN";
Ty = IntPtrTy;
break;
}
llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
llvm::GlobalValue *GV = nullptr;
if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
IdentifierInfo &II = Context.Idents.get(GV->getName());
TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
const VarDecl *VD = nullptr;
for (const auto *Result : DC->lookup(&II))
if ((VD = dyn_cast<VarDecl>(Result)))
break;
if (Triple.isOSBinFormatELF()) {
if (!VD)
GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
} else {
GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
if (!VD || !VD->hasAttr<DLLExportAttr>())
GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
else
GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
}
setDSOLocal(GV);
}
}
// Decay array -> ptr
CFConstantStringClassRef =
IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
: llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
}
QualType CFTy = Context.getCFConstantStringType();
auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
ConstantInitBuilder Builder(*this);
auto Fields = Builder.beginStruct(STy);
// Class pointer.
Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
// Flags.
if (IsSwiftABI) {
Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
} else {
Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
}
// String pointer.
llvm::Constant *C = nullptr;
if (isUTF16) {
auto Arr = llvm::makeArrayRef(
reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
Entry.first().size() / 2);
C = llvm::ConstantDataArray::get(VMContext, Arr);
} else {
C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
}
// Note: -fwritable-strings doesn't make the backing store strings of
// CFStrings writable. (See <rdar://problem/10657500>)
auto *GV =
new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
llvm::GlobalValue::PrivateLinkage, C, ".str");
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
// Don't enforce the target's minimum global alignment, since the only use
// of the string is via this class initializer.
CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
: Context.getTypeAlignInChars(Context.CharTy);
GV->setAlignment(Align.getAsAlign());
// FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
// Without it LLVM can merge the string with a non unnamed_addr one during
// LTO. Doing that changes the section it ends in, which surprises ld64.
if (Triple.isOSBinFormatMachO())
GV->setSection(isUTF16 ? "__TEXT,__ustring"
: "__TEXT,__cstring,cstring_literals");
// Make sure the literal ends up in .rodata to allow for safe ICF and for
// the static linker to adjust permissions to read-only later on.
else if (Triple.isOSBinFormatELF())
GV->setSection(".rodata");
// String.
llvm::Constant *Str =
llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
if (isUTF16)
// Cast the UTF16 string to the correct type.
Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
Fields.add(Str);
// String length.
llvm::IntegerType *LengthTy =
llvm::IntegerType::get(getModule().getContext(),
Context.getTargetInfo().getLongWidth());
if (IsSwiftABI) {
if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
LengthTy = Int32Ty;
else
LengthTy = IntPtrTy;
}
Fields.addInt(LengthTy, StringLength);
// Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
// properly aligned on 32-bit platforms.
CharUnits Alignment =
IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
// The struct.
GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
/*isConstant=*/false,
llvm::GlobalVariable::PrivateLinkage);
GV->addAttribute("objc_arc_inert");
switch (Triple.getObjectFormat()) {
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("unknown file format");
case llvm::Triple::GOFF:
llvm_unreachable("GOFF is not yet implemented");
case llvm::Triple::XCOFF:
llvm_unreachable("XCOFF is not yet implemented");
case llvm::Triple::COFF:
case llvm::Triple::ELF:
case llvm::Triple::Wasm:
GV->setSection("cfstring");
break;
case llvm::Triple::MachO:
GV->setSection("__DATA,__cfstring");
break;
}
Entry.second = GV;
return ConstantAddress(GV, GV->getValueType(), Alignment);
}
bool CodeGenModule::getExpressionLocationsEnabled() const {
return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
}
QualType CodeGenModule::getObjCFastEnumerationStateType() {
if (ObjCFastEnumerationStateType.isNull()) {
RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
D->startDefinition();
QualType FieldTypes[] = {
Context.UnsignedLongTy,
Context.getPointerType(Context.getObjCIdType()),
Context.getPointerType(Context.UnsignedLongTy),
Context.getConstantArrayType(Context.UnsignedLongTy,
llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
};
for (size_t i = 0; i < 4; ++i) {
FieldDecl *Field = FieldDecl::Create(Context,
D,
SourceLocation(),
SourceLocation(), nullptr,
FieldTypes[i], /*TInfo=*/nullptr,
/*BitWidth=*/nullptr,
/*Mutable=*/false,
ICIS_NoInit);
Field->setAccess(AS_public);
D->addDecl(Field);
}
D->completeDefinition();
ObjCFastEnumerationStateType = Context.getTagDeclType(D);
}
return ObjCFastEnumerationStateType;
}
llvm::Constant *
CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
assert(!E->getType()->isPointerType() && "Strings are always arrays");
// Don't emit it as the address of the string, emit the string data itself
// as an inline array.
if (E->getCharByteWidth() == 1) {
SmallString<64> Str(E->getString());
// Resize the string to the right size, which is indicated by its type.
const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
Str.resize(CAT->getSize().getZExtValue());
return llvm::ConstantDataArray::getString(VMContext, Str, false);
}
auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
llvm::Type *ElemTy = AType->getElementType();
unsigned NumElements = AType->getNumElements();
// Wide strings have either 2-byte or 4-byte elements.
if (ElemTy->getPrimitiveSizeInBits() == 16) {
SmallVector<uint16_t, 32> Elements;
Elements.reserve(NumElements);
for(unsigned i = 0, e = E->getLength(); i != e; ++i)
Elements.push_back(E->getCodeUnit(i));
Elements.resize(NumElements);
return llvm::ConstantDataArray::get(VMContext, Elements);
}
assert(ElemTy->getPrimitiveSizeInBits() == 32);
SmallVector<uint32_t, 32> Elements;
Elements.reserve(NumElements);
for(unsigned i = 0, e = E->getLength(); i != e; ++i)
Elements.push_back(E->getCodeUnit(i));
Elements.resize(NumElements);
return llvm::ConstantDataArray::get(VMContext, Elements);
}
static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
CodeGenModule &CGM, StringRef GlobalName,
CharUnits Alignment) {
unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
CGM.GetGlobalConstantAddressSpace());
llvm::Module &M = CGM.getModule();
// Create a global variable for this string
auto *GV = new llvm::GlobalVariable(
M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
GV->setAlignment(Alignment.getAsAlign());
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
if (GV->isWeakForLinker()) {
assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
GV->setComdat(M.getOrInsertComdat(GV->getName()));
}
CGM.setDSOLocal(GV);
return GV;
}
/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
/// constant array for the given string literal.
ConstantAddress
CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
StringRef Name) {
CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
llvm::GlobalVariable **Entry = nullptr;
if (!LangOpts.WritableStrings) {
Entry = &ConstantStringMap[C];
if (auto GV = *Entry) {
if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
GV->setAlignment(Alignment.getAsAlign());
return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
GV->getValueType(), Alignment);
}
}
SmallString<256> MangledNameBuffer;
StringRef GlobalVariableName;
llvm::GlobalValue::LinkageTypes LT;
// Mangle the string literal if that's how the ABI merges duplicate strings.
// Don't do it if they are writable, since we don't want writes in one TU to
// affect strings in another.
if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
!LangOpts.WritableStrings) {
llvm::raw_svector_ostream Out(MangledNameBuffer);
getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
LT = llvm::GlobalValue::LinkOnceODRLinkage;
GlobalVariableName = MangledNameBuffer;
} else {
LT = llvm::GlobalValue::PrivateLinkage;
GlobalVariableName = Name;
}
auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
if (Entry)
*Entry = GV;
SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
QualType());
return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
GV->getValueType(), Alignment);
}
/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
/// array for the given ObjCEncodeExpr node.
ConstantAddress
CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
std::string Str;
getContext().getObjCEncodingForType(E->getEncodedType(), Str);
return GetAddrOfConstantCString(Str);
}
/// GetAddrOfConstantCString - Returns a pointer to a character array containing
/// the literal and a terminating '\0' character.
/// The result has pointer to array type.
ConstantAddress CodeGenModule::GetAddrOfConstantCString(
const std::string &Str, const char *GlobalName) {
StringRef StrWithNull(Str.c_str(), Str.size() + 1);
CharUnits Alignment =
getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
llvm::Constant *C =
llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
// Don't share any string literals if strings aren't constant.
llvm::GlobalVariable **Entry = nullptr;
if (!LangOpts.WritableStrings) {
Entry = &ConstantStringMap[C];
if (auto GV = *Entry) {
if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
GV->setAlignment(Alignment.getAsAlign());
return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
GV->getValueType(), Alignment);
}
}
// Get the default prefix if a name wasn't specified.
if (!GlobalName)
GlobalName = ".str";
// Create a global variable for this.
auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
GlobalName, Alignment);
if (Entry)
*Entry = GV;
return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
GV->getValueType(), Alignment);
}
ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
const MaterializeTemporaryExpr *E, const Expr *Init) {
assert((E->getStorageDuration() == SD_Static ||
E->getStorageDuration() == SD_Thread) && "not a global temporary");
const auto *VD = cast<VarDecl>(E->getExtendingDecl());
// If we're not materializing a subobject of the temporary, keep the
// cv-qualifiers from the type of the MaterializeTemporaryExpr.
QualType MaterializedType = Init->getType();
if (Init == E->getSubExpr())
MaterializedType = E->getType();
CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
if (!InsertResult.second) {
// We've seen this before: either we already created it or we're in the
// process of doing so.
if (!InsertResult.first->second) {
// We recursively re-entered this function, probably during emission of
// the initializer. Create a placeholder. We'll clean this up in the
// outer call, at the end of this function.
llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
InsertResult.first->second = new llvm::GlobalVariable(
getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
nullptr);
}
return ConstantAddress(
InsertResult.first->second,
InsertResult.first->second->getType()->getPointerElementType(), Align);
}
// FIXME: If an externally-visible declaration extends multiple temporaries,
// we need to give each temporary the same name in every translation unit (and
// we also need to make the temporaries externally-visible).
SmallString<256> Name;
llvm::raw_svector_ostream Out(Name);
getCXXABI().getMangleContext().mangleReferenceTemporary(
VD, E->getManglingNumber(), Out);
APValue *Value = nullptr;
if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
// If the initializer of the extending declaration is a constant
// initializer, we should have a cached constant initializer for this
// temporary. Note that this might have a different value from the value
// computed by evaluating the initializer if the surrounding constant
// expression modifies the temporary.
Value = E->getOrCreateValue(false);
}
// Try evaluating it now, it might have a constant initializer.
Expr::EvalResult EvalResult;
if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
!EvalResult.hasSideEffects())
Value = &EvalResult.Val;
LangAS AddrSpace =
VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
Optional<ConstantEmitter> emitter;
llvm::Constant *InitialValue = nullptr;
bool Constant = false;
llvm::Type *Type;
if (Value) {
// The temporary has a constant initializer, use it.
emitter.emplace(*this);
InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
MaterializedType);
Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
Type = InitialValue->getType();
} else {
// No initializer, the initialization will be provided when we
// initialize the declaration which performed lifetime extension.
Type = getTypes().ConvertTypeForMem(MaterializedType);
}
// Create a global variable for this lifetime-extended temporary.
llvm::GlobalValue::LinkageTypes Linkage =
getLLVMLinkageVarDefinition(VD, Constant);
if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
const VarDecl *InitVD;
if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
// Temporaries defined inside a class get linkonce_odr linkage because the
// class can be defined in multiple translation units.
Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
} else {
// There is no need for this temporary to have external linkage if the
// VarDecl has external linkage.
Linkage = llvm::GlobalVariable::InternalLinkage;
}
}
auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
auto *GV = new llvm::GlobalVariable(
getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
/*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
if (emitter) emitter->finalize(GV);
setGVProperties(GV, VD);
GV->setAlignment(Align.getAsAlign());
if (supportsCOMDAT() && GV->isWeakForLinker())
GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
if (VD->getTLSKind())
setTLSMode(GV, *VD);
llvm::Constant *CV = GV;
if (AddrSpace != LangAS::Default)
CV = getTargetCodeGenInfo().performAddrSpaceCast(
*this, GV, AddrSpace, LangAS::Default,
Type->getPointerTo(
getContext().getTargetAddressSpace(LangAS::Default)));
// Update the map with the new temporary. If we created a placeholder above,
// replace it with the new global now.
llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
if (Entry) {
Entry->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
}
Entry = CV;
return ConstantAddress(CV, Type, Align);
}
/// EmitObjCPropertyImplementations - Emit information for synthesized
/// properties for an implementation.
void CodeGenModule::EmitObjCPropertyImplementations(const
ObjCImplementationDecl *D) {
for (const auto *PID : D->property_impls()) {
// Dynamic is just for type-checking.
if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
ObjCPropertyDecl *PD = PID->getPropertyDecl();
// Determine which methods need to be implemented, some may have
// been overridden. Note that ::isPropertyAccessor is not the method
// we want, that just indicates if the decl came from a
// property. What we want to know is if the method is defined in
// this implementation.
auto *Getter = PID->getGetterMethodDecl();
if (!Getter || Getter->isSynthesizedAccessorStub())
CodeGenFunction(*this).GenerateObjCGetter(
const_cast<ObjCImplementationDecl *>(D), PID);
auto *Setter = PID->getSetterMethodDecl();
if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
CodeGenFunction(*this).GenerateObjCSetter(
const_cast<ObjCImplementationDecl *>(D), PID);
}
}
}
static bool needsDestructMethod(ObjCImplementationDecl *impl) {
const ObjCInterfaceDecl *iface = impl->getClassInterface();
for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
ivar; ivar = ivar->getNextIvar())
if (ivar->getType().isDestructedType())
return true;
return false;
}
static bool AllTrivialInitializers(CodeGenModule &CGM,
ObjCImplementationDecl *D) {
CodeGenFunction CGF(CGM);
for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
E = D->init_end(); B != E; ++B) {
CXXCtorInitializer *CtorInitExp = *B;
Expr *Init = CtorInitExp->getInit();
if (!CGF.isTrivialInitializer(Init))
return false;
}
return true;
}
/// EmitObjCIvarInitializations - Emit information for ivar initialization
/// for an implementation.
void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
// We might need a .cxx_destruct even if we don't have any ivar initializers.
if (needsDestructMethod(D)) {
IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
getContext(), D->getLocation(), D->getLocation(), cxxSelector,
getContext().VoidTy, nullptr, D,
/*isInstance=*/true, /*isVariadic=*/false,
/*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
/*isImplicitlyDeclared=*/true,
/*isDefined=*/false, ObjCMethodDecl::Required);
D->addInstanceMethod(DTORMethod);
CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
D->setHasDestructors(true);
}
// If the implementation doesn't have any ivar initializers, we don't need
// a .cxx_construct.
if (D->getNumIvarInitializers() == 0 ||
AllTrivialInitializers(*this, D))
return;
IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
// The constructor returns 'self'.
ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
getContext(), D->getLocation(), D->getLocation(), cxxSelector,
getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
/*isVariadic=*/false,
/*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
/*isImplicitlyDeclared=*/true,
/*isDefined=*/false, ObjCMethodDecl::Required);
D->addInstanceMethod(CTORMethod);
CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
D->setHasNonZeroConstructors(true);
}
// EmitLinkageSpec - Emit all declarations in a linkage spec.
void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
ErrorUnsupported(LSD, "linkage spec");
return;
}
EmitDeclContext(LSD);
}
void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
for (auto *I : DC->decls()) {
// Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
// are themselves considered "top-level", so EmitTopLevelDecl on an
// ObjCImplDecl does not recursively visit them. We need to do that in
// case they're nested inside another construct (LinkageSpecDecl /
// ExportDecl) that does stop them from being considered "top-level".
if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
for (auto *M : OID->methods())
EmitTopLevelDecl(M);
}
EmitTopLevelDecl(I);
}
}
/// EmitTopLevelDecl - Emit code for a single top level declaration.
void CodeGenModule::EmitTopLevelDecl(Decl *D) {
// Ignore dependent declarations.
if (D->isTemplated())
return;
// Consteval function shouldn't be emitted.
if (auto *FD = dyn_cast<FunctionDecl>(D))
if (FD->isConsteval())
return;
switch (D->getKind()) {
case Decl::CXXConversion:
case Decl::CXXMethod:
case Decl::Function:
EmitGlobal(cast<FunctionDecl>(D));
// Always provide some coverage mapping
// even for the functions that aren't emitted.
AddDeferredUnusedCoverageMapping(D);
break;
case Decl::CXXDeductionGuide:
// Function-like, but does not result in code emission.
break;
case Decl::Var:
case Decl::Decomposition:
case Decl::VarTemplateSpecialization:
EmitGlobal(cast<VarDecl>(D));
if (auto *DD = dyn_cast<DecompositionDecl>(D))
for (auto *B : DD->bindings())
if (auto *HD = B->getHoldingVar())
EmitGlobal(HD);
break;
// Indirect fields from global anonymous structs and unions can be
// ignored; only the actual variable requires IR gen support.
case Decl::IndirectField:
break;
// C++ Decls
case Decl::Namespace:
EmitDeclContext(cast<NamespaceDecl>(D));
break;
case Decl::ClassTemplateSpecialization: {
const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
if (CGDebugInfo *DI = getModuleDebugInfo())
if (Spec->getSpecializationKind() ==
TSK_ExplicitInstantiationDefinition &&
Spec->hasDefinition())
DI->completeTemplateDefinition(*Spec);
} LLVM_FALLTHROUGH;
case Decl::CXXRecord: {
CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
if (CGDebugInfo *DI = getModuleDebugInfo()) {
if (CRD->hasDefinition())
DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
if (auto *ES = D->getASTContext().getExternalSource())
if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
DI->completeUnusedClass(*CRD);
}
// Emit any static data members, they may be definitions.
for (auto *I : CRD->decls())
if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
EmitTopLevelDecl(I);
break;
}
// No code generation needed.
case Decl::UsingShadow:
case Decl::ClassTemplate:
case Decl::VarTemplate:
case Decl::Concept:
case Decl::VarTemplatePartialSpecialization:
case Decl::FunctionTemplate:
case Decl::TypeAliasTemplate:
case Decl::Block:
case Decl::Empty:
case Decl::Binding:
break;
case Decl::Using: // using X; [C++]
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitUsingDecl(cast<UsingDecl>(*D));
break;
case Decl::UsingEnum: // using enum X; [C++]
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
break;
case Decl::NamespaceAlias:
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
break;
case Decl::UsingDirective: // using namespace X; [C++]
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
break;
case Decl::CXXConstructor:
getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
break;
case Decl::CXXDestructor:
getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
break;
case Decl::StaticAssert:
// Nothing to do.
break;
// Objective-C Decls
// Forward declarations, no (immediate) code generation.
case Decl::ObjCInterface:
case Decl::ObjCCategory:
break;
case Decl::ObjCProtocol: {
auto *Proto = cast<ObjCProtocolDecl>(D);
if (Proto->isThisDeclarationADefinition())
ObjCRuntime->GenerateProtocol(Proto);
break;
}
case Decl::ObjCCategoryImpl:
// Categories have properties but don't support synthesize so we
// can ignore them here.
ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
break;
case Decl::ObjCImplementation: {
auto *OMD = cast<ObjCImplementationDecl>(D);
EmitObjCPropertyImplementations(OMD);
EmitObjCIvarInitializations(OMD);
ObjCRuntime->GenerateClass(OMD);
// Emit global variable debug information.
if (CGDebugInfo *DI = getModuleDebugInfo())
if (getCodeGenOpts().hasReducedDebugInfo())
DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
OMD->getClassInterface()), OMD->getLocation());
break;
}
case Decl::ObjCMethod: {
auto *OMD = cast<ObjCMethodDecl>(D);
// If this is not a prototype, emit the body.
if (OMD->getBody())
CodeGenFunction(*this).GenerateObjCMethod(OMD);
break;
}
case Decl::ObjCCompatibleAlias:
ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
break;
case Decl::PragmaComment: {
const auto *PCD = cast<PragmaCommentDecl>(D);
switch (PCD->getCommentKind()) {
case PCK_Unknown:
llvm_unreachable("unexpected pragma comment kind");
case PCK_Linker:
AppendLinkerOptions(PCD->getArg());
break;
case PCK_Lib:
AddDependentLib(PCD->getArg());
break;
case PCK_Compiler:
case PCK_ExeStr:
case PCK_User:
break; // We ignore all of these.
}
break;
}
case Decl::PragmaDetectMismatch: {
const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
AddDetectMismatch(PDMD->getName(), PDMD->getValue());
break;
}
case Decl::LinkageSpec:
EmitLinkageSpec(cast<LinkageSpecDecl>(D));
break;
case Decl::FileScopeAsm: {
// File-scope asm is ignored during device-side CUDA compilation.
if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
break;
// File-scope asm is ignored during device-side OpenMP compilation.
if (LangOpts.OpenMPIsDevice)
break;
// File-scope asm is ignored during device-side SYCL compilation.
if (LangOpts.SYCLIsDevice)
break;
auto *AD = cast<FileScopeAsmDecl>(D);
getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
break;
}
case Decl::Import: {
auto *Import = cast<ImportDecl>(D);
// If we've already imported this module, we're done.
if (!ImportedModules.insert(Import->getImportedModule()))
break;
// Emit debug information for direct imports.
if (!Import->getImportedOwningModule()) {
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitImportDecl(*Import);
}
// Find all of the submodules and emit the module initializers.
llvm::SmallPtrSet<clang::Module *, 16> Visited;
SmallVector<clang::Module *, 16> Stack;
Visited.insert(Import->getImportedModule());
Stack.push_back(Import->getImportedModule());
while (!Stack.empty()) {
clang::Module *Mod = Stack.pop_back_val();
if (!EmittedModuleInitializers.insert(Mod).second)
continue;
for (auto *D : Context.getModuleInitializers(Mod))
EmitTopLevelDecl(D);
// Visit the submodules of this module.
for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
SubEnd = Mod->submodule_end();
Sub != SubEnd; ++Sub) {
// Skip explicit children; they need to be explicitly imported to emit
// the initializers.
if ((*Sub)->IsExplicit)
continue;
if (Visited.insert(*Sub).second)
Stack.push_back(*Sub);
}
}
break;
}
case Decl::Export:
EmitDeclContext(cast<ExportDecl>(D));
break;
case Decl::OMPThreadPrivate:
EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
break;
case Decl::OMPAllocate:
EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
break;
case Decl::OMPDeclareReduction:
EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
break;
case Decl::OMPDeclareMapper:
EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
break;
case Decl::OMPRequires:
EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
break;
case Decl::Typedef:
case Decl::TypeAlias: // using foo = bar; [C++11]
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->EmitAndRetainType(
getContext().getTypedefType(cast<TypedefNameDecl>(D)));
break;
case Decl::Record:
if (CGDebugInfo *DI = getModuleDebugInfo())
if (cast<RecordDecl>(D)->getDefinition())
DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
break;
case Decl::Enum:
if (CGDebugInfo *DI = getModuleDebugInfo())
if (cast<EnumDecl>(D)->getDefinition())
DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
break;
default:
// Make sure we handled everything we should, every other kind is a
// non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
// function. Need to recode Decl::Kind to do that easily.
assert(isa<TypeDecl>(D) && "Unsupported decl kind");
break;
}
}
void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
// Do we need to generate coverage mapping?
if (!CodeGenOpts.CoverageMapping)
return;
switch (D->getKind()) {
case Decl::CXXConversion:
case Decl::CXXMethod:
case Decl::Function:
case Decl::ObjCMethod:
case Decl::CXXConstructor:
case Decl::CXXDestructor: {
if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
break;
SourceManager &SM = getContext().getSourceManager();
if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
break;
auto I = DeferredEmptyCoverageMappingDecls.find(D);
if (I == DeferredEmptyCoverageMappingDecls.end())
DeferredEmptyCoverageMappingDecls[D] = true;
break;
}
default:
break;
};
}
void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
// Do we need to generate coverage mapping?
if (!CodeGenOpts.CoverageMapping)
return;
if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
if (Fn->isTemplateInstantiation())
ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
}
auto I = DeferredEmptyCoverageMappingDecls.find(D);
if (I == DeferredEmptyCoverageMappingDecls.end())
DeferredEmptyCoverageMappingDecls[D] = false;
else
I->second = false;
}
void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
// We call takeVector() here to avoid use-after-free.
// FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
// we deserialize function bodies to emit coverage info for them, and that
// deserializes more declarations. How should we handle that case?
for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
if (!Entry.second)
continue;
const Decl *D = Entry.first;
switch (D->getKind()) {
case Decl::CXXConversion:
case Decl::CXXMethod:
case Decl::Function:
case Decl::ObjCMethod: {
CodeGenPGO PGO(*this);
GlobalDecl GD(cast<FunctionDecl>(D));
PGO.emitEmptyCounterMapping(D, getMangledName(GD),
getFunctionLinkage(GD));
break;
}
case Decl::CXXConstructor: {
CodeGenPGO PGO(*this);
GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
PGO.emitEmptyCounterMapping(D, getMangledName(GD),
getFunctionLinkage(GD));
break;
}
case Decl::CXXDestructor: {
CodeGenPGO PGO(*this);
GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
PGO.emitEmptyCounterMapping(D, getMangledName(GD),
getFunctionLinkage(GD));
break;
}
default:
break;
};
}
}
void CodeGenModule::EmitMainVoidAlias() {
// In order to transition away from "__original_main" gracefully, emit an
// alias for "main" in the no-argument case so that libc can detect when
// new-style no-argument main is in used.
if (llvm::Function *F = getModule().getFunction("main")) {
if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
}
}
/// Turns the given pointer into a constant.
static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
const void *Ptr) {
uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
return llvm::ConstantInt::get(i64, PtrInt);
}
static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
llvm::NamedMDNode *&GlobalMetadata,
GlobalDecl D,
llvm::GlobalValue *Addr) {
if (!GlobalMetadata)
GlobalMetadata =
CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
// TODO: should we report variant information for ctors/dtors?
llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
llvm::ConstantAsMetadata::get(GetPointerConstant(
CGM.getLLVMContext(), D.getDecl()))};
GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
}
/// For each function which is declared within an extern "C" region and marked
/// as 'used', but has internal linkage, create an alias from the unmangled
/// name to the mangled name if possible. People expect to be able to refer
/// to such functions with an unmangled name from inline assembly within the
/// same translation unit.
void CodeGenModule::EmitStaticExternCAliases() {
if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
return;
for (auto &I : StaticExternCValues) {
IdentifierInfo *Name = I.first;
llvm::GlobalValue *Val = I.second;
if (Val && !getModule().getNamedValue(Name->getName()))
addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
}
}
bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
GlobalDecl &Result) const {
auto Res = Manglings.find(MangledName);
if (Res == Manglings.end())
return false;
Result = Res->getValue();
return true;
}
/// Emits metadata nodes associating all the global values in the
/// current module with the Decls they came from. This is useful for
/// projects using IR gen as a subroutine.
///
/// Since there's currently no way to associate an MDNode directly
/// with an llvm::GlobalValue, we create a global named metadata
/// with the name 'clang.global.decl.ptrs'.
void CodeGenModule::EmitDeclMetadata() {
llvm::NamedMDNode *GlobalMetadata = nullptr;
for (auto &I : MangledDeclNames) {
llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
// Some mangled names don't necessarily have an associated GlobalValue
// in this module, e.g. if we mangled it for DebugInfo.
if (Addr)
EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
}
}
/// Emits metadata nodes for all the local variables in the current
/// function.
void CodeGenFunction::EmitDeclMetadata() {
if (LocalDeclMap.empty()) return;
llvm::LLVMContext &Context = getLLVMContext();
// Find the unique metadata ID for this name.
unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
llvm::NamedMDNode *GlobalMetadata = nullptr;
for (auto &I : LocalDeclMap) {
const Decl *D = I.first;
llvm::Value *Addr = I.second.getPointer();
if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Alloca->setMetadata(
DeclPtrKind, llvm::MDNode::get(
Context, llvm::ValueAsMetadata::getConstant(DAddr)));
} else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
}
}
}
void CodeGenModule::EmitVersionIdentMetadata() {
llvm::NamedMDNode *IdentMetadata =
TheModule.getOrInsertNamedMetadata("llvm.ident");
std::string Version = getClangFullVersion();
llvm::LLVMContext &Ctx = TheModule.getContext();
llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
}
void CodeGenModule::EmitCommandLineMetadata() {
llvm::NamedMDNode *CommandLineMetadata =
TheModule.getOrInsertNamedMetadata("llvm.commandline");
std::string CommandLine = getCodeGenOpts().RecordCommandLine;
llvm::LLVMContext &Ctx = TheModule.getContext();
llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
}
void CodeGenModule::EmitCoverageFile() {
if (getCodeGenOpts().CoverageDataFile.empty() &&
getCodeGenOpts().CoverageNotesFile.empty())
return;
llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
if (!CUNode)
return;
llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
llvm::LLVMContext &Ctx = TheModule.getContext();
auto *CoverageDataFile =
llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
auto *CoverageNotesFile =
llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
llvm::MDNode *CU = CUNode->getOperand(i);
llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
}
}
llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
bool ForEH) {
// Return a bogus pointer if RTTI is disabled, unless it's for EH.
// FIXME: should we even be calling this method if RTTI is disabled
// and it's not for EH?
if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
getTriple().isNVPTX()))
return llvm::Constant::getNullValue(Int8PtrTy);
if (ForEH && Ty->isObjCObjectPointerType() &&
LangOpts.ObjCRuntime.isGNUFamily())
return ObjCRuntime->GetEHType(Ty);
return getCXXABI().getAddrOfRTTIDescriptor(Ty);
}
void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
// Do not emit threadprivates in simd-only mode.
if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
return;
for (auto RefExpr : D->varlists()) {
auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
bool PerformInit =
VD->getAnyInitializer() &&
!VD->getAnyInitializer()->isConstantInitializer(getContext(),
/*ForRef=*/false);
Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
VD, Addr, RefExpr->getBeginLoc(), PerformInit))
CXXGlobalInits.push_back(InitFunction);
}
}
llvm::Metadata *
CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
StringRef Suffix) {
if (auto *FnType = T->getAs<FunctionProtoType>())
T = getContext().getFunctionType(
FnType->getReturnType(), FnType->getParamTypes(),
FnType->getExtProtoInfo().withExceptionSpec(EST_None));
llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
if (InternalId)
return InternalId;
if (isExternallyVisible(T->getLinkage())) {
std::string OutName;
llvm::raw_string_ostream Out(OutName);
getCXXABI().getMangleContext().mangleTypeName(T, Out);
Out << Suffix;
InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
} else {
InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
llvm::ArrayRef<llvm::Metadata *>());
}
return InternalId;
}
llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
}
llvm::Metadata *
CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
}
// Generalize pointer types to a void pointer with the qualifiers of the
// originally pointed-to type, e.g. 'const char *' and 'char * const *'
// generalize to 'const void *' while 'char *' and 'const char **' generalize to
// 'void *'.
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
if (!Ty->isPointerType())
return Ty;
return Ctx.getPointerType(
QualType(Ctx.VoidTy).withCVRQualifiers(
Ty->getPointeeType().getCVRQualifiers()));
}
// Apply type generalization to a FunctionType's return and argument types
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
SmallVector<QualType, 8> GeneralizedParams;
for (auto &Param : FnType->param_types())
GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
return Ctx.getFunctionType(
GeneralizeType(Ctx, FnType->getReturnType()),
GeneralizedParams, FnType->getExtProtoInfo());
}
if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
return Ctx.getFunctionNoProtoType(
GeneralizeType(Ctx, FnType->getReturnType()));
llvm_unreachable("Encountered unknown FunctionType");
}
llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
GeneralizedMetadataIdMap, ".generalized");
}
/// Returns whether this module needs the "all-vtables" type identifier.
bool CodeGenModule::NeedAllVtablesTypeId() const {
// Returns true if at least one of vtable-based CFI checkers is enabled and
// is not in the trapping mode.
return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
!CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
(LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
!CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
(LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
!CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
(LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
!CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
}
void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
CharUnits Offset,
const CXXRecordDecl *RD) {
llvm::Metadata *MD =
CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
VTable->addTypeMetadata(Offset.getQuantity(), MD);
if (CodeGenOpts.SanitizeCfiCrossDso)
if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
VTable->addTypeMetadata(Offset.getQuantity(),
llvm::ConstantAsMetadata::get(CrossDsoTypeId));
if (NeedAllVtablesTypeId()) {
llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
VTable->addTypeMetadata(Offset.getQuantity(), MD);
}
}
llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
if (!SanStats)
SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
return *SanStats;
}
llvm::Value *
CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
CodeGenFunction &CGF) {
llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
auto *Call = CGF.EmitRuntimeCall(
CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
return Call;
}
CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
/* forPointeeType= */ true);
}
CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
LValueBaseInfo *BaseInfo,
TBAAAccessInfo *TBAAInfo,
bool forPointeeType) {
if (TBAAInfo)
*TBAAInfo = getTBAAAccessInfo(T);
// FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
// that doesn't return the information we need to compute BaseInfo.
// Honor alignment typedef attributes even on incomplete types.
// We also honor them straight for C++ class types, even as pointees;
// there's an expressivity gap here.
if (auto TT = T->getAs<TypedefType>()) {
if (auto Align = TT->getDecl()->getMaxAlignment()) {
if (BaseInfo)
*BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
return getContext().toCharUnitsFromBits(Align);
}
}
bool AlignForArray = T->isArrayType();
// Analyze the base element type, so we don't get confused by incomplete
// array types.
T = getContext().getBaseElementType(T);
if (T->isIncompleteType()) {
// We could try to replicate the logic from
// ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
// type is incomplete, so it's impossible to test. We could try to reuse
// getTypeAlignIfKnown, but that doesn't return the information we need
// to set BaseInfo. So just ignore the possibility that the alignment is
// greater than one.
if (BaseInfo)
*BaseInfo = LValueBaseInfo(AlignmentSource::Type);
return CharUnits::One();
}
if (BaseInfo)
*BaseInfo = LValueBaseInfo(AlignmentSource::Type);
CharUnits Alignment;
const CXXRecordDecl *RD;
if (T.getQualifiers().hasUnaligned()) {
Alignment = CharUnits::One();
} else if (forPointeeType && !AlignForArray &&
(RD = T->getAsCXXRecordDecl())) {
// For C++ class pointees, we don't know whether we're pointing at a
// base or a complete object, so we generally need to use the
// non-virtual alignment.
Alignment = getClassPointerAlignment(RD);
} else {
Alignment = getContext().getTypeAlignInChars(T);
}
// Cap to the global maximum type alignment unless the alignment
// was somehow explicit on the type.
if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
if (Alignment.getQuantity() > MaxAlign &&
!getContext().isAlignmentRequired(T))
Alignment = CharUnits::fromQuantity(MaxAlign);
}
return Alignment;
}
bool CodeGenModule::stopAutoInit() {
unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
if (StopAfter) {
// This number is positive only when -ftrivial-auto-var-init-stop-after=* is
// used
if (NumAutoVarInit >= StopAfter) {
return true;
}
if (!NumAutoVarInit) {
unsigned DiagID = getDiags().getCustomDiagID(
DiagnosticsEngine::Warning,
"-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
"number of times ftrivial-auto-var-init=%1 gets applied.");
getDiags().Report(DiagID)
<< StopAfter
<< (getContext().getLangOpts().getTrivialAutoVarInit() ==
LangOptions::TrivialAutoVarInitKind::Zero
? "zero"
: "pattern");
}
++NumAutoVarInit;
}
return false;
}
void CodeGenModule::printPostfixForExternalizedStaticVar(
llvm::raw_ostream &OS) const {
OS << "__static__" << getContext().getCUIDHash();
}
|
\chapter{线性表}
这类题目考察线性表的操作,例如,数组,单链表,双向链表等。
\section{数组} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Remove Duplicates from Sorted Array}
\label{sec:remove-duplicates-from-sorted-array}
\subsubsection{描述}
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example, Given input array \code{A = [1,1,2]},
Your function should return length = 2, and A is now \code{[1,2]}.
\subsubsection{分析}
无
\subsubsection{代码1}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (n == 0) return 0;
int index = 0;
for (int i = 1; i < n; i++) {
if (A[index] != A[i])
A[++index] = A[i];
}
return index + 1;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array
// 使用STL,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(int A[], int n) {
return distance(A, unique(A, A + n));
}
};
\end{Code}
\subsubsection{代码3}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array
// 使用STL,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(int A[], int n) {
return removeDuplicates(A, A + n, A) - A;
}
template<typename InIt, typename OutIt>
OutIt removeDuplicates(InIt first, InIt last, OutIt output) {
while (first != last) {
*output++ = *first;
first = upper_bound(first, last, *first);
}
return output;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Remove Duplicates from Sorted Array II,见 \S \ref{sec:remove-duplicates-from-sorted-array-ii}
\myenddot
\subsection{Remove Duplicates from Sorted Array II}
\label{sec:remove-duplicates-from-sorted-array-ii}
\subsubsection{描述}
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array \code{A = [1,1,1,2,2,3]},
Your function should return length = 5, and A is now \code{[1,1,2,2,3]}
\subsubsection{分析}
加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解决。如果是没有排序的数组,则需要引入一个hashmap来记录出现次数。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array II
// 时间复杂度O(n),空间复杂度O(1)
// @author hex108 (https://github.com/hex108)
class Solution {
public:
int removeDuplicates(int A[], int n) {
if (n <= 2) return n;
int index = 2;
for (int i = 2; i < n; i++){
if (A[i] != A[index - 2])
A[index++] = A[i];
}
return index;
}
};
\end{Code}
\subsubsection{代码2}
下面是一个更简洁的版本。上面的代码略长,不过扩展性好一些,例如将\fn{occur < 2}改为\fn{occur < 3},就变成了允许重复最多3次。
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array II
// @author 虞航仲 (http://weibo.com/u/1666779725)
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(int A[], int n) {
int index = 0;
for (int i = 0; i < n; ++i) {
if (i > 0 && i < n - 1 && A[i] == A[i - 1] && A[i] == A[i + 1])
continue;
A[index++] = A[i];
}
return index;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Remove Duplicates from Sorted Array,见 \S \ref{sec:remove-duplicates-from-sorted-array}
\myenddot
\subsection{Search in Rotated Sorted Array}
\label{sec:search-in-rotated-sorted-array}
\subsubsection{描述}
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., \code{0 1 2 4 5 6 7} might become \code{4 5 6 7 0 1 2}).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
\subsubsection{分析}
二分查找,难度主要在于左右边界的确定。
\subsubsection{代码}
\begin{Code}
// LeetCode, Search in Rotated Sorted Array
// 时间复杂度O(log n),空间复杂度O(1)
class Solution {
public:
int search(int A[], int n, int target) {
int first = 0, last = n;
while (first != last) {
const int mid = first + (last - first) / 2;
if (A[mid] == target)
return mid;
if (A[first] <= A[mid]) {
if (A[first] <= target && target < A[mid])
last = mid;
else
first = mid + 1;
} else {
if (A[mid] < target && target <= A[last-1])
first = mid + 1;
else
last = mid;
}
}
return -1;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Search in Rotated Sorted Array II,见 \S \ref{sec:search-in-rotated-sorted-array-ii}
\myenddot
\subsection{Search in Rotated Sorted Array II}
\label{sec:search-in-rotated-sorted-array-ii}
\subsubsection{描述}
Follow up for "Search in Rotated Sorted Array": What if \emph{duplicates} are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
\subsubsection{分析}
允许重复元素,则上一题中如果\fn{A[m]>=A[l]},那么\fn{[l,m]}为递增序列的假设就不能成立了,比如\code{[1,3,1,1,1]}。
如果\fn{A[m]>=A[l]}不能确定递增,那就把它拆分成两个条件:
\begindot
\item 若\fn{A[m]>A[l]},则区间\fn{[l,m]}一定递增
\item 若\fn{A[m]==A[l]} 确定不了,那就\fn{l++},往下看一步即可。
\myenddot
\subsubsection{代码}
\begin{Code}
// LeetCode, Search in Rotated Sorted Array II
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
bool search(int A[], int n, int target) {
int first = 0, last = n;
while (first != last) {
const int mid = first + (last - first) / 2;
if (A[mid] == target)
return true;
if (A[first] < A[mid]) {
if (A[first] <= target && target < A[mid])
last = mid;
else
first = mid + 1;
} else if (A[first] > A[mid]) {
if (A[mid] < target && target <= A[last-1])
first = mid + 1;
else
last = mid;
} else
//skip duplicate one
first++;
}
return false;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Search in Rotated Sorted Array,见 \S \ref{sec:search-in-rotated-sorted-array}
\myenddot
\subsection{Median of Two Sorted Arrays}
\label{sec:median-of-two-sorted-arrays}
\subsubsection{描述}
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be $O(\log (m+n))$.
\subsubsection{分析}
这是一道非常经典的题。这题更通用的形式是,给定两个已经排序好的数组,找到两者所有元素中第$k$大的元素。
$O(m+n)$的解法比较直观,直接merge两个数组,然后求第$k$大的元素。
不过我们仅仅需要第$k$大的元素,是不需要“排序”这么复杂的操作的。可以用一个计数器,记录当前已经找到第$m$大的元素了。同时我们使用两个指针\fn{pA}和\fn{pB},分别指向A和B数组的第一个元素,使用类似于merge sort的原理,如果数组A当前元素小,那么\fn{pA++},同时\fn{m++};如果数组B当前元素小,那么\fn{pB++},同时\fn{m++}。最终当$m$等于$k$的时候,就得到了我们的答案,$O(k)$时间,$O(1)$空间。但是,当$k$很接近$m+n$的时候,这个方法还是$O(m+n)$的。
有没有更好的方案呢?我们可以考虑从$k$入手。如果我们每次都能够删除一个一定在第$k$大元素之前的元素,那么我们需要进行$k$次。但是如果每次我们都删除一半呢?由于A和B都是有序的,我们应该充分利用这里面的信息,类似于二分查找,也是充分利用了“有序”。
假设A和B的元素个数都大于$k/2$,我们将A的第$k/2$个元素(即\fn{A[k/2-1]})和B的第$k/2$个元素(即\fn{B[k/2-1]})进行比较,有以下三种情况(为了简化这里先假设$k$为偶数,所得到的结论对于$k$是奇数也是成立的):
\begindot
\item \fn{A[k/2-1] == B[k/2-1]}
\item \fn{A[k/2-1] > B[k/2-1]}
\item \fn{A[k/2-1] < B[k/2-1]}
\myenddot
如果\fn{A[k/2-1] < B[k/2-1]},意味着\fn{A[0]}到\fn{A[k/2-1}的肯定在$A \cup B$的top k元素的范围内,换句话说,\fn{A[k/2-1}不可能大于$A \cup B$的第$k$大元素。留给读者证明。
因此,我们可以放心的删除A数组的这$k/2$个元素。同理,当\fn{A[k/2-1] > B[k/2-1]}时,可以删除B数组的$k/2$个元素。
当\fn{A[k/2-1] == B[k/2-1]}时,说明找到了第$k$大的元素,直接返回\fn{A[k/2-1]}或\fn{B[k/2-1]}即可。
因此,我们可以写一个递归函数。那么函数什么时候应该终止呢?
\begindot
\item 当A或B是空时,直接返回\fn{B[k-1]}或\fn{A[k-1]};
\item 当\fn{k=1}是,返回\fn{min(A[0], B[0])};
\item 当\fn{A[k/2-1] == B[k/2-1]}时,返回\fn{A[k/2-1]}或\fn{B[k/2-1]}
\myenddot
\subsubsection{代码}
\begin{Code}
// LeetCode, Median of Two Sorted Arrays
// 时间复杂度O(log(m+n)),空间复杂度O(log(m+n))
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int total = m + n;
if (total & 0x1)
return find_kth(A, m, B, n, total / 2 + 1);
else
return (find_kth(A, m, B, n, total / 2)
+ find_kth(A, m, B, n, total / 2 + 1)) / 2.0;
}
private:
static int find_kth(int A[], int m, int B[], int n, int k) {
//always assume that m is equal or smaller than n
if (m > n) return find_kth(B, n, A, m, k);
if (m == 0) return B[k - 1];
if (k == 1) return min(A[0], B[0]);
//divide k into two parts
int ia = min(k / 2, m), ib = k - ia;
if (A[ia - 1] < B[ib - 1])
return find_kth(A + ia, m - ia, B, n, k - ia);
else if (A[ia - 1] > B[ib - 1])
return find_kth(A, m, B + ib, n - ib, k - ib);
else
return A[ia - 1];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Longest Consecutive Sequence} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:longest-consecutive-sequence}
\subsubsection{描述}
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given \code{[100, 4, 200, 1, 3, 2]},
The longest consecutive elements sequence is \code{[1, 2, 3, 4]}. Return its length: 4.
Your algorithm should run in $O(n)$ complexity.
\subsubsection{分析}
如果允许$O(n \log n)$的复杂度,那么可以先排序,可是本题要求$O(n)$。
由于序列里的元素是无序的,又要求$O(n)$,首先要想到用哈希表。
用一个哈希表 \fn{unordered_map<int, bool> used}记录每个元素是否使用,对每个元素,
以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。
\subsubsection{代码}
\begin{Code}
// Leet Code, Longest Consecutive Sequence
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int longestConsecutive(const vector<int> &num) {
unordered_map<int, bool> used;
for (auto i : num) used[i] = false;
int longest = 0;
for (auto i : num) {
if (used[i]) continue;
int length = 1;
used[i] = true;
for (int j = i + 1; used.find(j) != used.end(); ++j) {
used[j] = true;
++length;
}
for (int j = i - 1; used.find(j) != used.end(); --j) {
used[j] = true;
++length;
}
longest = max(longest, length);
}
return longest;
}
};
\end{Code}
\subsubsection{分析2}
第一直觉是个聚类的操作,应该有union,find的操作.连续序列可以用两端和长度来表示.
本来用两端就可以表示,但考虑到查询的需求,将两端分别暴露出来.用
\fn{unordered_map<int, int> map}来
存储.原始思路来自于\url{http://discuss.leetcode.com/questions/1070/longest-consecutive-sequence}
\subsubsection{代码}
\begin{Code}
// Leet Code, Longest Consecutive Sequence
// 时间复杂度O(n),空间复杂度O(n)
// Author: @advancedxy
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int, int> map;
int size = num.size();
int l = 1;
for (int i = 0; i < size; i++) {
if (map.find(num[i]) != map.end()) continue;
map[num[i]] = 1;
if (map.find(num[i] - 1) != map.end()) {
l = max(l, mergeCluster(map, num[i] - 1, num[i]));
}
if (map.find(num[i] + 1) != map.end()) {
l = max(l, mergeCluster(map, num[i], num[i] + 1));
}
}
return size == 0 ? 0 : l;
}
private:
int mergeCluster(unordered_map<int, int> &map, int left, int right) {
int upper = right + map[right] - 1;
int lower = left - map[left] + 1;
int length = upper - lower + 1;
map[upper] = length;
map[lower] = length;
return length;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Two Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:Two-sum}
\subsubsection{描述}
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: \code{numbers=\{2, 7, 11, 15\}, target=9}
Output: \code{index1=1, index2=2}
\subsubsection{分析}
方法1:暴力,复杂度$O(n^2)$,会超时
方法2:hash。用一个哈希表,存储每个数对应的下标,复杂度$O(n)$.
方法3:先排序,然后左右夹逼,排序$O(n\log n)$,左右夹逼$O(n)$,最终$O(n\log n)$。
但是注意,这题需要返回的是下标,而不是数字本身,因此这个方法行不通。
\subsubsection{代码}
\begin{Code}
//LeetCode, Two Sum
// 方法2:hash。用一个哈希表,存储每个数对应的下标
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<int> twoSum(vector<int> &num, int target) {
unordered_map<int, int> mapping;
vector<int> result;
for (int i = 0; i < num.size(); i++) {
mapping[num[i]] = i;
}
for (int i = 0; i < num.size(); i++) {
const int gap = target - num[i];
if (mapping.find(gap) != mapping.end() && mapping[gap] > i) {
result.push_back(i + 1);
result.push_back(mapping[gap] + 1);
break;
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 3Sum, 见 \S \ref{sec:3sum}
\item 3Sum Closest, 见 \S \ref{sec:3sum-closest}
\item 4Sum, 见 \S \ref{sec:4sum}
\myenddot
\subsection{3Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:3sum}
\subsubsection{描述}
Given an array $S$ of $n$ integers, are there elements $a, b, c$ in $S$ such that $a + b + c = 0$? Find all unique triplets in the array which gives the sum of zero.
Note:
\begindot
\item Elements in a triplet $(a,b,c)$ must be in non-descending order. (ie, $a \leq b \leq c$)
\item The solution set must not contain duplicate triplets.
\myenddot
For example, given array \code{S = \{-1 0 1 2 -1 -4\}}.
A solution set is:
\begin{Code}
(-1, 0, 1)
(-1, -1, 2)
\end{Code}
\subsubsection{分析}
先排序,然后左右夹逼,复杂度 $O(n^2)$。
这个方法可以推广到$k$-sum,先排序,然后做$k-2$次循环,在最内层循环左右夹逼,时间复杂度是 $O(\max\{n \log n, n^{k-1}\})$。
\subsubsection{代码}
\begin{Code}
// LeetCode, 3Sum
// 先排序,然后左右夹逼,注意跳过重复的数,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& num) {
vector<vector<int>> result;
if (num.size() < 3) return result;
sort(num.begin(), num.end());
const int target = 0;
auto last = num.end();
for (auto i = num.begin(); i < last-2; ++i) {
auto j = i+1;
if (i > num.begin() && *i == *(i-1)) continue;
auto k = last-1;
while (j < k) {
if (*i + *j + *k < target) {
++j;
while(*j == *(j - 1) && j < k) ++j;
} else if (*i + *j + *k > target) {
--k;
while(*k == *(k + 1) && j < k) --k;
} else {
result.push_back({ *i, *j, *k });
++j;
--k;
while(*j == *(j - 1) && *k == *(k + 1) && j < k) ++j;
}
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Two sum, 见 \S \ref{sec:Two-sum}
\item 3Sum Closest, 见 \S \ref{sec:3sum-closest}
\item 4Sum, 见 \S \ref{sec:4sum}
\myenddot
\subsection{3Sum Closest} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:3sum-closest}
\subsubsection{描述}
Given an array $S$ of $n$ integers, find three integers in $S$ such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array \code{S = \{-1 2 1 -4\}}, and \code{target = 1}.
The sum that is closest to the target is 2. (\code{-1 + 2 + 1 = 2}).
\subsubsection{分析}
先排序,然后左右夹逼,复杂度 $O(n^2)$。
\subsubsection{代码}
\begin{Code}
// LeetCode, 3Sum Closest
// 先排序,然后左右夹逼,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
int threeSumClosest(vector<int>& num, int target) {
int result = 0;
int min_gap = INT_MAX;
sort(num.begin(), num.end());
for (auto a = num.begin(); a != prev(num.end(), 2); ++a) {
auto b = next(a);
auto c = prev(num.end());
while (b < c) {
const int sum = *a + *b + *c;
const int gap = abs(sum - target);
if (gap < min_gap) {
result = sum;
min_gap = gap;
}
if (sum < target) ++b;
else --c;
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Two sum, 见 \S \ref{sec:Two-sum}
\item 3Sum, 见 \S \ref{sec:3sum}
\item 4Sum, 见 \S \ref{sec:4sum}
\myenddot
\subsection{4Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:4sum}
\subsubsection{描述}
Given an array $S$ of $n$ integers, are there elements $a, b, c$, and $d$ in $S$ such that $a + b + c + d = target$? Find all unique quadruplets in the array which gives the sum of target.
Note:
\begindot
\item Elements in a quadruplet $(a,b,c,d)$ must be in non-descending order. (ie, $a \leq b \leq c \leq d$)
\item The solution set must not contain duplicate quadruplets.
\myenddot
For example, given array \code{S = \{1 0 -1 0 -2 2\}}, and \code{target = 0}.
A solution set is:
\begin{Code}
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
\end{Code}
\subsubsection{分析}
先排序,然后左右夹逼,复杂度 $O(n^3)$,会超时。
可以用一个hashmap先缓存两个数的和,最终复杂度$O(n^3)$。这个策略也适用于 3Sum 。
\subsubsection{左右夹逼}
\begin{Code}
// LeetCode, 4Sum
// 先排序,然后左右夹逼,时间复杂度O(n^3),空间复杂度O(1)
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& num, int target) {
vector<vector<int>> result;
if (num.size() < 4) return result;
sort(num.begin(), num.end());
auto last = num.end();
for (auto a = num.begin(); a < prev(last, 3); ++a) {
for (auto b = next(a); b < prev(last, 2); ++b) {
auto c = next(b);
auto d = prev(last);
while (c < d) {
if (*a + *b + *c + *d < target) {
++c;
} else if (*a + *b + *c + *d > target) {
--d;
} else {
result.push_back({ *a, *b, *c, *d });
++c;
--d;
}
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
\end{Code}
\subsubsection{map做缓存}
\begin{Code}
// LeetCode, 4Sum
// 用一个hashmap先缓存两个数的和
// 时间复杂度,平均O(n^2),最坏O(n^4),空间复杂度O(n^2)
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int>> result;
if (num.size() < 4) return result;
sort(num.begin(), num.end());
unordered_map<int, vector<pair<int, int> > > cache;
for (size_t a = 0; a < num.size(); ++a) {
for (size_t b = a + 1; b < num.size(); ++b) {
cache[num[a] + num[b]].push_back(pair<int, int>(a, b));
}
}
for (int c = 0; c < num.size(); ++c) {
for (size_t d = c + 1; d < num.size(); ++d) {
const int key = target - num[c] - num[d];
if (cache.find(key) == cache.end()) continue;
const auto& vec = cache[key];
for (size_t k = 0; k < vec.size(); ++k) {
if (c <= vec[k].second)
continue; // 有重叠
result.push_back( { num[vec[k].first],
num[vec[k].second], num[c], num[d] });
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
\end{Code}
\subsubsection{multimap}
\begin{Code}
// LeetCode, 4Sum
// 用一个 hashmap 先缓存两个数的和
// 时间复杂度O(n^2),空间复杂度O(n^2)
// @author 龚陆安(http://weibo.com/luangong)
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& num, int target) {
vector<vector<int>> result;
if (num.size() < 4) return result;
sort(num.begin(), num.end());
unordered_multimap<int, pair<int, int>> cache;
for (int i = 0; i + 1 < num.size(); ++i)
for (int j = i + 1; j < num.size(); ++j)
cache.insert(make_pair(num[i] + num[j], make_pair(i, j)));
for (auto i = cache.begin(); i != cache.end(); ++i) {
int x = target - i->first;
auto range = cache.equal_range(x);
for (auto j = range.first; j != range.second; ++j) {
auto a = i->second.first;
auto b = i->second.second;
auto c = j->second.first;
auto d = j->second.second;
if (a != c && a != d && b != c && b != d) {
vector<int> vec = { num[a], num[b], num[c], num[d] };
sort(vec.begin(), vec.end());
result.push_back(vec);
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
\end{Code}
\subsubsection{方法4}
\begin{Code}
// LeetCode, 4Sum
// 先排序,然后左右夹逼,时间复杂度O(n^3logn),空间复杂度O(1),会超时
// 跟方法1相比,表面上优化了,实际上更慢了,切记!
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& num, int target) {
vector<vector<int>> result;
if (num.size() < 4) return result;
sort(num.begin(), num.end());
auto last = num.end();
for (auto a = num.begin(); a < prev(last, 3);
a = upper_bound(a, prev(last, 3), *a)) {
for (auto b = next(a); b < prev(last, 2);
b = upper_bound(b, prev(last, 2), *b)) {
auto c = next(b);
auto d = prev(last);
while (c < d) {
if (*a + *b + *c + *d < target) {
c = upper_bound(c, d, *c);
} else if (*a + *b + *c + *d > target) {
d = prev(lower_bound(c, d, *d));
} else {
result.push_back({ *a, *b, *c, *d });
c = upper_bound(c, d, *c);
d = prev(lower_bound(c, d, *d));
}
}
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Two sum, 见 \S \ref{sec:Two-sum}
\item 3Sum, 见 \S \ref{sec:3sum}
\item 3Sum Closest, 见 \S \ref{sec:3sum-closest}
\myenddot
\subsection{Remove Element} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:remove-element }
\subsubsection{描述}
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
\subsubsection{分析}
无
\subsubsection{代码1}
\begin{Code}
// LeetCode, Remove Element
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int index = 0;
for (int i = 0; i < n; ++i) {
if (A[i] != elem) {
A[index++] = A[i];
}
}
return index;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Remove Element
// 使用remove(),时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeElement(int A[], int n, int elem) {
return distance(A, remove(A, A+n, elem));
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Next Permutation} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:next-permutation}
\subsubsection{描述}
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
\begin{Code}
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
\end{Code}
\subsubsection{分析}
算法过程如图~\ref{fig:permutation}所示(来自\myurl{http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html})。
\begin{center}
\includegraphics[width=360pt]{next-permutation.png}\\
\figcaption{下一个排列算法流程}\label{fig:permutation}
\end{center}
\subsubsection{代码}
\begin{Code}
// LeetCode, Next Permutation
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
void nextPermutation(vector<int> &num) {
next_permutation(num.begin(), num.end());
}
template<typename BidiIt>
bool next_permutation(BidiIt first, BidiIt last) {
// Get a reversed range to simplify reversed traversal.
const auto rfirst = reverse_iterator<BidiIt>(last);
const auto rlast = reverse_iterator<BidiIt>(first);
// Begin from the second last element to the first element.
auto pivot = next(rfirst);
// Find `pivot`, which is the first element that is no less than its
// successor. `Prev` is used since `pivort` is a `reversed_iterator`.
while (pivot != rlast && *pivot >= *prev(pivot))
++pivot;
// No such elemenet found, current sequence is already the largest
// permutation, then rearrange to the first permutation and return false.
if (pivot == rlast) {
reverse(rfirst, rlast);
return false;
}
// Scan from right to left, find the first element that is greater than
// `pivot`.
auto change = find_if(rfirst, pivot, bind1st(less<int>(), *pivot));
swap(*change, *pivot);
reverse(rfirst, pivot);
return true;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Permutation Sequence, 见 \S \ref{sec:permutation-sequence}
\item Permutations, 见 \S \ref{sec:permutations}
\item Permutations II, 见 \S \ref{sec:permutations-ii}
\item Combinations, 见 \S \ref{sec:combinations}
\myenddot
\subsection{Permutation Sequence} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:permutation-sequence}
\subsubsection{描述}
The set \fn{[1,2,3,…,n]} contains a total of $n!$ unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for $n = 3$):
\begin{Code}
"123"
"132"
"213"
"231"
"312"
"321"
\end{Code}
Given $n$ and $k$, return the kth permutation sequence.
Note: Given $n$ will be between 1 and 9 inclusive.
\subsubsection{分析}
简单的,可以用暴力枚举法,调用 $k-1$ 次 \fn{next_permutation()}。
暴力枚举法把前 $k$个排列都求出来了,比较浪费,而我们只需要第$k$个排列。
利用康托编码的思路,假设有$n$个不重复的元素,第$k$个排列是$a_1, a_2, a_3, ..., a_n$,那么$a_1$是哪一个位置呢?
我们把$a_1$去掉,那么剩下的排列为
$a_2, a_3, ..., a_n$, 共计$n-1$个元素,$n-1$个元素共有$(n-1)!$个排列,于是就可以知道 $a_1 = k / (n-1)!$。
同理,$a_2, a_3, ..., a_n$的值推导如下:
\begin{eqnarray}
k_2 &=& k\%(n-1)! \nonumber \\
a_2 &=& k_2/(n-2)! \nonumber \\
\quad & \cdots \nonumber \\
k_{n-1} &=& k_{n-2}\%2! \nonumber \\
a_{n-1} &=& k_{n-1}/1! \nonumber \\
a_n &=& 0 \nonumber
\end{eqnarray}
\subsubsection{使用next_permutation()}
\begin{Code}
// LeetCode, Permutation Sequence
// 使用next_permutation(),TLE
class Solution {
public:
string getPermutation(int n, int k) {
string s(n, '0');
for (int i = 0; i < n; ++i)
s[i] += i+1;
for (int i = 0; i < k-1; ++i)
next_permutation(s.begin(), s.end());
return s;
}
template<typename BidiIt>
bool next_permutation(BidiIt first, BidiIt last) {
// 代码见上一题 Next Permutation
}
};
\end{Code}
\subsubsection{康托编码}
\begin{Code}
// LeetCode, Permutation Sequence
// 康托编码,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
string getPermutation(int n, int k) {
string s(n, '0');
string result;
for (int i = 0; i < n; ++i)
s[i] += i + 1;
return kth_permutation(s, k);
}
private:
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i)
result *= i;
return result;
}
// seq 已排好序,是第一个排列
template<typename Sequence>
Sequence kth_permutation(const Sequence &seq, int k) {
const int n = seq.size();
Sequence S(seq);
Sequence result;
int base = factorial(n - 1);
--k; // 康托编码从0开始
for (int i = n - 1; i > 0; k %= base, base /= i, --i) {
auto a = next(S.begin(), k / base);
result.push_back(*a);
S.erase(a);
}
result.push_back(S[0]); // 最后一个
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Next Permutation, 见 \S \ref{sec:next-permutation}
\item Permutations, 见 \S \ref{sec:permutations}
\item Permutations II, 见 \S \ref{sec:permutations-ii}
\item Combinations, 见 \S \ref{sec:combinations}
\myenddot
\subsection{Valid Sudoku} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:valid-sudoku}
\subsubsection{描述}
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules \myurl{http://sudoku.com.au/TheRules.aspx} .
The Sudoku board could be partially filled, where empty cells are filled with the character \fn{'.'}.
\begin{center}
\includegraphics[width=150pt]{sudoku.png}\\
\figcaption{A partially filled sudoku which is valid}\label{fig:sudoku}
\end{center}
\subsubsection{分析}
细节实现题。
\subsubsection{代码}
\begin{Code}
// LeetCode, Valid Sudoku
// 时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
bool isValidSudoku(const vector<vector<char>>& board) {
bool used[9];
for (int i = 0; i < 9; ++i) {
fill(used, used + 9, false);
for (int j = 0; j < 9; ++j) // 检查行
if (!check(board[i][j], used))
return false;
fill(used, used + 9, false);
for (int j = 0; j < 9; ++j) // 检查列
if (!check(board[j][i], used))
return false;
}
for (int r = 0; r < 3; ++r) // 检查 9 个子格子
for (int c = 0; c < 3; ++c) {
fill(used, used + 9, false);
for (int i = r * 3; i < r * 3 + 3; ++i)
for (int j = c * 3; j < c * 3 + 3; ++j)
if (!check(board[i][j], used))
return false;
}
return true;
}
bool check(char ch, bool used[9]) {
if (ch == '.') return true;
if (used[ch - '1']) return false;
return used[ch - '1'] = true;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Sudoku Solver, 见 \S \ref{sec:sudoku-solver}
\myenddot
\subsection{Trapping Rain Water} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:trapping-rain-water}
\subsubsection{描述}
Given $n$ non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given \code{[0,1,0,2,1,0,1,3,2,1,2,1]}, return 6.
\begin{center}
\includegraphics{trapping-rain-water.png}\\
\figcaption{Trapping Rain Water}\label{fig:trapping-rain-water}
\end{center}
\subsubsection{分析}
对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是\code{min(max_left, max_right) - height}。所以,
\begin{enumerate}
\item 从左往右扫描一遍,对于每个柱子,求取左边最大值;
\item 从右往左扫描一遍,对于每个柱子,求最大右值;
\item 再扫描一遍,把每个柱子的面积并累加。
\end{enumerate}
也可以,
\begin{enumerate}
\item 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;
\item 处理左边一半;
\item 处理右边一半。
\end{enumerate}
\subsubsection{代码1}
\begin{Code}
// LeetCode, Trapping Rain Water
// 思路1,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int trap(int A[], int n) {
int *max_left = new int[n]();
int *max_right = new int[n]();
for (int i = 1; i < n; i++) {
max_left[i] = max(max_left[i - 1], A[i - 1]);
max_right[n - 1 - i] = max(max_right[n - i], A[n - i]);
}
int sum = 0;
for (int i = 0; i < n; i++) {
int height = min(max_left[i], max_right[i]);
if (height > A[i]) {
sum += height - A[i];
}
}
delete[] max_left;
delete[] max_right;
return sum;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Trapping Rain Water
// 思路2,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int trap(int A[], int n) {
int max = 0; // 最高的柱子,将数组分为两半
for (int i = 0; i < n; i++)
if (A[i] > A[max]) max = i;
int water = 0;
for (int i = 0, peak = 0; i < max; i++)
if (A[i] > peak) peak = A[i];
else water += peak - A[i];
for (int i = n - 1, top = 0; i > max; i--)
if (A[i] > top) top = A[i];
else water += top - A[i];
return water;
}
};
\end{Code}
\subsubsection{代码3}
第三种解法,用一个栈辅助,小于栈顶的元素压入,大于等于栈顶就把栈里所有小于或等于当前值的元素全部出栈处理掉。
\begin{Code}
// LeetCode, Trapping Rain Water
// 用一个栈辅助,小于栈顶的元素压入,大于等于栈顶就把栈里所有小于或
// 等于当前值的元素全部出栈处理掉,计算面积,最后把当前元素入栈
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int trap(int a[], int n) {
stack<pair<int, int>> s;
int water = 0;
for (int i = 0; i < n; ++i) {
int height = 0;
while (!s.empty()) { // 将栈里比当前元素矮或等高的元素全部处理掉
int bar = s.top().first;
int pos = s.top().second;
// bar, height, a[i] 三者夹成的凹陷
water += (min(bar, a[i]) - height) * (i - pos - 1);
height = bar;
if (a[i] < bar) // 碰到了比当前元素高的,跳出循环
break;
else
s.pop(); // 弹出栈顶,因为该元素处理完了,不再需要了
}
s.push(make_pair(a[i], i));
}
return water;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Container With Most Water, 见 \S \ref{sec:container-with-most-water}
\item Largest Rectangle in Histogram, 见 \S \ref{sec:largest-rectangle-in-histogram}
\myenddot
\subsection{Rotate Image} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:rotate-image}
\subsubsection{描述}
You are given an $n \times n$ 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
\subsubsection{分析}
首先想到,纯模拟,从外到内一圈一圈的转,但这个方法太慢。
如下图,首先沿着副对角线翻转一次,然后沿着水平中线翻转一次。
\begin{center}
\includegraphics[width=200pt]{rotate-image.png}\\
\figcaption{Rotate Image}\label{fig:rotate-image}
\end{center}
或者,首先沿着水平中线翻转一次,然后沿着主对角线翻转一次。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Rotate Image
// 思路 1,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
const int n = matrix.size();
for (int i = 0; i < n; ++i) // 沿着副对角线反转
for (int j = 0; j < n - i; ++j)
swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]);
for (int i = 0; i < n / 2; ++i) // 沿着水平中线反转
for (int j = 0; j < n; ++j)
swap(matrix[i][j], matrix[n - 1 - i][j]);
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Rotate Image
// 思路 2,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
const int n = matrix.size();
for (int i = 0; i < n / 2; ++i) // 沿着水平中线反转
for (int j = 0; j < n; ++j)
swap(matrix[i][j], matrix[n - 1 - i][j]);
for (int i = 0; i < n; ++i) // 沿着主对角线反转
for (int j = i + 1; j < n; ++j)
swap(matrix[i][j], matrix[j][i]);
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Plus One} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:plus-one}
\subsubsection{描述}
Given a number represented as an array of digits, plus one to the number.
\subsubsection{分析}
高精度加法。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Plus One
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
add(digits, 1);
return digits;
}
private:
// 0 <= digit <= 9
void add(vector<int> &digits, int digit) {
int c = digit; // carry, 进位
for (auto it = digits.rbegin(); it != digits.rend(); ++it) {
*it += c;
c = *it / 10;
*it %= 10;
}
if (c > 0) digits.insert(digits.begin(), 1);
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Plus One
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
add(digits, 1);
return digits;
}
private:
// 0 <= digit <= 9
void add(vector<int> &digits, int digit) {
int c = digit; // carry, 进位
for_each(digits.rbegin(), digits.rend(), [&c](int &d){
d += c;
c = d / 10;
d %= 10;
});
if (c > 0) digits.insert(digits.begin(), 1);
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Climbing Stairs} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:climbing-stairs}
\subsubsection{描述}
You are climbing a stair case. It takes $n$ steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
\subsubsection{分析}
设$f(n)$表示爬$n$阶楼梯的不同方法数,为了爬到第$n$阶楼梯,有两个选择:
\begindot
\item 从第$n-1$阶前进1步;
\item 从第$n-1$阶前进2步;
\myenddot
因此,有$f(n)=f(n-1)+f(n-2)$。
这是一个斐波那契数列。
方法1,递归,太慢;方法2,迭代。
方法3,数学公式。斐波那契数列的通项公式为 $a_n=\dfrac{1}{\sqrt{5}}\left[\left(\dfrac{1+\sqrt{5}}{2}\right)^n-\left(\dfrac{1-\sqrt{5}}{2}\right)^n\right]$。
\subsubsection{迭代}
\begin{Code}
// LeetCode, Climbing Stairs
// 迭代,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int climbStairs(int n) {
int prev = 0;
int cur = 1;
for(int i = 1; i <= n ; ++i){
int tmp = cur;
cur += prev;
prev = tmp;
}
return cur;
}
};
\end{Code}
\subsubsection{数学公式}
\begin{Code}
// LeetCode, Climbing Stairs
// 数学公式,时间复杂度O(1),空间复杂度O(1)
class Solution {
public:
int climbStairs(int n) {
const double s = sqrt(5);
return floor((pow((1+s)/2, n+1) + pow((1-s)/2, n+1))/s + 0.5);
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Decode Ways, 见 \S \ref{sec:decode-ways}
\myenddot
\subsection{Gray Code} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:gray-code}
\subsubsection{描述}
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer $n$ representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given $n = 2$, return \fn{[0,1,3,2]}. Its gray code sequence is:
\begin{Code}
00 - 0
01 - 1
11 - 3
10 - 2
\end{Code}
Note:
\begindot
\item For a given $n$, a gray code sequence is not uniquely defined.
\item For example, \fn{[0,2,3,1]} is also a valid gray code sequence according to the above definition.
\item For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
\myenddot
\subsubsection{分析}
格雷码(Gray Code)的定义请参考 \myurl{http://en.wikipedia.org/wiki/Gray_code}
\textbf{自然二进制码转换为格雷码:$g_0=b_0, g_i=b_i \oplus b_{i-1}$}
保留自然二进制码的最高位作为格雷码的最高位,格雷码次高位为二进制码的高位与次高位异或,其余各位与次高位的求法类似。例如,将自然二进制码1001,转换为格雷码的过程是:保留最高位;然后将第1位的1和第2位的0异或,得到1,作为格雷码的第2位;将第2位的0和第3位的0异或,得到0,作为格雷码的第3位;将第3位的0和第4位的1异或,得到1,作为格雷码的第4位,最终,格雷码为1101。
\textbf{格雷码转换为自然二进制码:$b_0=g_0, b_i=g_i \oplus b_{i-1}$}
保留格雷码的最高位作为自然二进制码的最高位,次高位为自然二进制高位与格雷码次高位异或,其余各位与次高位的求法类似。例如,将格雷码1000转换为自然二进制码的过程是:保留最高位1,作为自然二进制码的最高位;然后将自然二进制码的第1位1和格雷码的第2位0异或,得到1,作为自然二进制码的第2位;将自然二进制码的第2位1和格雷码的第3位0异或,得到1,作为自然二进制码的第3位;将自然二进制码的第3位1和格雷码的第4位0异或,得到1,作为自然二进制码的第4位,最终,自然二进制码为1111。
格雷码有\textbf{数学公式},整数$n$的格雷码是$n \oplus (n/2)$。
这题要求生成$n$比特的所有格雷码。
方法1,最简单的方法,利用数学公式,对从 $0\sim2^n-1$的所有整数,转化为格雷码。
方法2,$n$比特的格雷码,可以递归地从$n-1$比特的格雷码生成。如图\S \ref{fig:gray-code-construction}所示。
\begin{center}
\includegraphics[width=160pt]{gray-code-construction.png}\\
\figcaption{The first few steps of the reflect-and-prefix method.}\label{fig:gray-code-construction}
\end{center}
\subsubsection{数学公式}
\begin{Code}
// LeetCode, Gray Code
// 数学公式,时间复杂度O(2^n),空间复杂度O(1)
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result;
const size_t size = 1 << n; // 2^n
result.reserve(size);
for (size_t i = 0; i < size; ++i)
result.push_back(binary_to_gray(i));
return result;
}
private:
static unsigned int binary_to_gray(unsigned int n) {
return n ^ (n >> 1);
}
};
\end{Code}
\subsubsection{Reflect-and-prefix method}
\begin{Code}
// LeetCode, Gray Code
// reflect-and-prefix method
// 时间复杂度O(2^n),空间复杂度O(1)
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result;
result.reserve(1<<n);
result.push_back(0);
for (int i = 0; i < n; i++) {
const int highest_bit = 1 << i;
for (int j = result.size() - 1; j >= 0; j--) // 要反着遍历,才能对称
result.push_back(highest_bit | result[j]);
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Set Matrix Zeroes} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:set-matrix-zeroes}
\subsubsection{描述}
Given a $m \times n$ matrix, if an element is 0, set its entire row and column to 0. Do it in place.
\textbf{Follow up:}
Did you use extra space?
A straight forward solution using $O(mn)$ space is probably a bad idea.
A simple improvement uses $O(m + n)$ space, but still not the best solution.
Could you devise a constant space solution?
\subsubsection{分析}
$O(m+n)$空间的方法很简单,设置两个bool数组,记录每行和每列是否存在0。
想要常数空间,可以复用第一行和第一列。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Set Matrix Zeroes
// 时间复杂度O(m*n),空间复杂度O(m+n)
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
const size_t m = matrix.size();
const size_t n = matrix[0].size();
vector<bool> row(m, false); // 标记该行是否存在0
vector<bool> col(n, false); // 标记该列是否存在0
for (size_t i = 0; i < m; ++i) {
for (size_t j = 0; j < n; ++j) {
if (matrix[i][j] == 0) {
row[i] = col[j] = true;
}
}
}
for (size_t i = 0; i < m; ++i) {
if (row[i])
fill(&matrix[i][0], &matrix[i][0] + n, 0);
}
for (size_t j = 0; j < n; ++j) {
if (col[j]) {
for (size_t i = 0; i < m; ++i) {
matrix[i][j] = 0;
}
}
}
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Set Matrix Zeroes
// 时间复杂度O(m*n),空间复杂度O(1)
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
const size_t m = matrix.size();
const size_t n = matrix[0].size();
bool row_has_zero = false; // 第一行是否存在 0
bool col_has_zero = false; // 第一列是否存在 0
for (size_t i = 0; i < n; i++)
if (matrix[0][i] == 0) {
row_has_zero = true;
break;
}
for (size_t i = 0; i < m; i++)
if (matrix[i][0] == 0) {
col_has_zero = true;
break;
}
for (size_t i = 1; i < m; i++)
for (size_t j = 1; j < n; j++)
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
for (size_t i = 1; i < m; i++)
for (size_t j = 1; j < n; j++)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (row_has_zero)
for (size_t i = 0; i < n; i++)
matrix[0][i] = 0;
if (col_has_zero)
for (size_t i = 0; i < m; i++)
matrix[i][0] = 0;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Gas Station} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:gas-station}
\subsubsection{描述}
There are $N$ gas stations along a circular route, where the amount of gas at station $i$ is \fn{gas[i]}.
You have a car with an unlimited gas tank and it costs \fn{cost[i]} of gas to travel from station $i$ to its next station ($i$+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
\subsubsection{分析}
首先想到的是$O(N^2)$的解法,对每个点进行模拟。
$O(N)$的解法是,设置两个变量,\fn{sum}判断当前的指针的有效性;\fn{total}则判断整个数组是否有解,有就返回通过\fn{sum}得到的下标,没有则返回-1。
\subsubsection{代码}
\begin{Code}
// LeetCode, Gas Station
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int total = 0;
int j = -1;
for (int i = 0, sum = 0; i < gas.size(); ++i) {
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if (sum < 0) {
j = i;
sum = 0;
}
}
return total >= 0 ? j + 1 : -1;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Candy} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:candy}
\subsubsection{描述}
There are $N$ children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
\begindot
\item Each child must have at least one candy.
\item Children with a higher rating get more candies than their neighbors.
\myenddot
What is the minimum candies you must give?
\subsubsection{分析}
无
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Candy
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int candy(vector<int> &ratings) {
const int n = ratings.size();
vector<int> increment(n);
// 左右各扫描一遍
for (int i = 1, inc = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1])
increment[i] = max(inc++, increment[i]);
else
inc = 1;
}
for (int i = n - 2, inc = 1; i >= 0; i--) {
if (ratings[i] > ratings[i + 1])
increment[i] = max(inc++, increment[i]);
else
inc = 1;
}
// 初始值为n,因为每个小朋友至少一颗糖
return accumulate(&increment[0], &increment[0]+n, n);
}
};
\end{Code}
\subsubsection{递归版}
\begin{Code}
// LeetCode, Candy
// 备忘录法,时间复杂度O(n),空间复杂度O(n)
// @author fancymouse (http://weibo.com/u/1928162822)
class Solution {
public:
int candy(const vector<int>& ratings) {
vector<int> f(ratings.size());
int sum = 0;
for (int i = 0; i < ratings.size(); ++i)
sum += solve(ratings, f, i);
return sum;
}
int solve(const vector<int>& ratings, vector<int>& f, int i) {
if (f[i] == 0) {
f[i] = 1;
if (i > 0 && ratings[i] > ratings[i - 1])
f[i] = max(f[i], solve(ratings, f, i - 1) + 1);
if (i < ratings.size() - 1 && ratings[i] > ratings[i + 1])
f[i] = max(f[i], solve(ratings, f, i + 1) + 1);
}
return f[i];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Single Number} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:single-number}
\subsubsection{描述}
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
\subsubsection{分析}
异或,不仅能处理两次的情况,只要出现偶数次,都可以清零。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Single Number
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int singleNumber(int A[], int n) {
int x = 0;
for (size_t i = 0; i < n; ++i)
x ^= A[i];
return x;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Single Number
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int singleNumber(int A[], int n) {
return accumulate(A, A + n, 0, bit_xor<int>());
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Single Number II, 见 \S \ref{sec:single-number-ii}
\myenddot
\subsection{Single Number II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:single-number-ii}
\subsubsection{描述}
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
\subsubsection{分析}
本题和上一题 Single Number,考察的是位运算。
方法1:创建一个长度为\fn{sizeof(int)}的数组\fn{count[sizeof(int)]},\fn{count[i]}表示在在$i$位出现的1的次数。如果\fn{count[i]}是3的整数倍,则忽略;否则就把该位取出来组成答案。
方法2:用\fn{one}记录到当前处理的元素为止,二进制1出现“1次”(mod 3 之后的 1)的有哪些二进制位;用\fn{two}记录到当前计算的变量为止,二进制1出现“2次”(mod 3 之后的 2)的有哪些二进制位。当\fn{one}和\fn{two}中的某一位同时为1时表示该二进制位上1出现了3次,此时需要清零。即\textbf{用二进制模拟三进制运算}。最终\fn{one}记录的是最终结果。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Single Number II
// 方法1,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int singleNumber(int A[], int n) {
const int W = sizeof(int) * 8; // 一个整数的bit数,即整数字长
int count[W]; // count[i]表示在在i位出现的1的次数
fill_n(&count[0], W, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < W; j++) {
count[j] += (A[i] >> j) & 1;
count[j] %= 3;
}
}
int result = 0;
for (int i = 0; i < W; i++) {
result += (count[i] << i);
}
return result;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Single Number II
// 方法2,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int singleNumber(int A[], int n) {
int one = 0, two = 0, three = 0;
for (int i = 0; i < n; ++i) {
two |= (one & A[i]);
one ^= A[i];
three = ~(one & two);
one &= three;
two &= three;
}
return one;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Single Number, 见 \S \ref{sec:single-number}
\myenddot
\section{单链表} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
单链表节点的定义如下:
\begin{Code}
// 单链表节点
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) { }
};
\end{Code}
\subsection{Add Two Numbers}
\label{sec:add-two-numbers}
\subsubsection{描述}
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: {\small \fontspec{Latin Modern Mono} (2 -> 4 -> 3) + (5 -> 6 -> 4)}
Output: {\small \fontspec{Latin Modern Mono} 7 -> 0 -> 8}
\subsubsection{分析}
跟Add Binary(见 \S \ref{sec:add-binary})很类似
\subsubsection{代码}
\begin{Code}
// LeetCode, Add Two Numbers
// 跟Add Binary 很类似
// 时间复杂度O(m+n),空间复杂度O(1)
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode dummy(-1); // 头节点
int carry = 0;
ListNode *prev = &dummy;
for (ListNode *pa = l1, *pb = l2;
pa != nullptr || pb != nullptr;
pa = pa == nullptr ? nullptr : pa->next,
pb = pb == nullptr ? nullptr : pb->next,
prev = prev->next) {
const int ai = pa == nullptr ? 0 : pa->val;
const int bi = pb == nullptr ? 0 : pb->val;
const int value = (ai + bi + carry) % 10;
carry = (ai + bi + carry) / 10;
prev->next = new ListNode(value); // 尾插法
}
if (carry > 0)
prev->next = new ListNode(carry);
return dummy.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Add Binary, 见 \S \ref{sec:add-binary}
\myenddot
\subsection{Reverse Linked List II}
\label{sec:reverse-linked-list-ii}
\subsubsection{描述}
Reverse a linked list from position $m$ to $n$. Do it in-place and in one-pass.
For example:
Given \code{1->2->3->4->5->nullptr}, $m$ = 2 and $n$ = 4,
return \code{1->4->3->2->5->nullptr}.
Note:
Given m, n satisfy the following condition:
$1 \leq m \leq n \leq $ length of list.
\subsubsection{分析}
这题非常繁琐,有很多边界检查,15分钟内做到bug free很有难度!
\subsubsection{代码}
\begin{Code}
// LeetCode, Reverse Linked List II
// 迭代版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode dummy(-1);
dummy.next = head;
ListNode *prev = &dummy;
for (int i = 0; i < m-1; ++i)
prev = prev->next;
ListNode* const head2 = prev;
prev = head2->next;
ListNode *cur = prev->next;
for (int i = m; i < n; ++i) {
prev->next = cur->next;
cur->next = head2->next;
head2->next = cur; // 头插法
cur = prev->next;
}
return dummy.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Partition List}
\label{sec:partition-list}
\subsubsection{描述}
Given a linked list and a value $x$, partition it such that all nodes less than $x$ come before nodes greater than or equal to $x$.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given \code{1->4->3->2->5->2} and \code{x = 3}, return \code{1->2->2->4->3->5}.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Partition List
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode left_dummy(-1); // 头结点
ListNode right_dummy(-1); // 头结点
auto left_cur = &left_dummy;
auto right_cur = &right_dummy;
for (ListNode *cur = head; cur; cur = cur->next) {
if (cur->val < x) {
left_cur->next = cur;
left_cur = cur;
} else {
right_cur->next = cur;
right_cur = cur;
}
}
left_cur->next = right_dummy.next;
right_cur->next = nullptr;
return left_dummy.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Remove Duplicates from Sorted List}
\label{sec:remove-duplicates-from-sorted-list}
\subsubsection{描述}
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given \code{1->1->2}, return \code{1->2}.
Given \code{1->1->2->3->3}, return \code{1->2->3}.
\subsubsection{分析}
无
\subsubsection{递归版}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted List
// 递归版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (!head) return head;
ListNode dummy(head->val + 1); // 值只要跟head不同即可
dummy.next = head;
recur(&dummy, head);
return dummy.next;
}
private:
static void recur(ListNode *prev, ListNode *cur) {
if (cur == nullptr) return;
if (prev->val == cur->val) { // 删除head
prev->next = cur->next;
delete cur;
recur(prev, prev->next);
} else {
recur(prev->next, cur->next);
}
}
};
\end{Code}
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted List
// 迭代版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (head == nullptr) return nullptr;
for (ListNode *prev = head, *cur = head->next; cur; cur = cur->next) {
if (prev->val == cur->val) {
prev->next = cur->next;
delete cur;
} else {
prev = cur;
}
}
return head;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Remove Duplicates from Sorted List II,见 \S \ref{sec:remove-duplicates-from-sorted-list-ii}
\myenddot
\subsection{Remove Duplicates from Sorted List II}
\label{sec:remove-duplicates-from-sorted-list-ii}
\subsubsection{描述}
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given \code{1->2->3->3->4->4->5}, return \code{1->2->5}.
Given \code{1->1->1->2->3}, return \code{2->3}.
\subsubsection{分析}
无
\subsubsection{递归版}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted List II
// 递归版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (!head || !head->next) return head;
ListNode *p = head->next;
if (head->val == p->val) {
while (p && head->val == p->val) {
ListNode *tmp = p;
p = p->next;
delete tmp;
}
delete head;
return deleteDuplicates(p);
} else {
head->next = deleteDuplicates(head->next);
return head;
}
}
};
\end{Code}
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted List II
// 迭代版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (head == nullptr) return head;
ListNode dummy(INT_MIN); // 头结点
dummy.next = head;
ListNode *prev = &dummy, *cur = head;
while (cur != nullptr) {
bool duplicated = false;
while (cur->next != nullptr && cur->val == cur->next->val) {
duplicated = true;
ListNode *temp = cur;
cur = cur->next;
delete temp;
}
if (duplicated) { // 删除重复的最后一个元素
ListNode *temp = cur;
cur = cur->next;
delete temp;
continue;
}
prev->next = cur;
prev = prev->next;
cur = cur->next;
}
prev->next = cur;
return dummy.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Remove Duplicates from Sorted List,见 \S \ref{sec:remove-duplicates-from-sorted-list}
\myenddot
\subsection{Rotate List}
\label{sec:rotate-list}
\subsubsection{描述}
Given a list, rotate the list to the right by $k$ places, where $k$ is non-negative.
For example:
Given \code{1->2->3->4->5->nullptr} and \code{k = 2}, return \code{4->5->1->2->3->nullptr}.
\subsubsection{分析}
先遍历一遍,得出链表长度$len$,注意$k$可能大于$len$,因此令$k \%= len$。将尾节点next指针指向首节点,形成一个环,接着往后跑$len-k$步,从这里断开,就是要求的结果了。
\subsubsection{代码}
\begin{Code}
// LeetCode, Remove Rotate List
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == nullptr || k == 0) return head;
int len = 1;
ListNode* p = head;
while (p->next) { // 求长度
len++;
p = p->next;
}
k = len - k % len;
p->next = head; // 首尾相连
for(int step = 0; step < k; step++) {
p = p->next; //接着往后跑
}
head = p->next; // 新的首节点
p->next = nullptr; // 断开环
return head;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Remove Nth Node From End of List}
\label{sec:remove-nth-node-from-end-of-list}
\subsubsection{描述}
Given a linked list, remove the $n^{th}$ node from the end of list and return its head.
For example, Given linked list: \code{1->2->3->4->5}, and $n$ = 2.
After removing the second node from the end, the linked list becomes \code{1->2->3->5}.
Note:
\begindot
\item Given $n$ will always be valid.
\item Try to do this in one pass.
\myenddot
\subsubsection{分析}
设两个指针$p,q$,让$q$先走$n$步,然后$p$和$q$一起走,直到$q$走到尾节点,删除\fn{p->next}即可。
\subsubsection{代码}
\begin{Code}
// LeetCode, Remove Nth Node From End of List
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode dummy{-1, head};
ListNode *p = &dummy, *q = &dummy;
for (int i = 0; i < n; i++) // q先走n步
q = q->next;
while(q->next) { // 一起走
p = p->next;
q = q->next;
}
ListNode *tmp = p->next;
p->next = p->next->next;
delete tmp;
return dummy.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Swap Nodes in Pairs}
\label{sec:swap-nodes-in-pairs}
\subsubsection{描述}
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given \code{1->2->3->4}, you should return the list as \code{2->1->4->3}.
Your algorithm should use only constant space. You may \emph{not} modify the values in the list, only nodes itself can be changed.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Swap Nodes in Pairs
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode dummy(-1);
dummy.next = head;
for(ListNode *prev = &dummy, *cur = prev->next, *next = cur->next;
next;
prev = cur, cur = cur->next, next = cur ? cur->next: nullptr) {
prev->next = next;
cur->next = next->next;
next->next = cur;
}
return dummy.next;
}
};
\end{Code}
下面这种写法更简洁,但题目规定了不准这样做。
\begin{Code}
// LeetCode, Swap Nodes in Pairs
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* p = head;
while (p && p->next) {
swap(p->val, p->next->val);
p = p->next->next;
}
return head;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Reverse Nodes in k-Group, 见 \S \ref{sec:reverse-nodes-in-k-group}
\myenddot
\subsection{Reverse Nodes in k-Group}
\label{sec:reverse-nodes-in-k-group}
\subsubsection{描述}
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of $k$ then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: \code{1->2->3->4->5}
For $k = 2$, you should return: \code{2->1->4->3->5}
For $k = 3$, you should return: \code{3->2->1->4->5}
\subsubsection{分析}
无
\subsubsection{递归版}
\begin{Code}
// LeetCode, Reverse Nodes in k-Group
// 递归版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (head == nullptr || head->next == nullptr || k < 2)
return head;
ListNode *next_group = head;
for (int i = 0; i < k; ++i) {
if (next_group)
next_group = next_group->next;
else
return head;
}
// next_group is the head of next group
// new_next_group is the new head of next group after reversion
ListNode *new_next_group = reverseKGroup(next_group, k);
ListNode *prev = NULL, *cur = head;
while (cur != next_group) {
ListNode *next = cur->next;
cur->next = prev ? prev : new_next_group;
prev = cur;
cur = next;
}
return prev; // prev will be the new head of this group
}
};
\end{Code}
\subsubsection{迭代版}
\begin{Code}
// LeetCode, Reverse Nodes in k-Group
// 迭代版,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (head == nullptr || head->next == nullptr || k < 2) return head;
ListNode dummy(-1);
dummy.next = head;
for(ListNode *prev = &dummy, *end = head; end; end = prev->next) {
for (int i = 1; i < k && end; i++)
end = end->next;
if (end == nullptr) break; // 不足 k 个
prev = reverse(prev, prev->next, end);
}
return dummy.next;
}
// prev 是 first 前一个元素, [begin, end] 闭区间,保证三者都不为 null
// 返回反转后的倒数第1个元素
ListNode* reverse(ListNode *prev, ListNode *begin, ListNode *end) {
ListNode *end_next = end->next;
for (ListNode *p = begin, *cur = p->next, *next = cur->next;
cur != end_next;
p = cur, cur = next, next = next ? next->next : nullptr) {
cur->next = p;
}
begin->next = end_next;
prev->next = end;
return begin;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Swap Nodes in Pairs, 见 \S \ref{sec:swap-nodes-in-pairs}
\myenddot
\subsection{Copy List with Random Pointer}
\label{sec:copy-list-with-random-pointer}
\subsubsection{描述}
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Copy List with Random Pointer
// 两遍扫描,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
for (RandomListNode* cur = head; cur != nullptr; ) {
RandomListNode* node = new RandomListNode(cur->label);
node->next = cur->next;
cur->next = node;
cur = node->next;
}
for (RandomListNode* cur = head; cur != nullptr; ) {
if (cur->random != NULL)
cur->next->random = cur->random->next;
cur = cur->next->next;
}
// 分拆两个单链表
RandomListNode dummy(-1);
for (RandomListNode* cur = head, *new_cur = &dummy;
cur != nullptr; ) {
new_cur->next = cur->next;
new_cur = new_cur->next;
cur->next = cur->next->next;
cur = cur->next;
}
return dummy.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Linked List Cycle}
\label{sec:Linked-List-Cycle}
\subsubsection{描述}
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
\subsubsection{分析}
最容易想到的方法是,用一个哈希表\fn{unordered_map<int, bool> visited},记录每个元素是否被访问过,一旦出现某个元素被重复访问,说明存在环。空间复杂度$O(n)$,时间复杂度$O(N)$。
最好的方法是时间复杂度$O(n)$,空间复杂度$O(1)$的。设置两个指针,一个快一个慢,快的指针每次走两步,慢的指针每次走一步,如果快指针和慢指针相遇,则说明有环。参考\myurl{ http://leetcode.com/2010/09/detecting-loop-in-singly-linked-list.html}
\subsubsection{代码}
\begin{Code}
//LeetCode, Linked List Cycle
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
bool hasCycle(ListNode *head) {
// 设置两个指针,一个快一个慢
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Linked List Cycle II, 见 \S \ref{sec:Linked-List-Cycle-II}
\myenddot
\subsection{Linked List Cycle II}
\label{sec:Linked-List-Cycle-II}
\subsubsection{描述}
Given a linked list, return the node where the cycle begins. If there is no cycle, return \fn{null}.
Follow up:
Can you solve it without using extra space?
\subsubsection{分析}
当fast与slow相遇时,slow肯定没有遍历完链表,而fast已经在环内循环了$n$圈($1 \leq n$)。假设slow走了$s$步,则fast走了$2s$步(fast步数还等于$s$加上在环上多转的$n$圈),设环长为$r$,则:
\begin{eqnarray}
2s &=& s + nr \nonumber \\
s &=& nr \nonumber
\end{eqnarray}
设整个链表长$L$,环入口点与相遇点距离为$a$,起点到环入口点的距离为$x$,则
\begin{eqnarray}
x + a &=& nr = (n – 1)r +r = (n-1)r + L - x \nonumber \\
x &=& (n-1)r + (L – x – a) \nonumber
\end{eqnarray}
$L – x – a$为相遇点到环入口点的距离,由此可知,从链表头到环入口点等于$n-1$圈内环+相遇点到环入口点,于是我们可以从\fn{head}开始另设一个指针\fn{slow2},两个慢指针每次前进一步,它俩一定会在环入口点相遇。
\subsubsection{代码}
\begin{Code}
//LeetCode, Linked List Cycle II
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
ListNode *slow2 = head;
while (slow2 != slow) {
slow2 = slow2->next;
slow = slow->next;
}
return slow2;
}
}
return nullptr;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Linked List Cycle, 见 \S \ref{sec:Linked-List-Cycle}
\myenddot
\subsection{Reorder List}
\label{sec:Reorder-List}
\subsubsection{描述}
Given a singly linked list $L: L_0 \rightarrow L_1 \rightarrow \cdots \rightarrow L_{n-1} \rightarrow L_n$,
reorder it to: $L_0 \rightarrow L_n \rightarrow L_1 \rightarrow L_{n-1} \rightarrow L_2 \rightarrow L_{n-2} \rightarrow \cdots$
You must do this in-place without altering the nodes' values.
For example,
Given \fn{\{1,2,3,4\}}, reorder it to \fn{\{1,4,2,3\}}.
\subsubsection{分析}
题目规定要in-place,也就是说只能使用$O(1)$的空间。
可以找到中间节点,断开,把后半截单链表reverse一下,再合并两个单链表。
\subsubsection{代码}
\begin{Code}
// LeetCode, Reorder List
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
void reorderList(ListNode *head) {
if (head == nullptr || head->next == nullptr) return;
ListNode *slow = head, *fast = head, *prev = nullptr;
while (fast && fast->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = nullptr; // cut at middle
slow = reverse(slow);
// merge two lists
ListNode *curr = head;
while (curr->next) {
ListNode *tmp = curr->next;
curr->next = slow;
slow = slow->next;
curr->next->next = tmp;
curr = tmp;
}
curr->next = slow;
}
ListNode* reverse(ListNode *head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode *prev = head;
for (ListNode *curr = head->next, *next = curr->next; curr;
prev = curr, curr = next, next = next ? next->next : nullptr) {
curr->next = prev;
}
head->next = nullptr;
return prev;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{LRU Cache}
\label{sec:LRU-Cachet}
\subsubsection{描述}
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
\fn{get(key)} - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
\fn{set(key, value)} - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
\subsubsection{分析}
为了使查找、插入和删除都有较高的性能,我们使用一个双向链表(\fn{std::list})和一个哈希表(\fn{std::unordered_map}),因为:
\begin{itemize}
\item{哈希表保存每个节点的地址,可以基本保证在$O(1)$时间内查找节点}
\item{双向链表插入和删除效率高,单向链表插入和删除时,还要查找节点的前驱节点}
\end{itemize}
具体实现细节:
\begin{itemize}
\item{越靠近链表头部,表示节点上次访问距离现在时间最短,尾部的节点表示最近访问最少}
\item{访问节点时,如果节点存在,把该节点交换到链表头部,同时更新hash表中该节点的地址}
\item{插入节点时,如果cache的size达到了上限capacity,则删除尾部节点,同时要在hash表中删除对应的项;新节点插入链表头部}
\end{itemize}
\subsubsection{代码}
\begin{Code}
// LeetCode, LRU Cache
// 时间复杂度O(logn),空间复杂度O(n)
class LRUCache{
private:
struct CacheNode {
int key;
int value;
CacheNode(int k, int v) :key(k), value(v){}
};
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if (cacheMap.find(key) == cacheMap.end()) return -1;
// 把当前访问的节点移到链表头部,并且更新map中该节点的地址
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
return cacheMap[key]->value;
}
void set(int key, int value) {
if (cacheMap.find(key) == cacheMap.end()) {
if (cacheList.size() == capacity) { //删除链表尾部节点(最少访问的节点)
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
// 插入新节点到链表头部, 并且在map中增加该节点
cacheList.push_front(CacheNode(key, value));
cacheMap[key] = cacheList.begin();
} else {
//更新节点的值,把当前访问的节点移到链表头部,并且更新map中该节点的地址
cacheMap[key]->value = value;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
}
}
private:
list<CacheNode> cacheList;
unordered_map<int, list<CacheNode>::iterator> cacheMap;
int capacity;
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
|
/***************************************************************
*
* Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_getmnt.h"
/*
The function getmnt() is Ultrix specific and returns a different
structure than the similar functions available on other UNIX
variants. We simulate "getmnt()" by calling the appropriate platform
specific library routines. N.B. we simulate getmnt() only to the
extent needed specifically by condor. This is NOT a generally correct
simulation.
*/
#if defined(Darwin) || defined(CONDOR_FREEBSD)
#include <sys/stat.h>
#include <sys/mount.h>
int
getmnt( int * start, struct fs_data buf[], unsigned bufsize,
int mode, char * path )
{
struct statfs *data = NULL;
struct stat st_buf;
int n_entries;
int i;
if( (n_entries=getmntinfo(&data,MNT_NOWAIT)) < 0 ) {
perror( "getmntinfo" );
exit( 1 );
}
for( i=0; i<n_entries; i++ ) {
if( stat(data[i].f_mntonname,&st_buf) < 0 ) {
buf[i].fd_req.dev = 0;
} else {
buf[i].fd_req.dev = st_buf.st_dev;
}
buf[i].fd_req.devname = data[i].f_mntonname;
buf[i].fd_req.path = data[i].f_mntfromname;
}
return n_entries;
}
#elif defined(AIX32)
FILE *setmntent();
struct mntent *getmntent();
char *strdup();
int
getmnt( start, buf, bufsize, mode, path )
int *start;
struct fs_data buf[];
unsigned bufsize;
int mode;
char *path;
{
int status;
int mount_table_size = 1024;
struct vmount *ptr;
struct stat st_buf;
int i;
int lim;
ptr = (struct vmount *)malloc( mount_table_size );
status = mntctl( MCTL_QUERY, mount_table_size, ptr );
/* If the mount table we have supplied is too small, then mntctl
will return the required size in the first word and return 0.
*/
if( status == 0 ) {
mount_table_size = *(int *)ptr;
free( ptr );
ptr = (struct vmount *)malloc( mount_table_size );
status = mntctl( MCTL_QUERY, mount_table_size, ptr );
}
if( status < 0 ) {
perror( "mntctl" );
exit( 1 );
}
/* "lim" should be the number of entries we can store in the buffer
supplied by the calling routine, or the number of entries
in the real mount table - whichever is smaller */
lim = bufsize / sizeof(struct fs_data);
if( status < lim ) {
lim = status;
}
for( i=0; i < lim; i++ ) {
add( ptr, &buf[i] );
ptr = (struct vmount *) ( (char *)ptr + ptr->vmt_length );
}
return status;
}
#define OBJECT vmt2dataptr(vm,VMT_OBJECT)
#define STUB vmt2dataptr(vm,VMT_STUB)
#define HOSTNAME vmt2dataptr(vm,VMT_HOSTNAME)
add( vm, ent )
struct vmount *vm;
struct fs_data *ent;
{
char buf[1024];
struct stat st_buf;
if( vm->vmt_gfstype == MNT_NFS ) {
sprintf( buf, "%s:%s", HOSTNAME, OBJECT );
} else {
strcpy( buf, OBJECT );
}
if( stat(STUB,&st_buf) < 0 ) {
ent->fd_req.dev = 0;
} else {
if( vm->vmt_gfstype == MNT_NFS ) {
ent->fd_req.dev = st_buf.st_vfs;
} else {
ent->fd_req.dev = st_buf.st_dev;
}
}
ent->fd_req.devname = strdup(buf);
ent->fd_req.path = strdup( STUB );
}
#elif defined(Solaris)
/* Solaris specific change ..dhaval
6/26 */
/*FILE *setmntent();*/
int
getmnt( int * start, struct fs_data buf[], unsigned bufsize,
int mode, char * path )
{
FILE *tab;
int check;
struct mnttab *ent;
struct stat st_buf;
int i;
int lim;
/* if( (tab=setmntent("/etc/mnttab","r")) == NULL ) {
perror( "setmntent" );
exit( 1 );
} */
if( (tab=safe_fopen_wrapper("/etc/mnttab","r",0644)) == NULL ) {
perror( "setmntent" );
exit( 1 );
}
lim = bufsize / sizeof(struct fs_data);
for( i=0; (i < lim) && (check=getmntent(tab,ent)); i++ ) {
if( stat(ent->mnt_mountp,&st_buf) < 0 ) {
buf[i].fd_req.dev = 0;
} else {
buf[i].fd_req.dev = st_buf.st_dev;
}
buf[i].fd_req.devname = strdup(ent->mnt_special);
buf[i].fd_req.path = strdup(ent->mnt_mountp);
}
return i;
}
#else
/* BEGIN !ULTRIX, !AIX version - use setmntent() and getmntent() */
FILE *setmntent();
struct mntent *getmntent();
// I believe this is *only* used by std::universe
extern "C" int
getmnt( int* /*start*/, struct fs_data buf[],
unsigned int bufsize, int /*mode*/, char* /*path*/ )
{
FILE *tab;
struct mntent *ent;
struct stat st_buf;
int i;
int lim;
if( (tab=setmntent("/etc/mtab","r")) == NULL ) {
perror( "setmntent" );
exit( 1 );
}
lim = bufsize / sizeof(struct fs_data);
for( i=0; (i < lim) && (ent=getmntent(tab)); i++ ) {
if( stat(ent->mnt_dir,&st_buf) < 0 ) {
buf[i].fd_req.dev = 0;
} else {
buf[i].fd_req.dev = st_buf.st_dev;
}
buf[i].fd_req.devname = strdup(ent->mnt_fsname);
buf[i].fd_req.path = strdup(ent->mnt_dir);
}
return i;
}
/* END !ULTRIX version */
#endif
|
/*
* Name: IAIStringFormatUtils.cpp
* $Revision: 1 $
* Author:
* Date:
* Purpose: Plug-in side implementation of the
* ai::Locale and ai::NumberFormat object interface.
* This file should NOT be included in the
* core application.
*
* ADOBE SYSTEMS INCORPORATED
* Copyright 2004-2007 Adobe Systems Incorporated.
* All rights reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute this file
* in accordance with the terms of the Adobe license agreement
* accompanying it. If you have received this file from a source other
* than Adobe, then your use, modification, or distribution of it
* requires the prior written permission of Adobe.
*
*/
#include "IAIStringFormatUtils.h"
#include "AIStringFormatUtils.h"
#include "SPBlocks.h"
#ifdef _IAISTRINGFORMATUTILS_SUITE_INCLUDE_H_
#include _IAISTRINGFORMATUTILS_SUITE_INCLUDE_H_
#else
#ifndef _IAISTRINGFORMATUTILS_SUITE_USE_C_LINKAGE_
#define _IAISTRINGFORMATUTILS_SUITE_USE_C_LINKAGE_ 1
#endif
#if _IAISTRINGFORMATUTILS_SUITE_USE_C_LINKAGE_
extern "C"
{
#endif
/** The plug-in using the ai::Locale or the ai::NumberFormat class is required to provide
these global suite pointers. These pointers must be valid prior
to any call to ai::Locale and ai::NumberFormat methods.
*/
extern AIStringFormatUtilsSuite* sAIStringFormatUtils;
extern SPBlocksSuite *sSPBlocks;
#if _IAISTRINGFORMATUTILS_SUITE_USE_C_LINKAGE_
}
#endif // _IAISTRINGFORMATUTILS_SUITE_USE_C_LINKAGE_
#endif
/** Checks the result. If @a result indicates an error, it is
thrown as an ai::Error exception. If result does not indicate
an error, this function simply returns.
@param result result code to check. */
static void check_result(AIErr result)
{
if ( result != kNoErr )
{
throw ai::Error(result);
}
}
/* ai::Locale methods */
std::string ai::Locale::getLocale(const ai::LocaleID id)
{
ai::AutoBuffer<char> locale;
sAIStringFormatUtils->GetLocaleString(id, locale);
if ( locale.GetCount() > 0 )
{
return std::string(locale.GetBuffer(), locale.GetCount());
}
else
{
return std::string();
}
}
ai::LocaleID ai::Locale::getID(const std::string& locale)
{
ai::LocaleID id;
sAIStringFormatUtils->GetLocaleID(locale.c_str(), id );
return id;
}
ai::LocaleID ai::Locale::getSystemLocaleID()
{
ai::LocaleID localeID;
localeID = getID(ai::Locale::getLocale(kSystem));
return localeID;
}
ai::LocaleID ai::Locale::getApplicationLocaleID()
{
ai::LocaleID localeID;
localeID = getID(ai::Locale::getLocale(kApplication));
return localeID;
}
/* ai::NumberFormat methods */
ai::NumberFormat::NumberFormat(void) AINOTHROW
:fImpl(0)
{
}
ai::NumberFormat::NumberFormat(const ai::LocaleID locale)
:fImpl(0)
{
AIErr result = sAIStringFormatUtils->Initialize(*this, locale);
check_result(result);
}
ai::NumberFormat::NumberFormat(bool /*dummyUseStaticFormatter*/)
:fImpl(0)
{
AIErr result = sAIStringFormatUtils->InitializeDefaultInstance(*this);
check_result(result);
}
ai::NumberFormat::NumberFormat (const NumberFormat& s)
: fImpl(0)
{
AIErr result = sAIStringFormatUtils->Copy(*this, s);
check_result(result);
}
ai::NumberFormat::~NumberFormat()
{
if (fImpl)
sAIStringFormatUtils->Destroy(*this);
}
ai::NumberFormat ai::NumberFormat::getFormat(const ai::LocaleID locale)
{
if (locale == ai::Locale::kDefault)
return NumberFormat(true);
else
return NumberFormat(locale);
}
ai::NumberFormat& ai::NumberFormat::operator= (const NumberFormat& rhs)
{
AIErr result = sAIStringFormatUtils->Copy(*this, rhs);
check_result(result);
return *this;
}
ai::UnicodeString& ai::NumberFormat::toString(const float value, const ai::int32 precision, ai::UnicodeString& str,
bool padToPrecision)
{
AIErr result = sAIStringFormatUtils->RealToString(*this, value, precision, padToPrecision, str);
check_result(result);
return str;
}
ai::UnicodeString& ai::NumberFormat::toString(const ai::int32 value, ai::UnicodeString& str)
{
AIErr result = sAIStringFormatUtils->IntegerToString(*this, value, str);
check_result(result);
return str;
}
ai::UnicodeString& ai::NumberFormat::toString(const double value, const ai::int32 precision, ai::UnicodeString& str,
bool padToPrecision)
{
AIErr result = sAIStringFormatUtils->DoubleToString(*this, value, precision, padToPrecision, str);
check_result(result);
return str;
}
bool ai::NumberFormat::parseString(const ai::UnicodeString& str, float& value)
{
AIErr result = sAIStringFormatUtils->StringToReal(*this, str, value);
if (result == kCannotParseStringError)
return false;
check_result(result);
return true;
}
bool ai::NumberFormat::parseString(const ai::UnicodeString& str, ai::int32& value)
{
AIErr result = sAIStringFormatUtils->StringToInteger(*this, str, value);
if (result == kCannotParseStringError)
return false;
check_result(result);
return true;
}
bool ai::NumberFormat::parseString(const ai::UnicodeString& str, double& value)
{
AIErr result = sAIStringFormatUtils->StringToDouble(*this, str, value);
if (result == kCannotParseStringError)
return false;
check_result(result);
return true;
}
ai::UnicodeString ai::NumberFormat::getDecimalSeparator()
{
ai::UnicodeString str;
AIErr result = sAIStringFormatUtils->GetDecimalSeparator(*this, str);
check_result(result);
return str;
}
ai::UnicodeString ai::NumberFormat::getThousandsSeparator()
{
ai::UnicodeString str;
AIErr result = sAIStringFormatUtils->GetThousandsSeparator(*this, str);
check_result(result);
return str;
}
|
/*
* This file is part of the Cadence LEF/DEF Open Source
* Distribution, Product Version 5.6, and is subject to the Cadence
* LEF/DEF Open Source License Agreement. Your continued use of
* this file constitutes your acceptance of the terms of the LEF/DEF
* Open Source License and an agreement to abide by its terms. If
* you don't agree with this, you must remove this and any other
* files which are part of the distribution and destroy any copies
* made.
*
* For updates, support, or to become part of the LEF/DEF Community,
* check www.openeda.org for details.
*/
/* FEF_malloc.cpp */
#include <stdio.h>
#include <stdlib.h>
#include "lex.h"
#include "FEF_malloc.h"
#include "FEF_util.h"
extern char lefDebug[100];
/**********************************************************************/
/**********************************************************************/
void *FEF_calloc(int num_elem,int elem_size,const char *comment)
{
int n = num_elem*elem_size;
void *ptr;
if(lefDebug[1])
printf("%s calloc -> %d * %d = %d bytes"
,comment,num_elem,elem_size,n);
if(num_elem<1) lefiNerr(169);
if(elem_size<1) lefiNerr(169);
ptr = calloc(num_elem,elem_size);
if( ! ptr ) NoMemory();
return ptr;
}
/**********************************************************************/
/**********************************************************************/
void *FEF_malloc(int num_bytes,const char *comment)
{
void *ptr;
if(lefDebug[1])
printf("%s malloc -> %d bytes",comment,num_bytes);
if(num_bytes<1) lefiNerr(115);
ptr = lefMalloc(num_bytes);
if( ! ptr ) NoMemory();
return ptr;
}
/**********************************************************************/
void *FEF_free_then_malloc(void *ptr,int num_bytes,const char *comment)
{
if(lefDebug[1])
printf("%s free, then malloc -> %d bytes",comment,num_bytes);
if(num_bytes<1) lefiNerr(116);
if(ptr)
{
free((char*)ptr);
/*
# ifdef WIN32
_heapmin();
# endif
*/
}
ptr = lefMalloc(num_bytes);
if( ! ptr ) NoMemory();
return ptr;
}
/**********************************************************************/
void *FEF_realloc(void *ptr,int num_bytes,const char *comment)
{
if(lefDebug[1])
printf("%s realloc -> %d bytes",comment,num_bytes);
if(num_bytes<1) lefiNerr(117);
if(ptr)
ptr = lefRealloc((char*)ptr,num_bytes);
else
ptr = lefMalloc(num_bytes);
if( ! ptr ) NoMemory();
return ptr;
}
/**********************************************************************/
/**********************************************************************/
void *FEF_relax(void *ptr,int num_bytes,const char *comment)
{
void *old_ptr;
void *new_ptr;
if(lefDebug[1])
printf("%s FEF_relax(lefRealloc) -> %d bytes",comment,num_bytes);
if(!ptr) lefiNerr(168);
old_ptr = ptr;
new_ptr = lefRealloc((char*)ptr,num_bytes);
if(new_ptr != old_ptr)
if(lefDebug[0])
lefiNwarn(944);
return new_ptr;
}
/**********************************************************************/
/**********************************************************************/
void FEF_free(void *ptr,const char *comment)
{
if(lefDebug[1])
printf("%s free",comment);
if(ptr)
{
free((char*)ptr);
/*
# ifdef WIN32
_heapmin();
# endif
*/
}
else lefiNerr(118);
}
/**********************************************************************/
/**********************************************************************/
void NoMemory()
{
printf("ERROR **** out of memory ***\n");
exit(1);
}
/**********************************************************************/
/**********************************************************************/
/* Replacement for malloc() that keeps track of what's out, and can free it all*/
static int nout = 0;
static int array_size = 0;
static char **what;
char *memory_malloc(unsigned n)
{
if (array_size == 0) { /* first time */
array_size = 64;
what = (char **)lefMalloc(array_size * sizeof(char *));
if (what == NULL)
NoMemory();
}
nout++;
if (nout > array_size) {
array_size <<= 1;
what = (char **)lefRealloc((char *)what, array_size*sizeof(char *));
if (what == NULL)
NoMemory();
}
what[nout-1] = (char *)lefMalloc(n);
if (what[nout-1] == NULL)
NoMemory();
return what[nout-1];
}
void memory_free()
{
int i;
for(i=0; i<nout; i++)
free(what[i]);
if(what != NULL)
free((char *)what);
/*
#ifdef WIN32
_heapmin();
#endif
*/
}
|
#include <Windows.h>
#include <iostream>
#include <thread>
using namespace std;
bool clicking = false;
void LeftClick()
{
INPUT Input = { 0 };
// left down
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
::SendInput(1, &Input, sizeof(INPUT));
// left up
::ZeroMemory(&Input, sizeof(INPUT));
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
::SendInput(1, &Input, sizeof(INPUT));
}
void Clicker()
{
while (true)
{
Sleep(20);
if (!clicking)
continue;
LeftClick();
}
}
int main()
{
SetConsoleTitle("Simple AutoClicker program");
thread clickerthread(Clicker);
cout << "Press F8 to start clicking. \n\n";
// Wait for input
while (true)
{
// Toggle clicking
if (GetAsyncKeyState(VK_F8) & 1)
{
clicking = !clicking;
if (clicking)
cout << "Clicking: on\n";
else
{
cout << "Clicking: off\n";
}
}
}
return 0;
}
|
#include <novatel_gps_driver/conv_llh_to_xyz.hpp>
double ConvLLHToXYZ::get_lat(void) const {
return m_lat;
}
double ConvLLHToXYZ::get_lon(void) const {
return m_lon;
}
double ConvLLHToXYZ::get_h(void) const {
return m_h;
}
double ConvLLHToXYZ::get_x(void) const {
return m_x;
}
double ConvLLHToXYZ::get_y(void) const {
return m_y;
}
double ConvLLHToXYZ::get_z(void) const {
return m_z;
}
void ConvLLHToXYZ::set_llh(double lat, double lon, double h) {
m_lat = lat;
m_lon = lon;
m_h = h;
}
void ConvLLHToXYZ::set_xyz(double x, double y, double z) {
m_x = x;
m_y = y;
m_z = z;
}
void ConvLLHToXYZ::conv_llh_to_xyz(void) {
const double lat0 = 38.0;
const double lon0 = 129.0;
const double a = 6378137.0;
const double f = 1.0 / 298.2572221010;
const double b = a * (1.0-f);
const double k0 = 1.0;
const double dx = 600000.0;
const double dy = 200000.0;
const double phi = get_lat()*M_PI / 180.0;
const double phi0 = 38.0*M_PI / 180.0;
const double lambda = get_lon()*M_PI / 180.0;
const double lambda0 = 129.0*M_PI / 180.0;
double e1;
double e2;
double T;
double C;
double A;
double N;
double M;
double M0;
double YE, XN;
e1 = (pow(a, 2)-pow(b, 2)) / pow(a, 2);
e2 = (pow(a, 2)-pow(b, 2)) / pow(b, 2);
T = pow(tan(phi), 2);
C = e1 / (1.0-e1) * pow(cos(phi), 2);
A = (lambda-lambda0) * cos(phi);
N = a / sqrt(1.0-e1*pow(sin(phi), 2));
M = a * ((1.0 - e1/4.0 - 3.0*pow(e1, 2)/64.0 - 5.0*pow(e1, 3)/256.0)*phi
- (3.0*e1/8.0 + 3.0*pow(e1, 2)/32.0 + 45.0*pow(e1, 3)/1024.0)*sin(2.0*phi)
+ (15.0*pow(e1, 2)/256.0 + 45.0*pow(e1, 3)/1024.0)*sin(4.0*phi)
- 35.0*pow(e1, 3)/3072.0*sin(6.0*phi));
M0 = a * ((1.0 - e1/4.0 - 3.0*pow(e1, 2)/64.0 - 5.0*pow(e1, 3)/256.0)*phi0
- (3.0*e1/8.0 + 3.0*pow(e1, 2)/32.0 + 45.0*pow(e1, 3)/1024.0)*sin(2.0*phi0)
+ (15.0*pow(e1, 2)/256.0 + 45.0*pow(e1, 3)/1024.0)*sin(4.0*phi0)
- 35.0*pow(e1, 3)/3072.0*sin(6.0*phi0));
YE = dy + k0 * N * (A
+ pow(A, 3)/6.0*(1.0-T+C)
+ pow(A, 5)/120.0*(5.0-18.0*T+pow(T, 2)+72.0*C-58.0*e2));
XN = dx + k0 * (M - M0
+ N*tan(phi)
* (pow(A, 2)/2.0 + pow(A, 4)/24.0*(5.0-T+9.0*C+4.0*pow(C, 2))
+ pow(A, 6)/720.0*(61.0-58.0*T+pow(T, 2)+600.0*C-330.0*e2)));
set_xyz(XN, YE, 0.0);
}
|
//===-- runtime/edit-input.cpp ----------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "edit-input.h"
#include "flang/Common/real.h"
#include "flang/Common/uint128.h"
#include <algorithm>
namespace Fortran::runtime::io {
static std::optional<char32_t> PrepareInput(
IoStatementState &io, const DataEdit &edit, std::optional<int> &remaining) {
remaining.reset();
if (edit.descriptor == DataEdit::ListDirected) {
io.GetNextNonBlank();
} else {
if (edit.width.value_or(0) > 0) {
remaining = *edit.width;
}
io.SkipSpaces(remaining);
}
return io.NextInField(remaining);
}
static bool EditBOZInput(IoStatementState &io, const DataEdit &edit, void *n,
int base, int totalBitSize) {
std::optional<int> remaining;
std::optional<char32_t> next{PrepareInput(io, edit, remaining)};
common::UnsignedInt128 value{0};
for (; next; next = io.NextInField(remaining)) {
char32_t ch{*next};
if (ch == ' ') {
continue;
}
int digit{0};
if (ch >= '0' && ch <= '1') {
digit = ch - '0';
} else if (base >= 8 && ch >= '2' && ch <= '7') {
digit = ch - '0';
} else if (base >= 10 && ch >= '8' && ch <= '9') {
digit = ch - '0';
} else if (base == 16 && ch >= 'A' && ch <= 'Z') {
digit = ch + 10 - 'A';
} else if (base == 16 && ch >= 'a' && ch <= 'z') {
digit = ch + 10 - 'a';
} else {
io.GetIoErrorHandler().SignalError(
"Bad character '%lc' in B/O/Z input field", ch);
return false;
}
value *= base;
value += digit;
}
// TODO: check for overflow
std::memcpy(n, &value, totalBitSize >> 3);
return true;
}
// Returns false if there's a '-' sign
static bool ScanNumericPrefix(IoStatementState &io, const DataEdit &edit,
std::optional<char32_t> &next, std::optional<int> &remaining) {
next = PrepareInput(io, edit, remaining);
bool negative{false};
if (next) {
negative = *next == '-';
if (negative || *next == '+') {
next = io.NextInField(remaining);
}
}
return negative;
}
bool EditIntegerInput(
IoStatementState &io, const DataEdit &edit, void *n, int kind) {
RUNTIME_CHECK(io.GetIoErrorHandler(), kind >= 1 && !(kind & (kind - 1)));
switch (edit.descriptor) {
case DataEdit::ListDirected:
case 'G':
case 'I':
break;
case 'B':
return EditBOZInput(io, edit, n, 2, kind << 3);
case 'O':
return EditBOZInput(io, edit, n, 8, kind << 3);
case 'Z':
return EditBOZInput(io, edit, n, 16, kind << 3);
default:
io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
"Data edit descriptor '%c' may not be used with an INTEGER data item",
edit.descriptor);
return false;
}
std::optional<int> remaining;
std::optional<char32_t> next;
bool negate{ScanNumericPrefix(io, edit, next, remaining)};
common::UnsignedInt128 value;
for (; next; next = io.NextInField(remaining)) {
char32_t ch{*next};
if (ch == ' ') {
if (edit.modes.editingFlags & blankZero) {
ch = '0'; // BZ mode - treat blank as if it were zero
} else {
continue;
}
}
int digit{0};
if (ch >= '0' && ch <= '9') {
digit = ch - '0';
} else {
io.GetIoErrorHandler().SignalError(
"Bad character '%lc' in INTEGER input field", ch);
return false;
}
value *= 10;
value += digit;
}
if (negate) {
value = -value;
}
std::memcpy(n, &value, kind);
return true;
}
static int ScanRealInput(char *buffer, int bufferSize, IoStatementState &io,
const DataEdit &edit, int &exponent) {
std::optional<int> remaining;
std::optional<char32_t> next;
int got{0};
std::optional<int> decimalPoint;
if (ScanNumericPrefix(io, edit, next, remaining) && next) {
if (got < bufferSize) {
buffer[got++] = '-';
}
}
if (!next) { // empty field means zero
if (got < bufferSize) {
buffer[got++] = '0';
}
return got;
}
if (got < bufferSize) {
buffer[got++] = '.'; // input field is normalized to a fraction
}
char32_t decimal = edit.modes.editingFlags & decimalComma ? ',' : '.';
auto start{got};
if ((*next >= 'a' && *next <= 'z') || (*next >= 'A' && *next <= 'Z')) {
// NaN or infinity - convert to upper case
for (; next &&
((*next >= 'a' && *next <= 'z') || (*next >= 'A' && *next <= 'Z'));
next = io.NextInField(remaining)) {
if (got < bufferSize) {
if (*next >= 'a' && *next <= 'z') {
buffer[got++] = *next - 'a' + 'A';
} else {
buffer[got++] = *next;
}
}
}
if (next && *next == '(') { // NaN(...)
while (next && *next != ')') {
next = io.NextInField(remaining);
}
}
exponent = 0;
} else if (*next == decimal || (*next >= '0' && *next <= '9')) {
for (; next; next = io.NextInField(remaining)) {
char32_t ch{*next};
if (ch == ' ') {
if (edit.modes.editingFlags & blankZero) {
ch = '0'; // BZ mode - treat blank as if it were zero
} else {
continue;
}
}
if (ch == '0' && got == start) {
// omit leading zeroes
} else if (ch >= '0' && ch <= '9') {
if (got < bufferSize) {
buffer[got++] = ch;
}
} else if (ch == decimal && !decimalPoint) {
// the decimal point is *not* copied to the buffer
decimalPoint = got - start; // # of digits before the decimal point
} else {
break;
}
}
if (got == start && got < bufferSize) {
buffer[got++] = '0'; // all digits were zeroes
}
if (next &&
(*next == 'e' || *next == 'E' || *next == 'd' || *next == 'D' ||
*next == 'q' || *next == 'Q')) {
io.SkipSpaces(remaining);
next = io.NextInField(remaining);
}
exponent = -edit.modes.scale; // default exponent is -kP
if (next &&
(*next == '-' || *next == '+' || (*next >= '0' && *next <= '9'))) {
bool negExpo{*next == '-'};
if (negExpo || *next == '+') {
next = io.NextInField(remaining);
}
for (exponent = 0; next && (*next >= '0' && *next <= '9');
next = io.NextInField(remaining)) {
exponent = 10 * exponent + *next - '0';
}
if (negExpo) {
exponent = -exponent;
}
}
if (decimalPoint) {
exponent += *decimalPoint;
} else {
// When no decimal point (or comma) appears in the value, the 'd'
// part of the edit descriptor must be interpreted as the number of
// digits in the value to be interpreted as being to the *right* of
// the assumed decimal point (13.7.2.3.2)
exponent += got - start - edit.digits.value_or(0);
}
} else {
// TODO: hex FP input
exponent = 0;
return 0;
}
if (remaining) {
while (next && *next == ' ') {
next = io.NextInField(remaining);
}
if (next) {
return 0; // error: unused nonblank character in fixed-width field
}
}
return got;
}
template <int binaryPrecision>
bool EditCommonRealInput(IoStatementState &io, const DataEdit &edit, void *n) {
static constexpr int maxDigits{
common::MaxDecimalConversionDigits(binaryPrecision)};
static constexpr int bufferSize{maxDigits + 18};
char buffer[bufferSize];
int exponent{0};
int got{ScanRealInput(buffer, maxDigits + 2, io, edit, exponent)};
if (got >= maxDigits + 2) {
io.GetIoErrorHandler().Crash("EditRealInput: buffer was too small");
return false;
}
if (got == 0) {
io.GetIoErrorHandler().SignalError("Bad REAL input value");
return false;
}
bool hadExtra{got > maxDigits};
if (exponent != 0) {
got += std::snprintf(&buffer[got], bufferSize - got, "e%d", exponent);
}
buffer[got] = '\0';
const char *p{buffer};
decimal::ConversionToBinaryResult<binaryPrecision> converted{
decimal::ConvertToBinary<binaryPrecision>(p, edit.modes.round)};
if (hadExtra) {
converted.flags = static_cast<enum decimal::ConversionResultFlags>(
converted.flags | decimal::Inexact);
}
// TODO: raise converted.flags as exceptions?
*reinterpret_cast<decimal::BinaryFloatingPointNumber<binaryPrecision> *>(n) =
converted.binary;
return true;
}
template <int binaryPrecision>
bool EditRealInput(IoStatementState &io, const DataEdit &edit, void *n) {
switch (edit.descriptor) {
case DataEdit::ListDirected:
case 'F':
case 'E': // incl. EN, ES, & EX
case 'D':
case 'G':
return EditCommonRealInput<binaryPrecision>(io, edit, n);
case 'B':
return EditBOZInput(
io, edit, n, 2, common::BitsForBinaryPrecision(binaryPrecision));
case 'O':
return EditBOZInput(
io, edit, n, 8, common::BitsForBinaryPrecision(binaryPrecision));
case 'Z':
return EditBOZInput(
io, edit, n, 16, common::BitsForBinaryPrecision(binaryPrecision));
default:
io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
"Data edit descriptor '%c' may not be used for REAL input",
edit.descriptor);
return false;
}
}
// 13.7.3 in Fortran 2018
bool EditLogicalInput(IoStatementState &io, const DataEdit &edit, bool &x) {
switch (edit.descriptor) {
case DataEdit::ListDirected:
case 'L':
case 'G':
break;
default:
io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
"Data edit descriptor '%c' may not be used for LOGICAL input",
edit.descriptor);
return false;
}
std::optional<int> remaining;
std::optional<char32_t> next{PrepareInput(io, edit, remaining)};
if (next && *next == '.') { // skip optional period
next = io.NextInField(remaining);
}
if (!next) {
io.GetIoErrorHandler().SignalError("Empty LOGICAL input field");
return false;
}
switch (*next) {
case 'T':
case 't':
x = true;
break;
case 'F':
case 'f':
x = false;
break;
default:
io.GetIoErrorHandler().SignalError(
"Bad character '%lc' in LOGICAL input field", *next);
return false;
}
if (remaining) { // ignore the rest of the field
io.HandleRelativePosition(*remaining);
}
return true;
}
// See 13.10.3.1 paragraphs 7-9 in Fortran 2018
static bool EditDelimitedCharacterInput(
IoStatementState &io, char *x, std::size_t length, char32_t delimiter) {
while (true) {
if (auto ch{io.GetCurrentChar()}) {
io.HandleRelativePosition(1);
if (*ch == delimiter) {
ch = io.GetCurrentChar();
if (ch && *ch == delimiter) {
// Repeated delimiter: use as character value. Can't straddle a
// record boundary.
io.HandleRelativePosition(1);
} else {
std::fill_n(x, length, ' ');
return true;
}
}
if (length > 0) {
*x++ = *ch;
--length;
}
} else if (!io.AdvanceRecord()) { // EOF
std::fill_n(x, length, ' ');
return false;
}
}
}
static bool EditListDirectedDefaultCharacterInput(
IoStatementState &io, char *x, std::size_t length) {
auto ch{io.GetCurrentChar()};
if (ch && (*ch == '\'' || *ch == '"')) {
io.HandleRelativePosition(1);
return EditDelimitedCharacterInput(io, x, length, *ch);
}
// Undelimited list-directed character input: stop at a value separator
// or the end of the current record.
std::optional<int> remaining{length};
for (std::optional<char32_t> next{io.NextInField(remaining)}; next;
next = io.NextInField(remaining)) {
switch (*next) {
case ' ':
case ',':
case ';':
case '/':
remaining = 0; // value separator: stop
break;
default:
*x++ = *next;
--length;
}
}
std::fill_n(x, length, ' ');
return true;
}
bool EditDefaultCharacterInput(
IoStatementState &io, const DataEdit &edit, char *x, std::size_t length) {
switch (edit.descriptor) {
case DataEdit::ListDirected:
return EditListDirectedDefaultCharacterInput(io, x, length);
case 'A':
case 'G':
break;
default:
io.GetIoErrorHandler().SignalError(IostatErrorInFormat,
"Data edit descriptor '%c' may not be used with a CHARACTER data item",
edit.descriptor);
return false;
}
std::optional<int> remaining{length};
if (edit.width && *edit.width > 0) {
remaining = *edit.width;
}
// When the field is wider than the variable, we drop the leading
// characters. When the variable is wider than the field, there's
// trailing padding.
std::int64_t skip{*remaining - static_cast<std::int64_t>(length)};
for (std::optional<char32_t> next{io.NextInField(remaining)}; next;
next = io.NextInField(remaining)) {
if (skip > 0) {
--skip;
} else {
*x++ = *next;
--length;
}
}
std::fill_n(x, length, ' ');
return true;
}
template bool EditRealInput<8>(IoStatementState &, const DataEdit &, void *);
template bool EditRealInput<11>(IoStatementState &, const DataEdit &, void *);
template bool EditRealInput<24>(IoStatementState &, const DataEdit &, void *);
template bool EditRealInput<53>(IoStatementState &, const DataEdit &, void *);
template bool EditRealInput<64>(IoStatementState &, const DataEdit &, void *);
template bool EditRealInput<113>(IoStatementState &, const DataEdit &, void *);
} // namespace Fortran::runtime::io
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: defines a RCon class used to send rcon commands to remote servers
//
// $NoKeywords: $
//=============================================================================
#include "playerlist.h"
#include "Iresponse.h"
#include "PlayerMsgHandler.h"
#include "Socket.h"
#include "proto_oob.h"
#include "DialogGameInfo.h"
#include "inetapi.h"
#include "TokenLine.h"
#include "dialogkickplayer.h"
extern void v_strncpy(char *dest, const char *src, int bufsize);
typedef enum
{
NONE = 0,
INFO_REQUESTED,
INFO_RECEIVED
} RCONSTATUS;
CPlayerList::CPlayerList(IResponse *target,serveritem_t &server, const char *rconPassword) {
memcpy(&m_Server, &server,sizeof(serveritem_t));
m_pResponseTarget=target;
m_bIsRefreshing=false;
m_bNewPlayerList=false;
m_bRconFailed=false;
v_strncpy(m_szRconPassword,rconPassword,100);
m_pRcon = new CRcon(this , server,rconPassword);
m_PlayerList=NULL;
m_pPlayerInfoMsg=NULL;
m_pQuery = new CSocket("internet player query", -1);
}
CPlayerList::~CPlayerList() {
delete m_pQuery;
delete m_pRcon;
}
//-----------------------------------------------------------------------------
// Purpose: sends a status query packet to a single server
//-----------------------------------------------------------------------------
void CPlayerList::SendQuery()
{
CMsgBuffer *buffer = m_pQuery->GetSendBuffer();
assert( buffer );
if ( !buffer )
{
return;
}
int bytecode = S2A_PLAYER;
if ( m_pPlayerInfoMsg != NULL )
{
delete m_pPlayerInfoMsg;
}
m_pPlayerInfoMsg=new CPlayerMsgHandlerDetails(this, &m_PlayerList,CMsgHandler::MSGHANDLER_ALL, &bytecode);
m_pQuery->AddMessageHandler(m_pPlayerInfoMsg);
m_bIsRefreshing=true;
netadr_t adr;
adr.ip[0] = m_Server.ip[0];
adr.ip[1] = m_Server.ip[1];
adr.ip[2] = m_Server.ip[2];
adr.ip[3] = m_Server.ip[3];
adr.port = (m_Server.port & 0xff) << 8 | (m_Server.port & 0xff00) >> 8;
adr.type = NA_IP;
// Set state
m_Server.received = (int)INFO_REQUESTED;
// Create query message
buffer->Clear();
// Write control sequence
buffer->WriteLong(0xffffffff);
// Write query string
buffer->WriteString("players");
// Sendmessage
m_pQuery->SendMessage( &adr );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CPlayerList::RunFrame()
{
if (m_pQuery && m_bIsRefreshing)
{
m_pQuery->Frame();
}
if(m_pRcon)
{
m_pRcon->RunFrame();
}
}
void CPlayerList::ServerResponded()
{
const char *rconResp = m_pRcon->RconResponse();
const char *cur = strstr(rconResp,"name userid uniqueid frag time ping loss adr\n")
+ strlen("name userid uniqueid frag time ping loss adr\n");
// status format:
// # name userid uniqueid frag time ping loss adr
// # 1 "Player" 1 4294967295 0 30:56 22 0 192.168.3.64:27005
for(int i=0;i<m_PlayerList.Count();i++)
{
if(cur!=NULL)
{
TokenLine playerLine;
playerLine.SetLine(cur);
if(playerLine.CountToken() >= 9 )
{
// playerLine.GetToken(1); // count
// playerLine.GetToken(2); // player name
// char *player= playerLine.GetToken(2);
m_PlayerList[i].userid=atoi(playerLine.GetToken(3)); // userid
v_strncpy(m_PlayerList[i].authid,playerLine.GetToken(4),20); // authid
//playerLine.GetToken(5); // frag
// playerLine.GetToken(6); // time
m_PlayerList[i].ping=atoi(playerLine.GetToken(7)); //ping
m_PlayerList[i].loss=atoi(playerLine.GetToken(8)); // loss
// playerLine.GetToken(9); // adr
}
cur=strchr(cur,'\n')+1;
}
}
m_bNewPlayerList=true;
m_bIsRefreshing=false;
// notify the UI of the new server info
m_pResponseTarget->ServerResponded();
}
void CPlayerList::ServerFailedToRespond()
{
m_bNewPlayerList=true;
m_bIsRefreshing=false;
if(m_bRconFailed==false)
{
m_bRconFailed=true;
// CDialogKickPlayer *box = new CDialogKickPlayer();
//box->addActionSignalTarget(this);
// box->Activate("","Bad Rcon Password","badrcon");
}
// rcon failed BUT we still have some valid data :)
m_pResponseTarget->ServerResponded();
}
void CPlayerList::UpdateServer()
{
m_pQuery->RemoveMessageHandler(m_pPlayerInfoMsg);
// you CANNOT delete this handler because we are inside of it at the moment... (yes, this was an ugly bug)
// delete m_pPlayerInfoMsg;
// now use "rcon status" to pull extra info about the players
m_pRcon->SendRcon("status");
}
void CPlayerList::Refresh()
{
SendQuery();
}
bool CPlayerList::IsRefreshing()
{
return m_bIsRefreshing;
}
serveritem_t &CPlayerList::GetServer()
{
return m_Server;
}
bool CPlayerList::NewPlayerList()
{
return m_bNewPlayerList;
}
CUtlVector<Players_t> *CPlayerList::GetPlayerList()
{
m_bNewPlayerList=false;
return &m_PlayerList;
}
void CPlayerList::SetPassword(const char *newPass)
{
m_pRcon->SetPassword(newPass);
m_bRconFailed=false;
}
|
/*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.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., 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 the copyright holders 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*/
#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__
#if _MSC_VER >= 1200
#pragma warning( disable: 4251 4710 4711 4514 4996 ) /* function AAA selected for automatic inline expansion */
#endif
#include "opencv2/video/tracking.hpp"
#include "opencv2/video/blobtrack.hpp"
#include "opencv2/video/background_segm.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/internal.hpp"
#endif
|
/*
* Briefing
* Dokumentacja: https://community.bistudio.com/wiki/createDiaryRecord
*/
/*
INFO: Jeśli chcesz użyć stringtable w briefingu, pamiętaj aby zamienić:
& na &
< na <
> na >
" na "
' na '
Wtedy możesz smiało użyć stringtable (przykład w stringtable.xml) i zamienić wpis
briefingu na "player createDiaryRecord ["Diary", ["Briefing", LLSTRING(Briefing)]];"
"
*/
private _adm = player createDiaryRecord ["diary", ["Techniczne","
<br/>
Interakcje pod menu interakcji.<br/>
Uważnie czytać znaleziony intel.<br/>
"]];
// NOTES: SITUATION
private _sit = player createDiaryRecord ["diary", ["Sytuacja","
Połowa 1974. <br/><br/>
Większość sił USA powoli wraca do kraju. Odpowiedzialność za utrzymanie kontroli zostaje przekazana na ręce ARVN, który niestety nie radzi sobie za dobrze z powierzonym zadaniem - w krótkim czasie siły Północy zdobywają znaczną część terenów Południa.
W Wietnamie pozostaje jeszcze komponent lotniczy oraz siły specjalne, które ewakuują zgromadzone dane oraz niszczą pozostawiony sprzęt, starają się także opóźnić ofensywę NVA.<br/><br/>
W rolę jednego z takich oddziałów wcielicie się wy. Będziecie sabotować linie zaopatrzenia wroga, przecinać komunikację, wysadzać tunele - aby dać czas pozostałym siłom na ewakuację.
Zaczynacie w helikopterze lecącym z południowego lotniska, na którym wysadziliście pozostawiony sprzęt.
"]];
|
// --------------------------------------------------
//
// (C) Copyright Chuck Allison and Jeremy Siek 2001 - 2002.
// (C) Copyright Gennaro Prota 2003 - 2006.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// -----------------------------------------------------------
// See http://www.boost.org/libs/dynamic_bitset/ for documentation.
//
// $Revision: 41369 $ $Date: 2007-11-25 13:07:19 -0500 (Sun, 25 Nov 2007) $ - $Name$
#ifndef BOOST_DYNAMIC_BITSET_CONFIG_HPP_GP_20040424
#define BOOST_DYNAMIC_BITSET_CONFIG_HPP_GP_20040424
#include "boost/config.hpp"
#include "boost/detail/workaround.hpp"
// support for pre 3.0 libstdc++ - thanks Phil Edwards!
#if defined (__STL_CONFIG_H) && !defined (__STL_USE_NEW_IOSTREAMS)
# define BOOST_OLD_IOSTREAMS
#endif
// this should be in the config system some day
// see http://lists.boost.org/MailArchives/boost/msg62291.php
#define BOOST_DYNAMIC_BITSET_GNUC_VERSION ( __GNUC__ * 100 * 100 \
+ __GNUC_MINOR__ * 100)
// no-op function to workaround gcc bug c++/8419
//
namespace boost { namespace detail {
template <typename T> T make_non_const(T t) { return t; }
}}
#if defined(__GNUC__) && BOOST_WORKAROUND(BOOST_DYNAMIC_BITSET_GNUC_VERSION, \
BOOST_TESTED_AT(30300))
# define BOOST_DYNAMIC_BITSET_WRAP_CONSTANT(expr) \
(boost::detail::make_non_const(expr))
#else
# define BOOST_DYNAMIC_BITSET_WRAP_CONSTANT(expr) (expr)
#endif
//
#if (defined __BORLANDC__ && BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))) \
|| (defined BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
#define BOOST_DYNAMIC_BITSET_DONT_USE_FRIENDS
#endif
// if we can't use friends then we simply expose private members
//
#if defined(BOOST_DYNAMIC_BITSET_DONT_USE_FRIENDS)
#define BOOST_DYNAMIC_BITSET_PRIVATE public
#else
#define BOOST_DYNAMIC_BITSET_PRIVATE private
#endif
// A couple of macros to cope with libraries without locale
// support. The first macro must be used to declare a reference
// to a ctype facet. The second one to widen a char by using
// that ctype object. If facets and locales aren't available
// the first macro is a no-op and the second one just expands
// to its parameter c.
//
#if defined (BOOST_USE_FACET)
#define BOOST_DYNAMIC_BITSET_CTYPE_FACET(ch, name, loc) \
const std::ctype<ch> & name = \
BOOST_USE_FACET(std::ctype<ch>, loc) /**/
#define BOOST_DYNAMIC_BITSET_WIDEN_CHAR(fac, c) \
(fac.widen(c))
#else
#define BOOST_DYNAMIC_BITSET_CTYPE_FACET(ch, name, loc) /**/
#define BOOST_DYNAMIC_BITSET_WIDEN_CHAR(fac, c) c
#endif
#endif // include guard
|
//
// cross_check.cpp
// MEDYAN
//
// Created by Aravind Chandrasekaran on 9/6/17.
// Copyright © 2017 University of Maryland. All rights reserved.
//
#include <stdio.h>
#include "cross_check.h"
bool cross_checkclass::Aux=false;
|
#include "key.h"
Key::Key(){
}
Key::Key( int x , int y ){ // OUR CONSTRUCTOR. Notice no default constructor
posX = x * 64.f; // as there will be no given situation where
posY = y * 64.f;
gridX = x;
gridY = y;
velX = 0;
velY = 0;
float sxmax = 0;
float symax = 0;
float sxmin = 0;
float symin = 0;
a_loader.loadObj( "resource/models/key.obj" , vertices , indices , normals , texcoords );
texture = a_loader.loadImage( "resource/materials/models/tex_key.raw" );
for( unsigned int i=0; i < vertices.size() ; ++i )
{
if( vertices[i] < sxmin ) { sxmin = vertices[i]; }
if( vertices[i] > sxmax ) { sxmax = vertices[i]; }
vertices[i] = vertices[i];
++i;
if( vertices[i] < symin ) { symin = vertices[i]; }
if( vertices[i] > symax ) { symax = vertices[i]; }
vertices[i] = vertices[i];
++i;
}
sizeX = sxmax - sxmin;
sizeY = symax - symin;
}
void Key::draw() { // DRAW OBJECT (basically each draw draws the array storing vertex information)
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDepthMask( false );
glEnable( GL_TEXTURE_2D );
glVertexPointer( 3 , GL_FLOAT , 0 , &vertices[0] );
glNormalPointer( GL_FLOAT, 0 , &normals[0] );
glTexCoordPointer( 3 , GL_FLOAT , 0 , &texcoords[0] );
glPushMatrix();
glTranslatef(posX , posY , 0 );
glBindTexture( GL_TEXTURE_2D , texture );
glDrawArrays(GL_TRIANGLES, 0 , (GLsizei)vertices.size()/3 );
glPopMatrix();
glDisable( GL_TEXTURE_2D );
glDepthMask( true );
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
|
#include "Intel8080Emulator.h"
Compucolor::Impl::Intel8080::Intel8080Emulator::Intel8080Emulator(
std::shared_ptr<Compucolor::Memory::IMemory> memory
):
_context(
std::unique_ptr<Compucolor::Impl::Intel8080::Intel8080EmulatorContext>(
new Compucolor::Impl::Intel8080::Intel8080EmulatorContext()
)
),
_cpu(
std::unique_ptr<Compucolor::Impl::Intel8080::i8080>(
new Compucolor::Impl::Intel8080::i8080()
)
),
_memory(memory)
{
_context->SetMemory(_memory);
}
void Compucolor::Impl::Intel8080::Intel8080Emulator::Start()
{
Compucolor::Impl::Intel8080::i8080_init(_cpu.get());
_cpu->read_byte = Intel8080Emulator::ReadByte;
_cpu->write_byte = Intel8080Emulator::WriteByte;
_cpu->port_in = Intel8080Emulator::ReadPort;
_cpu->port_out = Intel8080Emulator::WritePort;
_cpu->userdata = _context.get();
}
void Compucolor::Impl::Intel8080::Intel8080Emulator::Step()
{
Compucolor::Impl::Intel8080::i8080_step(_cpu.get());
}
void Compucolor::Impl::Intel8080::Intel8080Emulator::Stop()
{
}
void Compucolor::Impl::Intel8080::Intel8080Emulator::Reset()
{
Stop();
//TODO:
//reset cpu state
Start();
}
void Compucolor::Impl::Intel8080::Intel8080Emulator::SetBus(std::shared_ptr<Compucolor::Intel8080::IIntel8080Bus> intel8080Bus)
{
_context->SetBus(intel8080Bus);
}
void Compucolor::Impl::Intel8080::Intel8080Emulator::RegisterInterrupt(uint8_t opcode)
{
Compucolor::Impl::Intel8080::i8080_interrupt(_cpu.get(), opcode);
}
std::shared_ptr<Compucolor::Intel8080::IIntel8080Emulator> Compucolor::Impl::Intel8080::Intel8080Emulator::Creator(
Compucolor::Common::IPluginManager* manager
)
{
return std::shared_ptr<Compucolor::Intel8080::IIntel8080Emulator>(
new Compucolor::Impl::Intel8080::Intel8080Emulator(manager->GetMemory())
);
}
uint8_t Compucolor::Impl::Intel8080::Intel8080Emulator::ReadByte(void* userdata, uint16_t addr)
{
std::optional<std::shared_ptr<Compucolor::Memory::IMemory>> memory =
((Compucolor::Impl::Intel8080::Intel8080EmulatorContext*)userdata)->GetMemory();
if (memory.has_value())
{
return memory.value()->GetByte(addr);
}
return (uint8_t)0x00;
}
void Compucolor::Impl::Intel8080::Intel8080Emulator::WriteByte(void* userdata, uint16_t addr, uint8_t data)
{
std::optional<std::shared_ptr<Compucolor::Memory::IMemory>> memory =
((Compucolor::Impl::Intel8080::Intel8080EmulatorContext*)userdata)->GetMemory();
if (memory.has_value())
{
//Only write above the 0-3fff rom.
if (addr >= 0x4000)
{
memory.value()->SetByte(addr, data);
}
}
}
uint8_t Compucolor::Impl::Intel8080::Intel8080Emulator::ReadPort(void* userdata, uint8_t port)
{
std::optional<std::shared_ptr<Compucolor::Intel8080::IIntel8080Bus>> bus =
((Compucolor::Impl::Intel8080::Intel8080EmulatorContext*)userdata)->GetBus();
if (bus.has_value())
{
return bus.value()->Read(port);
}
return (uint8_t)0x00;
}
void Compucolor::Impl::Intel8080::Intel8080Emulator::WritePort(void* userdata, uint8_t port, uint8_t data)
{
std::optional<std::shared_ptr<Compucolor::Intel8080::IIntel8080Bus>> bus =
((Compucolor::Impl::Intel8080::Intel8080EmulatorContext*)userdata)->GetBus();
if (bus.has_value())
{
return bus.value()->Write(port, data);
}
}
|
///////////////////////////////////////////////////////////////////////
// C Implementation of Wu's Color Quantizer (v. 2)
// (see Graphics Gems vol. II, pp. 126-133)
//
// Author: Xiaolin Wu
// Dept. of Computer Science
// Univ. of Western Ontario
// London, Ontario N6A 5B7
// wu@csd.uwo.ca
//
// Algorithm: Greedy orthogonal bipartition of RGB space for variance
// minimization aided by inclusion-exclusion tricks.
// For speed no nearest neighbor search is done. Slightly
// better performance can be expected by more sophisticated
// but more expensive versions.
//
// The author thanks Tom Lane at Tom_Lane@G.GP.CS.CMU.EDU for much of
// additional documentation and a cure to a previous bug.
//
// Free to distribute, comments and suggestions are appreciated.
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// History
// -------
// July 2000: C++ Implementation of Wu's Color Quantizer
// and adaptation for the FreeImage 2 Library
// Author: Herv?Drolon (drolon@infonie.fr)
// March 2004: Adaptation for the FreeImage 3 library (port to big endian processors)
// Author: Herv?Drolon (drolon@infonie.fr)
///////////////////////////////////////////////////////////////////////
#include "Quantizers.h"
#include "FreeImage.h"
#include "Utilities.h"
///////////////////////////////////////////////////////////////////////
// Size of a 3D array : 33 x 33 x 33
#define SIZE_3D 35937
// 3D array indexation
#define INDEX(r, g, b) ((r << 10) + (r << 6) + r + (g << 5) + g + b)
#define MAXCOLOR 256
// Constructor / Destructor
WuQuantizer::WuQuantizer(FIBITMAP *dib) {
width = FreeImage_GetWidth(dib);
height = FreeImage_GetHeight(dib);
pitch = FreeImage_GetPitch(dib);
m_dib = dib;
gm2 = NULL;
wt = mr = mg = mb = NULL;
Qadd = NULL;
// Allocate 3D arrays
gm2 = (float*)malloc(SIZE_3D * sizeof(float));
wt = (LONG*)malloc(SIZE_3D * sizeof(LONG));
mr = (LONG*)malloc(SIZE_3D * sizeof(LONG));
mg = (LONG*)malloc(SIZE_3D * sizeof(LONG));
mb = (LONG*)malloc(SIZE_3D * sizeof(LONG));
// Allocate Qadd
Qadd = (WORD *)malloc(sizeof(WORD) * width * height);
if(!gm2 || !wt || !mr || !mg || !mb || !Qadd) {
if(gm2) free(gm2);
if(wt) free(wt);
if(mr) free(mr);
if(mg) free(mg);
if(mb) free(mb);
if(Qadd) free(Qadd);
throw FI_MSG_ERROR_MEMORY;
}
memset(gm2, 0, SIZE_3D * sizeof(float));
memset(wt, 0, SIZE_3D * sizeof(LONG));
memset(mr, 0, SIZE_3D * sizeof(LONG));
memset(mg, 0, SIZE_3D * sizeof(LONG));
memset(mb, 0, SIZE_3D * sizeof(LONG));
memset(Qadd, 0, sizeof(WORD) * width * height);
}
WuQuantizer::~WuQuantizer() {
if(gm2) free(gm2);
if(wt) free(wt);
if(mr) free(mr);
if(mg) free(mg);
if(mb) free(mb);
if(Qadd) free(Qadd);
}
// Histogram is in elements 1..HISTSIZE along each axis,
// element 0 is for base or marginal value
// NB: these must start out 0!
// Build 3-D color histogram of counts, r/g/b, c^2
void
WuQuantizer::Hist3D(LONG *vwt, LONG *vmr, LONG *vmg, LONG *vmb, float *m2, int ReserveSize, RGBQUAD *ReservePalette) {
int ind = 0;
int inr, ing, inb, table[256];
int i;
unsigned y, x;
for(i = 0; i < 256; i++)
table[i] = i * i;
if (FreeImage_GetBPP(m_dib) == 24) {
for(y = 0; y < height; y++) {
BYTE *bits = FreeImage_GetScanLine(m_dib, y);
for(x = 0; x < width; x++) {
inr = (bits[FI_RGBA_RED] >> 3) + 1;
ing = (bits[FI_RGBA_GREEN] >> 3) + 1;
inb = (bits[FI_RGBA_BLUE] >> 3) + 1;
ind = INDEX(inr, ing, inb);
Qadd[y*width + x] = (WORD)ind;
// [inr][ing][inb]
vwt[ind]++;
vmr[ind] += bits[FI_RGBA_RED];
vmg[ind] += bits[FI_RGBA_GREEN];
vmb[ind] += bits[FI_RGBA_BLUE];
m2[ind] += (float)(table[bits[FI_RGBA_RED]] + table[bits[FI_RGBA_GREEN]] + table[bits[FI_RGBA_BLUE]]);
bits += 3;
}
}
} else {
for(y = 0; y < height; y++) {
BYTE *bits = FreeImage_GetScanLine(m_dib, y);
for(x = 0; x < width; x++) {
inr = (bits[FI_RGBA_RED] >> 3) + 1;
ing = (bits[FI_RGBA_GREEN] >> 3) + 1;
inb = (bits[FI_RGBA_BLUE] >> 3) + 1;
ind = INDEX(inr, ing, inb);
Qadd[y*width + x] = (WORD)ind;
// [inr][ing][inb]
vwt[ind]++;
vmr[ind] += bits[FI_RGBA_RED];
vmg[ind] += bits[FI_RGBA_GREEN];
vmb[ind] += bits[FI_RGBA_BLUE];
m2[ind] += (float)(table[bits[FI_RGBA_RED]] + table[bits[FI_RGBA_GREEN]] + table[bits[FI_RGBA_BLUE]]);
bits += 4;
}
}
}
if( ReserveSize > 0 ) {
int max = 0;
for(i = 0; i < SIZE_3D; i++) {
if( vwt[i] > max ) max = vwt[i];
}
max++;
for(i = 0; i < ReserveSize; i++) {
inr = (ReservePalette[i].rgbRed >> 3) + 1;
ing = (ReservePalette[i].rgbGreen >> 3) + 1;
inb = (ReservePalette[i].rgbBlue >> 3) + 1;
ind = INDEX(inr, ing, inb);
wt[ind] = max;
mr[ind] = max * ReservePalette[i].rgbRed;
mg[ind] = max * ReservePalette[i].rgbGreen;
mb[ind] = max * ReservePalette[i].rgbBlue;
gm2[ind] = (float)max * (float)(table[ReservePalette[i].rgbRed] + table[ReservePalette[i].rgbGreen] + table[ReservePalette[i].rgbBlue]);
}
}
}
// At conclusion of the histogram step, we can interpret
// wt[r][g][b] = sum over voxel of P(c)
// mr[r][g][b] = sum over voxel of r*P(c) , similarly for mg, mb
// m2[r][g][b] = sum over voxel of c^2*P(c)
// Actually each of these should be divided by 'ImageSize' to give the usual
// interpretation of P() as ranging from 0 to 1, but we needn't do that here.
// We now convert histogram into moments so that we can rapidly calculate
// the sums of the above quantities over any desired box.
// Compute cumulative moments
void
WuQuantizer::M3D(LONG *vwt, LONG *vmr, LONG *vmg, LONG *vmb, float *m2) {
unsigned ind1, ind2;
BYTE i, r, g, b;
LONG line, line_r, line_g, line_b;
LONG area[33], area_r[33], area_g[33], area_b[33];
float line2, area2[33];
for(r = 1; r <= 32; r++) {
for(i = 0; i <= 32; i++) {
area2[i] = 0;
area[i] = area_r[i] = area_g[i] = area_b[i] = 0;
}
for(g = 1; g <= 32; g++) {
line2 = 0;
line = line_r = line_g = line_b = 0;
for(b = 1; b <= 32; b++) {
ind1 = INDEX(r, g, b); // [r][g][b]
line += vwt[ind1];
line_r += vmr[ind1];
line_g += vmg[ind1];
line_b += vmb[ind1];
line2 += m2[ind1];
area[b] += line;
area_r[b] += line_r;
area_g[b] += line_g;
area_b[b] += line_b;
area2[b] += line2;
ind2 = ind1 - 1089; // [r-1][g][b]
vwt[ind1] = vwt[ind2] + area[b];
vmr[ind1] = vmr[ind2] + area_r[b];
vmg[ind1] = vmg[ind2] + area_g[b];
vmb[ind1] = vmb[ind2] + area_b[b];
m2[ind1] = m2[ind2] + area2[b];
}
}
}
}
// Compute sum over a box of any given statistic
LONG
WuQuantizer::Vol( Box *cube, LONG *mmt ) {
return( mmt[INDEX(cube->r1, cube->g1, cube->b1)]
- mmt[INDEX(cube->r1, cube->g1, cube->b0)]
- mmt[INDEX(cube->r1, cube->g0, cube->b1)]
+ mmt[INDEX(cube->r1, cube->g0, cube->b0)]
- mmt[INDEX(cube->r0, cube->g1, cube->b1)]
+ mmt[INDEX(cube->r0, cube->g1, cube->b0)]
+ mmt[INDEX(cube->r0, cube->g0, cube->b1)]
- mmt[INDEX(cube->r0, cube->g0, cube->b0)] );
}
// The next two routines allow a slightly more efficient calculation
// of Vol() for a proposed subbox of a given box. The sum of Top()
// and Bottom() is the Vol() of a subbox split in the given direction
// and with the specified new upper bound.
// Compute part of Vol(cube, mmt) that doesn't depend on r1, g1, or b1
// (depending on dir)
LONG
WuQuantizer::Bottom(Box *cube, BYTE dir, LONG *mmt) {
switch(dir)
{
case FI_RGBA_RED:
return( - mmt[INDEX(cube->r0, cube->g1, cube->b1)]
+ mmt[INDEX(cube->r0, cube->g1, cube->b0)]
+ mmt[INDEX(cube->r0, cube->g0, cube->b1)]
- mmt[INDEX(cube->r0, cube->g0, cube->b0)] );
break;
case FI_RGBA_GREEN:
return( - mmt[INDEX(cube->r1, cube->g0, cube->b1)]
+ mmt[INDEX(cube->r1, cube->g0, cube->b0)]
+ mmt[INDEX(cube->r0, cube->g0, cube->b1)]
- mmt[INDEX(cube->r0, cube->g0, cube->b0)] );
break;
case FI_RGBA_BLUE:
return( - mmt[INDEX(cube->r1, cube->g1, cube->b0)]
+ mmt[INDEX(cube->r1, cube->g0, cube->b0)]
+ mmt[INDEX(cube->r0, cube->g1, cube->b0)]
- mmt[INDEX(cube->r0, cube->g0, cube->b0)] );
break;
}
return 0;
}
// Compute remainder of Vol(cube, mmt), substituting pos for
// r1, g1, or b1 (depending on dir)
LONG
WuQuantizer::Top(Box *cube, BYTE dir, int pos, LONG *mmt) {
switch(dir)
{
case FI_RGBA_RED:
return( mmt[INDEX(pos, cube->g1, cube->b1)]
-mmt[INDEX(pos, cube->g1, cube->b0)]
-mmt[INDEX(pos, cube->g0, cube->b1)]
+mmt[INDEX(pos, cube->g0, cube->b0)] );
break;
case FI_RGBA_GREEN:
return( mmt[INDEX(cube->r1, pos, cube->b1)]
-mmt[INDEX(cube->r1, pos, cube->b0)]
-mmt[INDEX(cube->r0, pos, cube->b1)]
+mmt[INDEX(cube->r0, pos, cube->b0)] );
break;
case FI_RGBA_BLUE:
return( mmt[INDEX(cube->r1, cube->g1, pos)]
-mmt[INDEX(cube->r1, cube->g0, pos)]
-mmt[INDEX(cube->r0, cube->g1, pos)]
+mmt[INDEX(cube->r0, cube->g0, pos)] );
break;
}
return 0;
}
// Compute the weighted variance of a box
// NB: as with the raw statistics, this is really the variance * ImageSize
float
WuQuantizer::Var(Box *cube) {
float dr = (float) Vol(cube, mr);
float dg = (float) Vol(cube, mg);
float db = (float) Vol(cube, mb);
float xx = gm2[INDEX(cube->r1, cube->g1, cube->b1)]
-gm2[INDEX(cube->r1, cube->g1, cube->b0)]
-gm2[INDEX(cube->r1, cube->g0, cube->b1)]
+gm2[INDEX(cube->r1, cube->g0, cube->b0)]
-gm2[INDEX(cube->r0, cube->g1, cube->b1)]
+gm2[INDEX(cube->r0, cube->g1, cube->b0)]
+gm2[INDEX(cube->r0, cube->g0, cube->b1)]
-gm2[INDEX(cube->r0, cube->g0, cube->b0)];
return (xx - (dr*dr+dg*dg+db*db)/(float)Vol(cube,wt));
}
// We want to minimize the sum of the variances of two subboxes.
// The sum(c^2) terms can be ignored since their sum over both subboxes
// is the same (the sum for the whole box) no matter where we split.
// The remaining terms have a minus sign in the variance formula,
// so we drop the minus sign and MAXIMIZE the sum of the two terms.
float
WuQuantizer::Maximize(Box *cube, BYTE dir, int first, int last , int *cut, LONG whole_r, LONG whole_g, LONG whole_b, LONG whole_w) {
LONG half_r, half_g, half_b, half_w;
int i;
float temp;
LONG base_r = Bottom(cube, dir, mr);
LONG base_g = Bottom(cube, dir, mg);
LONG base_b = Bottom(cube, dir, mb);
LONG base_w = Bottom(cube, dir, wt);
float max = 0.0;
*cut = -1;
for (i = first; i < last; i++) {
half_r = base_r + Top(cube, dir, i, mr);
half_g = base_g + Top(cube, dir, i, mg);
half_b = base_b + Top(cube, dir, i, mb);
half_w = base_w + Top(cube, dir, i, wt);
// now half_x is sum over lower half of box, if split at i
if (half_w == 0) { // subbox could be empty of pixels!
continue; // never split into an empty box
} else {
temp = ((float)half_r*half_r + (float)half_g*half_g + (float)half_b*half_b)/half_w;
}
half_r = whole_r - half_r;
half_g = whole_g - half_g;
half_b = whole_b - half_b;
half_w = whole_w - half_w;
if (half_w == 0) { // subbox could be empty of pixels!
continue; // never split into an empty box
} else {
temp += ((float)half_r*half_r + (float)half_g*half_g + (float)half_b*half_b)/half_w;
}
if (temp > max) {
max=temp;
*cut=i;
}
}
return max;
}
bool
WuQuantizer::Cut(Box *set1, Box *set2) {
BYTE dir;
int cutr, cutg, cutb;
LONG whole_r = Vol(set1, mr);
LONG whole_g = Vol(set1, mg);
LONG whole_b = Vol(set1, mb);
LONG whole_w = Vol(set1, wt);
float maxr = Maximize(set1, FI_RGBA_RED, set1->r0+1, set1->r1, &cutr, whole_r, whole_g, whole_b, whole_w);
float maxg = Maximize(set1, FI_RGBA_GREEN, set1->g0+1, set1->g1, &cutg, whole_r, whole_g, whole_b, whole_w);
float maxb = Maximize(set1, FI_RGBA_BLUE, set1->b0+1, set1->b1, &cutb, whole_r, whole_g, whole_b, whole_w);
if ((maxr >= maxg) && (maxr >= maxb)) {
dir = FI_RGBA_RED;
if (cutr < 0) {
return false; // can't split the box
}
} else if ((maxg >= maxr) && (maxg>=maxb)) {
dir = FI_RGBA_GREEN;
} else {
dir = FI_RGBA_BLUE;
}
set2->r1 = set1->r1;
set2->g1 = set1->g1;
set2->b1 = set1->b1;
switch (dir) {
case FI_RGBA_RED:
set2->r0 = set1->r1 = cutr;
set2->g0 = set1->g0;
set2->b0 = set1->b0;
break;
case FI_RGBA_GREEN:
set2->g0 = set1->g1 = cutg;
set2->r0 = set1->r0;
set2->b0 = set1->b0;
break;
case FI_RGBA_BLUE:
set2->b0 = set1->b1 = cutb;
set2->r0 = set1->r0;
set2->g0 = set1->g0;
break;
}
set1->vol = (set1->r1-set1->r0)*(set1->g1-set1->g0)*(set1->b1-set1->b0);
set2->vol = (set2->r1-set2->r0)*(set2->g1-set2->g0)*(set2->b1-set2->b0);
return true;
}
void
WuQuantizer::Mark(Box *cube, int label, BYTE *tag) {
for (int r = cube->r0 + 1; r <= cube->r1; r++) {
for (int g = cube->g0 + 1; g <= cube->g1; g++) {
for (int b = cube->b0 + 1; b <= cube->b1; b++) {
tag[INDEX(r, g, b)] = (BYTE)label;
}
}
}
}
// Wu Quantization algorithm
FIBITMAP *
WuQuantizer::Quantize(int PaletteSize, int ReserveSize, RGBQUAD *ReservePalette) {
BYTE *tag = NULL;
try {
Box cube[MAXCOLOR];
int next;
LONG i, weight;
int k;
float vv[MAXCOLOR], temp;
// Compute 3D histogram
Hist3D(wt, mr, mg, mb, gm2, ReserveSize, ReservePalette);
// Compute moments
M3D(wt, mr, mg, mb, gm2);
cube[0].r0 = cube[0].g0 = cube[0].b0 = 0;
cube[0].r1 = cube[0].g1 = cube[0].b1 = 32;
next = 0;
for (i = 1; i < PaletteSize; i++) {
if(Cut(&cube[next], &cube[i])) {
// volume test ensures we won't try to cut one-cell box
vv[next] = (cube[next].vol > 1) ? Var(&cube[next]) : 0;
vv[i] = (cube[i].vol > 1) ? Var(&cube[i]) : 0;
} else {
vv[next] = 0.0; // don't try to split this box again
i--; // didn't create box i
}
next = 0; temp = vv[0];
for (k = 1; k <= i; k++) {
if (vv[k] > temp) {
temp = vv[k]; next = k;
}
}
if (temp <= 0.0) {
PaletteSize = i + 1;
// Error: "Only got 'PaletteSize' boxes"
break;
}
}
// Partition done
// the space for array gm2 can be freed now
free(gm2);
gm2 = NULL;
// Allocate a new dib
FIBITMAP *new_dib = FreeImage_Allocate(width, height, 8);
if (new_dib == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
// create an optimized palette
RGBQUAD *new_pal = FreeImage_GetPalette(new_dib);
tag = (BYTE*) malloc(SIZE_3D * sizeof(BYTE));
if (tag == NULL) {
throw FI_MSG_ERROR_MEMORY;
}
memset(tag, 0, SIZE_3D * sizeof(BYTE));
for (k = 0; k < PaletteSize ; k++) {
Mark(&cube[k], k, tag);
weight = Vol(&cube[k], wt);
if (weight) {
new_pal[k].rgbRed = (BYTE)(((float)Vol(&cube[k], mr) / (float)weight) + 0.5f);
new_pal[k].rgbGreen = (BYTE)(((float)Vol(&cube[k], mg) / (float)weight) + 0.5f);
new_pal[k].rgbBlue = (BYTE)(((float)Vol(&cube[k], mb) / (float)weight) + 0.5f);
} else {
// Error: bogus box 'k'
new_pal[k].rgbRed = new_pal[k].rgbGreen = new_pal[k].rgbBlue = 0;
}
}
int npitch = FreeImage_GetPitch(new_dib);
for (unsigned y = 0; y < height; y++) {
BYTE *new_bits = FreeImage_GetBits(new_dib) + (y * npitch);
for (unsigned x = 0; x < width; x++) {
new_bits[x] = tag[Qadd[y*width + x]];
}
}
// output 'new_pal' as color look-up table contents,
// 'new_bits' as the quantized image (array of table addresses).
free(tag);
return (FIBITMAP*) new_dib;
} catch(...) {
free(tag);
}
return NULL;
}
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkNeighborhood.h"
#include "itkVector.h"
static void println(const char *s)
{
std::cout << std::endl << s << std::endl;
}
int itkNeighborhoodTest(int, char* [] )
{
unsigned int i;
println("TESTING WITH VNL_VECTOR ALLOCATOR");
itk::Neighborhood<float, 2, vnl_vector<float> > b;
b.SetRadius(3);
println("Test data access");
for (i=0; i<b.Size(); ++i) b[i] = (float)i;
b.Print(std::cout);
println("Test non_const iterators");
for (itk::Neighborhood<float, 2>::Iterator it = b.Begin();
it < b.End(); ++it) *it = 4.0f;
b.Print(std::cout);
println("Test const_iterators");
for (itk::Neighborhood<float, 2>::ConstIterator itc = b.Begin();
itc < b.End(); ++itc) std::cout << *itc << " ";
println("Copy the buffer into a vnl_vector");
vnl_vector<float> v = b.GetBufferReference();
v[2] = 0.0f;
std::cout << &v << std::endl;
b.Print(std::cout); // b unmodified
println("Pointer to the buffer with a const vnl_vector");
const vnl_vector<float> &vcp = b.GetBufferReference();
std::cout << &vcp << std::endl;
std::cout << vcp;
println("Point to the buffer using a vnl_vector");
vnl_vector<float> &vp = b.GetBufferReference();
std::cout << &vp << std::endl;
vp[2] = 0.0f;
b.Print(std::cout); // b modified
println("TESTING WITH DEFAULT ALLOCATOR");
itk::Neighborhood<float, 2> q;
itk::Size<2> rad;
rad[0] = 3;
rad[1] = 2;
q.SetRadius(rad);
q.Print(std::cout);
println("Testing assignment operator");
itk::Neighborhood<float, 2> p = q;
p.Print(std::cout);
println("Testing copy constructor");
itk::Neighborhood<float, 2> r(q);
r.Print(std::cout);
println("Testing instantiation with itk::Vector");
itk::Neighborhood< itk::Vector<float, 3>, 2 > s;
s.SetRadius(rad);
s.Print(std::cout);
println("Testing stride lengths");
itk::Neighborhood<float , 2> stride_2d;
stride_2d.SetRadius(1);
stride_2d.Print(std::cout);
println("3d");
itk::Neighborhood<float, 3> stride_3d;
stride_3d.SetRadius(1);
stride_3d.Print(std::cout);
println("Printing the indices of the 8 neighbors");
std::cout << stride_3d.GetOffset(4) << std::endl;
std::cout << stride_3d.GetOffset(10) << std::endl;
std::cout << stride_3d.GetOffset(12) << std::endl;
std::cout << stride_3d.GetOffset(13) << std::endl;
std::cout << stride_3d.GetOffset(14) << std::endl;
std::cout << stride_3d.GetOffset(16) << std::endl;
std::cout << stride_3d.GetOffset(22) << std::endl;
println("ANOTHER TEST");
itk::Neighborhood<float, 2> q2;
q2.SetRadius(3);
q2.Print(std::cout);
return EXIT_SUCCESS;
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#if ENABLE_CRY_PHYSICS
#include "utils.h"
#include "primitives.h"
#include "bvtree.h"
#include "geometry.h"
#include "raybv.h"
int CRayBV::GetNodeContents(int iNode, BV* pBVCollider, int bColliderUsed, int bColliderLocal,
geometry_under_test* pGTest, geometry_under_test* pGTestOp)
{
return m_pGeom->GetPrimitiveList(0, 1, pBVCollider->type, *pBVCollider, bColliderLocal, pGTest, pGTestOp, pGTest->primbuf, pGTest->idbuf);
//return 1; // ray should already be in the buffer
}
void CRayBV::GetNodeBV(BV*& pBV, int iNode, int iCaller)
{
pBV = &g_BVray;
g_BVray.iNode = 0;
g_BVray.type = ray::type;
g_BVray.aray.origin = m_pray->origin;
g_BVray.aray.dir = m_pray->dir;
}
void CRayBV::GetNodeBV(const Matrix33& Rw, const Vec3& offsw, float scalew, BV*& pBV, int iNode, int iCaller)
{
pBV = &g_BVray;
g_BVray.iNode = 0;
g_BVray.type = ray::type;
g_BVray.aray.origin = Rw * m_pray->origin * scalew + offsw;
g_BVray.aray.dir = Rw * m_pray->dir * scalew;
}
#endif // ENABLE_CRY_PHYSICS
|
#include "Client.h"
#include <iostream>
#include <unistd.h>
#include <SFML/Graphics.hpp>
#include <thread>
#include "state.h"
#include "ai.h"
#include "../render/StateLayer.h"
namespace render {
class StateLayer;
};
using namespace state;
using namespace engine;
using namespace render;
using namespace std;
using namespace client;
using namespace ai;
render::StateLayer statelayer;
bool updated = true;
void threadEngine(void* ptr1){
Engine* ptr_engine=(Engine*)ptr1;
while(1){
ptr_engine->update();
if(!updated){
updated = true;
}
}
}
Client::Client(){
srand(time(NULL));
//Initialisation générale
//Initialisation de la grille par le moteur
State& state = engine.getState();
state.initGrid("res/maptest.txt");
//Initialisation des personnages
CharacterFactory cf;
state.initPlayers(4);
//Definition en IA
state.getPlayers()[0]->setIa(true);
state.getPlayers()[1]->setIa(true);
state.getPlayers()[2]->setIa(true);
state.getPlayers()[3]->setIa(true);
//Classes
state.getPlayers()[0]->setCharacter(cf.createCharacter(KNIGHT));
state.getPlayers()[1]->setCharacter(cf.createCharacter(FROG));
state.getPlayers()[2]->setCharacter(cf.createCharacter(ARCHER));
state.getPlayers()[3]->setCharacter(cf.createCharacter(DWARF));
//Positions
state.getPlayers()[0]->setX(2);
state.getPlayers()[0]->setY(2);
state.getPlayers()[1]->setX(2);
state.getPlayers()[1]->setY(21);
state.getPlayers()[2]->setX(21);
state.getPlayers()[2]->setY(21);
state.getPlayers()[3]->setX(21);
state.getPlayers()[3]->setY(2);
//Initialisation des skills
SkillFactory sf;
state.getPlayers()[0]->setSkills({sf.createSkill(FRAPPE), sf.createSkill(PIETINEMENT)});
state.getPlayers()[1]->setSkills({sf.createSkill(FRAPPE), sf.createSkill(SOIN_LEGER)});
state.getPlayers()[2]->setSkills({sf.createSkill(FRAPPE), sf.createSkill(ARC)});
state.getPlayers()[3]->setSkills({sf.createSkill(SOIN), sf.createSkill(FEU_D_ENFER)});
state.getGrid()[7][6]->updateFieldStatus({TENT,999});
state.getGrid()[17][6]->updateFieldStatus({TOWER,999});
state.getGrid()[7][17]->updateFieldStatus({TOWER,999});
state.getGrid()[17][17]->updateFieldStatus({TENT,999});
state.getGrid()[12][16]->updateFieldStatus({FORT,999});
state.getGrid()[12][7]->updateFieldStatus({FORT,999});
//Debut du jeu
engine.startGame(state);
//Initialisation de la liste des différents elements pour l'affichage
//StateLayer statelayer;
statelayer.initLayers(state);
statelayer.initWindow(state);
state.registerObserver(&statelayer);
ia = new DeepIA;
}
void Client::run(){
//Creation puis affichage de la fenêtre
sf::RenderWindow& window = statelayer.getWindow();
std::thread th(threadEngine, &engine);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if(event.type == sf::Event::Closed){
window.close();
}
if (event.type == sf::Event::KeyPressed){
engine.setNextKeyCommand(event);
}
}
if (updated){
if (engine.getState().getPlayers().size()>1){
ia->run(engine);
updated = false;
}
engine.getState().notifyObservers(engine.getState());
}
window.display();
}
th.join();
}
|
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "script_utils.h"
namespace uscript {
} // namespace uscript
|
/*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/emr/model/ModifyExecutionPlanJobInfoResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Emr;
using namespace AlibabaCloud::Emr::Model;
ModifyExecutionPlanJobInfoResult::ModifyExecutionPlanJobInfoResult() :
ServiceResult()
{}
ModifyExecutionPlanJobInfoResult::ModifyExecutionPlanJobInfoResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ModifyExecutionPlanJobInfoResult::~ModifyExecutionPlanJobInfoResult()
{}
void ModifyExecutionPlanJobInfoResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
}
|
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt 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 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Copyright 2015 UT-Battelle, LLC.
// Copyright 2015 Los Alamos National Security.
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#include <math.h>
#include <vtkm/Math.h>
#include <vtkm/VectorAnalysis.h>
#include <vtkm/cont/DeviceAdapter.h>
#include <vtkm/cont/DeviceAdapterAlgorithm.h>
#include <vtkm/cont/RuntimeDeviceTracker.h>
#include <vtkm/cont/Timer.h>
#include <vtkm/cont/TryExecute.h>
#include <vtkm/exec/AtomicArray.h>
#include <vtkm/rendering/raytracing/BoundingVolumeHierarchy.h>
#include <vtkm/rendering/raytracing/Logger.h>
#include <vtkm/rendering/raytracing/MortonCodes.h>
#include <vtkm/rendering/raytracing/RayTracingTypeDefs.h>
#include <vtkm/rendering/raytracing/Worklets.h>
#include <vtkm/worklet/DispatcherMapField.h>
#include <vtkm/worklet/WorkletMapField.h>
#define AABB_EPSILON 0.00001f
namespace vtkm
{
namespace rendering
{
namespace raytracing
{
namespace detail
{
class LinearBVHBuilder
{
public:
class CountingIterator;
class FindAABBs;
template <typename Device>
class GatherFloat32;
template <typename Device>
class GatherVecCast;
class BVHData;
template <typename Device>
class PropagateAABBs;
template <typename Device>
class TreeBuilder;
VTKM_CONT
LinearBVHBuilder() {}
template <typename Device>
VTKM_CONT void SortAABBS(
BVHData& bvh,
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Id, 4>>& triangleIndices,
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Int32, 4>>& outputTriangleIndices,
Device vtkmNotUsed(device));
template <typename Device>
VTKM_CONT void RunOnDevice(LinearBVH& linearBVH, Device device);
}; // class LinearBVHBuilder
class LinearBVHBuilder::CountingIterator : public vtkm::worklet::WorkletMapField
{
public:
VTKM_CONT
CountingIterator() {}
typedef void ControlSignature(FieldOut<>);
typedef void ExecutionSignature(WorkIndex, _1);
VTKM_EXEC
void operator()(const vtkm::Id& index, vtkm::Id& outId) const { outId = index; }
}; //class countingIterator
class LinearBVHBuilder::FindAABBs : public vtkm::worklet::WorkletMapField
{
public:
VTKM_CONT
FindAABBs() {}
typedef void ControlSignature(FieldIn<>,
FieldOut<>,
FieldOut<>,
FieldOut<>,
FieldOut<>,
FieldOut<>,
FieldOut<>,
WholeArrayIn<Vec3RenderingTypes>);
typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7, _8);
template <typename PointPortalType>
VTKM_EXEC void operator()(const vtkm::Vec<vtkm::Id, 4> indices,
vtkm::Float32& xmin,
vtkm::Float32& ymin,
vtkm::Float32& zmin,
vtkm::Float32& xmax,
vtkm::Float32& ymax,
vtkm::Float32& zmax,
const PointPortalType& points) const
{
// cast to Float32
vtkm::Vec<vtkm::Float32, 3> point;
point = static_cast<vtkm::Vec<vtkm::Float32, 3>>(points.Get(indices[1]));
xmin = point[0];
ymin = point[1];
zmin = point[2];
xmax = xmin;
ymax = ymin;
zmax = zmin;
point = static_cast<vtkm::Vec<vtkm::Float32, 3>>(points.Get(indices[2]));
xmin = vtkm::Min(xmin, point[0]);
ymin = vtkm::Min(ymin, point[1]);
zmin = vtkm::Min(zmin, point[2]);
xmax = vtkm::Max(xmax, point[0]);
ymax = vtkm::Max(ymax, point[1]);
zmax = vtkm::Max(zmax, point[2]);
point = static_cast<vtkm::Vec<vtkm::Float32, 3>>(points.Get(indices[3]));
xmin = vtkm::Min(xmin, point[0]);
ymin = vtkm::Min(ymin, point[1]);
zmin = vtkm::Min(zmin, point[2]);
xmax = vtkm::Max(xmax, point[0]);
ymax = vtkm::Max(ymax, point[1]);
zmax = vtkm::Max(zmax, point[2]);
vtkm::Float32 xEpsilon, yEpsilon, zEpsilon;
const vtkm::Float32 minEpsilon = 1e-6f;
xEpsilon = vtkm::Max(minEpsilon, AABB_EPSILON * (xmax - xmin));
yEpsilon = vtkm::Max(minEpsilon, AABB_EPSILON * (ymax - ymin));
zEpsilon = vtkm::Max(minEpsilon, AABB_EPSILON * (zmax - zmin));
xmin -= xEpsilon;
ymin -= yEpsilon;
zmin -= zEpsilon;
xmax += xEpsilon;
ymax += yEpsilon;
zmax += zEpsilon;
}
}; //class FindAABBs
template <typename Device>
class LinearBVHBuilder::GatherFloat32 : public vtkm::worklet::WorkletMapField
{
private:
typedef typename vtkm::cont::ArrayHandle<vtkm::Float32> FloatArrayHandle;
typedef typename FloatArrayHandle::ExecutionTypes<Device>::PortalConst PortalConst;
typedef typename FloatArrayHandle::ExecutionTypes<Device>::Portal Portal;
PortalConst InputPortal;
Portal OutputPortal;
public:
VTKM_CONT
GatherFloat32(const FloatArrayHandle& inputPortal,
FloatArrayHandle& outputPortal,
const vtkm::Id& size)
: InputPortal(inputPortal.PrepareForInput(Device()))
{
this->OutputPortal = outputPortal.PrepareForOutput(size, Device());
}
typedef void ControlSignature(FieldIn<>);
typedef void ExecutionSignature(WorkIndex, _1);
VTKM_EXEC
void operator()(const vtkm::Id& outIndex, const vtkm::Id& inIndex) const
{
OutputPortal.Set(outIndex, InputPortal.Get(inIndex));
}
}; //class GatherFloat
template <typename Device>
class LinearBVHBuilder::GatherVecCast : public vtkm::worklet::WorkletMapField
{
private:
typedef typename vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Id, 4>> Vec4IdArrayHandle;
typedef typename vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Int32, 4>> Vec4IntArrayHandle;
typedef typename Vec4IdArrayHandle::ExecutionTypes<Device>::PortalConst PortalConst;
typedef typename Vec4IntArrayHandle::ExecutionTypes<Device>::Portal Portal;
private:
PortalConst InputPortal;
Portal OutputPortal;
public:
VTKM_CONT
GatherVecCast(const Vec4IdArrayHandle& inputPortal,
Vec4IntArrayHandle& outputPortal,
const vtkm::Id& size)
: InputPortal(inputPortal.PrepareForInput(Device()))
{
this->OutputPortal = outputPortal.PrepareForOutput(size, Device());
}
typedef void ControlSignature(FieldIn<>);
typedef void ExecutionSignature(WorkIndex, _1);
VTKM_EXEC
void operator()(const vtkm::Id& outIndex, const vtkm::Id& inIndex) const
{
OutputPortal.Set(outIndex, InputPortal.Get(inIndex));
}
}; //class GatherVec3Id
class LinearBVHBuilder::BVHData
{
public:
//TODO: make private
vtkm::cont::ArrayHandle<vtkm::Float32>* xmins;
vtkm::cont::ArrayHandle<vtkm::Float32>* ymins;
vtkm::cont::ArrayHandle<vtkm::Float32>* zmins;
vtkm::cont::ArrayHandle<vtkm::Float32>* xmaxs;
vtkm::cont::ArrayHandle<vtkm::Float32>* ymaxs;
vtkm::cont::ArrayHandle<vtkm::Float32>* zmaxs;
vtkm::cont::ArrayHandle<vtkm::UInt32> mortonCodes;
vtkm::cont::ArrayHandle<vtkm::Id> parent;
vtkm::cont::ArrayHandle<vtkm::Id> leftChild;
vtkm::cont::ArrayHandle<vtkm::Id> rightChild;
template <typename Device>
VTKM_CONT BVHData(vtkm::Id numPrimitives, Device vtkmNotUsed(device))
: NumPrimitives(numPrimitives)
{
InnerNodeCount = NumPrimitives - 1;
vtkm::Id size = NumPrimitives + InnerNodeCount;
xmins = new vtkm::cont::ArrayHandle<vtkm::Float32>();
ymins = new vtkm::cont::ArrayHandle<vtkm::Float32>();
zmins = new vtkm::cont::ArrayHandle<vtkm::Float32>();
xmaxs = new vtkm::cont::ArrayHandle<vtkm::Float32>();
ymaxs = new vtkm::cont::ArrayHandle<vtkm::Float32>();
zmaxs = new vtkm::cont::ArrayHandle<vtkm::Float32>();
parent.PrepareForOutput(size, Device());
leftChild.PrepareForOutput(InnerNodeCount, Device());
rightChild.PrepareForOutput(InnerNodeCount, Device());
mortonCodes.PrepareForOutput(NumPrimitives, Device());
}
VTKM_CONT
~BVHData()
{
//
delete xmins;
delete ymins;
delete zmins;
delete xmaxs;
delete ymaxs;
delete zmaxs;
}
VTKM_CONT
vtkm::Id GetNumberOfPrimitives() const { return NumPrimitives; }
VTKM_CONT
vtkm::Id GetNumberOfInnerNodes() const { return InnerNodeCount; }
private:
vtkm::Id NumPrimitives;
vtkm::Id InnerNodeCount;
}; // class BVH
template <typename Device>
class LinearBVHBuilder::PropagateAABBs : public vtkm::worklet::WorkletMapField
{
private:
typedef typename vtkm::cont::ArrayHandle<vtkm::Id> IdArrayHandle;
typedef typename vtkm::cont::ArrayHandle<vtkm::Int8> Int8Handle;
typedef typename vtkm::cont::ArrayHandle<Vec<vtkm::Float32, 2>> Float2ArrayHandle;
typedef typename vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Int32, 2>> VecInt2Handle;
typedef typename vtkm::cont::ArrayHandle<Vec<vtkm::Float32, 4>> Float4ArrayHandle;
typedef typename IdArrayHandle::ExecutionTypes<Device>::PortalConst IdConstPortal;
typedef typename Float2ArrayHandle::ExecutionTypes<Device>::Portal Float2ArrayPortal;
typedef typename VecInt2Handle::ExecutionTypes<Device>::Portal Int2ArrayPortal;
typedef typename Int8Handle::ExecutionTypes<Device>::Portal Int8ArrayPortal;
typedef typename Float4ArrayHandle::ExecutionTypes<Device>::Portal Float4ArrayPortal;
Float4ArrayPortal FlatBVH;
IdConstPortal Parents;
IdConstPortal LeftChildren;
IdConstPortal RightChildren;
vtkm::Int32 LeafCount;
//Int8Handle Counters;
//Int8ArrayPortal CountersPortal;
vtkm::exec::AtomicArray<vtkm::Int32, Device> Counters;
public:
VTKM_CONT
PropagateAABBs(IdArrayHandle& parents,
IdArrayHandle& leftChildren,
IdArrayHandle& rightChildren,
vtkm::Int32 leafCount,
Float4ArrayHandle flatBVH,
const vtkm::exec::AtomicArray<vtkm::Int32, Device>& counters)
: Parents(parents.PrepareForInput(Device()))
, LeftChildren(leftChildren.PrepareForInput(Device()))
, RightChildren(rightChildren.PrepareForInput(Device()))
, LeafCount(leafCount)
, Counters(counters)
{
this->FlatBVH = flatBVH.PrepareForOutput((LeafCount - 1) * 4, Device());
}
typedef void ControlSignature(ExecObject,
ExecObject,
ExecObject,
ExecObject,
ExecObject,
ExecObject);
typedef void ExecutionSignature(WorkIndex, _1, _2, _3, _4, _5, _6);
template <typename StrorageType>
VTKM_EXEC_CONT void operator()(
const vtkm::Id workIndex,
const vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32, StrorageType>& xmin,
const vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32, StrorageType>& ymin,
const vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32, StrorageType>& zmin,
const vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32, StrorageType>& xmax,
const vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32, StrorageType>& ymax,
const vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32, StrorageType>& zmax) const
{
//move up into the inner nodes
vtkm::Id currentNode = LeafCount - 1 + workIndex;
vtkm::Vec<vtkm::Id, 2> childVector;
while (currentNode != 0)
{
currentNode = Parents.Get(currentNode);
vtkm::Int32 oldCount = Counters.Add(currentNode, 1);
if (oldCount == 0)
return;
vtkm::Id currentNodeOffset = currentNode * 4;
childVector[0] = LeftChildren.Get(currentNode);
childVector[1] = RightChildren.Get(currentNode);
if (childVector[0] > (LeafCount - 2))
{
childVector[0] = childVector[0] - LeafCount + 1;
vtkm::Vec<vtkm::Float32, 4>
first4Vec; // = FlatBVH.Get(currentNode); only this one needs effects this
first4Vec[0] = xmin.Get(childVector[0]);
first4Vec[1] = ymin.Get(childVector[0]);
first4Vec[2] = zmin.Get(childVector[0]);
first4Vec[3] = xmax.Get(childVector[0]);
FlatBVH.Set(currentNodeOffset, first4Vec);
vtkm::Vec<vtkm::Float32, 4> second4Vec = FlatBVH.Get(currentNodeOffset + 1);
second4Vec[0] = ymax.Get(childVector[0]);
second4Vec[1] = zmax.Get(childVector[0]);
FlatBVH.Set(currentNodeOffset + 1, second4Vec);
childVector[0] = -(childVector[0] + 1);
}
else
{
vtkm::Id child = childVector[0] * 4;
vtkm::Vec<vtkm::Float32, 4> cFirst4Vec = FlatBVH.Get(child);
vtkm::Vec<vtkm::Float32, 4> cSecond4Vec = FlatBVH.Get(child + 1);
vtkm::Vec<vtkm::Float32, 4> cThird4Vec = FlatBVH.Get(child + 2);
cFirst4Vec[0] = vtkm::Min(cFirst4Vec[0], cSecond4Vec[2]);
cFirst4Vec[1] = vtkm::Min(cFirst4Vec[1], cSecond4Vec[3]);
cFirst4Vec[2] = vtkm::Min(cFirst4Vec[2], cThird4Vec[0]);
cFirst4Vec[3] = vtkm::Max(cFirst4Vec[3], cThird4Vec[1]);
FlatBVH.Set(currentNodeOffset, cFirst4Vec);
vtkm::Vec<vtkm::Float32, 4> second4Vec = FlatBVH.Get(currentNodeOffset + 1);
second4Vec[0] = vtkm::Max(cSecond4Vec[0], cThird4Vec[2]);
second4Vec[1] = vtkm::Max(cSecond4Vec[1], cThird4Vec[3]);
FlatBVH.Set(currentNodeOffset + 1, second4Vec);
}
if (childVector[1] > (LeafCount - 2))
{
childVector[1] = childVector[1] - LeafCount + 1;
vtkm::Vec<vtkm::Float32, 4> second4Vec = FlatBVH.Get(currentNodeOffset + 1);
second4Vec[2] = xmin.Get(childVector[1]);
second4Vec[3] = ymin.Get(childVector[1]);
FlatBVH.Set(currentNodeOffset + 1, second4Vec);
vtkm::Vec<vtkm::Float32, 4> third4Vec;
third4Vec[0] = zmin.Get(childVector[1]);
third4Vec[1] = xmax.Get(childVector[1]);
third4Vec[2] = ymax.Get(childVector[1]);
third4Vec[3] = zmax.Get(childVector[1]);
FlatBVH.Set(currentNodeOffset + 2, third4Vec);
childVector[1] = -(childVector[1] + 1);
}
else
{
vtkm::Id child = childVector[1] * 4;
vtkm::Vec<vtkm::Float32, 4> cFirst4Vec = FlatBVH.Get(child);
vtkm::Vec<vtkm::Float32, 4> cSecond4Vec = FlatBVH.Get(child + 1);
vtkm::Vec<vtkm::Float32, 4> cThird4Vec = FlatBVH.Get(child + 2);
vtkm::Vec<vtkm::Float32, 4> second4Vec = FlatBVH.Get(currentNodeOffset + 1);
second4Vec[2] = vtkm::Min(cFirst4Vec[0], cSecond4Vec[2]);
second4Vec[3] = vtkm::Min(cFirst4Vec[1], cSecond4Vec[3]);
FlatBVH.Set(currentNodeOffset + 1, second4Vec);
cThird4Vec[0] = vtkm::Min(cFirst4Vec[2], cThird4Vec[0]);
cThird4Vec[1] = vtkm::Max(cFirst4Vec[3], cThird4Vec[1]);
cThird4Vec[2] = vtkm::Max(cSecond4Vec[0], cThird4Vec[2]);
cThird4Vec[3] = vtkm::Max(cSecond4Vec[1], cThird4Vec[3]);
FlatBVH.Set(currentNodeOffset + 2, cThird4Vec);
}
vtkm::Vec<vtkm::Float32, 4> fourth4Vec;
vtkm::Int32 leftChild =
static_cast<vtkm::Int32>((childVector[0] >= 0) ? childVector[0] * 4 : childVector[0]);
memcpy(&fourth4Vec[0], &leftChild, 4);
vtkm::Int32 rightChild =
static_cast<vtkm::Int32>((childVector[1] >= 0) ? childVector[1] * 4 : childVector[1]);
memcpy(&fourth4Vec[1], &rightChild, 4);
FlatBVH.Set(currentNodeOffset + 3, fourth4Vec);
}
}
}; //class PropagateAABBs
template <typename Device>
class LinearBVHBuilder::TreeBuilder : public vtkm::worklet::WorkletMapField
{
public:
typedef typename vtkm::cont::ArrayHandle<vtkm::UInt32> UIntArrayHandle;
typedef typename vtkm::cont::ArrayHandle<vtkm::Id> IdArrayHandle;
typedef typename UIntArrayHandle::ExecutionTypes<Device>::PortalConst UIntPortalType;
typedef typename IdArrayHandle::ExecutionTypes<Device>::Portal IdPortalType;
private:
UIntPortalType MortonCodePortal;
IdPortalType ParentPortal;
vtkm::Id LeafCount;
vtkm::Id InnerCount;
//TODO: get instrinsic support
VTKM_EXEC
inline vtkm::Int32 CountLeadingZeros(vtkm::UInt32& x) const
{
vtkm::UInt32 y;
vtkm::UInt32 n = 32;
y = x >> 16;
if (y != 0)
{
n = n - 16;
x = y;
}
y = x >> 8;
if (y != 0)
{
n = n - 8;
x = y;
}
y = x >> 4;
if (y != 0)
{
n = n - 4;
x = y;
}
y = x >> 2;
if (y != 0)
{
n = n - 2;
x = y;
}
y = x >> 1;
if (y != 0)
return vtkm::Int32(n - 2);
return vtkm::Int32(n - x);
}
// returns the count of largest shared prefix between
// two morton codes. Ties are broken by the indexes
// a and b.
//
// returns count of the largest binary prefix
VTKM_EXEC
inline vtkm::Int32 delta(const vtkm::Int32& a, const vtkm::Int32& b) const
{
bool tie = false;
bool outOfRange = (b < 0 || b > LeafCount - 1);
//still make the call but with a valid adderss
vtkm::Int32 bb = (outOfRange) ? 0 : b;
vtkm::UInt32 aCode = MortonCodePortal.Get(a);
vtkm::UInt32 bCode = MortonCodePortal.Get(bb);
//use xor to find where they differ
vtkm::UInt32 exOr = aCode ^ bCode;
tie = (exOr == 0);
//break the tie, a and b must always differ
exOr = tie ? vtkm::UInt32(a) ^ vtkm::UInt32(bb) : exOr;
vtkm::Int32 count = CountLeadingZeros(exOr);
if (tie)
count += 32;
count = (outOfRange) ? -1 : count;
return count;
}
public:
VTKM_CONT
TreeBuilder(const UIntArrayHandle& mortonCodesHandle,
IdArrayHandle& parentHandle,
const vtkm::Id& leafCount)
: MortonCodePortal(mortonCodesHandle.PrepareForInput(Device()))
, LeafCount(leafCount)
{
InnerCount = LeafCount - 1;
this->ParentPortal = parentHandle.PrepareForOutput(InnerCount + LeafCount, Device());
}
typedef void ControlSignature(FieldOut<>, FieldOut<>);
typedef void ExecutionSignature(WorkIndex, _1, _2);
VTKM_EXEC
void operator()(const vtkm::Id& index, vtkm::Id& leftChild, vtkm::Id& rightChild) const
{
vtkm::Int32 idx = vtkm::Int32(index);
//something = MortonCodePortal.Get(index) + 1;
//determine range direction
vtkm::Int32 d = 0 > (delta(idx, idx + 1) - delta(idx, idx - 1)) ? -1 : 1;
//find upper bound for the length of the range
vtkm::Int32 minDelta = delta(idx, idx - d);
vtkm::Int32 lMax = 2;
while (delta(idx, idx + lMax * d) > minDelta)
lMax *= 2;
//binary search to find the lower bound
vtkm::Int32 l = 0;
for (int t = lMax / 2; t >= 1; t /= 2)
{
if (delta(idx, idx + (l + t) * d) > minDelta)
l += t;
}
vtkm::Int32 j = idx + l * d;
vtkm::Int32 deltaNode = delta(idx, j);
vtkm::Int32 s = 0;
vtkm::Float32 divFactor = 2.f;
//find the split postition using a binary search
for (vtkm::Int32 t = (vtkm::Int32)ceil(vtkm::Float32(l) / divFactor);;
divFactor *= 2, t = (vtkm::Int32)ceil(vtkm::Float32(l) / divFactor))
{
if (delta(idx, idx + (s + t) * d) > deltaNode)
{
s += t;
}
if (t == 1)
break;
}
vtkm::Int32 split = idx + s * d + vtkm::Min(d, 0);
//assign parent/child pointers
if (vtkm::Min(idx, j) == split)
{
//leaf
ParentPortal.Set(split + InnerCount, idx);
leftChild = split + InnerCount;
}
else
{
//inner node
ParentPortal.Set(split, idx);
leftChild = split;
}
if (vtkm::Max(idx, j) == split + 1)
{
//leaf
ParentPortal.Set(split + InnerCount + 1, idx);
rightChild = split + InnerCount + 1;
}
else
{
ParentPortal.Set(split + 1, idx);
rightChild = split + 1;
}
}
}; // class TreeBuilder
template <typename Device>
VTKM_CONT void LinearBVHBuilder::SortAABBS(
BVHData& bvh,
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Id, 4>>& triangleIndices,
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Int32, 4>>& outputTriangleIndices,
Device vtkmNotUsed(device))
{
//create array of indexes to be sorted with morton codes
vtkm::cont::ArrayHandle<vtkm::Id> iterator;
iterator.PrepareForOutput(bvh.GetNumberOfPrimitives(), Device());
vtkm::worklet::DispatcherMapField<CountingIterator, Device> iteratorDispatcher;
iteratorDispatcher.Invoke(iterator);
//std::cout<<"\n\n\n";
//sort the morton codes
vtkm::cont::DeviceAdapterAlgorithm<Device>::SortByKey(bvh.mortonCodes, iterator);
vtkm::Id arraySize = bvh.GetNumberOfPrimitives();
vtkm::cont::ArrayHandle<vtkm::Float32>* tempStorage;
vtkm::cont::ArrayHandle<vtkm::Float32>* tempPtr;
tempStorage = new vtkm::cont::ArrayHandle<vtkm::Float32>();
//xmins
vtkm::worklet::DispatcherMapField<GatherFloat32<Device>, Device>(
GatherFloat32<Device>(*bvh.xmins, *tempStorage, arraySize))
.Invoke(iterator);
tempPtr = bvh.xmins;
bvh.xmins = tempStorage;
tempStorage = tempPtr;
vtkm::worklet::DispatcherMapField<GatherFloat32<Device>, Device>(
GatherFloat32<Device>(*bvh.ymins, *tempStorage, arraySize))
.Invoke(iterator);
tempPtr = bvh.ymins;
bvh.ymins = tempStorage;
tempStorage = tempPtr;
//zmins
vtkm::worklet::DispatcherMapField<GatherFloat32<Device>, Device>(
GatherFloat32<Device>(*bvh.zmins, *tempStorage, arraySize))
.Invoke(iterator);
tempPtr = bvh.zmins;
bvh.zmins = tempStorage;
tempStorage = tempPtr;
//xmaxs
vtkm::worklet::DispatcherMapField<GatherFloat32<Device>, Device>(
GatherFloat32<Device>(*bvh.xmaxs, *tempStorage, arraySize))
.Invoke(iterator);
tempPtr = bvh.xmaxs;
bvh.xmaxs = tempStorage;
tempStorage = tempPtr;
//ymaxs
vtkm::worklet::DispatcherMapField<GatherFloat32<Device>, Device>(
GatherFloat32<Device>(*bvh.ymaxs, *tempStorage, arraySize))
.Invoke(iterator);
tempPtr = bvh.ymaxs;
bvh.ymaxs = tempStorage;
tempStorage = tempPtr;
//zmaxs
vtkm::worklet::DispatcherMapField<GatherFloat32<Device>, Device>(
GatherFloat32<Device>(*bvh.zmaxs, *tempStorage, arraySize))
.Invoke(iterator);
tempPtr = bvh.zmaxs;
bvh.zmaxs = tempStorage;
tempStorage = tempPtr;
vtkm::worklet::DispatcherMapField<GatherVecCast<Device>, Device>(
GatherVecCast<Device>(triangleIndices, outputTriangleIndices, arraySize))
.Invoke(iterator);
delete tempStorage;
} // method SortAABBs
// Adding this as a template parameter to allow restricted types and
// storage for dynamic coordinate system to limit crazy code bloat and
// compile times.
//
template <typename Device>
VTKM_CONT void LinearBVHBuilder::RunOnDevice(LinearBVH& linearBVH, Device device)
{
Logger* logger = Logger::GetInstance();
logger->OpenLogEntry("bvh_constuct");
logger->AddLogData("device", GetDeviceString(Device()));
vtkm::cont::Timer<Device> constructTimer;
vtkm::cont::DynamicArrayHandleCoordinateSystem coordsHandle = linearBVH.GetCoordsHandle();
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Id, 4>> triangleIndices = linearBVH.GetTriangles();
vtkm::Id numberOfTriangles = linearBVH.GetNumberOfTriangles();
logger->AddLogData("bvh_num_triangles ", numberOfTriangles);
const vtkm::Id numBBoxes = numberOfTriangles;
BVHData bvh(numBBoxes, device);
vtkm::cont::Timer<Device> timer;
vtkm::worklet::DispatcherMapField<FindAABBs, Device>(FindAABBs())
.Invoke(triangleIndices,
*bvh.xmins,
*bvh.ymins,
*bvh.zmins,
*bvh.xmaxs,
*bvh.ymaxs,
*bvh.zmaxs,
coordsHandle);
vtkm::Float64 time = timer.GetElapsedTime();
logger->AddLogData("find_aabb", time);
timer.Reset();
// Find the extent of all bounding boxes to generate normalization for morton codes
vtkm::Vec<vtkm::Float32, 3> minExtent(vtkm::Infinity32(), vtkm::Infinity32(), vtkm::Infinity32());
vtkm::Vec<vtkm::Float32, 3> maxExtent(
vtkm::NegativeInfinity32(), vtkm::NegativeInfinity32(), vtkm::NegativeInfinity32());
maxExtent[0] =
vtkm::cont::DeviceAdapterAlgorithm<Device>::Reduce(*bvh.xmaxs, maxExtent[0], MaxValue());
maxExtent[1] =
vtkm::cont::DeviceAdapterAlgorithm<Device>::Reduce(*bvh.ymaxs, maxExtent[1], MaxValue());
maxExtent[2] =
vtkm::cont::DeviceAdapterAlgorithm<Device>::Reduce(*bvh.zmaxs, maxExtent[2], MaxValue());
minExtent[0] =
vtkm::cont::DeviceAdapterAlgorithm<Device>::Reduce(*bvh.xmins, minExtent[0], MinValue());
minExtent[1] =
vtkm::cont::DeviceAdapterAlgorithm<Device>::Reduce(*bvh.ymins, minExtent[1], MinValue());
minExtent[2] =
vtkm::cont::DeviceAdapterAlgorithm<Device>::Reduce(*bvh.zmins, minExtent[2], MinValue());
time = timer.GetElapsedTime();
logger->AddLogData("calc_extents", time);
timer.Reset();
vtkm::Vec<vtkm::Float32, 3> deltaExtent = maxExtent - minExtent;
vtkm::Vec<vtkm::Float32, 3> inverseExtent;
for (int i = 0; i < 3; ++i)
{
inverseExtent[i] = (deltaExtent[i] == 0.f) ? 0 : 1.f / deltaExtent[i];
}
//Generate the morton codes
vtkm::worklet::DispatcherMapField<MortonCodeAABB, Device>(
MortonCodeAABB(inverseExtent, minExtent))
.Invoke(
*bvh.xmins, *bvh.ymins, *bvh.zmins, *bvh.xmaxs, *bvh.ymaxs, *bvh.zmaxs, bvh.mortonCodes);
time = timer.GetElapsedTime();
logger->AddLogData("morton_codes", time);
timer.Reset();
linearBVH.Allocate(bvh.GetNumberOfPrimitives(), Device());
SortAABBS(bvh, triangleIndices, linearBVH.LeafNodes, Device());
time = timer.GetElapsedTime();
logger->AddLogData("sort_aabbs", time);
timer.Reset();
vtkm::worklet::DispatcherMapField<TreeBuilder<Device>, Device>(
TreeBuilder<Device>(bvh.mortonCodes, bvh.parent, bvh.GetNumberOfPrimitives()))
.Invoke(bvh.leftChild, bvh.rightChild);
time = timer.GetElapsedTime();
logger->AddLogData("build_tree", time);
timer.Reset();
const vtkm::Int32 primitiveCount = vtkm::Int32(bvh.GetNumberOfPrimitives());
vtkm::cont::ArrayHandle<vtkm::Int32> counters;
counters.PrepareForOutput(bvh.GetNumberOfPrimitives() - 1, Device());
vtkm::Int32 zero = 0;
vtkm::worklet::DispatcherMapField<MemSet<vtkm::Int32>, Device>(MemSet<vtkm::Int32>(zero))
.Invoke(counters);
vtkm::exec::AtomicArray<vtkm::Int32, Device> atomicCounters(counters);
vtkm::worklet::DispatcherMapField<PropagateAABBs<Device>, Device>(
PropagateAABBs<Device>(
bvh.parent, bvh.leftChild, bvh.rightChild, primitiveCount, linearBVH.FlatBVH, atomicCounters))
.Invoke(vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32>(*bvh.xmins),
vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32>(*bvh.ymins),
vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32>(*bvh.zmins),
vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32>(*bvh.xmaxs),
vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32>(*bvh.ymaxs),
vtkm::exec::ExecutionWholeArrayConst<vtkm::Float32>(*bvh.zmaxs));
time = timer.GetElapsedTime();
logger->AddLogData("propagate_aabbs", time);
time = constructTimer.GetElapsedTime();
logger->CloseLogEntry(time);
}
} //namespace detail
struct LinearBVH::ConstructFunctor
{
LinearBVH* Self;
VTKM_CONT
ConstructFunctor(LinearBVH* self)
: Self(self)
{
}
template <typename Device>
bool operator()(Device)
{
Self->ConstructOnDevice(Device());
return true;
}
};
LinearBVH::LinearBVH()
: IsConstructed(false)
, CanConstruct(false){};
VTKM_CONT
LinearBVH::LinearBVH(vtkm::cont::DynamicArrayHandleCoordinateSystem coordsHandle,
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Id, 4>> triangles,
vtkm::Bounds coordBounds)
: CoordBounds(coordBounds)
, CoordsHandle(coordsHandle)
, Triangles(triangles)
, IsConstructed(false)
, CanConstruct(true)
{
}
VTKM_CONT
LinearBVH::LinearBVH(const LinearBVH& other)
: FlatBVH(other.FlatBVH)
, LeafNodes(other.LeafNodes)
, LeafCount(other.LeafCount)
, CoordBounds(other.CoordBounds)
, CoordsHandle(other.CoordsHandle)
, Triangles(other.Triangles)
, IsConstructed(other.IsConstructed)
, CanConstruct(other.CanConstruct)
{
}
template <typename Device>
VTKM_CONT void LinearBVH::Allocate(const vtkm::Id& leafCount, Device deviceAdapter)
{
LeafCount = leafCount;
LeafNodes.PrepareForOutput(leafCount, deviceAdapter);
FlatBVH.PrepareForOutput((leafCount - 1) * 4, deviceAdapter);
}
void LinearBVH::Construct()
{
if (IsConstructed)
return;
if (!CanConstruct)
throw vtkm::cont::ErrorBadValue(
"Linear BVH: coordinates and triangles must be set before calling construct!");
ConstructFunctor functor(this);
vtkm::cont::TryExecute(functor);
IsConstructed = true;
}
VTKM_CONT
void LinearBVH::SetData(vtkm::cont::DynamicArrayHandleCoordinateSystem coordsHandle,
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Id, 4>> triangles,
vtkm::Bounds coordBounds)
{
CoordBounds = coordBounds;
CoordsHandle = coordsHandle;
Triangles = triangles;
IsConstructed = false;
CanConstruct = true;
}
template <typename Device>
void LinearBVH::ConstructOnDevice(Device device)
{
Logger* logger = Logger::GetInstance();
vtkm::cont::Timer<Device> timer;
logger->OpenLogEntry("bvh");
if (!CanConstruct)
throw vtkm::cont::ErrorBadValue(
"Linear BVH: coordinates and triangles must be set before calling construct!");
if (!IsConstructed)
{
//
// This algorithm needs at least 2 triangles
//
vtkm::Id numTriangles = this->GetNumberOfTriangles();
if (numTriangles == 1)
{
vtkm::Vec<vtkm::Id, 4> triangle = Triangles.GetPortalControl().Get(0);
Triangles.Allocate(2);
Triangles.GetPortalControl().Set(0, triangle);
Triangles.GetPortalControl().Set(1, triangle);
}
detail::LinearBVHBuilder builder;
builder.RunOnDevice(*this, device);
IsConstructed = true;
}
vtkm::Float64 time = timer.GetElapsedTime();
logger->CloseLogEntry(time);
}
// explicitly export to workaround an intel compiler bug
#if defined(VTKM_ICC)
template VTKM_CONT_EXPORT void LinearBVH::ConstructOnDevice<vtkm::cont::DeviceAdapterTagSerial>(
vtkm::cont::DeviceAdapterTagSerial);
#ifdef VTKM_ENABLE_TBB
template VTKM_CONT_EXPORT void LinearBVH::ConstructOnDevice<vtkm::cont::DeviceAdapterTagTBB>(
vtkm::cont::DeviceAdapterTagTBB);
#endif
#ifdef VTKM_ENABLE_CUDA
template VTKM_CONT_EXPORT void LinearBVH::ConstructOnDevice<vtkm::cont::DeviceAdapterTagCuda>(
vtkm::cont::DeviceAdapterTagCuda);
#endif
#endif
VTKM_CONT
bool LinearBVH::GetIsConstructed() const
{
return IsConstructed;
}
VTKM_CONT
vtkm::cont::DynamicArrayHandleCoordinateSystem LinearBVH::GetCoordsHandle() const
{
return CoordsHandle;
}
VTKM_CONT
vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Id, 4>> LinearBVH::GetTriangles() const
{
return Triangles;
}
vtkm::Id LinearBVH::GetNumberOfTriangles() const
{
return Triangles.GetPortalConstControl().GetNumberOfValues();
}
}
}
} // namespace vtkm::rendering::raytracing
|
/*
**==============================================================================
**
** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE
** for license information.
**
**==============================================================================
*/
#include "NitsNewInterfaceTests.h"
NitsDefSetup0(Fixture0, MyStruct)
NitsTrace(PAL_T("Fixture0 being run"));
NitsContext()->_MyStruct->x = 0;
NitsContext()->_MyStruct->p = 0;
NitsEndSetup
NitsCleanup(Fixture0)
NitsTrace(PAL_T("Cleanup of Fixture0 being run"));
NitsContext()->_MyStruct->x = 0;
NitsEndCleanup
NitsCrash(Fixture0)
NitsContext()->_MyStruct->x = 0;
NitsEndCrash
NitsSetup(SimpleSetup)
NitsEndSetup
NitsTestSetIsolation(SimpleBody)
NitsTestSetTimeout(SimpleBody, 900)
NitsTest(SimpleBody)
NitsTrace(PAL_T("SimpleBody being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsTestWithSetup(BodyWithSimpleSetup, SimpleSetup)
NitsTrace(PAL_T("BodyWithSimpleSetup being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsSetup0(Fixture1, MyStruct)
NitsContext()->_MyStruct->x = 0;
NitsContext()->_MyStruct->p = 0;
NitsEndSetup
struct MyStruct sFixture2 = {9, 0};
NitsDefSetup1(Fixture2, MyStruct2, Fixture0, sFixture2)
NitsContext()->_MyStruct2->c = 0;
NitsContext()->_MyStruct2->d = 0;
// doing initialization directly; this way we will potentially have this following code pasted in several tests
NitsContext()->_Fixture0->_MyStruct->x = 0;
NitsContext()->_Fixture0->_MyStruct->p = 0;
NitsEndSetup
struct MyStruct sFixture4 = {12, 0};
NitsDefSetup1(Fixture4, MyStruct2, Fixture0, sFixture4)
NitsContext()->_MyStruct2->c = 0;
NitsContext()->_MyStruct2->d = 0;
NitsContext()->_Fixture0->_MyStruct->x = 0;
NitsContext()->_Fixture0->_MyStruct->p = 0;
NitsEndSetup
struct MyStruct sFixture3 = {3, 0};
NitsDefSplit2(Fixture3, MyStruct,
Fixture0,
Fixture1)
// convenient way of accessing currently selected choice
NitsContext()->_MyStruct->x = 0;
NitsContext()->_MyStruct->p = 0;
// you could do it this way too
NitsContext()->_Fixture0->_MyStruct->x = 0;
NitsContext()->_Fixture0->_MyStruct->p = 0;
NitsContext()->_Fixture1->_MyStruct->x = 0;
NitsContext()->_Fixture1->_MyStruct->p = 0;
NitsEndSetup
struct FirstTest
{
int x;
};
NitsTest0(FirstTestWithNewInterface)
NitsTrace(PAL_T("FirstTestWithNewInterface being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsTest(BodyOnlyTest)
NitsTrace(PAL_T("BodyOnlyTest being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsSetup(MySetup1)
NitsTrace(PAL_T("MySetup1 being run"));
NitsEndSetup
NitsCleanup(MySetup1)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup for MySetup1 being run"));
NitsEndCleanup
NitsCleanup(MySetup2)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup for MySetup2 being run"));
NitsEndCleanup
NitsSplit2(SetupWithTwoParentsSplit, NitsEmptyStruct,
MySetup1, MySetup2)
NitsTrace(PAL_T("SetupWithTwoParentsSplit being run"));
NitsEndSetup
NitsCleanup(SetupWithTwoParentsSplit)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup for SetupWithTwoParentsSplit being run"));
NitsEndCleanup
NitsTest1(BodyWithSplitParent, SetupWithTwoParentsSplit, NitsEmptyValue)
NitsTrace(PAL_T("BodyWithSplitParent being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsTestWithSetup(BodyWithSetup, MySetup1)
NitsTrace(PAL_T("BodyWithSetup being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsTest2(BodyWithTwoParents, MySetup1, NitsEmptyValue, MySetup2, NitsEmptyValue)
NitsTrace(PAL_T("BodyWithSetup being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsCleanup(BodyWithSplitParent)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup for BodyWithSplitParent being run"));
NitsEndCleanup
NitsSetup(P1_1)
NitsTrace(PAL_T("P1_1 being run"));
NitsEndSetup
NitsSetup(P1_2)
NitsTrace(PAL_T("P1_2 being run"));
NitsEndSetup
NitsSetup2(P1, NitsEmptyStruct,
P1_1, NitsEmptyValue,
P1_2, NitsEmptyValue)
NitsTrace(PAL_T("P1 being run"));
NitsEndSetup
NitsSetup(P2_1)
NitsTrace(PAL_T("P2_1 being run"));
NitsEndSetup
NitsSetup1(P2, NitsEmptyStruct,
P2_1, NitsEmptyValue)
NitsTrace(PAL_T("P2 being run"));
NitsEndSetup
NitsTest2(T1,
P1, NitsEmptyValue,
P2, NitsEmptyValue)
NitsTrace(PAL_T("T1 being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsSplit2(Split_P1_P2, NitsEmptyStruct,
P1, P2)
NitsTrace(PAL_T("Split_P1_P2 being run"));
NitsEndSplit
NitsTest1(T2,
Split_P1_P2, NitsEmptyValue)
NitsTrace(PAL_T("T2 being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsSetup(C1_1)
NitsTrace(PAL_T("C1_1 being run"));
NitsEndSetup
NitsCleanup(C1_1)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup of C1_1 being run"));
NitsEndCleanup
NitsSetup(C1_2)
NitsTrace(PAL_T("C1_2 being run"));
NitsEndSetup
NitsSplit2(C1, NitsEmptyStruct,
C1_1,
C1_2)
NitsTrace(PAL_T("C1 being run"));
NitsEndSplit
NitsCleanup(C1)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup of C1 being run"));
NitsEndCleanup
NitsSetup(D1_1)
if(NitsIsFixtureSelected(C1_1))
NitsOmitAndReturn;
NitsTrace(PAL_T("D1_1 being run"));
NitsEndSetup
NitsCleanup(D1_1)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup of D1_1 being run"));
NitsEndCleanup
NitsSetup(D1_2)
NitsTrace(PAL_T("D1_2 being run"));
NitsEndSetup
NitsSplit2(D1, NitsEmptyStruct,
D1_1,
D1_2)
NitsTrace(PAL_T("D1 being run"));
NitsEndSplit
NitsCleanup(D1)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup of D1 being run"));
NitsEndCleanup
NitsTest2(TC1D1,
C1, NitsEmptyValue,
D1, NitsEmptyValue)
NitsTrace(PAL_T("TC1D1 being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsCleanup(TC1D1)
PAL_UNUSED(NitsContext());
NitsTrace(PAL_T("Cleanup of TC1D1 being run"));
NitsEndCleanup
NitsSetup1(MySetup1C1, NitsEmptyStruct,
MySetup1, NitsEmptyValue)
NitsTrace(PAL_T("MySetup1C1 being run"));
NitsEndSetup
NitsSetup1(MySetup1C2, NitsEmptyStruct,
MySetup1, NitsEmptyValue)
NitsTrace(PAL_T("MySetup1C2 being run"));
NitsEndSetup
NitsTest2(VITest1,
MySetup1C1, NitsEmptyValue,
MySetup1C2, NitsEmptyValue)
NitsTrace(PAL_T("VITest1 being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
// DEMO Test
struct MyContext
{
char *bom;
int length;
};
char *currentBom = 0;
void SetBom(_In_reads_(length) char *bom, int length)
{
PAL_UNUSED(length);
currentBom = bom;
}
int DecodeData(_In_reads_(length) char *someData, int length)
{
PAL_UNUSED(someData);
PAL_UNUSED(length);
// do the decoding
// when successful return 1
return 1;
}
void PrintBom(_In_reads_(length) char *bom, int length)
{
int count = 0;
if(!bom || (length == 0))
return;
while((count < length) && bom[count] != 0)
{
// code to print each char
count++;
}
if(count == 3)
{
NitsTrace(PAL_T("BOM is 123"));
}
else if(count == 2)
{
NitsTrace(PAL_T("BOM is 45"));
}
}
NitsSetup0(UTF8, MyContext)
char temp[] = {1, 2, 3, 0};
NitsContext()->_MyContext->bom = temp;
NitsContext()->_MyContext->length = 4;
NitsTrace(PAL_T("Running UTF8"));
NitsEndSetup
NitsSetup0(UTF16, MyContext)
char temp[] = {4, 5, 0};
NitsContext()->_MyContext->bom = temp;
NitsContext()->_MyContext->length = 3;
NitsTrace(PAL_T("Running UTF16"));
NitsEndSetup
NitsSplit2(Encodings, MyContext, UTF8, UTF16)
NitsTrace(PAL_T("Running Encodings"));
PrintBom(NitsContext()->_MyContext->bom, NitsContext()->_MyContext->length);
NitsEndSplit
NitsTest1(DecoderTest,
Encodings, EncodingsDefaults)
int x = 0;
char someData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
NitsTrace(PAL_T("Running DecoderTest"));
PrintBom(NitsContext()->_Encodings->_MyContext->bom, NitsContext()->_Encodings->_MyContext->length);
SetBom(NitsContext()->_Encodings->_MyContext->bom, NitsContext()->_Encodings->_MyContext->length);
x = DecodeData(someData, 10);
NitsAssert(x, PAL_T("Foo failed"));
NitsEndTest
void FaultSimHelper1()
{
char *mem1 = (char *)SystemMalloc(10);
char *mem2 = (char *)SystemMalloc(15);
// faulting on mem1 alloc
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsAssert(false, PAL_T("mem1 alloc failed"));
}
if(mem1)
SystemFree(mem1);
// faulting on mem2 alloc
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsAssert(false, PAL_T("mem2 alloc failed"));
}
if(mem2)
SystemFree(mem2);
}
void FaultSimHelper()
{
char *mem1 = (char *)SystemMalloc(10);
char *mem2 = (char *)SystemMalloc(15);
char *mem3 = (char *)SystemMalloc(20);
char *mem4 = (char *)SystemMalloc(25);
// faulting on mem1 alloc
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsAssert(false, PAL_T("mem1 alloc failed"));
}
if(mem1)
SystemFree(mem1);
// faulting on mem2 alloc
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsAssert(false, PAL_T("mem2 alloc failed"));
}
if(mem2)
SystemFree(mem2);
// faulting on mem3 alloc
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsAssert(false, PAL_T("mem3 alloc failed"));
}
if(mem3)
SystemFree(mem3);
// faulting on mem4 alloc
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsAssert(false, PAL_T("mem4 alloc failed"));
}
if(mem4)
SystemFree(mem4);
FaultSimHelper1();
}
NitsTest2(VITest1FaultSim,
MySetup1C1, NitsEmptyValue,
MySetup1C2, NitsEmptyValue)
NitsEnableFaultSim;
NitsFaultSimMarkForRerun;
FaultSimHelper();
FaultSimHelper1();
NitsTrace(PAL_T("VITest1 being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
NitsTest2(TC1D1FaultSim,
C1, NitsEmptyValue,
D1, NitsEmptyValue)
NitsEnableFaultSim;
FaultSimHelper();
FaultSimHelper1();
NitsTrace(PAL_T("TC1D1 being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndSetup
NitsTest(FaultSimTest1)
NitsEnableFaultSim;
FaultSimHelper();
FaultSimHelper1();
NitsTrace(PAL_T("FaultSimTest1 being run"));
NitsAssert(true, PAL_T("test passed"));
NitsEndTest
struct FooStruct1
{
int i1;
};
struct FooStruct2
{
int i2;
};
NitsSetup0(FooSetup1, FooStruct1)
NitsAssert(NitsContext()->_FooStruct1->i1 == 10, PAL_T("wrong value"));
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("FooSetup1 fault occurred"));
NitsAssert(false, PAL_T("FooSetup1 fault location failed"));
NitsReturn;
}
NitsContext()->_FooStruct1->i1 = 15;
NitsTrace(PAL_T("FooSetup1 being run"));
NitsEndSetup
struct FooStruct1 sFooStruct1 = {10};
NitsSetup1(FooSetup2, FooStruct2, FooSetup1, sFooStruct1)
NitsAssert(NitsContext()->_FooSetup1->_FooStruct1->i1 == 15, PAL_T("wrong value"));
NitsAssert(NitsContext()->_FooStruct2->i2 == 20, PAL_T("wrong value"));
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("FooSetup2 fault occurred"));
NitsAssert(false, PAL_T("FooSetup2 fault location failed"));
NitsReturn;
}
NitsContext()->_FooSetup1->_FooStruct1->i1 = 35;
NitsContext()->_FooStruct2->i2 = 25;
NitsTrace(PAL_T("FooSetup2 being run"));
NitsEndSetup
struct FooStruct2 sFooStruct2 = {20};
NitsTest1(FooTest, FooSetup2, sFooStruct2)
NitsEnableFaultSim;
NitsFaultSimMarkForRerun;
NitsAssert(NitsContext()->_FooSetup2->_FooStruct2->i2 == 25, PAL_T("wrong value"));
NitsAssert(NitsContext()->_FooSetup2->_FooSetup1->_FooStruct1->i1 == 35, PAL_T("wrong value"));
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("FooTest fault occurred"));
NitsAssert(false, PAL_T("FooTest fault location failed"));
NitsReturn;
}
NitsContext()->_FooSetup2->_FooStruct2->i2 = 45;
NitsContext()->_FooSetup2->_FooSetup1->_FooStruct1->i1 = 55;
NitsTrace(PAL_T("FooTest being run"));
NitsEndTest
NitsCleanup(FooTest)
NitsAssert(NitsContext()->_FooSetup2->_FooStruct2->i2 == 45, PAL_T("wrong value"));
NitsAssert(NitsContext()->_FooSetup2->_FooSetup1->_FooStruct1->i1 == 55, PAL_T("wrong value"));
NitsTrace(PAL_T("FooTest cleanup being run"));
NitsEndCleanup
NitsTest(UselessTest)
/* Causes error due to not having test assertions. */
NitsEndTest
#include <pal/shlib.h>
typedef int (*FuncPtr)();
NitsTest(SampleProductTest)
Shlib *library = NULL;
FuncPtr funcPtr;
NitsEnableFaultSim;
#ifdef _MSC_VER
library = Shlib_Open(PAL_T("nitssampleproduct.dll"));
#else
library = Shlib_Open(PAL_T("libnitssampleproduct.so"));
#endif
if (library == NULL)
{
NitsAssert(false, PAL_T("sampleproduct library can not be opened"));
return;
}
funcPtr = (FuncPtr)Shlib_Sym(library, "DoSomething");
if (funcPtr == NULL)
{
Shlib_Close(library);
NitsAssert(false, PAL_T("DoSomething not found"));
return;
}
bool passed = (funcPtr() == 3);
NitsAssert(passed, PAL_T("DoSomething failed"));
Shlib_Close(library);
NitsEndTest
NitsTest(TestGetCustomStringAParams)
NitsTrace(NitsTestGetParam(PAL_T("loglevel")));
NitsAssert(PAL_TRUE, PAL_T(""));
NitsEndTest
NitsSetup(Var1)
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("Var1 fault occurred"));
NitsAssert(false, PAL_T("Var1 fault location failed"));
NitsReturn;
}
NitsTrace(PAL_T("Var1 being run"));
NitsEndSetup
NitsCleanup(Var1)
NitsTrace(PAL_T("Cleanup for Var1 being run"));
NitsEndCleanup
NitsSetup(Var2)
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("Var2 fault occurred"));
NitsAssert(false, PAL_T("Var2 fault location failed"));
NitsReturn;
}
NitsTrace(PAL_T("Var2 being run"));
NitsEndSetup
NitsCleanup(Var2)
NitsTrace(PAL_T("Cleanup for Var2 being run"));
NitsEndCleanup
NitsSplit2(VarSplit, NitsEmptyStruct, Var1, Var2)
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("VarSplit fault occurred"));
NitsAssert(false, PAL_T("VarSplit fault location failed"));
NitsReturn;
}
NitsTrace(PAL_T("VarSplit being run"));
NitsEndSplit
NitsCleanup(VarSplit)
NitsTrace(PAL_T("Cleanup for VarSplit being run"));
NitsEndCleanup
NitsSetup(SingleSetup)
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("SingleSetup fault occurred"));
NitsAssert(false, PAL_T("SingleSetup fault location failed"));
NitsReturn;
}
NitsTrace(PAL_T("SingleSetup being run"));
NitsEndSetup
NitsCleanup(SingleSetup)
NitsTrace(PAL_T("Cleanup for SingleSetup being run"));
NitsEndCleanup
NitsTest2(ComboTest, VarSplit, NitsEmptyValue, SingleSetup, NitsEmptyValue)
NitsEnableFaultSim;
NitsFaultSimMarkForRerun;
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("Combotest fault occurred"));
NitsAssert(false, PAL_T("Combotest fault location failed"));
NitsReturn;
}
NitsTrace(PAL_T("Combotest being run"));
NitsAssert(PAL_TRUE, PAL_T(""));
NitsEndTest
NitsCleanup(ComboTest)
NitsTrace(PAL_T("Cleanup for ComboTest being run"));
NitsEndCleanup
NitsModuleSetup(MyModuleSetup1)
NitsTrace(PAL_T("MyModuleSetup1 being run"));
NitsAssert(PAL_TRUE, PAL_T(""));
NitsEndModuleSetup
NitsCleanup(MyModuleSetup1)
NitsTrace(PAL_T("Cleanup for MyModuleSetup1 being run"));
NitsAssert(PAL_TRUE, PAL_T(""));
NitsEndCleanup
NitsModuleSetup(MyModuleSetup2)
NitsTrace(PAL_T("MyModuleSetup2 being run"));
NitsAssert(PAL_TRUE, PAL_T(""));
NitsEndModuleSetup
NitsCleanup(MyModuleSetup2)
NitsTrace(PAL_T("Cleanup for MyModuleSetup2 being run"));
NitsAssert(PAL_TRUE, PAL_T(""));
NitsEndCleanup
NitsSetup(FirstLevelSetup)
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("FirstLevelSetup fault occurred"));
NitsAssert(false, PAL_T("FirstLevelSetup fault location failed"));
NitsReturn;
}
NitsTrace(PAL_T("FirstLevelSetup being run"));
NitsEndSetup
NitsCleanup(FirstLevelSetup)
NitsTrace(PAL_T("Cleanup of FirstLevelSetup being run"));
NitsEndCleanup
NitsSetup1(SecondLevelSetup, NitsEmptyStruct, FirstLevelSetup, NitsEmptyValue)
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("SecondLevelSetup fault occurred"));
NitsAssert(false, PAL_T("SecondLevelSetup fault location failed"));
NitsReturn;
}
NitsTrace(PAL_T("SecondLevelSetup being run"));
NitsEndSetup
NitsCleanup(SecondLevelSetup)
NitsTrace(PAL_T("Cleanup of SecondLevelSetup being run"));
NitsEndCleanup
NitsTest2(TestWithALoop, SecondLevelSetup, NitsEmptyValue, FirstLevelSetup, NitsEmptyValue)
NitsEnableFaultSim;
NitsFaultSimMarkForRerun;
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("TestWithALoop fault occurred"));
NitsAssert(false, PAL_T("TestWithALoop fault location failed"));
NitsReturn;
}
NitsTrace(PAL_T("TestWithALoop being run"));
NitsAssert(PAL_TRUE, PAL_T(""));
NitsEndTest
NitsCleanup(TestWithALoop)
NitsTrace(PAL_T("Cleanup of TestWithALoop being run"));
NitsEndCleanup
NitsSetup(FailingSetup)
NitsAssert(false, PAL_T("FailingSetup failed"));
NitsTrace(PAL_T("FailingSetup being run"));
NitsEndSetup
NitsCleanup(FailingSetup)
NitsTrace(PAL_T("Cleanup of FailingSetup being run"));
NitsEndCleanup
NitsTestWithSetup(FailingSetupTest, FailingSetup)
NitsTrace(PAL_T("FailingSetupTest being run"));
NitsEndTest
NitsCleanup(FailingSetupTest)
NitsTrace(PAL_T("Cleanup of FailingSetupTest being run"));
NitsEndCleanup
NitsSetup(FailingLevel1Setup)
NitsAssert(false, PAL_T("FailingLevel1Setup failed"));
NitsTrace(PAL_T("FailingLevel1Setup being run"));
NitsEndSetup
NitsCleanup(FailingLevel1Setup)
NitsTrace(PAL_T("Cleanup of FailingLevel1Setup being run"));
NitsEndCleanup
NitsSetup1(FailingLevel2Setup, NitsEmptyStruct, FailingLevel1Setup, NitsEmptyValue)
NitsTrace(PAL_T("FailingLevel2Setup being run"));
NitsEndSetup
NitsCleanup(FailingLevel2Setup)
NitsTrace(PAL_T("Cleanup of FailingLevel2Setup being run"));
NitsEndCleanup
NitsTestWithSetup(FailingTwoLevelSetupTest, FailingLevel2Setup)
NitsTrace(PAL_T("FailingTwoLevelSetupTest being run"));
NitsEndTest
NitsCleanup(FailingTwoLevelSetupTest)
NitsTrace(PAL_T("Cleanup of FailingTwoLevelSetupTest being run"));
NitsEndCleanup
NitsSetup(Var1Fail)
NitsAssert(false, PAL_T("Var1Fail failed"));
NitsTrace(PAL_T("Var1Fail being run"));
NitsEndSetup
NitsCleanup(Var1Fail)
NitsTrace(PAL_T("Cleanup of Var1Fail being run"));
NitsEndCleanup
NitsSetup(Var2Success)
NitsTrace(PAL_T("Var2Success being run"));
NitsEndSetup
NitsCleanup(Var2Success)
NitsTrace(PAL_T("Cleanup of Var2Success being run"));
NitsEndCleanup
NitsSplit2(VarFailSuccess, NitsEmptyStruct, Var1Fail, Var2Success)
NitsTrace(PAL_T("VarFailSuccess being run"));
NitsEndSplit
NitsCleanup(VarFailSuccess)
NitsTrace(PAL_T("Cleanup of VarFailSuccess being run"));
NitsEndCleanup
NitsTestWithSetup(SplitTestOneFailOtherSuccess, VarFailSuccess)
NitsAssert(true, PAL_T("SplitTestOneFailOtherSuccess success"));
NitsTrace(PAL_T("SplitTestOneFailOtherSuccess being run"));
NitsEndTest
NitsCleanup(SplitTestOneFailOtherSuccess)
NitsTrace(PAL_T("Cleanup of SplitTestOneFailOtherSuccess being run"));
NitsEndCleanup
NitsTest(FailingCleanupTest)
NitsAssert(true, PAL_T("FailingCleanupTest success"));
NitsTrace(PAL_T("FailingCleanupTest being run"));
NitsEndTest
NitsCleanup(FailingCleanupTest)
NitsAssert(false, PAL_T("Cleanup for FailingCleanupTest fails"));
NitsTrace(PAL_T("Cleanup for FailingCleanupTest being run"));
NitsEndCleanup
NitsSetup(UnexpectedFaultSimErrorSetup)
NitsTrace(PAL_T("UnexpectedFaultSimErrorSetup being run"));
NitsEndSetup
NitsCleanup(UnexpectedFaultSimErrorSetup)
NitsTrace(PAL_T("Cleanup of UnexpectedFaultSimErrorSetup being run"));
NitsEndCleanup
PAL_Uint32 g_unexpectedFaultSimError = 0;
NitsTestWithSetup(UnexpectedFaultSimErrorTest, UnexpectedFaultSimErrorSetup)
NitsFaultSimMarkForRerun;
NitsEnableFaultSim;
g_unexpectedFaultSimError++;
if(g_unexpectedFaultSimError == 1)
{
NitsAssert(true, PAL_T("UnexpectedFaultSimErrorTest success"));
}
if(NitsShouldFault(NitsHere(), NitsAutomatic))
{
NitsTrace(PAL_T("UnexpectedFaultSimErrorTest fault occurred; will be ignored"));
}
if(g_unexpectedFaultSimError == 3)
{
NitsAssert(false, PAL_T("UnexpectedFaultSimErrorTest asserted false on without fault "));
}
NitsTrace(PAL_T("UnexpectedFaultSimErrorTest being run"));
NitsEndTest
NitsCleanup(UnexpectedFaultSimErrorTest)
NitsTrace(PAL_T("Cleanup of UnexpectedFaultSimErrorTest being run"));
NitsEndCleanup
/*********************************************************************************************************************************
** NITS DEMO:- Refactoring existing tests with new interface
**********************************************************************************************************************************/
/*********************************************************************************************************************************
** Dummy product
**********************************************************************************************************************************/
typedef struct _TestApplication
{
unsigned int applicationHandle;
} TestApplication;
TestApplication *Create_TestApplication()
{
TestApplication *application = (TestApplication *) SystemMalloc(sizeof(TestApplication));
if(application)
{
application->applicationHandle = 1;
}
return application;
}
void Close_TestApplication(TestApplication *application)
{
if(application)
SystemFree(application);
}
enum ProtocolType
{
ProtocolA,
ProtocolB
};
typedef struct _TestSession
{
TestApplication *application;
unsigned int sessionHandle;
ProtocolType protocolType;
} TestSession;
TestSession *Create_TestSession(TestApplication *application, ProtocolType protocol)
{
TestSession *session = (TestSession *) SystemMalloc(sizeof(TestSession));
if(session)
{
session->application = application;
session->sessionHandle = 1;
session->protocolType = protocol;
}
return session;
}
void Close_TestSession(TestSession *session)
{
if(session)
SystemFree(session);
}
typedef struct _TestOperation
{
TestSession *session;
unsigned int operationId;
} TestOperation;
TestOperation *Create_TestOperation(TestSession *session)
{
TestOperation *operation = (TestOperation *) SystemMalloc(sizeof(TestOperation));
if(operation)
{
operation->session = session;
operation->operationId = 1;
}
return operation;
}
void Close_TestOperation(TestOperation *operation)
{
if(operation)
SystemFree(operation);
}
int Execute_Operation(int a[5], ProtocolType protoType)
{
int sum = 0;
for(int i = 0; i < 5; i++)
{
sum += a[i];
}
if(protoType == ProtocolB)
{
return sum + 1;
}
else
{
return sum;
}
}
/*********************************************************************************************************************************
** Test code with duplication
**********************************************************************************************************************************/
NitsTest(TestOperationProtocolA)
TestApplication *application = Create_TestApplication();
NitsAssertOrReturn(application != NULL, PAL_T("application creation failed"));
TestSession *session = Create_TestSession(application, ProtocolA);
NitsAssertOrReturn(session != NULL, PAL_T("session creation failed on protocol A"));
TestOperation *operation = Create_TestOperation(session);
NitsAssertOrReturn(operation != NULL, PAL_T("operation creation failed"));
int a[5] = {0, 1, 2, 3, 4};
NitsAssertOrReturn(Execute_Operation(a, ProtocolA) == 10, PAL_T("Operation execute failed"));
NitsEndTest
NitsTest(TestOperationProtocolB)
TestApplication *application = Create_TestApplication();
NitsAssertOrReturn(application != NULL, PAL_T("application creation failed"));
TestSession *session = Create_TestSession(application, ProtocolB);
NitsAssertOrReturn(session != NULL, PAL_T("session creation failed on protocol B"));
TestOperation *operation = Create_TestOperation(session);
NitsAssertOrReturn(operation != NULL, PAL_T("operation creation failed"));
int a[5] = {0, 1, 2, 3, 4};
NitsAssertOrReturn(Execute_Operation(a, ProtocolB) == 11, PAL_T("Operation execute failed"));
NitsEndTest
/*********************************************************************************************************************************
** Refactored test code
**********************************************************************************************************************************/
struct CommonData
{
TestApplication *application;
TestSession *session;
TestOperation *operation;
};
NitsSetup0(CommonSetup, CommonData)
NitsTrace(PAL_T("CommonSetup being run"));
NitsEndSetup
NitsSetup1(SetupApplication, NitsEmptyStruct,
CommonSetup, CommonSetupDefaults)
NitsContext()->_CommonSetup->_CommonData->application = Create_TestApplication();
NitsTrace(PAL_T("SetupApplication being run"));
NitsAssertOrReturn(NitsContext()->_CommonSetup->_CommonData->application != NULL, PAL_T("application creation failed"));
NitsEndSetup
struct SessionData
{
int protocolType;
};
NitsSetup0(SetupSessionProtocolA, SessionData)
NitsTrace(PAL_T("SetupSessionProtocolA being run"));
NitsContext()->_SessionData->protocolType = ProtocolA;
NitsEndSetup
NitsSetup0(SetupSessionProtocolB, SessionData)
NitsTrace(PAL_T("SetupSessionProtocolB being run"));
NitsContext()->_SessionData->protocolType = ProtocolB;
NitsEndSetup
NitsSplit2(SetupSessionSplit, SessionData,
SetupSessionProtocolA, SetupSessionProtocolB)
NitsTrace(PAL_T("SetupSessionSplit being run"));
NitsEndSplit
NitsSetup2(SetupSessionProtocol, NitsEmptyStruct,
CommonSetup, CommonSetupDefaults,
SetupSessionSplit, SetupSessionSplitDefaults)
NitsContext()->_CommonSetup->_CommonData->session = Create_TestSession(NitsContext()->_CommonSetup->_CommonData->application,
(ProtocolType)NitsContext()->_SetupSessionSplit->_SetupSessionProtocolA->_SessionData->protocolType);
NitsAssertOrReturn(NitsContext()->_CommonSetup->_CommonData->session != NULL, PAL_T("session creation failed"));
NitsTrace(PAL_T("SetupSessionProtocol being run"));
NitsEndSetup
struct OperationData
{
int *a;
};
NitsSetup1(SetupOperation, OperationData,
CommonSetup, CommonSetupDefaults)
int a[5] = {0, 1, 2, 3, 4};
NitsContext()->_OperationData->a = a;
NitsContext()->_CommonSetup->_CommonData->operation = Create_TestOperation(NitsContext()->_CommonSetup->_CommonData->session);
NitsAssertOrReturn(NitsContext()->_CommonSetup->_CommonData->operation != NULL, PAL_T("operation creation failed"));
NitsTrace(PAL_T("SetupOperation being run"));
NitsEndSetup
NitsTest3(TestOperationBothProtocols,
SetupApplication, SetupApplicationDefaults,
SetupSessionProtocol, SetupSessionProtocolDefaults,
SetupOperation, SetupOperationDefaults)
int result = Execute_Operation(NitsContext()->_SetupOperation->_OperationData->a,
(ProtocolType)(NitsContext()->_SetupSessionProtocol->_SetupSessionSplit->_SessionData->protocolType));
if(NitsContext()->_SetupSessionProtocol->_SetupSessionSplit->_SessionData->protocolType == ProtocolA)
NitsAssert(result == 10, PAL_T("Operation execute failed"));
else if(NitsContext()->_SetupSessionProtocol->_SetupSessionSplit->_SessionData->protocolType == ProtocolB)
NitsAssert(result == 11, PAL_T("Operation execute failed"));
else
NitsAssert(false, PAL_T("unknown protocol"));
NitsTrace(PAL_T("TestOperationBothProtocols being run"));
NitsEndTest
|
#include<bits/stdc++.h>
#include"binarysearchtree.h"
#include"binarysearchtree.cpp"
using namespace std;
int main()
{
TreeType<int>BST;
if(BST.IsEmpty())
cout << "Tree is empty" << endl;
else
cout << "Tree is not empty" << endl;
BST.InsertItem(4);
BST.InsertItem(9);
BST.InsertItem(2);
BST.InsertItem(7);
BST.InsertItem(3);
BST.InsertItem(11);
BST.InsertItem(17);
BST.InsertItem(0);
BST.InsertItem(5);
BST.InsertItem(1);
if(BST.IsEmpty())
cout << "Tree is empty" << endl;
else
cout << "Tree is not empty" << endl;
cout << BST.LengthIs() << endl;
int x = 9;
bool flag;
BST.RetrieveItem(x,flag);
if(flag==true)
cout << "Item is found" << endl;
else
cout << "Item is not found" << endl;
x = 13;
BST.RetrieveItem(x,flag);
if(flag==true)
cout << "Item is found" << endl;
else
cout << "Item is not found" << endl;
BST.ResetTree(IN_ORDER);
BST.ResetTree(PRE_ORDER);
BST.ResetTree(POST_ORDER);
flag = false;
while(!flag)
{
BST.GetNextItem(x,IN_ORDER,flag);
cout << x << " " ;
}
cout << endl;
flag = false;
while(!flag)
{
BST.GetNextItem(x,PRE_ORDER,flag);
cout << x << " " ;
}
cout << endl;
flag = false;
while(!flag)
{
BST.GetNextItem(x,POST_ORDER,flag);
cout << x << " " ;
}
cout << endl;
return 0;
}
|
#pragma once
#include <cstdint>
#include <exception>
#include <util/debug.hpp>
#include <backends/gpu/fill.hpp>
#include "allocator.hpp"
#include "array.hpp"
#include "definitions.hpp"
#include "gpu.hpp"
#include "util.hpp"
namespace arb {
namespace memory {
// forward declare
template <typename T, class Allocator>
class device_coordinator;
template <typename T, class Allocator>
class host_coordinator;
namespace util {
template <typename T, typename Allocator>
struct type_printer<device_coordinator<T,Allocator>>{
static std::string print() {
#if VERBOSE > 1
return util::white("device_coordinator") + "<"
+ type_printer<T>::print()
+ ", " + type_printer<Allocator>::print() + ">";
#else
return util::white("device_coordinator")
+ "<" + type_printer<T>::print() + ">";
#endif
}
};
template <typename T, typename Allocator>
struct pretty_printer<device_coordinator<T,Allocator>>{
static std::string print(const device_coordinator<T,Allocator>& val) {
return type_printer<device_coordinator<T,Allocator>>::print();
}
};
} // namespace util
template <typename T>
class const_device_reference {
public:
using value_type = T;
using pointer = value_type*;
using const_pointer = const value_type*;
const_device_reference(const_pointer p) : pointer_(p) {}
operator T() const {
T tmp;
auto success
= cudaMemcpy(&tmp, pointer_, sizeof(T), cudaMemcpyDeviceToHost);
if(success != cudaSuccess) {
LOG_ERROR("cudaMemcpy(d2h, " + std::to_string(sizeof(T)) + ") " + cudaGetErrorString(success));
abort();
}
return T(tmp);
}
protected:
template <typename Other>
void operator =(Other&&) {}
const_pointer pointer_;
};
template <typename T>
class device_reference {
public:
using value_type = T;
using pointer = value_type*;
device_reference(pointer p) : pointer_(p) {}
device_reference& operator = (const T& value) {
auto success =
cudaMemcpy(pointer_, &value, sizeof(T), cudaMemcpyHostToDevice);
if(success != cudaSuccess) {
LOG_ERROR("cudaMemcpy(h2d, " + std::to_string(sizeof(T)) + ") " + cudaGetErrorString(success));
abort();
}
return *this;
}
operator T() const {
T tmp;
auto success =
cudaMemcpy(&tmp, pointer_, sizeof(T), cudaMemcpyDeviceToHost);
if(success != cudaSuccess) {
LOG_ERROR("cudaMemcpy(d2h, " + std::to_string(sizeof(T)) + ") " + cudaGetErrorString(success));
abort();
}
return T(tmp);
}
private:
pointer pointer_;
};
template <typename T, class Allocator_= cuda_allocator<T> >
class device_coordinator {
public:
using value_type = T;
using Allocator = typename Allocator_::template rebind<value_type>;
using pointer = value_type*;
using const_pointer = const value_type*;
using reference = device_reference<value_type>;
using const_reference = const_device_reference<value_type>;
using view_type = array_view<value_type, device_coordinator>;
using const_view_type = const_array_view<value_type, device_coordinator>;
using size_type = types::size_type;
using difference_type = types::difference_type;
template <typename Tother>
using rebind = device_coordinator<Tother, Allocator>;
view_type allocate(size_type n) {
Allocator allocator;
pointer ptr = n>0 ? allocator.allocate(n) : nullptr;
#ifdef VERBOSE
std::cerr << util::type_printer<device_coordinator>::print()
<< util::blue("::allocate") << "(" << n << ") -> " << util::print_pointer(ptr)
<< "\n";
#endif
return view_type(ptr, n);
}
void free(view_type& rng) {
Allocator allocator;
#ifdef VERBOSE
std::cerr << util::type_printer<device_coordinator>::print()
<< util::blue("::free") << "(size=" << rng.size() << ", pointer=" << util::print_pointer(rng.data()) << ")\n";
#endif
if(rng.data()) {
allocator.deallocate(rng.data(), rng.size());
}
impl::reset(rng);
}
// copy memory from one gpu range to another
void copy(const_view_type from, view_type to) {
//template<typename Alloc1, typename Alloc2>
//void copy(
//const_array_view<value_type, device_coordinator<value_type, Alloc1>> from,
//array_view<value_type, device_coordinator<value_type, Alloc2>> to)
//{
#ifdef VERBOSE
std::cerr << util::type_printer<device_coordinator>::print()
<< util::blue("::copy") << "(size=" << from.size() << ") "
<< util::print_pointer(from.data()) << " -> "
<< util::print_pointer(to.data()) << "\n";
#endif
EXPECTS(from.size()==to.size());
EXPECTS(!from.overlaps(to));
gpu::memcpy_d2d(from.data(), to.data(), from.size());
}
// copy memory from gpu to host
template <typename Allocator>
void copy(
const_view_type& from,
array_view<value_type, host_coordinator<value_type, Allocator>>& to)
{
#ifdef VERBOSE
std::cerr << util::type_printer<device_coordinator>::print()
<< util::blue("::copy") << "(d2h, size=" << from.size() << ") "
<< util::print_pointer(from.data()) << " -> "
<< util::print_pointer(to.data()) << "\n";
#endif
EXPECTS(from.size()==to.size());
gpu::memcpy_d2h(from.data(), to.data(), from.size());
}
// copy memory from host to gpu
template <class Alloc>
void copy(
const_array_view<value_type, host_coordinator<value_type, Alloc>> from,
view_type to)
{
#ifdef VERBOSE
std::cerr << util::type_printer<device_coordinator>::print()
<< util::blue("::copy") << "(size=" << from.size() << ") "
<< util::print_pointer(from.data()) << " -> "
<< util::print_pointer(to.data()) << "\n";
#endif
EXPECTS(from.size()==to.size());
gpu::memcpy_h2d(from.data(), to.data(), from.size());
}
// copy from pinned memory to device
// TODO : asynchronous version
template <size_t alignment>
void copy(
const_array_view<value_type, host_coordinator<value_type, pinned_allocator<value_type, alignment>>> from,
view_type to)
{
#ifdef VERBOSE
std::cerr << util::type_printer<device_coordinator>::print()
<< util::blue("::copy") << "(size=" << from.size() << ") " << from.data() << " -> " << to.data() << "\n";
#endif
EXPECTS(from.size()==to.size());
#ifdef VERBOSE
using oType = array_view< value_type, host_coordinator< value_type, pinned_allocator< value_type, alignment>>>;
std::cout << util::pretty_printer<device_coordinator>::print(*this)
<< "::" << util::blue("copy") << "(asynchronous, " << from.size() << ")"
<< "\n " << util::type_printer<oType>::print() << " "
<< util::print_pointer(from.data()) << " -> "
<< util::print_pointer(to.data()) << "\n";
#endif
auto status = cudaMemcpy(
reinterpret_cast<void*>(to.begin()),
reinterpret_cast<const void*>(from.begin()),
from.size()*sizeof(value_type),
cudaMemcpyHostToDevice
);
if(status != cudaSuccess) {
LOG_ERROR("cudaMemcpy(h2d, " + std::to_string(sizeof(T)*from.size()) + ") " + cudaGetErrorString(status));
abort();
}
}
// generates compile time error if there is an attempt to copy from memory
// that is managed by a coordinator for which there is no specialization
template <class CoordOther>
void copy(const array_view<value_type, CoordOther>& from, view_type& to) {
static_assert(true, "device_coordinator: unable to copy from other Coordinator");
}
// fill memory
void set(view_type &rng, value_type value) {
if (rng.size()) {
arb::gpu::fill<value_type>(rng.data(), value, rng.size());
}
}
// generate reference objects for a raw pointer.
reference make_reference(value_type* p) {
return reference(p);
}
const_reference make_reference(value_type const* p) const {
return const_reference(p);
}
static constexpr
auto alignment() -> decltype(Allocator_::alignment()) {
return Allocator_::alignment();
}
static constexpr
bool is_malloc_compatible() {
return Allocator_::is_malloc_compatible();
}
};
} // namespace memory
} // namespace arb
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet.h"
#include "walletdb.h"
#include "crypter.h"
#include "ui_interface.h"
#include "base58.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// mapWallet
//
struct CompareValueOnly
{
bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
};
CPubKey CWallet::GenerateNewKey()
{
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey(fCompressed);
// Compressed public keys were introduced in version 0.6.0
if (fCompressed)
SetMinVersion(FEATURE_COMPRPUBKEY);
if (!AddKey(key))
throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CWallet::AddKey(const CKey& key)
{
if (!CCryptoKeyStore::AddKey(key))
return false;
if (!fFileBacked)
return true;
if (!IsCrypted())
return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
return true;
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret);
else
return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret);
}
return false;
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase)
{
if (!IsLocked())
return false;
CCrypter crypter;
CKeyingMaterial vMasterKey;
{
LOCK(cs_wallet);
BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey))
return true;
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial vMasterKey;
BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey))
{
int64 nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
// This class implements an addrIncoming entry that causes pre-0.4
// clients to crash on startup if reading a private-key-encrypted wallet.
class CCorruptAddress
{
public:
IMPLEMENT_SERIALIZE
(
if (nType & SER_DISK)
READWRITE(nVersion);
)
};
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
if (fFileBacked)
{
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
if (nWalletVersion >= 40000)
{
// Versions prior to 0.4.0 did not support the "minversion" record.
// Use a CCorruptAddress to make them crash instead.
CCorruptAddress corruptAddress;
pwalletdb->WriteSetting("addrIncoming", corruptAddress);
}
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial vMasterKey;
RandAddSeedPerfmon();
vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
RandAddSeedPerfmon();
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64 nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
if (fFileBacked)
{
pwalletdbEncryption = new CWalletDB(strWalletFile);
if (!pwalletdbEncryption->TxnBegin())
return false;
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
}
if (!EncryptKeys(vMasterKey))
{
if (fFileBacked)
pwalletdbEncryption->TxnAbort();
exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (fFileBacked)
{
if (!pwalletdbEncryption->TxnCommit())
exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
Lock();
Unlock(strWalletPassphrase);
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
CDB::Rewrite(strWalletFile);
}
NotifyStatusChanged(this);
return true;
}
void CWallet::WalletUpdateSpent(const CTransaction &tx)
{
// Anytime a signature is successfully verified, it's proof the outpoint is spent.
// Update the wallet spent flag if it doesn't know due to wallet.dat being
// restored from backup or the user making copies of wallet.dat.
{
LOCK(cs_wallet);
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
CWalletTx& wtx = (*mi).second;
if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
{
printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
wtx.MarkSpent(txin.prevout.n);
wtx.WriteToDisk();
NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
}
}
}
}
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn)
{
uint256 hash = wtxIn.GetHash();
{
LOCK(cs_wallet);
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew)
wtx.nTimeReceived = GetAdjustedTime();
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
{
wtx.vMerkleBranch = wtxIn.vMerkleBranch;
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
}
//// debug print
printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!wtx.WriteToDisk())
return false;
#ifndef QT_GUI
// If default receiving address gets used, replace it with a new one
CScript scriptDefaultKey;
scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (txout.scriptPubKey == scriptDefaultKey)
{
CPubKey newDefaultKey;
if (GetKeyFromPool(newDefaultKey, false))
{
SetDefaultKey(newDefaultKey);
SetAddressBookName(vchDefaultKey.GetID(), "");
}
}
}
#endif
// since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
WalletUpdateSpent(wtx);
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
}
return true;
}
// Add a transaction to the wallet, or update it.
// pblock is optional, but should be provided if the transaction is known to be in a block.
// If fUpdate is true, existing transactions will be updated.
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
{
uint256 hash = tx.GetHash();
{
LOCK(cs_wallet);
bool fExisted = mapWallet.count(hash);
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
CWalletTx wtx(this,tx);
// Get merkle branch if transaction was found in a block
if (pblock)
wtx.SetMerkleBranch(pblock);
return AddToWallet(wtx);
}
else
WalletUpdateSpent(tx);
}
return false;
}
bool CWallet::EraseFromWallet(uint256 hash)
{
if (!fFileBacked)
return false;
{
LOCK(cs_wallet);
if (mapWallet.erase(hash))
CWalletDB(strWalletFile).EraseTx(hash);
}
return true;
}
bool CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]))
return true;
}
}
return false;
}
int64 CWallet::GetDebit(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]))
return prev.vout[txin.prevout.n].nValue;
}
}
return 0;
}
bool CWallet::IsChange(const CTxOut& txout) const
{
CTxDestination address;
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a TX_PUBKEYHASH that is mine but isn't in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
{
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
int64 CWalletTx::GetTxTime() const
{
return nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase())
{
// Generated block
if (hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
}
else
{
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
{
nGeneratedImmature = nGeneratedMature = nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
if (IsCoinBase())
{
if (GetBlocksToMaturity() > 0)
nGeneratedImmature = pwallet->GetCredit(*this);
else
nGeneratedMature = GetCredit();
return;
}
// Compute fee:
int64 nDebit = GetDebit();
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
int64 nValueOut = GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
BOOST_FOREACH(const CTxOut& txout, vout)
{
CTxDestination address;
vector<unsigned char> vchPubKey;
if (!ExtractDestination(txout.scriptPubKey, address))
{
printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString().c_str());
}
// Don't report 'change' txouts
if (nDebit > 0 && pwallet->IsChange(txout))
continue;
if (nDebit > 0)
listSent.push_back(make_pair(address, txout.nValue));
if (pwallet->IsMine(txout))
listReceived.push_back(make_pair(address, txout.nValue));
}
}
void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
int64& nSent, int64& nFee) const
{
nGenerated = nReceived = nSent = nFee = 0;
int64 allGeneratedImmature, allGeneratedMature, allFee;
allGeneratedImmature = allGeneratedMature = allFee = 0;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (strAccount == "")
nGenerated = allGeneratedMature;
if (strAccount == strSentAccount)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
nSent += s.second;
nFee = allFee;
}
{
LOCK(pwallet->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
{
if (pwallet->mapAddressBook.count(r.first))
{
map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
nReceived += r.second;
}
else if (strAccount.empty())
{
nReceived += r.second;
}
}
}
}
void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
{
vtxPrev.clear();
const int COPY_DEPTH = 3;
if (SetMerkleBranch() < COPY_DEPTH)
{
vector<uint256> vWorkQueue;
BOOST_FOREACH(const CTxIn& txin, vin)
vWorkQueue.push_back(txin.prevout.hash);
// This critsect is OK because txdb is already open
{
LOCK(pwallet->cs_wallet);
map<uint256, const CMerkleTx*> mapWalletPrev;
set<uint256> setAlreadyDone;
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hash = vWorkQueue[i];
if (setAlreadyDone.count(hash))
continue;
setAlreadyDone.insert(hash);
CMerkleTx tx;
map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
if (mi != pwallet->mapWallet.end())
{
tx = (*mi).second;
BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
}
else if (mapWalletPrev.count(hash))
{
tx = *mapWalletPrev[hash];
}
else if (!fClient && txdb.ReadDiskTx(hash, tx))
{
;
}
else
{
printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
continue;
}
int nDepth = tx.SetMerkleBranch();
vtxPrev.push_back(tx);
if (nDepth < COPY_DEPTH)
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
vWorkQueue.push_back(txin.prevout.hash);
}
}
}
}
reverse(vtxPrev.begin(), vtxPrev.end());
}
bool CWalletTx::WriteToDisk()
{
return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
}
// Scan the block chain (starting in pindexStart) for transactions
// from or to us. If fUpdate is true, found transactions that already
// exist in the wallet will be updated.
int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
int ret = 0;
CBlockIndex* pindex = pindexStart;
{
LOCK(cs_wallet);
while (pindex)
{
CBlock block;
block.ReadFromDisk(pindex, true);
BOOST_FOREACH(CTransaction& tx, block.vtx)
{
if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
ret++;
}
pindex = pindex->pnext;
}
}
return ret;
}
int CWallet::ScanForWalletTransaction(const uint256& hashTx)
{
CTransaction tx;
tx.ReadFromDisk(COutPoint(hashTx, 0));
if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
return 1;
return 0;
}
void CWallet::ReacceptWalletTransactions()
{
CTxDB txdb("r");
bool fRepeat = true;
while (fRepeat)
{
LOCK(cs_wallet);
fRepeat = false;
vector<CDiskTxPos> vMissingTx;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
if (wtx.IsCoinBase() && wtx.IsSpent(0))
continue;
CTxIndex txindex;
bool fUpdated = false;
if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
{
// Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
if (txindex.vSpent.size() != wtx.vout.size())
{
printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
continue;
}
for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
{
if (wtx.IsSpent(i))
continue;
if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
{
wtx.MarkSpent(i);
fUpdated = true;
vMissingTx.push_back(txindex.vSpent[i]);
}
}
if (fUpdated)
{
printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
wtx.MarkDirty();
wtx.WriteToDisk();
}
}
else
{
// Reaccept any txes of ours that aren't already in a block
if (!wtx.IsCoinBase())
wtx.AcceptWalletTransaction(txdb, false);
}
}
if (!vMissingTx.empty())
{
// TODO: optimize this to scan just part of the block chain?
if (ScanForWalletTransactions(pindexGenesisBlock))
fRepeat = true; // Found missing transactions: re-do Reaccept.
}
}
}
void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
{
BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
{
if (!tx.IsCoinBase())
{
uint256 hash = tx.GetHash();
if (!txdb.ContainsTx(hash))
RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
}
}
if (!IsCoinBase())
{
uint256 hash = GetHash();
if (!txdb.ContainsTx(hash))
{
printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
}
}
}
void CWalletTx::RelayWalletTransaction()
{
CTxDB txdb("r");
RelayWalletTransaction(txdb);
}
void CWallet::ResendWalletTransactions()
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
static int64 nNextTime;
if (GetTime() < nNextTime)
return;
bool fFirst = (nNextTime == 0);
nNextTime = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
static int64 nLastTime;
if (nTimeBestReceived < nLastTime)
return;
nLastTime = GetTime();
// Rebroadcast any of our txes that aren't in a block yet
printf("ResendWalletTransactions()\n");
CTxDB txdb("r");
{
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast until it's had plenty of time that
// it should have gotten in already by now.
if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *item.second;
wtx.RelayWalletTransaction(txdb);
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Actions
//
int64 CWallet::GetBalance() const
{
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsFinal() && pcoin->IsConfirmed())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
int64 CWallet::GetUnconfirmedBalance() const
{
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
int64 CWallet::GetImmatureBalance() const
{
int64 nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx& pcoin = (*it).second;
if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.GetDepthInMainChain() >= 2)
nTotal += GetCredit(pcoin);
}
}
return nTotal;
}
// populate vCoins with vector of spendable COutputs
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
{
vCoins.clear();
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsFinal())
continue;
if (fOnlyConfirmed && !pcoin->IsConfirmed())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
// If output is less than minimum value, then don't include transaction.
// This is to help deal with dust spam clogging up create transactions.
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
}
}
}
static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
vector<char>& vfBest, int64& nBest, int iterations = 1000)
{
vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
int64 nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
{
nTotal += vValue[i].first;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].first;
vfIncluded[i] = false;
}
}
}
}
}
}
bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<int64>::max();
coinLowestLarger.second.first = NULL;
vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
int64 nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
BOOST_FOREACH(COutput output, vCoins)
{
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
continue;
int i = output.i;
int64 n = pcoin->vout[i].nValue;
pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
if (n == nTargetValue)
{
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
return true;
}
else if (n < nTargetValue + CENT)
{
vValue.push_back(coin);
nTotalLower += n;
}
else if (n < coinLowestLarger.first)
{
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue)
{
for (unsigned int i = 0; i < vValue.size(); ++i)
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (coinLowestLarger.second.first == NULL)
return false;
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
return true;
}
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
vector<char> vfBest;
int64 nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger.second.first &&
((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
{
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
}
else {
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
//// debug print
printf("SelectCoins() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
printf("%s ", FormatMoney(vValue[i].first).c_str());
printf("total %s\n", FormatMoney(nBest).c_str());
}
return true;
}
bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
vector<COutput> vCoins;
AvailableCoins(vCoins);
return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet));
}
bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
{
int64 nValue = 0;
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
{
if (nValue < 0)
return false;
nValue += s.second;
}
if (vecSend.empty() || nValue < 0)
return false;
wtxNew.BindWallet(this);
{
LOCK2(cs_main, cs_wallet);
// txdb must be opened before the mapWallet lock
CTxDB txdb("r");
{
nFeeRet = nTransactionFee;
loop
{
wtxNew.vin.clear();
wtxNew.vout.clear();
wtxNew.fFromMe = true;
int64 nTotalValue = nValue + nFeeRet;
double dPriority = 0;
// vouts to the payees
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
wtxNew.vout.push_back(CTxOut(s.second, s.first));
// Choose coins to use
set<pair<const CWalletTx*,unsigned int> > setCoins;
int64 nValueIn = 0;
if (!SelectCoins(nTotalValue, setCoins, nValueIn))
return false;
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
}
int64 nChange = nValueIn - nValue - nFeeRet;
// if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
// or until nChange becomes zero
// NOTE: this depends on the exact behaviour of GetMinFee
if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < COIN)
{
int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
nChange -= nMoveToFee;
nFeeRet += nMoveToFee;
}
if (nChange > 0)
{
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey = reservekey.GetReservedKey();
// assert(mapKeys.count(vchPubKey));
// Fill a vout to ourself
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-bitcoin-address
CScript scriptChange;
scriptChange.SetDestination(vchPubKey.GetID());
// Insert change txn at random position:
vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
}
else
reservekey.ReturnKey();
// Fill vin
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
// Sign
int nIn = 0;
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
return false;
// Limit size
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
return false;
dPriority /= nBytes;
// Check that enough fee is included
int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
bool fAllowFree = CTransaction::AllowFree(dPriority);
int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
if (nFeeRet < max(nPayFee, nMinFee))
{
nFeeRet = max(nPayFee, nMinFee);
continue;
}
// Fill vtxPrev by copying from previous transactions vtxPrev
wtxNew.AddSupportingTransactions(txdb);
wtxNew.fTimeReceivedIsTxTime = true;
break;
}
}
}
return true;
}
bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
{
vector< pair<CScript, int64> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
}
// Call after CreateTransaction unless you want to abort
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
{
{
LOCK2(cs_main, cs_wallet);
printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
// maybe makes sense; please don't do it anywhere else.
CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Mark old coins as spent
set<CWalletTx*> setCoins;
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
{
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
coin.MarkSpent(txin.prevout.n);
coin.WriteToDisk();
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
}
if (fFileBacked)
delete pwalletdb;
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
// Broadcast
if (!wtxNew.AcceptToMemoryPool())
{
// This must not fail. The transaction has already been signed and recorded.
printf("CommitTransaction() : Error: Transaction not valid");
return false;
}
wtxNew.RelayWalletTransaction();
}
return true;
}
string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
{
CReserveKey reservekey(this);
int64 nFeeRequired;
if (IsLocked())
{
string strError = _("Error: Wallet locked, unable to create transaction ");
printf("SendMoney() : %s", strError.c_str());
return strError;
}
if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
{
string strError;
if (nValue + nFeeRequired > GetBalance())
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
else
strError = _("Error: Transaction creation failed ");
printf("SendMoney() : %s", strError.c_str());
return strError;
}
if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
return "ABORTED";
if (!CommitTransaction(wtxNew, reservekey))
return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
return "";
}
string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
{
// Check amount
if (nValue <= 0)
return _("Invalid amount");
if (nValue + nTransactionFee > GetBalance())
return _("Insufficient funds");
// Parse Bitcoin address
CScript scriptPubKey;
scriptPubKey.SetDestination(address);
return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
}
int CWallet::LoadWallet(bool& fFirstRunRet)
{
if (!fFileBacked)
return false;
fFirstRunRet = false;
int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (CDB::Rewrite(strWalletFile, "\x04pool"))
{
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// the requires a new key.
}
nLoadWalletRet = DB_NEED_REWRITE;
}
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
fFirstRunRet = !vchDefaultKey.IsValid();
CreateThread(ThreadFlushWalletDB, &strWalletFile);
return DB_LOAD_OK;
}
bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
{
std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
mapAddressBook[address] = strName;
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
if (!fFileBacked)
return false;
return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
}
bool CWallet::DelAddressBookName(const CTxDestination& address)
{
mapAddressBook.erase(address);
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
if (!fFileBacked)
return false;
return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
}
void CWallet::PrintWallet(const CBlock& block)
{
{
LOCK(cs_wallet);
if (mapWallet.count(block.vtx[0].GetHash()))
{
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
}
}
printf("\n");
}
bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
{
wtx = (*mi).second;
return true;
}
}
return false;
}
bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
{
if (fFileBacked)
{
if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
return false;
}
vchDefaultKey = vchPubKey;
return true;
}
bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
{
if (!pwallet->fFileBacked)
return false;
strWalletFileOut = pwallet->strWalletFile;
return true;
}
//
// Mark old keypool keys as used,
// and generate all new keys
//
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile);
BOOST_FOREACH(int64 nIndex, setKeyPool)
walletdb.ErasePool(nIndex);
setKeyPool.clear();
if (IsLocked())
return false;
int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
for (int i = 0; i < nKeys; i++)
{
int64 nIndex = i+1;
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
}
printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
}
return true;
}
bool CWallet::TopUpKeyPool()
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
CWalletDB walletdb(strWalletFile);
// Top up key pool
unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
while (setKeyPool.size() < (nTargetSize + 1))
{
int64 nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool() : writing generated key failed");
setKeyPool.insert(nEnd);
printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
}
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
// Get the oldest key
if(setKeyPool.empty())
return;
CWalletDB walletdb(strWalletFile);
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("ReserveKeyFromKeyPool() : read failed");
if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
assert(keypool.vchPubKey.IsValid());
printf("keypool reserve %"PRI64d"\n", nIndex);
}
}
int64 CWallet::AddReserveKey(const CKeyPool& keypool)
{
{
LOCK2(cs_main, cs_wallet);
CWalletDB walletdb(strWalletFile);
int64 nIndex = 1 + *(--setKeyPool.end());
if (!walletdb.WritePool(nIndex, keypool))
throw runtime_error("AddReserveKey() : writing added key failed");
setKeyPool.insert(nIndex);
return nIndex;
}
return -1;
}
void CWallet::KeepKey(int64 nIndex)
{
// Remove from key pool
if (fFileBacked)
{
CWalletDB walletdb(strWalletFile);
walletdb.ErasePool(nIndex);
}
printf("keypool keep %"PRI64d"\n", nIndex);
}
void CWallet::ReturnKey(int64 nIndex)
{
// Return to key pool
{
LOCK(cs_wallet);
setKeyPool.insert(nIndex);
}
printf("keypool return %"PRI64d"\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
{
int64 nIndex = 0;
CKeyPool keypool;
{
LOCK(cs_wallet);
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
{
if (fAllowReuse && vchDefaultKey.IsValid())
{
result = vchDefaultKey;
return true;
}
if (IsLocked()) return false;
result = GenerateNewKey();
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
int64 CWallet::GetOldestKeyPoolTime()
{
int64 nIndex = 0;
CKeyPool keypool;
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
return GetTime();
ReturnKey(nIndex);
return keypool.nTime;
}
CPubKey CReserveKey::GetReservedKey()
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else
{
printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool.");
vchPubKey = pwallet->vchDefaultKey;
}
}
assert(vchPubKey.IsValid());
return vchPubKey;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1)
pwallet->ReturnKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
{
setAddress.clear();
CWalletDB walletdb(strWalletFile);
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH(const int64& id, setKeyPool)
{
CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool))
throw runtime_error("GetAllReserveKeyHashes() : read failed");
assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID))
throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
setAddress.insert(keyID);
}
}
void CWallet::UpdatedTransaction(const uint256 &hashTx)
{
{
LOCK(cs_wallet);
// Only notify UI if this transaction is in this wallet
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
NotifyTransactionChanged(this, hashTx, CT_UPDATED);
}
}
|
#ifdef DEBUG_THREEVECTOR
#include <iostream>
#include <assert.h>
#include <stdlib.h>
using namespace std;
#endif
#include "dem_parser/threevector.h"
#include <math.h>
#define sind(x) (sin(fmod((x),360) * M_PI / 180))
#define cosd(x) (cos(fmod((x),360) * M_PI / 180))
ThreeVector::ThreeVector() {
this->x = 0;
this->y = 0;
this->z = 0;
}
ThreeVector::ThreeVector(double x, double y, double z){
this->x = x;
this->y = y;
this->z = z;
}
double ThreeVector::magnitude(){
return sqrt(x*x + y*y + z*z);
}
ThreeVector ThreeVector::normalize() {
double m = this->magnitude();
ThreeVector a;
if (m != 0) {
a.x = x/m;
a.y = y/m;
a.z = z/m;
}
return a;
}
double ThreeVector::dotProduct(ThreeVector a ,ThreeVector b) {
return a.x*b.x + a.y*b.y + a.z*b.z;
}
double ThreeVector::dotProduct(ThreeVector a , double x, double y, double z) {
return a.x*x + a.y*y + a.z*z;
}
double ThreeVector::dot(double x, double y, double z){
return ThreeVector::dotProduct(*this, x,y,z);
}
double ThreeVector::dot(ThreeVector b) {
return ThreeVector::dotProduct(*this, b);
}
ThreeVector ThreeVector::crossProduct(ThreeVector a ,ThreeVector b) {
ThreeVector cp(0,0,0);
cp.x = (a.y * b.z - a.z * b.y);
cp.y = -1.0*(a.x * b.z - a.z * b.x);
cp.z = (a.x * b.y - a.y * b.x);
return cp;
}
ThreeVector ThreeVector::cross(double x, double y, double z) {
ThreeVector b(x,y,z);
return ThreeVector::crossProduct(*this, b);
}
ThreeVector ThreeVector::cross(ThreeVector b) {
return ThreeVector::crossProduct(*this, b);
}
ThreeVector calculateECEF(double lat, double lon, double height) {
const double a = 6378137.0;
const double b = 6356752.314245;
double N = a*a / sqrt(pow(a*cosd(lat),2) + pow(b*sind(lat),2));
double x = (N + height)*cosd(lat)*cosd(lon);
double y = (N + height)*cosd(lat)*sind(lon);
double z = (pow(b/a, 2)*N + height)*sind(lat);
ThreeVector r(x,y,z);
return r;
}
#ifdef DEBUG_THREEVECTOR
int main() {
for (int i = 0; i < 10000000; i++) {
int h = rand()%3;
int v = rand()%1000 - 500;
ThreeVector a;
a.x = h == 0 ? v : 0;
a.y = h == 1 ? v : 0;
a.z = h == 2 ? v : 0;
assert(abs(a.magnitude() - abs(v)) < 0.00001);
assert(a.magnitude() >= 0.0);
}
for (int i = 0; i < 10000000; i++) {
ThreeVector a(rand()%1000 - 500, rand()%1000 - 500, rand()%1000 - 500);
ThreeVector b(rand()%1000 - 500, rand()%1000 - 500, rand()%1000 - 500);
assert((a.normalize().magnitude() < 1.0001 &&
a.normalize().magnitude() > 0.9999) ||
a.magnitude() == 0.0 );
assert(abs(a.cross(b).dot(a)) < 0.00001);
assert(abs(a.cross(b).dot(b)) < 0.00001);
ThreeVector c = a-b;
assert((a.x - b.x) == c.x);
assert((a.y - b.y) == c.y);
assert((a.z - b.z) == c.z);
ThreeVector d = a+b;
assert((a.x + b.x) == d.x);
assert((a.y + b.y) == d.y);
assert((a.z + b.z) == d.z);
}
ThreeVector northPole = calculateECEF(0, 0, 0);
cout << northPole.x << "," << northPole.y << "," << northPole.z << endl;
}
#endif
|
#ifndef _FTK_CONNECT_COMPONENT_TRACKER
#define _FTK_CONNECT_COMPONENT_TRACKER
#include <ftk/filters/filter.hh>
#include <ftk/tracking_graph/tracking_graph.hh>
namespace ftk {
template <typename TimeIndexType=size_t, typename LabelIdType=size_t>
struct connected_component_tracker : public filter
{
connected_component_tracker() {}
virtual ~connected_component_tracker() {};
virtual bool advance_timestep();
virtual void update_timestep();
void update() {};
void finalize();
virtual void push_labeled_data_snapshot(const std::vector<LabelIdType>& labels);
const std::vector<LabelIdType>& get_last_labeled_data_snapshot() const {return labeled_data_snapshots.back();}
template <typename ContainerType>
void push_unlabeled_data_snapshot(const std::vector<LabelIdType>& labels, std::function<ContainerType(LabelIdType)> neighbors);
bool pop_snapshot();
const ftk::tracking_graph<>& get_tracking_graph() const {return tg;}
protected:
ftk::tracking_graph<TimeIndexType, LabelIdType> tg;
std::deque<std::vector<LabelIdType>> labeled_data_snapshots;
TimeIndexType current_timestep = 0;
};
/////
template <typename TimeIndexType, typename LabelIdType>
void connected_component_tracker<TimeIndexType, LabelIdType>::finalize()
{
tg.relabel();
}
template <typename TimeIndexType, typename LabelIdType>
void connected_component_tracker<TimeIndexType, LabelIdType>::update_timestep()
{
if (labeled_data_snapshots.size() < 2) return;
const auto &labels0 = labeled_data_snapshots[0],
&labels1 = labeled_data_snapshots[1];
for (size_t i = 0; i < labels0.size(); i ++)
if (labels0[i] != 0 && labels1[i] != 0) {
// fprintf(stderr, "edge: %d --> %d\n", labels0[i], labels1[i]);
tg.add_edge(current_timestep-1, labels0[i], current_timestep, labels1[i]);
}
}
template <typename TimeIndexType, typename LabelIdType>
bool connected_component_tracker<TimeIndexType, LabelIdType>::advance_timestep()
{
// fprintf(stderr, "#labeled_data_snapshots=%zu\n", labeled_data_snapshots.size());
update_timestep();
current_timestep ++;
if (labeled_data_snapshots.size() > 1)
pop_snapshot();
return labeled_data_snapshots.size() > 0;
}
template <typename TimeIndexType, typename LabelIdType>
void connected_component_tracker<TimeIndexType, LabelIdType>::push_labeled_data_snapshot(const std::vector<LabelIdType>& labels)
{
labeled_data_snapshots.push_back(labels);
}
template <typename TimeIndexType, typename LabelIdType>
bool connected_component_tracker<TimeIndexType, LabelIdType>::pop_snapshot()
{
if (labeled_data_snapshots.size() > 0) {
labeled_data_snapshots.pop_front();
return true;
} else return false;
}
}
#endif
|
// ======================================================================== //
// Copyright 2009-2013 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "renderers/integratorrenderer.h"
/* include all integrators */
#include "integrators/pathtraceintegrator.h"
/* include all samplers */
#include "samplers/sampler.h"
/* include all image filters */
#include "filters/boxfilter.h"
#include "filters/bsplinefilter.h"
namespace embree
{
IntegratorRenderer::IntegratorRenderer(const Parms& parms)
: iteration(0)
{
/*! create integrator to use */
std::string _integrator = parms.getString("integrator","pathtracer");
if (_integrator == "pathtracer") integrator = new PathTraceIntegrator(parms);
else throw std::runtime_error("unknown integrator type: "+_integrator);
/*! create sampler to use */
std::string _samplers = parms.getString("sampler","multijittered");
if (_samplers == "multijittered" ) samplers = new SamplerFactory(parms);
else throw std::runtime_error("unknown sampler type: "+_samplers);
/*! create pixel filter to use */
std::string _filter = parms.getString("filter","bspline");
if (_filter == "none" ) filter = NULL;
else if (_filter == "box" ) filter = new BoxFilter;
else if (_filter == "bspline") filter = new BSplineFilter;
else throw std::runtime_error("unknown filter type: "+_filter);
/*! get framebuffer configuration */
gamma = parms.getFloat("gamma",1.0f);
/*! show progress to the user */
showProgress = parms.getInt("showprogress",0);
}
void IntegratorRenderer::renderFrame(const Ref<Camera>& camera, const Ref<BackendScene>& scene, const Ref<ToneMapper>& toneMapper, Ref<SwapChain > swapchain, int accumulate)
{
if (accumulate == 0) iteration = 0;
new RenderJob(this,camera,scene,toneMapper,swapchain,accumulate,iteration);
iteration++;
}
IntegratorRenderer::RenderJob::RenderJob (Ref<IntegratorRenderer> renderer, const Ref<Camera>& camera, const Ref<BackendScene>& scene,
const Ref<ToneMapper>& toneMapper, Ref<SwapChain > swapchain, int accumulate, int iteration)
: renderer(renderer), camera(camera), scene(scene), toneMapper(toneMapper), swapchain(swapchain),
accumulate(accumulate), iteration(iteration), tileID(0), atomicNumRays(0)
{
numTilesX = ((int)swapchain->getWidth() +TILE_SIZE-1)/TILE_SIZE;
numTilesY = ((int)swapchain->getHeight()+TILE_SIZE-1)/TILE_SIZE;
rcpWidth = rcp(float(swapchain->getWidth()));
rcpHeight = rcp(float(swapchain->getHeight()));
this->framebuffer = swapchain->buffer();
this->framebuffer->startRendering(numTilesX*numTilesY);
if (renderer->showProgress) new (&progress) Progress(numTilesX*numTilesY);
if (renderer->showProgress) progress.start();
renderer->samplers->reset();
renderer->integrator->requestSamples(renderer->samplers, scene);
renderer->samplers->init(iteration,renderer->filter);
#if 1
TaskScheduler::EventSync event;
TaskScheduler::Task task(&event,_renderTile,this,TaskScheduler::getNumThreads(),_finish,this,"render::tile");
TaskScheduler::addTask(-1,TaskScheduler::GLOBAL_BACK,&task);
event.sync();
#else
new (&task) TaskScheduler::Task (NULL,_renderTile,this,TaskScheduler::getNumThreads(),_finish,this,"render::tile");
TaskScheduler::addTask(-1,TaskScheduler::GLOBAL_BACK,&task);
#endif
}
void IntegratorRenderer::RenderJob::finish(size_t threadIndex, size_t threadCount, TaskScheduler::Event* event)
{
if (renderer->showProgress) progress.end();
double dt = getSeconds()-t0;
/*! print fps, render time, and rays per second */
std::ostringstream stream;
stream << "render ";
stream.setf(std::ios::fixed, std::ios::floatfield);
stream.precision(2);
stream << 1.0f/dt << " fps, ";
stream.precision(0);
stream << dt*1000.0f << " ms, ";
stream.precision(3);
stream << atomicNumRays/dt*1E-6 << " mrps";
std::cout << stream.str() << std::endl;
delete this;
}
void IntegratorRenderer::RenderJob::renderTile(size_t threadIndex, size_t threadCount, size_t taskIndex, size_t taskCount, TaskScheduler::Event* event)
{
/*! create a new sampler */
IntegratorState state;
if (taskIndex == taskCount-1) t0 = getSeconds();
/*! tile pick loop */
while (true)
{
/*! pick a new tile */
size_t tile = tileID++;
if (tile >= numTilesX*numTilesY) break;
/*! process all tile samples */
const int tile_x = (tile%numTilesX)*TILE_SIZE;
const int tile_y = (tile/numTilesX)*TILE_SIZE;
Random randomNumberGenerator(tile_x * 91711 + tile_y * 81551 + 3433*swapchain->firstActiveLine());
for (size_t dy=0; dy<TILE_SIZE; dy++)
{
size_t y = tile_y+dy;
if (y >= swapchain->getHeight()) continue;
if (!swapchain->activeLine(y)) continue;
size_t _y = swapchain->raster2buffer(y);
for (size_t dx=0; dx<TILE_SIZE; dx++)
{
size_t x = tile_x+dx;
if (x >= swapchain->getWidth()) continue;
const int set = randomNumberGenerator.getInt(renderer->samplers->sampleSets);
Color L = zero;
size_t spp = renderer->samplers->samplesPerPixel;
for (size_t s=0; s<spp; s++)
{
PrecomputedSample& sample = renderer->samplers->samples[set][s];
const float fx = (float(x) + sample.pixel.x)*rcpWidth;
const float fy = (float(y) + sample.pixel.y)*rcpHeight;
Ray primary; camera->ray(Vec2f(fx,fy), sample.getLens(), primary);
primary.time = sample.getTime();
state.sample = &sample;
state.pixel = Vec2f(fx,fy);
L += renderer->integrator->Li(primary, scene, state);
}
const Color L0 = swapchain->update(x, _y, L, spp, accumulate);
const Color L1 = toneMapper->eval(L0,x,y,swapchain);
framebuffer->set(x, _y, L1);
}
}
/*! print progress bar */
if (renderer->showProgress) progress.next();
/*! mark one more tile as finished */
framebuffer->finishTile();
}
/*! we access the atomic ray counter only once per tile */
atomicNumRays += state.numRays;
}
}
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkFEMSolverHyperbolic.cxx,v $
Language: C++
Date: $Date: 2009-01-30 21:53:03 $
Version: $Revision: 1.7 $
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#ifndef itkFEMSolverHyperbolic_hxx
#define itkFEMSolverHyperbolic_hxx
#include "itkFEMSolverHyperbolic.h"
#include "itkMath.h"
namespace itk {
namespace fem {
template <unsigned int VDimension>
SolverHyperbolic<VDimension>
::SolverHyperbolic()
{
this->InitializeLinearSystemWrapper();
this->InitializeMatrixForAssembly( 2 );
this->m_Beta=0.25;
this->m_Gamma=0.5;
this->m_TimeStep=1.0;
this->m_NumberOfIterations = 1;
}
template <unsigned int VDimension>
void
SolverHyperbolic<VDimension>
::InitializeLinearSystemWrapper(void)
{
// set the maximum number of matrices and vectors that
// we will need to store inside.
this->m_ls->SetNumberOfMatrices(5);
this->m_ls->SetNumberOfVectors(6);
this->m_ls->SetNumberOfSolutions(3);
}
template <unsigned int VDimension>
void
SolverHyperbolic<VDimension>
::AssembleElementMatrix(Element::Pointer e)
{
// Copy the element stiffness matrix for faster access.
Element::MatrixType Ke;
e->GetStiffnessMatrix(Ke);
Element::MatrixType Me;
e->GetMassMatrix(Me);
// ... same for number of DOF
int Ne=e->GetNumberOfDegreesOfFreedom();
// step over all rows in element matrix
for(int j=0; j<Ne; j++)
{
// step over all columns in element matrix
for(int k=0; k<Ne; k++)
{
// error checking. all GFN should be =>0 and <NGFN
if ( e->GetDegreeOfFreedom(j) >= this->GetInput()->GetNumberOfDegreesOfFreedom() ||
e->GetDegreeOfFreedom(k) >= this->GetInput()->GetNumberOfDegreesOfFreedom() )
{
throw FEMExceptionSolution(__FILE__,__LINE__,"Solver::AssembleElementMatrix()","Illegal GFN!");
}
/**
* Here we finally update the corresponding element
* in the master stiffness matrix. We first check if
* element in Ke is zero, to prevent zeros from being
* allocated in sparse matrix.
*/
if ( Math::NotExactlyEquals(Ke[j][k],Float(0.0)) )
{
this->m_ls->AddMatrixValue( e->GetDegreeOfFreedom(j), e->GetDegreeOfFreedom(k), Ke[j][k], matrix_K );
}
if ( Math::NotExactlyEquals(Me[j][k],Float(0.0)) )
{
this->m_ls->AddMatrixValue( e->GetDegreeOfFreedom(j), e->GetDegreeOfFreedom(k), Me[j][k], matrix_M );
}
}
}
}
template <unsigned int VDimension>
void
SolverHyperbolic<VDimension>
::InitializeMatrixForAssembly(unsigned int N)
{
this->m_ls->SetSystemOrder(N);
this->m_ls->InitializeMatrix();
this->m_ls->InitializeMatrix(matrix_K);
this->m_ls->InitializeMatrix(matrix_M);
this->m_ls->InitializeMatrix(matrix_C);
for(unsigned int i=0; i<N; i++)
{
this->m_ls->SetMatrixValue(i,i,1.0,matrix_C);
}
}
template <unsigned int VDimension>
void
SolverHyperbolic<VDimension>
::FinalizeMatrixAfterAssembly( void )
{
// Apply the boundary conditions to the matrix
// FIXME: this doesn't work in general
this->ApplyBC(0,matrix_M);
this->ApplyBC(0,matrix_K);
// Calculate initial values of vector_a
// M*a0=F - C*v0 - K*d0
// FIXME: take into account the d0 and v0.
this->m_ls->InitializeSolution(0);
this->m_ls->InitializeSolution(solution_a);
this->m_ls->CopyMatrix(matrix_M,0);
this->AssembleF();
this->m_ls->Solve();
this->m_ls->InitializeVector(vector_tmp);
this->m_ls->CopySolution2Vector(0,vector_tmp);
this->m_ls->InitializeSolution(solution_a);
this->m_ls->CopyVector2Solution(vector_tmp,solution_a);
this->m_ls->DestroyVector(vector_tmp);
this->m_ls->InitializeSolution(solution_d);
this->m_ls->InitializeSolution(solution_v);
// Compose the lhs of system of lin. eq.
this->m_ls->InitializeMatrix(matrix_tmp);
this->m_ls->CopyMatrix(matrix_C,matrix_tmp);
this->m_ls->ScaleMatrix(this->m_Gamma*this->m_TimeStep, matrix_tmp);
this->m_ls->AddMatrixMatrix(0,matrix_tmp);
this->m_ls->CopyMatrix(matrix_K,matrix_tmp);
this->m_ls->ScaleMatrix(this->m_Beta*this->m_TimeStep*this->m_TimeStep, matrix_tmp);
this->m_ls->AddMatrixMatrix(0,matrix_tmp);
this->m_ls->DestroyMatrix(matrix_tmp);
}
template <unsigned int VDimension>
void
SolverHyperbolic<VDimension>
::Solve()
{
this->m_ls->InitializeVector(vector_tmp);
this->m_ls->InitializeVector(vector_dhat);
this->m_ls->InitializeVector(vector_vhat);
this->m_ls->InitializeVector(vector_ahat);
// We're using the Newmark method to obtain the solution
// Assume that vectors solution_a solution_v and solution_d contain
// solutions obtained at the previous time step.
// Calculate the predictors
for(unsigned int i=0; i<this->m_ls->GetSystemOrder(); i++)
{
Float d0=this->m_ls->GetSolutionValue(i,solution_d);
Float v0=this->m_ls->GetSolutionValue(i,solution_v);
Float a0=this->m_ls->GetSolutionValue(i,solution_a);
this->m_ls->SetVectorValue( i, -(d0+this->m_TimeStep*v0+0.5*this->m_TimeStep*this->m_TimeStep*(1.0-2.0*this->m_Beta)*a0), vector_dhat);
this->m_ls->SetVectorValue( i, -(v0+this->m_TimeStep*(1.0-this->m_Gamma)*a0), vector_vhat);
}
// Calculate the rhs of master equation
this->m_ls->MultiplyMatrixVector(vector_tmp,matrix_C,vector_vhat);
this->m_ls->AddVectorVector(0,vector_tmp);
this->m_ls->MultiplyMatrixVector(vector_tmp,matrix_K,vector_dhat);
this->m_ls->AddVectorVector(0,vector_tmp);
// Solve the system of linear equations for accelerations
this->m_ls->Solve();
// move the solution for a to the correct vector
this->m_ls->CopySolution2Vector(0,vector_tmp);
this->m_ls->CopyVector2Solution(vector_tmp,solution_a);
// Calculate displacements and velocities
for(unsigned int i=0; i<this->m_ls->GetSystemOrder(); i++)
{
Float dhat=-this->m_ls->GetVectorValue(i,vector_dhat);
Float vhat=-this->m_ls->GetVectorValue(i,vector_vhat);
Float a1=this->m_ls->GetSolutionValue(i,solution_a);
this->m_ls->SetSolutionValue(i, dhat +
this->m_Beta*this->m_TimeStep*this->m_TimeStep*a1
, solution_d);
this->m_ls->SetSolutionValue(i, vhat +
this->m_Gamma*this->m_TimeStep*a1
, solution_v);
}
this->m_ls->DestroyVector(vector_tmp);
this->m_ls->DestroyVector(vector_dhat);
this->m_ls->DestroyVector(vector_vhat);
this->m_ls->DestroyVector(vector_ahat);
}
// ----------------------------------------------------------------------------
template <unsigned int VDimension>
void
SolverHyperbolic<VDimension>
::GenerateData()
{
/* Call Solver */
this->RunSolver();
}
/**
* Solve for the displacement vector u
*/
template <unsigned int VDimension>
void
SolverHyperbolic<VDimension>
::RunSolver()
{
this->AssembleK(); // Assemble the global stiffness matrix K
this->DecomposeK(); // Invert K
for (unsigned int nit = 0; nit < m_NumberOfIterations; nit++)
{
this->AssembleF();
this->Solve();
}
}
/**
* PrintSelf
*/
template <unsigned int VDimension>
void
SolverHyperbolic<VDimension>
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf( os, indent );
os << indent << "Number Of Iterations: " << this->m_NumberOfIterations << std::endl;
os << indent << "Time Step: " << this->m_TimeStep << std::endl;
os << indent << "Beta: " << this->m_Beta << std::endl;
os << indent << "Gamma: " << this->m_Gamma << std::endl;
}
} // end namespace fem
} // end namespace itk
#endif // itkFEMSolverHyperbolic_hxx
|
/*
You are given an array of integers nums, there is a sliding window of size k which is moving
from the very left of the array to the very right. You can only see the k numbers in the window.
Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1
Output: [1]
Example 3:
Input: nums = [1,-1], k = 1
Output: [1,-1]
Example 4:
Input: nums = [9,11], k = 2
Output: [11]
Example 5:
Input: nums = [4,-2], k = 2
Output: [4]
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
*/
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector <int> res;
deque <int> maxi;
int start = 0, end = 0, n = nums.size();
while (end < n) {
if (maxi.empty()) maxi.push_back(nums[end]);
else {
while (!maxi.empty() && maxi.back() < nums[end]) {
maxi.pop_back();
}
maxi.push_back(nums[end]);
}
if (end - start + 1 < k) {
end++;
}
else if (end - start + 1 == k) {
res.push_back(maxi.front());
if (maxi.front() == nums[start]) maxi.pop_front();
start++;
end++;
}
}
return res;
}
};
|
//===-- SIBufMemMerge.cpp -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// Modifications Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.
// Notified per clause 4(b) of the license.
//
//===----------------------------------------------------------------------===//
//
//
// This pass attempts to merge buffer memory operations
// For instance:
// s_buffer_load_dword s34, s[28:31], 0x9
// s_buffer_load_dword s35, s[28:31], 0xa
// ==>
// s_buffer_load_dwordx2 s[34:35], s[28:31], 0x9
//
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "SIInstrInfo.h"
#include "SIRegisterInfo.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "Utils/AMDGPUBaseInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <cassert>
#include <iterator>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "si-bufmem-merge"
namespace {
// \brief Struct representing the available values in the densemap
struct SimpleMI {
MachineInstr *Inst;
int OriginalOrder;
int Phase;
static const int DWORD_SIZE_IN_BITS = 32;
static const int BYTES_PER_DWORD = 4;
SimpleMI(MachineInstr *MI) : Inst(MI), OriginalOrder(-1), Phase(-1) {
assert((isSentinel() || canHandle(MI)) && "MachineInstr can't be handled");
}
SimpleMI(MachineInstr *MI, int CurrPhase) : Inst(MI), OriginalOrder(-1),
Phase(CurrPhase) {
assert((isSentinel() || canHandle(MI)) && "MachineInstr can't be handled");
}
bool isSentinel() const {
return Inst == DenseMapInfo<MachineInstr *>::getEmptyKey() ||
Inst == DenseMapInfo<MachineInstr *>::getTombstoneKey();
}
static bool canHandle(MachineInstr *Inst) {
return
Inst->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORD_IMM ||
Inst->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM ||
Inst->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM ||
Inst->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM;
}
unsigned getSBase(const SIInstrInfo *TII) const {
return TII->getNamedOperand(*Inst, AMDGPU::OpName::sbase)->getReg();
}
unsigned getGLC(const SIInstrInfo *TII) const {
return TII->getNamedOperand(*Inst, AMDGPU::OpName::glc)->getImm();
}
/// Get the offset encoded in the instruction
unsigned getOffset(const SIInstrInfo *TII) const {
return TII->getNamedOperand(*Inst, AMDGPU::OpName::offset)->getImm();
}
/// Get the offset in dwords
unsigned getDwordOffset(const SIInstrInfo *TII, const GCNSubtarget *ST)
const {
unsigned Offset = TII->getNamedOperand(*Inst,
AMDGPU::OpName::offset)->getImm();
return Offset / AMDGPU::getSMRDEncodedOffset(*ST, BYTES_PER_DWORD);
}
MachineOperand *getDest(const SIInstrInfo *TII) const {
return TII->getNamedOperand(*Inst, AMDGPU::OpName::sdst);
}
const TargetRegisterClass *getDestRC(const SIInstrInfo *TII) const {
return TII->getOpRegClass(*Inst,
AMDGPU::getNamedOperandIdx(Inst->getOpcode(),
AMDGPU::OpName::sdst));
}
unsigned getSize(const SIInstrInfo *TII) const {
const TargetRegisterClass *RC = getDestRC(TII);
return TII->getRegisterInfo().getRegSizeInBits(*RC) / DWORD_SIZE_IN_BITS;
}
};
}
namespace {
class SIBufMemMerge : public MachineFunctionPass {
private:
const GCNSubtarget *ST = nullptr;
const SIInstrInfo *TII = nullptr;
const SIRegisterInfo *TRI = nullptr;
MachineRegisterInfo *MRI = nullptr;
public:
static char ID;
SIBufMemMerge() : MachineFunctionPass(ID) {
initializeSIBufMemMergePass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
StringRef getPassName() const override {
return "SI Memory operation coalescer";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
MachineFunctionPass::getAnalysisUsage(AU);
}
unsigned getMaxSize(unsigned int size);
void processSubSection(const SmallVector<SimpleMI, 8> &Candidates,
unsigned StartIdx, unsigned EndIdx, unsigned Size,
const MachineOperand& SBase, const MachineOperand& GLC);
bool processList(SmallVector<SmallVector<SimpleMI, 8>, 8> &CandidateList);
bool optimizeBlock(MachineBasicBlock &MBB);
};
} // end anonymous namespace.
INITIALIZE_PASS_BEGIN(SIBufMemMerge, DEBUG_TYPE,
"SI Memory operation coalescer", false, false)
INITIALIZE_PASS_END(SIBufMemMerge, DEBUG_TYPE,
"SI Memory operation coalescer", false, false)
char SIBufMemMerge::ID = 0;
char &llvm::SIBufMemMergeID = SIBufMemMerge::ID;
FunctionPass *llvm::createSIBufMemMergePass() {
return new SIBufMemMerge();
}
namespace llvm {
template <> struct DenseMapInfo<SimpleMI> {
static inline SimpleMI getEmptyKey() {
return DenseMapInfo<MachineInstr *>::getEmptyKey();
}
static inline SimpleMI getTombstoneKey() {
return DenseMapInfo<MachineInstr *>::getTombstoneKey();
}
static unsigned getHashValue(SimpleMI Val);
static bool isEqual(SimpleMI LHS, SimpleMI RHS);
};
}
unsigned DenseMapInfo<SimpleMI>::getHashValue(SimpleMI Val) {
MachineInstr *Inst = Val.Inst;
MachineFunction *MF = Inst->getParent()->getParent();
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const SIInstrInfo *TII = ST.getInstrInfo();
if (Inst->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORD_IMM ||
Inst->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM ||
Inst->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM ||
Inst->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM) {
const unsigned SBase = Val.getSBase(TII);
const int64_t GLC = Val.getGLC(TII);
const unsigned Size = Val.getSize(TII);
const unsigned Phase = Val.Phase;
return hash_combine(Inst->getOpcode(), SBase, GLC, Size, Phase);
}
llvm_unreachable_internal();
return 0;
}
bool DenseMapInfo<SimpleMI>::isEqual(SimpleMI LHS, SimpleMI RHS) {
MachineInstr *LHSI = LHS.Inst, *RHSI = RHS.Inst;
if (LHS.isSentinel() || RHS.isSentinel())
return LHSI == RHSI;
if (LHSI->getOpcode() != RHSI->getOpcode())
return false;
if (LHSI->isIdenticalTo(*RHSI))
return true;
MachineFunction *MF = LHSI->getParent()->getParent();
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const SIInstrInfo *TII = ST.getInstrInfo();
// We are actually only interested in certain operands as we expect some to
// differ
if (LHSI->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORD_IMM ||
LHSI->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM ||
LHSI->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM ||
LHSI->getOpcode() == AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM) {
return LHS.getSBase(TII) == RHS.getSBase(TII) &&
LHS.getGLC(TII) == RHS.getGLC(TII) &&
LHS.getSize(TII) == RHS.getSize(TII) &&
LHS.Phase == RHS.Phase;
}
return false;
}
unsigned SIBufMemMerge::getMaxSize(unsigned int size) {
if (size >= 16) return 16;
if (size >= 8) return 8;
if (size >= 4) return 4;
if (size >= 2) return 2;
if (size >= 1) return 1;
return 0;
}
void SIBufMemMerge::processSubSection(const SmallVector<SimpleMI, 8> &Candidates,
unsigned int StartIdx, unsigned int EndIdx,
unsigned int Size,
const llvm::MachineOperand &SBase,
const llvm::MachineOperand &GLC) {
// Loop through the indices creating the largest size we can from the
// remaining elements
while(Size) {
LLVM_DEBUG(
dbgs() << "Processing : \n";
for( auto I = StartIdx; I <= EndIdx ; ++I)
dbgs() << "\t" << *Candidates[I].Inst << "\n";);
unsigned nextSize;
const MCInstrDesc *MergeInstr = nullptr;
// Sizes are all the same for a set of candidates
unsigned eltSize = Candidates[StartIdx].getSize(TII);
while ((nextSize = getMaxSize(Size))) {
if (nextSize == eltSize) {
// Don't need a replacement here as the replacement size and the
// original size are the same
LLVM_DEBUG(dbgs() << "Skipping coalesced replacement as same size: "
<< *Candidates[StartIdx].Inst);
++StartIdx;
Size -= nextSize;
continue;
}
LLVM_DEBUG(dbgs() << "Creating new coalesced instruction of X" << nextSize
<< "\n");
const TargetRegisterClass *SuperRC = nullptr;
switch(nextSize) {
default:
llvm_unreachable_internal();
break;
case 16:
SuperRC = &AMDGPU::SReg_512RegClass;
MergeInstr = &TII->get(AMDGPU::S_BUFFER_LOAD_DWORDX16_IMM);
break;
case 8:
SuperRC = &AMDGPU::SReg_256RegClass;
MergeInstr = &TII->get(AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM);
break;
case 4:
SuperRC = &AMDGPU::SReg_128RegClass;
MergeInstr = &TII->get(AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM);
break;
case 2:
SuperRC = &AMDGPU::SReg_64_XEXECRegClass;
MergeInstr = &TII->get(AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM);
break;
case 1:
MergeInstr = &TII->get(AMDGPU::S_BUFFER_LOAD_DWORD_IMM);
SuperRC = &AMDGPU::SReg_32RegClass;
break;
}
unsigned DestReg = MRI->createVirtualRegister(SuperRC);
// Find the insert point for the instructions being coalesced
// This is the minimum OriginalOrder value within StartIdx to EndIdx
auto InsertElt = std::min_element(Candidates.begin() + StartIdx,
Candidates.begin() + StartIdx +
(nextSize/eltSize),
[] (SimpleMI const& a, SimpleMI const& b)
{
return a.OriginalOrder < b.OriginalOrder;
});
DebugLoc DL = InsertElt->Inst->getDebugLoc();
MachineBasicBlock *MBB = InsertElt->Inst->getParent();
MachineInstrBuilder NewMergeInst =
BuildMI(*MBB, InsertElt->Inst, DL, *MergeInstr, DestReg)
.addReg(SBase.getReg()) // addr
.addImm(Candidates[StartIdx].getOffset(TII)) // offset
.addImm(GLC.getImm()) // glc
.addImm(0); // slc
(void)NewMergeInst;
// Copy the new dest register to the old ones
unsigned SubOffset = 0;
const MCInstrDesc &CopyDesc = TII->get(TargetOpcode::COPY);
// We know that the old sub registers for this subrange will be contained
// entirely as this is one the constraints on construction
auto I = StartIdx;
while (SubOffset < nextSize) {
unsigned SubRegIdx =
TII->getRegisterInfo().calcSubRegIdx(Candidates[I].getDestRC(TII),
SubOffset);
const auto *Dest = Candidates[I].getDest(TII);
BuildMI(*MBB, InsertElt->Inst, DL, CopyDesc)
.add(*Dest)
.addReg(DestReg, 0, SubRegIdx);
SubOffset += Candidates[I].getSize(TII);
++I;
}
// Erase the instructions already dealt with
for (auto J = StartIdx; J < I; J++) {
Candidates[J].Inst->eraseFromParent();
}
LLVM_DEBUG(dbgs() << "Inserted coalesced instruction for DwordX"
<< nextSize << " " << *NewMergeInst << "\n");
Size -= nextSize;
StartIdx = I;
}
}
}
bool SIBufMemMerge::processList(
SmallVector<SmallVector<SimpleMI, 8>, 8> &CandidateList) {
bool Modified = false;
for ( auto EachList : CandidateList) {
// Preserve the insert point
int Order = 0;
for (auto &Elt : EachList)
Elt.OriginalOrder = Order++;
LLVM_DEBUG(dbgs() << "Processing the following list\n");
LLVM_DEBUG(for (auto Elt : EachList) dbgs() << Elt.OriginalOrder << " : "
<< *(Elt.Inst) << "\n";);
std::sort(EachList.begin(), EachList.end(), [this](SimpleMI a, SimpleMI b) {
return a.getOffset(TII) < b.getOffset(TII);
});
const auto *SBase = TII->getNamedOperand(*EachList.front().Inst,
AMDGPU::OpName::sbase);
const auto *GLC = TII->getNamedOperand(*EachList.front().Inst,
AMDGPU::OpName::glc);
bool StartingRun = true;
// Sections is StartIdx, EndIdx, Size
SmallVector<std::tuple<unsigned, unsigned, unsigned>, 8> Sections;
unsigned OffsetStart = 0, PreviousOffset = 0;
unsigned StartIdx = 0, EndIdx = 0;
unsigned CurrentSize = 0, PreviousSize = 0;
bool PushSection = true;
for ( SimpleMI Elt : EachList ) {
unsigned CurrentOffset = Elt.getDwordOffset(TII, ST);
CurrentSize = Elt.getSize(TII);
PushSection = true;
if (StartingRun) {
OffsetStart = PreviousOffset = CurrentOffset;
PreviousSize = CurrentSize;
StartingRun = false;
continue;
}
if (CurrentOffset == PreviousOffset + PreviousSize) {
PreviousOffset = CurrentOffset;
PreviousSize = CurrentSize;
++EndIdx;
continue;
}
// A gap found
Sections.push_back(std::make_tuple(StartIdx, EndIdx,
PreviousOffset + CurrentSize -
OffsetStart));
OffsetStart = PreviousOffset = CurrentOffset;
StartIdx = EndIdx = EndIdx + 1;
PushSection = false;
}
// Check we haven't got a unpushed section pending
if (PushSection)
Sections.push_back(std::make_tuple(StartIdx, EndIdx,
PreviousOffset + CurrentSize -
OffsetStart));
// Now have a list of contiguous runs in Sections vector
// Process each one
for (auto SubSection : Sections) {
unsigned StartIdx, EndIdx, Size;
std::tie(StartIdx, EndIdx, Size) = SubSection;
// Process all subsections with more than one operation
if (EndIdx > StartIdx) {
processSubSection(EachList, StartIdx, EndIdx, Size, *SBase, *GLC);
Modified = true;
}
}
}
return Modified;
}
// We coalesce candidate instructions within a basic block
// Scan through the block and identify candidate instructions and add to the
// worklist if they are valid
bool SIBufMemMerge::optimizeBlock(MachineBasicBlock &MBB) {
bool Modified = false;
DenseMap<SimpleMI, unsigned> CandidateMap;
SmallVector<SmallVector<SimpleMI, 8>, 8> CandidateList;
unsigned int NextIdx = 0;
unsigned int Phase = 0;
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) {
MachineInstr &MI = *I;
// Any instruction that stores prevents any futher coalescing
if (MI.mayStore()) {
LLVM_DEBUG(dbgs() << "Found an intermediate store instruction " << MI << "\n");
Phase += 1; // Stop adding any instructions to existing lists - new ones
// required after blocking instruction
continue;
}
// Not volatile
if (MI.hasOrderedMemoryRef())
continue;
switch(MI.getOpcode()) {
case AMDGPU::S_BUFFER_LOAD_DWORD_IMM:
case AMDGPU::S_BUFFER_LOAD_DWORDX2_IMM:
case AMDGPU::S_BUFFER_LOAD_DWORDX4_IMM:
case AMDGPU::S_BUFFER_LOAD_DWORDX8_IMM:
SimpleMI SMI(&MI, Phase);
auto CandidateIdx = CandidateMap.find(SMI);
if (CandidateIdx == CandidateMap.end()) {
// Generate a new list and add to the map
CandidateList.push_back(SmallVector<SimpleMI,8>());
CandidateList.back().push_back(SMI);
CandidateMap[SMI] = NextIdx++;
} else {
CandidateList[CandidateIdx->getSecond()].push_back(SMI);
}
break;
}
}
Modified |= processList(CandidateList);
return Modified;
}
bool SIBufMemMerge::runOnMachineFunction(MachineFunction &MF) {
if (skipFunction(MF.getFunction()))
return false;
MRI = &MF.getRegInfo();
ST = &MF.getSubtarget<GCNSubtarget>();
TII = ST->getInstrInfo();
TRI = &TII->getRegisterInfo();
LLVM_DEBUG(dbgs() << "Running SIBufMemMerge\n");
bool Modified = false;
for (MachineBasicBlock &MBB : MF)
Modified |= optimizeBlock(MBB);
return Modified;
}
|
#include "CBabobba.h"
#include "../../common/ai/CPlayerBase.h"
#include "../../common/ai/CPlayerLevel.h"
#include "../../common/ai/CBullet.h"
#include <base/utils/misc.h>
namespace galaxy
{
/*
$2F48W #Babobba jump 0
$2F66W #Babobba jump
$2F84W #Babobba sit 2
$2FA2W #Babobba sit [shoot] 3
$2FC0W #Babobba jump? 4
$2FDEW #Babobba stunned 5
$2FFCW #Babobba napping 6
$301AW #Babobba napping
$3038W #Babobba napping
$3056W #Babobba napping [Asleep]
$3074W #Babobba napping
$3092W #Babobba napping
$30B0W #Babobba napping
*/
constexpr int MOVE_X_SPEED = 30;
constexpr int SIT_TIME = 80;
constexpr int NAP_TIME = 300;
constexpr int SHOOT_TIME = 10;
constexpr int MAX_JUMP_INERTIA = -120;
enum BABOBBAACTIONS
{
A_BABOBBA_JUMP = 0,
A_BABOBBA_SIT = 2,
A_BABOBBA_SHOOT = 3,
A_BABOBBA_JUMP_ALT = 4,
A_BABOBBA_STUNNED = 5,
A_BABOBBA_NAPPING = 6
};
constexpr int CSF_DISTANCE_TO_FIRE = 7<<CSF;
CBabobba::CBabobba(CMap* pmap, const Uint16 foeID, const Uint32 x, const Uint32 y) :
CStunnable(pmap, foeID, x, y),
mTimer(0),
mGoodFireChance(false)
{
mActionMap[A_BABOBBA_JUMP] = (GASOFctr) &CBabobba::processJumping;
mActionMap[A_BABOBBA_SIT] = (GASOFctr) &CBabobba::processSitting;
mActionMap[A_BABOBBA_SHOOT] = (GASOFctr) &CBabobba::processShooting;
mActionMap[A_BABOBBA_JUMP_ALT] = (GASOFctr) &CBabobba::processJumpingAlt;
mActionMap[A_BABOBBA_STUNNED] = (GASOFctr) &CStunnable::processGettingStunned;
mActionMap[A_BABOBBA_NAPPING] = (GASOFctr) &CBabobba::processNapping;
setupGalaxyObjectOnMap(gBehaviorEngine.isDemo() ? 0x221E : 0x2F48, A_BABOBBA_JUMP);
xDirection = LEFT;
yinertia = MAX_JUMP_INERTIA;
}
void CBabobba::processJumping()
{
// Move normally in the direction
if( xDirection == RIGHT )
{
moveRight( MOVE_X_SPEED );
}
else
{
moveLeft( MOVE_X_SPEED );
}
if(blockedd && yinertia >= 0)
{
setAction(A_BABOBBA_SIT);
playSound(SOUND_BABOBBA_LAND);
}
}
void CBabobba::processSitting()
{
mTimer++;
if(mTimer < SIT_TIME)
return;
mTimer = 0;
if(mGoodFireChance)
{
setAction(A_BABOBBA_SHOOT);
playSound(SOUND_BABOBBA_CINDER);
// Create cinder
CCinder *cinder = new CCinder(mpMap, 0,
getXMidPos(), getYUpPos(), xDirection, mSprVar);
spawnObj( cinder );
}
setAction(A_BABOBBA_NAPPING);
}
void CBabobba::processShooting()
{
mTimer++;
if(mTimer < SHOOT_TIME)
return;
mTimer = 0;
setAction(A_BABOBBA_SIT);
}
void CBabobba::processJumpingAlt()
{
}
void CBabobba::processNapping()
{
mTimer++;
if(mTimer < NAP_TIME)
return;
mTimer = 0;
yinertia = MAX_JUMP_INERTIA;
setAction(A_BABOBBA_JUMP);
playSound(SOUND_BABOBBA_JUMP);
}
bool CBabobba::isNearby(CSpriteObject &theObject)
{
if( !getProbability(30) )
return false;
if( CPlayerLevel *player = dynamic_cast<CPlayerLevel*>(&theObject) )
{
if( player->getXMidPos() < getXMidPos() )
xDirection = LEFT;
else
xDirection = RIGHT;
const int objX = theObject.getXMidPos();
const int objY = theObject.getYMidPos();
const int babobbaX = getXMidPos();
const int babobbaY = getYMidPos();
mGoodFireChance = false;
if( objX < babobbaX - CSF_DISTANCE_TO_FIRE ||
objX > babobbaX + CSF_DISTANCE_TO_FIRE )
return false;
if( objY < babobbaY - CSF_DISTANCE_TO_FIRE ||
objY > babobbaY + CSF_DISTANCE_TO_FIRE )
return false;
mGoodFireChance = true;
}
return true;
}
void CBabobba::getTouchedBy(CSpriteObject& theObject)
{
if(mIsDead || theObject.mIsDead)
return;
CStunnable::getTouchedBy(theObject);
// Was it a bullet? Than make it stunned.
if( dynamic_cast<CBullet*>(&theObject) )
{
setAction(A_BABOBBA_STUNNED);
mIsDead = true;
theObject.mIsDead = true;
}
if(getActionNumber(A_BABOBBA_NAPPING))
return;
if( CPlayerBase *player = dynamic_cast<CPlayerBase*>(&theObject) )
{
player->kill(false);
}
}
void CBabobba::process()
{
performCollisions();
performGravityHigh();
if( blockedl )
xDirection = RIGHT;
else if(blockedr)
xDirection = LEFT;
if(!processActionRoutine())
exists = false;
(this->*mp_processState)();
}
/// Classes for cinder, which is some fire that land on the floor and vanishes
/*
$30CEW #Babobba cinder tossed
$30ECW #Babobba cinder landed
$310AW #Babobba cinder dying
*/
enum CINDERACTIONS
{
A_CINDER_TOSSED = 0,
A_CINDER_LANDED = 1,
A_CINDER_DYING = 2
};
const int CINDER_X_SPEED = 50;
const int CINDER_DYING_TIME = 50;
CCinder::CCinder(CMap* pmap, const Uint16 foeID,
const Uint32 x, const Uint32 y, const int horDir, const int sprVar) :
CGalaxyActionSpriteObject(pmap, foeID, x, y, sprVar),
mTimer(0)
{
mActionMap[A_CINDER_TOSSED] = (void (CGalaxyActionSpriteObject::*)()) &CCinder::processTossed;
mActionMap[A_CINDER_LANDED] = (void (CGalaxyActionSpriteObject::*)()) &CCinder::processLanded;
mActionMap[A_CINDER_DYING] = (void (CGalaxyActionSpriteObject::*)()) &CCinder::processDying;
setupGalaxyObjectOnMap(gBehaviorEngine.isDemo() ? 0x2368 : 0x30CE, A_CINDER_TOSSED);
yinertia = -60;
xDirection = horDir;
}
void CCinder::processTossed()
{
// Move normally in the direction
moveXDir(xDirection*CINDER_X_SPEED);
if(blockedd)
{
setAction(A_CINDER_LANDED);
}
}
void CCinder::processLanded()
{
mTimer++;
if(mTimer < CINDER_DYING_TIME)
return;
mTimer = 0;
setAction(A_CINDER_DYING);
}
void CCinder::processDying()
{
mTimer++;
if(mTimer < CINDER_DYING_TIME)
return;
mTimer = 0;
mIsDead = true;
exists = false;
}
void CCinder::getTouchedBy(CSpriteObject& theObject)
{
if( CPlayerBase *player = dynamic_cast<CPlayerBase*>(&theObject) )
{
player->kill(false);
}
}
void CCinder::process()
{
performCollisions();
performGravityHigh();
if(!processActionRoutine())
exists = false;
(this->*mp_processState)();
}
};
|
/*Exercise 1 - Calculations
Convert the C program given below which converts a length given in cm to inches to a C++ program.
Please Note that the input command in C++ is std::cin. This is a representation of the Keyboard.
e.g.
float data1;
int data2;
scanf("%f", &data1); --> std::cin >> data1;
scanf("%d", &data2); --> std::cin >> data2;
You already know that printf() in C is std::cout in C++ e.g.
printf("Hello World") --> std::cout << "Hello World";
2.54cm = 1 inch
*/
#include <iostream>
int main()
{
float cm, inches;
std::cout << "Enter a length in cm :" <<std::endl;
std::cin >> cm;
inches = cm / 2.54;
std::cout << "Length in inches is " << inches <<std::endl;
}
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2018 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactionrecord.h"
#include "base58.h"
#include "consensus/consensus.h"
#include "validation.h"
#include "timedata.h"
#include "wallet/wallet.h"
#include "privatesend.h"
#include <stdint.h>
#include <boost/foreach.hpp>
/* Return positive answer if transaction should be shown in list.
*/
bool TransactionRecord::showTransaction(const CWalletTx &wtx)
{
if (wtx.IsCoinBase())
{
// Ensures we show generated coins / mined transactions at depth 1
if (!wtx.IsInMainChain())
{
return false;
}
}
return true;
}
/*
* Decompose CWallet transaction to model transaction records.
*/
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
QList<TransactionRecord> parts;
int64_t nTime = wtx.GetTxTime();
CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
CAmount nNet = nCredit - nDebit;
uint256 hash = wtx.GetHash();
std::map<std::string, std::string> mapValue = wtx.mapValue;
if (nNet > 0 || wtx.IsCoinBase())
{
//
// Credit
//
for(unsigned int i = 0; i < wtx.tx->vout.size(); i++)
{
const CTxOut& txout = wtx.tx->vout[i];
isminetype mine = wallet->IsMine(txout);
if(mine)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = i; // vout index
sub.credit = txout.nValue;
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
{
// Received by Meraki address
sub.type = TransactionRecord::RecvWithAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
sub.type = TransactionRecord::RecvFromOther;
sub.address = mapValue["from"];
}
if (wtx.IsCoinBase())
{
// Generated
sub.type = TransactionRecord::Generated;
}
parts.append(sub);
}
}
}
else
{
bool fAllFromMeDenom = true;
int nFromMe = 0;
bool involvesWatchAddress = false;
isminetype fAllFromMe = ISMINE_SPENDABLE;
BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
{
if(wallet->IsMine(txin)) {
fAllFromMeDenom = fAllFromMeDenom && wallet->IsDenominated(txin.prevout);
nFromMe++;
}
isminetype mine = wallet->IsMine(txin);
if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
bool fAllToMeDenom = true;
int nToMe = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) {
if(wallet->IsMine(txout)) {
fAllToMeDenom = fAllToMeDenom && CPrivateSend::IsDenominatedAmount(txout.nValue);
nToMe++;
}
isminetype mine = wallet->IsMine(txout);
if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllToMe > mine) fAllToMe = mine;
}
if(fAllFromMeDenom && fAllToMeDenom && nFromMe * nToMe) {
parts.append(TransactionRecord(hash, nTime, TransactionRecord::PrivateSendDenominate, "", -nDebit, nCredit));
parts.last().involvesWatchAddress = false; // maybe pass to TransactionRecord as constructor argument
}
else if (fAllFromMe && fAllToMe)
{
// Payment to self
// TODO: this section still not accurate but covers most cases,
// might need some additional work however
TransactionRecord sub(hash, nTime);
// Payment to self by default
sub.type = TransactionRecord::SendToSelf;
sub.address = "";
if(mapValue["DS"] == "1")
{
sub.type = TransactionRecord::PrivateSend;
CTxDestination address;
if (ExtractDestination(wtx.tx->vout[0].scriptPubKey, address))
{
// Sent to Meraki address
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Sent to IP, or other non-address transaction like OP_EVAL
sub.address = mapValue["to"];
}
}
else
{
sub.idx = parts.size();
if(wtx.tx->vin.size() == 1 && wtx.tx->vout.size() == 1
&& CPrivateSend::IsCollateralAmount(nDebit)
&& CPrivateSend::IsCollateralAmount(nCredit)
&& CPrivateSend::IsCollateralAmount(-nNet))
{
sub.type = TransactionRecord::PrivateSendCollateralPayment;
} else {
for (const auto& txout : wtx.tx->vout) {
if (txout.nValue == CPrivateSend::GetMaxCollateralAmount()) {
sub.type = TransactionRecord::PrivateSendMakeCollaterals;
continue; // Keep looking, could be a part of PrivateSendCreateDenominations
} else if (CPrivateSend::IsDenominatedAmount(txout.nValue)) {
sub.type = TransactionRecord::PrivateSendCreateDenominations;
break; // Done, it's definitely a tx creating mixing denoms, no need to look any further
}
}
}
}
CAmount nChange = wtx.GetChange();
sub.debit = -(nDebit - nChange);
sub.credit = nCredit - nChange;
parts.append(sub);
parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument
}
else if (fAllFromMe)
{
//
// Debit
//
CAmount nTxFee = nDebit - wtx.tx->GetValueOut();
bool fDone = false;
if(wtx.tx->vin.size() == 1 && wtx.tx->vout.size() == 1
&& CPrivateSend::IsCollateralAmount(nDebit)
&& nCredit == 0 // OP_RETURN
&& CPrivateSend::IsCollateralAmount(-nNet))
{
TransactionRecord sub(hash, nTime);
sub.idx = 0;
sub.type = TransactionRecord::PrivateSendCollateralPayment;
sub.debit = -nDebit;
parts.append(sub);
fDone = true;
}
for (unsigned int nOut = 0; nOut < wtx.tx->vout.size() && !fDone; nOut++)
{
const CTxOut& txout = wtx.tx->vout[nOut];
TransactionRecord sub(hash, nTime);
sub.idx = nOut;
sub.involvesWatchAddress = involvesWatchAddress;
if(wallet->IsMine(txout))
{
// Ignore parts sent to self, as this is usually the change
// from a transaction sent back to our own address.
continue;
}
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
// Sent to Meraki address
sub.type = TransactionRecord::SendToAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Sent to IP, or other non-address transaction like OP_EVAL
sub.type = TransactionRecord::SendToOther;
sub.address = mapValue["to"];
}
if(mapValue["DS"] == "1")
{
sub.type = TransactionRecord::PrivateSend;
}
CAmount nValue = txout.nValue;
/* Add fee to first output */
if (nTxFee > 0)
{
nValue += nTxFee;
nTxFee = 0;
}
sub.debit = -nValue;
parts.append(sub);
}
}
else
{
//
// Mixed debit transaction, can't break down payees
//
parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0));
parts.last().involvesWatchAddress = involvesWatchAddress;
}
}
return parts;
}
void TransactionRecord::updateStatus(const CWalletTx &wtx, int numISLocks, int chainLockHeight)
{
AssertLockHeld(cs_main);
// Determine transaction status
// Find the block the tx is in
CBlockIndex* pindex = NULL;
BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end())
pindex = (*mi).second;
// Sort order, unrecorded transactions sort to the top
status.sortKey = strprintf("%010d-%01d-%010u-%03d",
(pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
(wtx.IsCoinBase() ? 1 : 0),
wtx.nTimeReceived,
idx);
status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
status.depth = wtx.GetDepthInMainChain();
status.cur_num_blocks = chainActive.Height();
status.cachedNumISLocks = numISLocks;
status.cachedChainLockHeight = chainLockHeight;
if (!CheckFinalTx(wtx))
{
if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD)
{
status.status = TransactionStatus::OpenUntilBlock;
status.open_for = wtx.tx->nLockTime - chainActive.Height();
}
else
{
status.status = TransactionStatus::OpenUntilDate;
status.open_for = wtx.tx->nLockTime;
}
}
// For generated transactions, determine maturity
else if(type == TransactionRecord::Generated)
{
if (wtx.GetBlocksToMaturity() > 0)
{
status.status = TransactionStatus::Immature;
if (wtx.IsInMainChain())
{
status.matures_in = wtx.GetBlocksToMaturity();
// Check if the block was requested by anyone
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
status.status = TransactionStatus::MaturesWarning;
}
else
{
status.status = TransactionStatus::NotAccepted;
}
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
else
{
status.lockedByInstantSend = wtx.IsLockedByInstantSend();
if (status.depth < 0)
{
status.status = TransactionStatus::Conflicted;
}
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
{
status.status = TransactionStatus::Offline;
}
else if (status.depth == 0)
{
status.status = TransactionStatus::Unconfirmed;
if (wtx.isAbandoned())
status.status = TransactionStatus::Abandoned;
}
else if (status.depth < RecommendedNumConfirmations && !wtx.IsChainLocked())
{
status.status = TransactionStatus::Confirming;
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
}
bool TransactionRecord::statusUpdateNeeded(int numISLocks, int chainLockHeight)
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != chainActive.Height()
|| status.cachedNumISLocks != numISLocks
|| status.cachedChainLockHeight != chainLockHeight;
}
QString TransactionRecord::getTxID() const
{
return QString::fromStdString(hash.ToString());
}
int TransactionRecord::getOutputIndex() const
{
return idx;
}
|
//
// CGen
// https://cgen.sophisticatedways.net
// Copyright © 2018 Volodymyr Skladanivskyy. All rights reserved.
// Published under terms of MIT license.
//
#ifndef shared_hpp
#define shared_hpp
#include <map>
#include <vector>
#include "variablesarray.hpp"
#define APP_VERSION "1.1"
#define APP_TITLE "CGen"
#define APP_URL "https://cgen.sophisticatedways.net"
#define APP_DESCRIPTION "CGen is a tool for encoding SHA-1 and SHA-256 hash functions into CNF/DIMACS and ANF/PolyBoRi formats"
#define APP_USAGE_SHORT "\
Usage: \n\
cgen encode (SHA1|SHA256) [-f (ANF|CNF)] [-r <rounds>] [-v <name> <value>]... [<encoder options>] <output file name>\n\
cgen (assign | define) [-v <name> <value>]... <input file name> <output file name>\n\
cgen --help\n\
cgen --version\n\
";
#define APP_USAGE_LONG "\
Commands:\n\
encode (SHA1|SHA256) - generate the encoding\n\
assign - read DIMACS CNF from <input file name>, assign variables as specified and save it to <output file name>\n\
define - define one or more named variablesin the specified DIMACS CNF file\n\
Options:\n\
-f (ANF|CNF) - encoding form, CNF if not specified \n\
-v <name> <value> - specification of the named variable,\n\
its mapping to binary variables and/or its constant values\n\
refer for detailed specifications online\n\
-r <value> - number of SHA1 rounds to encode\n\
-h | --help\n\
--version\n\
Further documentation and usage examples available at https://cgen.sophisticatedways.net.\n\
";
#define ERROR_COMMAND_NONE "No command specified"
#define ERROR_UNKNOWN_OPTION "unknown option"
#define ERROR_UNKNOWN_ARGUMENT "unknown argument"
#define ERROR_COMMAND_LINE_PARSE "Command line parsing error"
#define ERROR_INVALID_ARGUMENT "Error"
#define ERROR_MISSING_ALGORITHM "Algorithm for encoding not specified"
#define ERROR_UNKNOWN_ALGORITHM "Unknown algorithm for encoding"
#define ERROR_INVALID_VARIABLE_NAME "Invalid variable name"
#define ERROR_MISSING_VARIABLE_VALUE "Variable value is missing"
#define ERROR_DUPLICATED_VARIABLE_NAME "Variable may only appear once on the options list"
#define ERROR_NO_VARIABLES "No variables specified"
#define ERROR_EXCEPT_MUST_FOLLOW_ASSIGN_ENCODE "\"except\" variable modifiers are only allowed for\"assign\" or \"encode\" commands"
#define ERROR_EXCEPT_PAD_MUST_FOLLOW_CONSTANT "\"except\" and \"pad\" variable modifiers must follow its constant assignment"
#define ERROR_RANGE_FIRST_LAST "For binary variables range the first element must be less or equal to the last"
#define ERROR_RANGE_FIRST_ZERO "For binary variables range the first element must be greater than 0"
#define ERROR_PAD_UNKNOWN_VALUE "\"pad\" variable modifier only supports \"SHA1\" and \"SHA256\" values"
#define ERROR_R_MUST_FOLLOW_ENCODE "Rounds option can only be specified after \"encode\""
#define ERROR_ADD_MAX_ARGS_MUST_FOLLOW_ENCODE "add_max_args option can only be specified after \"encode\""
#define ERROR_XOR_MAX_ARGS_MUST_FOLLOW_ENCODE "xor_max_args option can only be specified after \"encode\""
#define ERROR_V_MUST_FOLLOW_ASSIGN_ENCODE_DEFINE "Variable options can only be specified after \"assign\", \"encode\" or \"define\""
#define ERROR_MISSING_INPUT_FILE_NAME "Input file name is not specified"
#define ERROR_MISSING_OUTPUT_FILE_NAME "Output file name is not specified"
#define ERROR_ROUNDS_RANGE "Rounds number is out of range"
#define ERROR_ADD_MAX_ARGS_RANGE "add_max_args is out of range, must be between 2 and 6"
#define ERROR_XOR_MAX_ARGS_RANGE "add_max_args is out of range, must be between 2 and 10"
#define ERROR_ENCODE_UNKNOWN_VARIABLE_NAME "Unknown variable name, \"encode\" only expects \"M\" and \"H\" case sensitive"
#define ERROR_UNKNOWN_VARIABLE_NAME "named variable is not defined in the DIMACS file"
#define ERROR_VARIABLE_ALREADY_DEFINED " named variable already defined in the DIMACS file"
#define ERROR_ASSIGN_VARIABLE_VALUE_TOO_LONG "Named variable value is too long for its definiton in the DIMACS file"
#define ERROR_ASSIGN_VARIABLE_CONSTANT_MISMATCH "Variable is already assigned to a conflicting binary constant"
#define ERROR_NAMED_VARIABLE_OUT_OF_RANGE " named variable includes a binary variable number greated than than the DIMACS file allows"
#define ERROR_COMPUTE_HASH_NO_MESSAGE "Computing hash requires full message value specified"
#define ERROR_EXCEPT_VARIABLES_RANGE_OUT_OF_BOUNDS "\"except\" variables range is out of bounds"
#define ERROR_RANDOM_NOT_ENOUGH_VARIABLES "Less variables than the requested number of random values to set"
#define ERROR_FAILED_OPENING_OUTPUT_FILE "Failed to open the output file"
#define WARNING_FORMULA_IS_EMPTY "The formula is SATISFIED, no clauses in the output file"
#define ERROR_UNKNOWN_FORMAT "Unknown output format"
#define ERROR_ANF_ENCODE_ONLY "ANF output is only supported for \"encode\" command"
enum CGenCommand {cmdNone, cmdEncode, cmdAssign, cmdDefine, cmdHelp, cmdVersion};
enum CGenAlgorithm {algNone, algSHA1, algSHA256};
enum CGenFormat {fmtCnfDimacs, fmtAnfPolybori};
enum CGenVariableMode {vmValue, vmRandom, vmCompute, vmDefine};
typedef struct {
CGenVariableMode mode;
uint32_t var_range_first = 0;
uint32_t var_range_last = 0;
uint32_t random_count = 0;
ple::VariablesArray data;
} CGenVariableInfo;
typedef std::map<std::string, CGenVariableInfo> CGenVariablesMap;
#endif /* shared_hpp */
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2004 Ferdinando Ametrano
Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program 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 license for more details.
*/
#include <ql/time/calendars/unitedkingdom.hpp>
#include <ql/errors.hpp>
namespace QuantLib {
UnitedKingdom::UnitedKingdom(UnitedKingdom::Market market) {
// all calendar instances on the same market share the same
// implementation instance
static ext::shared_ptr<Calendar::Impl> settlementImpl(
new UnitedKingdom::SettlementImpl);
static ext::shared_ptr<Calendar::Impl> exchangeImpl(
new UnitedKingdom::ExchangeImpl);
static ext::shared_ptr<Calendar::Impl> metalsImpl(
new UnitedKingdom::MetalsImpl);
switch (market) {
case Settlement:
impl_ = settlementImpl;
break;
case Exchange:
impl_ = exchangeImpl;
break;
case Metals:
impl_ = metalsImpl;
break;
default:
QL_FAIL("unknown market");
}
}
bool UnitedKingdom::SettlementImpl::isBusinessDay(const Date& date) const {
Weekday w = date.weekday();
Day d = date.dayOfMonth(), dd = date.dayOfYear();
Month m = date.month();
Year y = date.year();
Day em = easterMonday(y);
if (isWeekend(w)
// New Year's Day (possibly moved to Monday)
|| ((d == 1 || ((d == 2 || d == 3) && w == Monday)) &&
m == January)
// Good Friday
|| (dd == em-3)
// Easter Monday
|| (dd == em)
// first Monday of May (Early May Bank Holiday)
// moved to May 8th in 1995 and 2020 for V.E. day
|| (d <= 7 && w == Monday && m == May && y != 1995 && y != 2020)
|| (d == 8 && m == May && (y == 1995 || y == 2020))
// last Monday of May (Spring Bank Holiday)
|| (d >= 25 && w == Monday && m == May && y != 2002 && y != 2012)
// last Monday of August (Summer Bank Holiday)
|| (d >= 25 && w == Monday && m == August)
// Christmas (possibly moved to Monday or Tuesday)
|| ((d == 25 || (d == 27 && (w == Monday || w == Tuesday)))
&& m == December)
// Boxing Day (possibly moved to Monday or Tuesday)
|| ((d == 26 || (d == 28 && (w == Monday || w == Tuesday)))
&& m == December)
// June 3rd, 2002 only (Golden Jubilee Bank Holiday)
// June 4rd, 2002 only (special Spring Bank Holiday)
|| ((d == 3 || d == 4) && m == June && y == 2002)
// April 29th, 2011 only (Royal Wedding Bank Holiday)
|| (d == 29 && m == April && y == 2011)
// June 4th, 2012 only (Diamond Jubilee Bank Holiday)
// June 5th, 2012 only (Special Spring Bank Holiday)
|| ((d == 4 || d == 5) && m == June && y == 2012)
// December 31st, 1999 only
|| (d == 31 && m == December && y == 1999))
return false;
return true;
}
bool UnitedKingdom::ExchangeImpl::isBusinessDay(const Date& date) const {
Weekday w = date.weekday();
Day d = date.dayOfMonth(), dd = date.dayOfYear();
Month m = date.month();
Year y = date.year();
Day em = easterMonday(y);
if (isWeekend(w)
// New Year's Day (possibly moved to Monday)
|| ((d == 1 || ((d == 2 || d == 3) && w == Monday)) &&
m == January)
// Good Friday
|| (dd == em-3)
// Easter Monday
|| (dd == em)
// first Monday of May (Early May Bank Holiday)
// moved to May 8th in 1995 and 2020 for V.E. day
|| (d <= 7 && w == Monday && m == May && y != 1995 && y != 2020)
|| (d == 8 && m == May && (y == 1995 || y == 2020))
// last Monday of May (Spring Bank Holiday)
|| (d >= 25 && w == Monday && m == May && y != 2002 && y != 2012)
// last Monday of August (Summer Bank Holiday)
|| (d >= 25 && w == Monday && m == August)
// Christmas (possibly moved to Monday or Tuesday)
|| ((d == 25 || (d == 27 && (w == Monday || w == Tuesday)))
&& m == December)
// Boxing Day (possibly moved to Monday or Tuesday)
|| ((d == 26 || (d == 28 && (w == Monday || w == Tuesday)))
&& m == December)
// June 3rd, 2002 only (Golden Jubilee Bank Holiday)
// June 4rd, 2002 only (special Spring Bank Holiday)
|| ((d == 3 || d == 4) && m == June && y == 2002)
// April 29th, 2011 only (Royal Wedding Bank Holiday)
|| (d == 29 && m == April && y == 2011)
// June 4th, 2012 only (Diamond Jubilee Bank Holiday)
// June 5th, 2012 only (Special Spring Bank Holiday)
|| ((d == 4 || d == 5) && m == June && y == 2012)
// December 31st, 1999 only
|| (d == 31 && m == December && y == 1999))
return false;
return true;
}
bool UnitedKingdom::MetalsImpl::isBusinessDay(const Date& date) const {
Weekday w = date.weekday();
Day d = date.dayOfMonth(), dd = date.dayOfYear();
Month m = date.month();
Year y = date.year();
Day em = easterMonday(y);
if (isWeekend(w)
// New Year's Day (possibly moved to Monday)
|| ((d == 1 || ((d == 2 || d == 3) && w == Monday)) &&
m == January)
// Good Friday
|| (dd == em-3)
// Easter Monday
|| (dd == em)
// first Monday of May (Early May Bank Holiday)
// moved to May 8th in 1995 and 2020 for V.E. day
|| (d <= 7 && w == Monday && m == May && y != 1995 && y != 2020)
|| (d == 8 && m == May && (y == 1995 || y == 2020))
// last Monday of May (Spring Bank Holiday)
|| (d >= 25 && w == Monday && m == May && y != 2002 && y != 2012)
// last Monday of August (Summer Bank Holiday)
|| (d >= 25 && w == Monday && m == August)
// Christmas (possibly moved to Monday or Tuesday)
|| ((d == 25 || (d == 27 && (w == Monday || w == Tuesday)))
&& m == December)
// Boxing Day (possibly moved to Monday or Tuesday)
|| ((d == 26 || (d == 28 && (w == Monday || w == Tuesday)))
&& m == December)
// June 3rd, 2002 only (Golden Jubilee Bank Holiday)
// June 4rd, 2002 only (special Spring Bank Holiday)
|| ((d == 3 || d == 4) && m == June && y == 2002)
// April 29th, 2011 only (Royal Wedding Bank Holiday)
|| (d == 29 && m == April && y == 2011)
// June 4th, 2012 only (Diamond Jubilee Bank Holiday)
// June 5th, 2012 only (Special Spring Bank Holiday)
|| ((d == 4 || d == 5) && m == June && y == 2012)
// December 31st, 1999 only
|| (d == 31 && m == December && y == 1999))
return false;
return true;
}
}
|
// Copyright 2021 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/ast/invariant_decoration.h"
#include "src/ast/test_helper.h"
namespace tint {
namespace ast {
namespace {
using InvariantDecorationTest = TestHelper;
TEST_F(InvariantDecorationTest, ToStr) {
auto* d = create<InvariantDecoration>();
EXPECT_EQ(str(d), "InvariantDecoration");
}
} // namespace
} // namespace ast
} // namespace tint
|
//
// QuotedPrintableDecoder.cpp
//
// $Id: //poco/1.4/Net/src/QuotedPrintableDecoder.cpp#2 $
//
// Library: Net
// Package: Messages
// Module: QuotedPrintableDecoder
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "Poco/Net/QuotedPrintableDecoder.h"
#include "Poco/NumberParser.h"
#include "Poco/Exception.h"
#include "Poco/Ascii.h"
using Poco::UnbufferedStreamBuf;
using Poco::NumberParser;
using Poco::DataFormatException;
namespace Poco {
namespace Net {
QuotedPrintableDecoderBuf::QuotedPrintableDecoderBuf(std::istream& istr):
_buf(*istr.rdbuf())
{
}
QuotedPrintableDecoderBuf::~QuotedPrintableDecoderBuf()
{
}
int QuotedPrintableDecoderBuf::readFromDevice()
{
int ch = _buf.sbumpc();
while (ch == '=')
{
ch = _buf.sbumpc();
if (ch == '\r')
{
ch = _buf.sbumpc(); // read \n
}
else if (Poco::Ascii::isHexDigit(ch))
{
std::string hex;
hex += (char) ch;
ch = _buf.sbumpc();
if (Poco::Ascii::isHexDigit(ch))
{
hex += (char) ch;
return NumberParser::parseHex(hex);
}
throw DataFormatException("Incomplete hex number in quoted-printable encoded stream");
}
else if (ch != '\n')
{
throw DataFormatException("Invalid occurrence of '=' in quoted-printable encoded stream");
}
ch = _buf.sbumpc();
}
return ch;
}
QuotedPrintableDecoderIOS::QuotedPrintableDecoderIOS(std::istream& istr): _buf(istr)
{
poco_ios_init(&_buf);
}
QuotedPrintableDecoderIOS::~QuotedPrintableDecoderIOS()
{
}
QuotedPrintableDecoderBuf* QuotedPrintableDecoderIOS::rdbuf()
{
return &_buf;
}
QuotedPrintableDecoder::QuotedPrintableDecoder(std::istream& istr):
QuotedPrintableDecoderIOS(istr),
std::istream(&_buf)
{
}
QuotedPrintableDecoder::~QuotedPrintableDecoder()
{
}
} } // namespace Poco::Net
|
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "halide_image.h"
#include "halide_image_io.h"
#include "pipeline_native.h"
#include "pipeline_hls.h"
#include "coreir.h"
#include "coreir/passes/transform/rungenerators.h"
#include "coreir/simulator/interpreter.h"
#include "coreir/libs/commonlib.h"
#include <iostream>
#include <fstream>
using namespace Halide::Tools;
using namespace CoreIR;
using namespace std;
int main(int argc, char **argv) {
Image<uint16_t> in(64, 64, 1);
Image<uint8_t> out_native(in.width(), in.height(), in.channels());
Image<uint8_t> out_hls(in.width(), in.height(), in.channels());
Image<uint8_t> out_coreir(in.width(), in.height(), in.channels());
in = load_image(argv[1]);
printf("start.\n");
pipeline_native(in, out_native);
save_image(out_native, "out.png");
save_image(out_native, "out.pgm");
printf("finished running native code\n");
pipeline_hls(in, out_hls);
printf("finished running HLS code\n");
bool success = true;
for (int y = 0; y < out_native.height(); y++) {
for (int x = 0; x < out_native.width(); x++) {
for (int c = 0; c < out_native.channels(); c++) {
if (out_native(x, y, c) != out_hls(x, y, c)) {
printf("out_native(%d, %d, %d) = %d, but out_c(%d, %d, %d) = %d\n",
x, y, c, out_native(x, y, c),
x, y, c, out_hls(x, y, c));
success = false;
}
}
}
}
// New context for coreir test
Context* c = newContext();
Namespace* g = c->getGlobal();
CoreIRLoadLibrary_commonlib(c);
if (!loadFromFile(c,"./design_prepass.json")) {
cout << "Could not Load from json!!" << endl;
c->die();
}
c->runPasses({"rungenerators", "flattentypes", "flatten", "wireclocks-coreir"});
Module* m = g->getModule("DesignTop");
assert(m != nullptr);
SimulatorState state(m);
state.setValue("self.in_arg_1_0_0", BitVector(16));
state.resetCircuit();
//state.setClock("self.clk", 0, 1);
std::ofstream instream;
std::ofstream outstream;
instream.open("coreir_input.txt");
outstream.open("coreir_output.txt");
for (int y = 0; y < in.height(); y++) {
for (int x = 0; x < in.width(); x++) {
for (int c = 0; c < in.channels(); c++) {
// set input value
state.setValue("self.in_arg_1_0_0", BitVector(16, in(x,y,c)));
instream << state.getBitVec("self.in_arg_1_0_0") << endl;
// propogate to all wires
state.exeCombinational();
// read output wire
outstream << state.getBitVec("self.out_0_0") << endl;
out_coreir(x,y,c) = state.getBitVec("self.out_0_0").to_type<uint16_t>();
if (y>=0 && out_native(x, y, c) != out_coreir(x, y, c)) {
printf("out_native(%d, %d, %d) = %d, but out_coreir(%d, %d, %d) = %d\n",
x, y, c, out_native(x, y, c),
x, y, c, out_coreir(x, y, c));
success = false;
}
// give another rising edge (execute seq)
state.exeSequential();
}
}
}
instream.close();
outstream.close();
deleteContext(c);
printf("finished running CoreIR code\n");
if (success) {
printf("Succeeded!\n");
return 0;
} else {
printf("Failed!\n");
return 1;
}
}
|
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <cstdio>
#include <cerrno>
using namespace std;
class AIRLINE
{
/****************************************
Ticket Booking Requirements
******************************************/
char name[20],email[30],address[20],departure[15],arrival[15],sex,phone[11];
int age,bookingId;
char passport[15];
int userFlightNo;
char date[15]; // Date Variable
char *locations[6];
/*****************************************
Flight Management Requirements
*******************************************/
char flightName[30] , seatNo[5] , flightDate[10] , travelClass[10];
int seatEconomy , seatBusiness , seatPremium;
float fareEconomy , fareBusiness , farePremium;
int flightNo;
char flightOrigin[15] , flightDestination[15];
public :
int id; // A General Variable
//Settings the Parameters as per the User's INPUT
AIRLINE () {
id = 0;
locations [0] = (char *)"PATNA" ;
locations [1] = (char *)"AMRITSAR" ;
locations [2] = (char *)"BENGALURU" ;
locations [3] = (char *)"NEW DELHI" ;
locations [4] = (char *)"MUMBAI" ;
locations [5] = (char *)"CHANDIGARH" ;
}
void printTicket();
int locationsMenu();
void makeQueryString(int);
int fareCalculator(int , char);
void setDate(int);
int checkAvailablity();
void setName();
void setEmail();
void setAddress();
void setPhone();
void setDeparture();
void setArrival();
void setAge();
void setSex();
void setPassport();
void setBookingId();
void setUserFlightNo();
//Getters
char * getName();
char * getEmail();
char * getAddress();
char * getDate();
char * getDeparture();
char * getArrival();
char getSex();
int getAge();
char * getPhone();
int getBookingId();
char * getPassport();
int getUserFlightNo();
void disAll();
// Flight Management
void setFlightName();
void setFlightNo();
void setSeatNo();
void setSeatEconomy(int);
void setSeatBusiness(int);
void setSeatPremium(int);
void setFlightOrigin();
void setFlightDestination();
void setFare();
char setTravelClass();
void decSeatNum(char , int);
void incSeatNum(char , int);
void disFlightAll();
char * getFlightName();
int getFlightNo();
char * getSeatNo();
int getSeatClass(char);
char * getFlightDate();
char * getFlightOrigin();
char * getFlightDestination();
int getFare(char);
char * getTravelClass();
char getTravelClassChar();
int getSeatEconomy();
int getSeatBusiness();
int getSeatPremium();
// General Functions Required for Seat
//void setId();
int getId(){ return id;}
};
int AIRLINE :: locationsMenu()
{
loc:
cout << "\t1. Patna\n";
cout << "\t2. Amritsar\n";
cout << "\t3. Bengaluru\n";
cout << "\t4. New Delhi\n";
cout << "\t5. Mumbai\n";
cout << "\t6. Chandigarh\n";
cout << "Please Input Your Choice Number :- ";
int n;
cin >> n;
if (n < 1 || n > 6) {
cout << "You entered an invalid choice , Please input a valid choice\n";
goto loc;
}
return n - 1;
}
void AIRLINE :: setName()
{
enter:
cout << "Enter Your Name :- ";
cin.get();
cin.getline(name,20);
int i = 0;
int count = 0;
while (name[i] != '\0')
{
if ((name[i] >= 65 && name[i] <=90) || (name[i] >= 97 && name[i] <= 122))
{}
else if (name[i] >=48 && name[i] <= 57)
{
cout << "\t\t/////////////////////////////////////////////////////////////////////\n";
cout << "\t\t///You entered an invalid character in name ///\n";
cout << "\t\t///Note :- Use Only [Alphabets] and [Space] are allowed in name ///\n";
cout << "\t\t/////////////////////////////////////////////////////////////////////\n";
goto enter;
}
count++;
i++;
}
if (count < 5) {
cout << "Name could not be less than 5 Characters . Please Try Again\n";
goto enter;
}
}
void AIRLINE :: setEmail()
{
email :
cout << "Enter Your Email Address :- ";
cin.getline(email,30);
int i = 0;
int counter = 0;
int counter_2 = 0;
while (email[i] != '\0')
{
// Adding Checking for @
if ((int)email[i] == 64)
counter++;
i++;
}
i = 0;
while (email[i] != '\0') {
// Checking for . (period) in Email Address
if((int)email[i] == 46)
counter_2++;
i++;
}
if(counter =! 1 || counter_2 != 1)
{
cout << "\t\tPlease enter a Valid Email Address\n";
goto email;
}
}
void AIRLINE :: setAddress()
{
cout << "Enter Your Permanent Address :- ";
cin.get();
cin.getline(address,20);
}
void AIRLINE :: setDate(int parameter)
{
int dd , mm , yy;
cout << "Enter the Date of Journey :\n";
dd_re:
cout << " Day [DD] : ";
cin >> dd;
if (dd < 0 || dd > 31) {
cout << "You Entered an invalid date . Please Try Again\n";
goto dd_re;
}
mm_re:
cout << " Month [MM] : ";
cin >> mm;
if (mm == 2 && dd > 28) {
cout << "February , 2017 has only 28 Days . Please enter the date again\n";
goto dd_re;
}
if (mm < 0 || mm > 12) {
cout << "Months are in range [1 - 12] only , Please make a correct choice \n";
goto mm_re;
}
yy_re:
cout << "Year [YYYY] : ";
cin >> yy;
if (yy != 2017) {
cout << "You can only book tickets for current year . Please make Correct Choice \n";
goto yy_re;
}
char separator[2];
separator[0] = (char) 47; // ASCII Code for '/' -> 47
separator[1] = '\0';
char DD[3];
int dd_u = dd % 10;
int dd_t = dd / 10;
DD[0] = (char)dd_t + '0';
DD[1] = (char)dd_u + '0';
DD[2] = '\0';
if (parameter == 0) {
strcpy(date , DD);
strcat(date , separator);
}
else {
strcpy(flightDate , DD);
strcat(flightDate , separator);
}
char MM[3];
int mm_u = mm % 10;
int mm_t = mm / 10;
MM[0] = (char) mm_t + '0';
MM[1] = (char) mm_u + '0';
MM[2] = '\0';
if (parameter == 0) {
strcat(date , MM);
strcat(date , separator);
}
else {
strcat(flightDate , MM);
strcat(flightDate , separator);
}
int yy_u = yy % 10;
yy = yy / 10;
int yy_t = yy % 10;
yy = yy / 10;
int yy_h = yy % 10;
yy = yy / 10;
int yy_th = yy;
char YY[5];
YY[0] = (char) yy_th + '0';
YY[1] = (char) yy_h + '0';
YY[2] = (char) yy_t + '0';
YY[3] = (char) yy_u + '0';
YY[4] = '\0';
if (parameter == 0)
strcat(date , YY);
else
strcat(flightDate , YY);
}
void AIRLINE :: setPhone()
{
phone:
cout << "Enter your Phone Number :- ";
cin >> phone;
if (strlen(phone) != 10 ) {
cout << "You entered an invalid phone number . Please Try Again \n";
goto phone;
}
if (phone[0] == '9' || phone[0] == '8' || phone[0] == '7') { }
else {
cout << "You entered an invalid phone number . Please Try Again \n";
goto phone;
}
int i = 0;
int count = 0;
while (phone[i] >= 48 && phone[i] <= 57 && phone[i] != '\0') {
count++;
i++;
}
if (count != strlen(phone))
goto phone;
}
void AIRLINE :: makeQueryString(int p)
{
int index = locationsMenu();
char * ptr = locations[index];
int len = strlen(locations[index]);
char place[len + 1];
for(int i = 0 ; i <= len ; i++) {
if (i == len)
place[i] = '\0';
else
place[i] = (char)*(ptr + i);
}
switch (p) {
case 1:
strcpy(departure , place);
break;
case 2:
strcpy(arrival , place);
break;
case 3:
strcpy(flightOrigin , place);
break;
case 4:
strcpy(flightDestination , place);
}
}
void AIRLINE :: setDeparture()
{
cout << "Please select your City of Departure : \n";
makeQueryString(1); // 1 to set Departure
}
void AIRLINE :: setArrival()
{
cout << "Please select your City of Arrival :\n";
makeQueryString(2); // 2 to set Arrival
}
void AIRLINE :: setAge()
{
age_re:
cout << "Enter your Age :- ";
cin >> age;
if (age < 0 || age > 100) {
cout << "Your age doesn't match as per the Flight Standards [01 - 99]. Please enter your valid age\n";
goto age_re;
}
}
void AIRLINE :: setSex()
{
sex_re:
cout << "Enter Your Sex (M/F):- ";
char tmp;
cin >> tmp;
if( (tmp == 'M' || tmp == 'm') || (tmp == 'f' ||tmp == 'F')) { }
else {
cout << "\t\t\tYou are entering an invalid choice . Please make a correct choice\n";
goto sex_re;
}
sex = tmp;
}
void AIRLINE :: setBookingId()
{
fstream f("booking.dat");
if (errno != 0)
bookingId = 1231100;
else {
AIRLINE x;
f.read((char *) &x , sizeof(x));
while (f.eof() != 1) {
f.read((char *) &x , sizeof(x));
}
bookingId = x.getBookingId() + 1;
}
f.close();
cout << "Booking Id : - " << bookingId << endl;
}
void AIRLINE :: setPassport()
{
password_re:
cout << "Enter your Passport Number :- ";
char tmp[15];
cin >> tmp;
int i = 0;
int count = 0;
while (tmp[i] != '\0') {
count++;
i++;
}
if (count < 10) {
cout << "\t\t\tPassport Number can't be less than 10 characters . Please enter correct info\n";
goto password_re;
}
strcpy(passport , tmp);
}
void AIRLINE :: setUserFlightNo() {
userFlight_re:
cout << "Enter the Flight Number for which you want to book : ";
cin >> userFlightNo;
AIRLINE check;
fstream fun("flights.dat");
fun.read((char *)&check , sizeof(check));
int flag = 0;
while(fun.eof() != 1) {
if (userFlightNo == check.getFlightNo()) {
flag = 1;
break;
}
else
flag = 0;
fun.read((char *)&check , sizeof(check));
}
fun.close();
if (flag == 0) {
cout << "You entered an invalid Flight Number , Please try again\n";
goto userFlight_re;
}
}
/********************************************************************
//Accessing the Parameters for different operations
************************************************************************/
char * AIRLINE :: getName()
{
return name;
}
char * AIRLINE :: getEmail()
{
return email;
}
char * AIRLINE :: getAddress()
{
return address;
}
char * AIRLINE :: getDate()
{
return date;
}
char AIRLINE :: getSex()
{
return sex;
}
char * AIRLINE :: getPhone()
{
return phone;
}
char * AIRLINE :: getDeparture()
{
return departure;
}
char * AIRLINE :: getArrival()
{
return arrival;
}
int AIRLINE :: getBookingId()
{
return bookingId;
}
char * AIRLINE :: getPassport()
{
return passport;
}
int AIRLINE :: getUserFlightNo() {
return userFlightNo;
}
// ################ Display all Function for displaying all the SET parameters #######################################
void AIRLINE :: disAll()
{
cout.setf(ios::left);
cout <<setw(10)<<getBookingId()<<setw(15)<<getName()<<setw(12)<<getDate()<<setw(15)<<getUserFlightNo()<<setw(15)<<getPhone()<<setw(20)<<getEmail()<<setw(12)<<getTravelClass()<<setw(12)<<getPassport()<<setw(8)<<getSeatNo()<<endl;
}
//
// Method definitions for Flight Part
// ------------------------------------
void AIRLINE :: setFlightName()
{
int flag ;
name_re:
cout << "Enter the Flight Name : ";
cin.get();
char tmp[30];
cin.getline(tmp , 30);
AIRLINE a;
flag = 0;
fstream f("flights.dat");
if (errno != 0) {
strcpy(flightName , tmp);
}
else {
f.seekg(0 , ios::beg);
f.read((char *) &a , sizeof (a));
while (f.eof() != 1) {
if (strcmp(tmp , a.getFlightName()) == 0) {
cout << "Flight Name Already exists\n";
flag = 1;
goto name_re;
}
f.read((char *) &a , sizeof (a));
}
if (flag == 0) {
strcpy(flightName , tmp);
}
f.close();
}
return;
}
void AIRLINE :: setFlightNo()
{
re_enter:
cout << "Enter the Flight Number : ";
int temp;
cin >> temp;
AIRLINE tmp;
fstream fl_id;
fl_id.open("flights.dat" ,ios::in|ios::out|ios::binary|ios::app);
fl_id.seekg(0,ios::beg);
fl_id.read((char *)&tmp , sizeof(tmp));
while (fl_id.eof() != 1) {
if (temp == tmp.getFlightNo()) {
cout << "Flight No. already exists in the database . Please Try Again\n";
goto re_enter;
}
fl_id.read((char *)&tmp , sizeof(tmp));
}
fl_id.close();
flightNo = temp;
}
void AIRLINE :: setSeatEconomy(int p) {
if (p == 0) {
cout << "No. of Seats for Economy : ";
cin >> seatEconomy;
}
else
seatEconomy = p;
}
void AIRLINE :: setSeatBusiness(int p) {
if (p == 0) {
cout << "No. of Seats for Business : ";
cin >> seatBusiness;
}
else
seatBusiness = p;
}
void AIRLINE :: setSeatPremium(int p) {
if (p == 0) {
cout <<"No. of Seats for Premium : ";
cin >> seatPremium;
}
else
seatPremium = p;
}
void AIRLINE :: setSeatNo()
{
AIRLINE tmp;
fstream f_id("booking.dat");
if (errno != 0)
id = 1;
else {
f_id.read((char *)&tmp , sizeof(tmp));
while (f_id.eof() != 1) {
f_id.read((char *)&tmp , sizeof(tmp));
}
id = tmp.getId() + 1;
}
f_id.close();
int id_u = id % 10;
int id_t = id / 10;
char id_str[5];
id_str[0] = (char)id_t + '0';
id_str[1] = (char)id_u + '0';
id_str[2] = '\0';
if (id <= 20)
strcat(id_str , "A");
else if (id <= 40)
strcat(id_str , "B");
else if (id <= 60)
strcat(id_str , "C");
else if (id <= 80)
strcat(id_str , "D");
else if (id <= 100)
strcat(id_str , "E");
else if (id <= 120)
strcat(id_str , "F");
strcpy(seatNo , id_str);
return;
}
void AIRLINE :: setFlightOrigin()
{
cout << "Choose the Origin Place for Flight :\n";
cout << "------------------------------------\n";
makeQueryString(3); // 3 to set Flight Origin
}
void AIRLINE :: setFlightDestination()
{
cout << "Select the Destination for Flight\n";
cout << "---------------------------------\n";
makeQueryString(4); // 4 to set Flight Destination
}
void AIRLINE :: setFare()
{
cout << "Fare for Economy Class : ";
cin >> fareEconomy;
cout << "Fare for Business Class : ";
cin >> fareBusiness;
cout << "Fare for Premium Class : ";
cin >> farePremium;
cout << "\nThank You , Fare List has been successfully updated\n";
}
char AIRLINE :: setTravelClass()
{
stc:
cout << "Choose your Travelling Class\n";
cout << "1. Economy Class\n";
cout << "2. Business Class\n";
cout << "3. Premium Class\n";
cout << "Enter your choice : ";
int book;
cin >> book;
switch(book) {
case 1:
strcpy(travelClass , "Economy");
break;
case 2:
strcpy(travelClass , "Business");
break;
case 3:
strcpy(travelClass , "Premium");
break;
default:
cout << "You entered an invalid choice . Try Again \n";
goto stc;
}
if (book == 1)
return 'E';
if (book == 2)
return 'B';
if (book == 3)
return 'P';
}
void AIRLINE :: decSeatNum(char ch , int flNo) {
fstream file;
fstream file_tmp;
file.open("flights.dat",ios::in|ios::out|ios::app|ios::binary);
file_tmp.open("temp.dat",ios::in|ios::out|ios::app|ios::binary);
AIRLINE tmp;
file.seekg(0,ios::beg);
file.read((char *) &tmp , sizeof(tmp));
while(file.eof() != 1) {
if (flNo == tmp.getFlightNo()) {
if (ch == 'E') {
tmp.setSeatEconomy(tmp.getSeatEconomy() - 1);
}
else if (ch == 'B') {
tmp.setSeatBusiness(tmp.getSeatBusiness() - 1);
}
else if (ch == 'P') {
tmp.setSeatPremium(tmp.getSeatPremium() - 1);
}
file_tmp.write((char *)&tmp , sizeof(tmp));
file.read((char *) &tmp , sizeof(tmp));
}
else {
file_tmp.write((char *) & tmp , sizeof (tmp));
file.read((char *) &tmp , sizeof(tmp));
}
}
file.close();
system("rm flights.dat");
system("mv temp.dat flights.dat");
}
void AIRLINE :: incSeatNum(char ch , int flNo) {
fstream file;
fstream file_tmp;
file.open("flights.dat",ios::in|ios::out|ios::app|ios::binary);
file_tmp.open("temp.dat",ios::in|ios::out|ios::app|ios::binary);
AIRLINE tmp;
file.seekg(0,ios::beg);
file.read((char *) &tmp , sizeof(tmp));
while(file.eof() != 1) {
if (flNo == tmp.getFlightNo()) {
if (ch == 'E') {
tmp.setSeatEconomy(tmp.getSeatEconomy() + 1);
}
else if (ch == 'B') {
tmp.setSeatBusiness(tmp.getSeatBusiness() + 1);
}
else if (ch == 'P') {
tmp.setSeatPremium(tmp.getSeatPremium() + 1);
}
file_tmp.write((char *)&tmp , sizeof(tmp));
file.read((char *) &tmp , sizeof(tmp));
}
else {
file_tmp.write((char *) & tmp , sizeof (tmp));
file.read((char *) &tmp , sizeof(tmp));
}
}
file.close();
system("rm flights.dat");
system("mv temp.dat flights.dat");
}
//################################################################################
char * AIRLINE :: getFlightName()
{
return flightName;
}
int AIRLINE :: getFlightNo()
{
return flightNo;
}
char * AIRLINE :: getSeatNo()
{
return seatNo;
}
/*int AIRLINE :: getSeatClass(char x)
{
if (x == 'E')
return seatEconomy;
else if (x == 'B')
return seatBusiness;
else if (x == 'P')
return seatPremium;
}
*/
int AIRLINE :: getSeatEconomy() { return seatEconomy;}
int AIRLINE :: getSeatBusiness() { return seatBusiness;}
int AIRLINE :: getSeatPremium() {return seatPremium;}
char * AIRLINE :: getFlightDate()
{
return flightDate;
}
char * AIRLINE :: getFlightOrigin()
{
return flightOrigin;
}
char * AIRLINE :: getFlightDestination()
{
return flightDestination;
}
int AIRLINE :: fareCalculator(int flNo , char trClass) {
int fare = 0;
AIRLINE temp;
fstream fareCal("flights.dat");
fareCal.read((char *)&temp , sizeof(temp));
while (fareCal.eof() != 1) {
if (flNo == temp.getFlightNo()) {
fare = temp.getFare(trClass);
}
fareCal.read((char *)&temp , sizeof(temp));
}
fareCal.close();
return fare;
}
int AIRLINE :: getFare(char x)
{
if (x == 'E')
return fareEconomy;
else if (x == 'B')
return fareBusiness;
else if (x == 'P')
return farePremium;
}
char * AIRLINE :: getTravelClass()
{
return travelClass;
}
char AIRLINE :: getTravelClassChar() {
if (strcmp(travelClass , "Economy") == 0)
return 'E';
else if (strcmp(travelClass , "Business") == 0)
return 'B';
else if (strcmp(travelClass , "Premium") == 0)
return 'P';
}
//disFlightAll
void AIRLINE :: disFlightAll()
{
cout.setf(ios::left);
cout<<setw(15)<<flightNo<<setw(25)<<flightName<<setw(12)<<flightDate<<setw(15)<<flightOrigin<<setw(15);
cout<<flightDestination<<setw(5)<<getSeatEconomy()<<setw(5)<<getSeatBusiness()<<setw(5)<<getSeatPremium()<<endl;
}
//################################################################################################################
//
//################################################################################################################
// Various Fuctions which are called in the main() function below
int MENU()
{
system("clear");
cout <<"\n\n\n\n\n\n\n\n\n";
cout << "\t\t\t**********************************************************************\n";
cout << "\t\t\t Welcome to PHENOMENAL AIRLINE SERVICES \n";
cout << "\t\t\t**********************************************************************\n";
cout <<endl;
cout << "\t\t\t\t\tPlease Choose from the following MENU\n";
cout << "\t\t\t\t\t-------------------------------------\n";
cout << "\t\t\t\t\t1. BOOKING\t\t2. FLIGHT_DETAILS\n";
cout << "\t\t\t\t\t3. SEARCH\t\t4. MODIFY\n";
cout << "\t\t\t\t\t5. CANCELLATION\t\t6. PASSENGER'S LIST\n";
cout << "\t\t\t\t\t7. PRINT TICKET\t\t8. EXIT\n";
int choice;
cout << "\n\t\t\t\t\t\tEnter Your Choice :- ";
cin >> choice;
if(choice < 1 || choice > 8)
{
system("clear");
cout << "\t\tYou entered an invalid choice . Please choose Again \n\n";
return 0;
}
else
return choice;
}
void disFormat()
{
cout <<endl;
cout.setf(ios::left);
cout<<setw(10)<<"Book. ID"<<setw(15)<<"Name"<<setw(12)<<"Date"<<setw(15)<<"Flight Id"<<setw(15)<<"Phone"<<setw(20)<<"Email"<<setw(12)<<"Class"<<setw(12)<<"Passport"<<setw(8)<<" Seat "<<endl;
cout<<setw(10)<<"--------"<<setw(15)<<"----"<<setw(12)<<"----"<<setw(15)<<"---------"<<setw(15)<<"-----"<<setw(20)<<"-----"<<setw(12)<<"-----"<<setw(12)<<"--------"<<setw(8)<<"------"<<endl;
}
void disFlightFormat()
{
cout <<endl;
cout.setf(ios::left);
cout<<setw(15)<<"Flight No."<<setw(25)<<"Flight Name"<<setw(12)<<"Date"<<setw(15)<<"Origin"<<setw(15)<<"Destination"<<setw(5)<<" E "<<setw(5) << " B " <<setw(5) << " P " << endl;
cout<<setw(15)<<"----------"<<setw(25)<<"-----------"<<setw(12)<<"----"<<setw(15)<<"-------"<<setw(15)<<"----------"<<setw(5)<<"---"<<setw(5) << "---" <<setw(5) << "---" << endl;
}
char exitFlightFormat()
{
char ch;
cout << "Press 'r' to return to the Flights Portal Menu or 'q' to quit\n";
cout << "\tPress any other key to go to Home Page\n";
cin >> ch;
return ch;
}
int exitFormat()
{
char ch;
cout << "\tPress 'q'/'Q' to quit or any other key to got back to Home Screen\n";
cin >> ch;
if(ch == 'Q' || ch == 'q')
exit(EXIT_FAILURE);
else
return 1;
}
void password() {
cout << "You need to enter your Password to continue from here onwards\n";
cout << "Please enter Carefully , you will only get 3 chances\n";
int chances = 3;
//char default_Password[15] = "phenomenal";
pass_re:
cout << "Enter your Password : ";
char id[15];
cin >> id;
if (strcmp(id , "phenomenal") == 0) {
cout << "Login Successful\n";
return;
}
else {
--chances;
if (chances == 0){
cout << "You entered Wrong Password 3 times.\n";
cout << "Terminating the program\n";
exit(EXIT_FAILURE);
}
cout << "\t\t\t! Wrong Password . Please Try Again\n";
goto pass_re;
}
}
void AIRLINE :: printTicket() {
cout << "\t\t\t###################################################################################\n";
cout << "\t\t\t PHENOMENAL AIRLINE SERVICES \n";
cout << "\t\t\t--------------------------------------------------------------------------------- \n";
cout << "\t\t\t"<<getTravelClass()<<" Class \n";
cout << "\t\t\t Name BookingID \n";
cout << "\t\t\t -------------- ---------------- \n";
cout << "\t\t\t "<<getName()<<" \t\t"<<getBookingId()<<" \n";
cout << "\t\t\t-----------------------------------------------------------------------------------\n";
cout << "\t\t\tFlight No : "<<getUserFlightNo()<<"\t\t\t\t\t Date : "<<getDate()<<" \n";
cout << "\t\t\t-----------------------------------------------------------------------------------\n";
cout << "\t\t\tOrigin : "<<getDeparture()<<"\t\t Destination : "<<getArrival()<<"\t\t Seat : "<<getSeatNo()<<"\n";
cout << "\t\t\t###################################################################################\n";
}
void acetLogo() {
system("clear");
cout <<"\n\n\n\n\n\n\n\n";
cout <<"\t\t\t ////////////// ////////////// ////////////// ////////////// \n";
cout <<"\t\t\t // // // // // \n";
cout <<"\t\t\t // // // // // \n";
cout <<"\t\t\t // // // // // \n";
cout <<"\t\t\t // // // ////////// // \n";
cout <<"\t\t\t ////////////// // // // \n";
cout <<"\t\t\t // // // // // \n";
cout <<"\t\t\t // // // // // \n";
cout <<"\t\t\t // // // // // \n";
cout <<"\t\t\t // // ////////////// ////////////// // \n";
cout <<"\n";
cout <<"\n";
cout <<"\t\t\t /////////////////////\n";
cout <<"\t\t\t // SEMESTER - III //\n";
cout <<"\t\t\t /////////////////////\n";
cout <<"\n\n";
cout <<"\t\t\t //////////////////////////////////////\n";
cout <<"\t\t\t // AIRLINE RESERVATION SYSTEM //\n";
cout <<"\t\t\t //////////////////////////////////////\n";
cout <<"\n";
cout <<"\t\t\t Press Enter to Continue .....\n";
cin.get();
}
int main()
{
acetLogo();
password();
start :
int choice = MENU();
if (choice == 0)
goto start;
switch(choice)
{
case 1:
{
//system("setterm -background 1 -foreground white");
system("clear");
cout <<"\n\n\n\n\n\n";
cout << "\t\t\tWelcome to the Ticket Booking Services\n";
AIRLINE b;
b.setBookingId();
fstream tb;
tb.open("booking.dat",ios::in|ios::out|ios::binary|ios::app);
cout << "Enter the following details to book your ticket :\n";
b.setDeparture();
b.setArrival();
int fare;
cout << "Your Arrival and Departure places : \n";
cout << b.getDeparture() << " and " << b.getArrival() << endl;
AIRLINE tmp;
fstream fl;
fl.open("flights.dat",ios::in|ios::out|ios::binary|ios::app);
fl.seekg(0,ios::beg);
//tb.write((char *)&b , sizeof(b));
cout << "Following are the Flights that suit your needs :\n\n";
disFlightFormat();
fl.seekg(0,ios::beg);
fl.read((char *)&tmp, sizeof(tmp));
int *p = new int(0);
while (fl.eof() != 1)
{
if (strcmp(b.getDeparture() , tmp.getFlightOrigin()) == 0) {
*p += 1;
tmp.disFlightAll();
}
fl.read((char *)&tmp, sizeof(tmp));
}
if (*p == 0) {
cout << "\t\t\tNo Flight satisfies your demands , We are very sorry \n";
cout << "Press Any Key to go to main menu : ";
cin.get();
goto start;
}
delete p;
b.setUserFlightNo();
b.setName();
b.setAge();
b.setPassport();
b.setAddress();
b.setEmail();
b.setPhone();
b.setSex();
b.setDate(0);
char ch = b.setTravelClass();
// Auto Decrementing the seat from respective class
b.decSeatNum(ch , b.getUserFlightNo());
b.setSeatNo();
fare = b.fareCalculator(b.getUserFlightNo() , ch);
cout << "After ch : " << ch << endl;
cout <<"Total Fare for Journey : " << fare << endl;
cout << "\nAll Details successfully accepted\n";
cout << "\t\tTicket Booking Done!!!\n";
tb.write((char *)&b , sizeof(b));
cout << "Ticket Details are :- \n";
disFormat();
b.disAll();
int q = exitFormat();
if (q == 1)
goto start;
}
break;
case 2:
{
flight_menu:
AIRLINE flight;
system("clear");
cout <<"\n\n\n\n\n\n\n\n";
cout << "\t\t\t\tWelcome to the Flights Portal\n";
cout << "\n\t\t\tHere You can manage all the Flights going in/out of your Airlines\n";
cout << "\t\t\t\t\tHere is Your Menu :- \n\n";
cout << "\t\t\t\t1. Add Flights\t\t2. Remove Flights\n";
cout << "\t\t\t\t3. Edit Fare\t\t4. Manage Seats\n";
cout << "\t\t\t\t5. Flights Search\t6. Total Flights\n";
cout << "\n\t\t\t\tEnter your preferred choice :- ";
int fl_choice;
cin >> fl_choice;
switch(fl_choice)
{
case 1:
{
cout << "\t\t\tWelcome to the Add Flights Section\n";
cout << "\tFollowing Details are required for adding a flight , Enter them carefullly\n";
flight.setFlightName();
flight.setFlightNo();
flight.setFlightOrigin();
flight.setFlightDestination();
flight.setDate(1);
// Setting the seats per class
cout << "Enter the Seat Details\n";
//flight.setSeatClass();
flight.setSeatEconomy(0);
flight.setSeatBusiness(0);
flight.setSeatPremium(0);
cout << "Economy : " << flight.getSeatEconomy() <<endl;
//Setting the fare Details
cout << "\tEnter the Fare Details for the Flight\n";
flight.setFare();
fstream flight_add;
flight_add.open("flights.dat",ios::in|ios::out|ios::binary|ios::app);
flight_add.write((char *)&flight, sizeof(flight));
flight_add.close();
cout << "\t\tFlight has been successfully added\n";
cout << "Following are the Flight details that you added ;- \n";
disFlightFormat();
flight.disFlightAll();
char ch = exitFlightFormat();
if (ch == 'q' || ch == 'Q')
exit(EXIT_FAILURE);
else if (ch == 'r' || ch == 'R')
goto flight_menu;
else
goto start;
}
break;
case 2:
{
cout << "Welcome to the 'Remove Flight' Menu\n";
cout << "Enter the Flight No. for flight that you want to be removed : \n";
int tmp;
cin >> tmp;
fstream flight_remove , flight_tmp;
flight_remove.open("flights.dat",ios::in|ios::out|ios::binary|ios::app);
flight_remove.seekg(0,ios::beg);
flight_tmp.open("tmp.dat",ios::in|ios::out|ios::binary|ios::app);
int flag = 0;
while (flight_remove.eof() != 1)
{
if (tmp == flight.getFlightNo())
{
flag = 1;
cout << "\tYou are going to delete the Following Flight\n";
disFlightFormat();
flight.disFlightAll();
cout << "Press 'y' to confirm removing the flights from Operations\n";
char ch;
cin >> ch;
if (ch == 'Y' || ch == 'y')
flight_remove.read((char *) &flight , sizeof(flight));
}
else
{
flight_remove.read((char *)&flight , sizeof(flight));
flight_tmp.write((char *)&flight , sizeof(flight));
}
}
if (flag == 0)
{
cout << "\nYou eneterd an invalid Flight Number\n";
goto end;
}
remove("flights.dat");
rename("tmp.dat" , "flights.dat");
cout << "Flight Successfully Removed from Operations :- \n";
end:
char ch = exitFlightFormat();
if (ch == 'q' || ch == 'Q')
exit(EXIT_FAILURE);
else if (ch == 'r' || ch == 'R')
goto flight_menu;
else
goto start;
}
break;
case 3:
{
cout << "Welcome to the Fare Management Portal\n:- ";
cout << "Enter the Flight No. for Flight you want to manage Fare :- ";
int tmp;
cin >> tmp;
fstream flight_fare;
flight_fare.open("flights.dat",ios::in|ios::out|ios::binary|ios::app);
flight_fare.seekg(0,ios::beg);
flight_fare.read((char *)&flight , sizeof(flight));
int flag = 0;
while (flight_fare.eof() != 1)
{
if (tmp == flight.getFlightNo())
{
flag = 1;
cout << "Current Fare Details are :- \n";
cout << "Economy : " << flight.getFare('E')<<endl;
cout << "Business : " << flight.getFare('B')<<endl;
cout << "Premim : " << flight.getFare('P')<<endl;
cout << "Enter the new Fare Details :- \n";
flight.setFare();
flight_fare.write((char *) &flight , sizeof(flight));
cout << "\t\tFlight Fare Succssfully modified\n";
}
flight_fare.read((char *)&flight , sizeof(flight));
}
if (flag == 0)
cout << "\nYou eneterd an invalid Flight Number\n";
char ch = exitFlightFormat();
if (ch == 'q' || ch == 'Q')
exit(EXIT_FAILURE);
else if (ch == 'r' || ch == 'R')
goto flight_menu;
else
goto start;
}
break;
case 4:
{
cout << "\tWelcome to the Seat Management Portal\n";
cout << "Here You can manage Seats Per Category of Passengers\n";
cout << "Please enter the following details : \n";
cout << "Enter the Flight No. whose Seats you want to manage :- ";
int tmp;
cin >> tmp;
fstream flight_seat;
flight_seat.open("flights.dat",ios::in|ios::out|ios::binary|ios::app);
fstream flight_rewrite;
flight_rewrite.open("flights_copy.dat" , ios::in|ios::out|ios::binary|ios::app);
int flag = 0;
flight_seat.read((char *)&flight , sizeof(flight));
while (flight_seat.eof() != 1)
{
if ( tmp == flight.getFlightNo())
{
flag = 1;
cout << "Flight No. matched as per records\n";
cout << "Following are the current seats in Flight :- \n";
disFlightFormat();
flight.disFlightAll();
cout << "Enter the following details to modify the seats :- \n";
flight.setSeatEconomy(0);
flight.setSeatBusiness(0);
flight.setSeatPremium(0);
flight_rewrite.write((char *) &flight , sizeof(flight));
flight_seat.read((char *)& flight , sizeof(flight));
cout << "Seats Successfully Modified \n";
}
else {
flight_rewrite.write((char *) &flight , sizeof(flight));
flight_seat.read((char *)& flight , sizeof(flight));
}
}
if (flag == 0)
cout << "\tNo Flight exists with the given Flight Id\n";
system("rm flights.dat");
system("mv flights_copy.dat flights.dat");
char ch = exitFlightFormat();
if (ch == 'q' || ch == 'Q')
exit(EXIT_SUCCESS);
else if (ch == 'r' || ch == 'R')
goto flight_menu;
else
goto start;
}
break;
case 5:
{
cout << "Welcome to the Flights Search Menu\n";
cout << "Enter the Flight Number you want to search : ";
int tmp;
cin >> tmp;
int flag = 0;
fstream fl_search("flights.dat");
fl_search.seekg(0,ios::beg);
fl_search.read((char *)&flight , sizeof(flight));
while (fl_search.eof() != 1) {
if (tmp == flight.getFlightNo()) {
flag = 1;
cout << "Here is the Flight You are looking for : \n";
disFlightFormat();
flight.disFlightAll();
fl_search.read((char *)&flight , sizeof(flight));
}
}
if (flag == 0)
cout << "!!! You entered an invalid Flight Number !!!\n";
char ch = exitFlightFormat();
if (ch == 'Q' || ch == 'q')
exit(EXIT_SUCCESS);
else if (ch == 'r' || ch == 'R')
goto flight_menu;
else
goto start;
}
break;
case 6:
{
cout << "Welcome to the Total Flights Section\n";
cout << "\tFollowing are the flights that are managed by our Airline \n";
fstream fl_dis("flights.dat");
if (errno != 0) {
cout << "\t\t\tNo Flights are currently under Administration\n";
}
fl_dis.seekg(0,ios::beg);
fl_dis.read((char *)&flight , sizeof(flight));
int count = 0;
disFlightFormat();
while (fl_dis.eof() != 1) {
count++;
flight.disFlightAll();
fl_dis.read((char *) & flight , sizeof(flight));
}
cout << "\n\t\t\tTotal Number of Flights Managed : " << count << endl;
char ch = exitFlightFormat();
if (ch == 'Q' || ch == 'q')
exit(EXIT_SUCCESS);
else if (ch == 'r' || ch == 'R')
goto flight_menu;
else
goto start;
}
break;
}
}
break;
case 3:
{
system("clear");
AIRLINE s;
fstream f3;
f3.open("booking.dat",ios::in|ios::binary|ios::app);
f3.seekg(0,ios::beg);
int k = 0;
do
{
cout <<"\n\n\n\n\n\n\n";
cout << "\t\t\t\tWeclome to the Search Page\n";
cout << "\t\t\tChoose from the following search criterias\n";
cout << "\t\t\t------------------------------------------\n";
cout << "\t\t\t1. AIRLINE ID (Highly Recommended)\n";
cout << "\t\t\t2. NAME\n";
cout << "\t\t\t3. EMAIL\n";
cout << "\t\t\t4. PHONE\n";
cin >> choice;
if(choice < 1|| choice >4)
k++;
else
break;
}while(k != 0);
int flag = 0;
char query[30];
switch (choice)
{
case 1:
{
int query;
cout << "Enter the AIRLINE ID :- ";
cin >>query;
f3.read((char *)&s,sizeof(s));
while(f3.eof() != 1)
{
if(query == s.getBookingId())
{
flag = 1;
disFormat();
s.disAll();
}
f3.read((char *)&s,sizeof(s));
}
if (flag == 0)
{
cout << "\tSearch query not found!\n";
exit(EXIT_FAILURE);
}
int q = exitFormat();
if (q == 1)
goto start;
f3.close();
}
break;
case 2:
{
cout << "Enter the Name which you want to search :- ";
cin.get();
cin.getline(query,30);
f3.read((char *)&s,sizeof(s));
while(f3.eof() != 1)
{
if(strcmp(query,s.getName()) == 0)
{
flag = 1;
disFormat();
s.disAll();
}
f3.read((char *)&s,sizeof(s));
}
if(flag == 0)
{
cout << "Search Query not found!!!!";
exit(EXIT_FAILURE);
}
int q = exitFormat();
if(q == 1)
goto start;
f3.close();
}
break;
case 3:
{
cout << "Enter the Email which you want to search :- ";
cin >> query;
f3.read((char *)&s,sizeof(s));
while(f3.eof() != 1)
{
if(strcmp(query,s.getEmail()) == 0)
{
flag = 1;
disFormat();
s.disAll();
}
f3.read((char *)&s,sizeof(s));
}
if(flag == 0)
cout << "\tSearch Query not Found!!!\n";
int q = exitFormat();
if (q == 1)
goto start;
f3.close();
}
break;
case 4:
{
cout << "Enter the phone number which you want to search :- ";
char query[15];
cin >> query;
f3.read((char *)&s,sizeof(s));
while(f3.eof() != 1)
{
if(strcmp(query , s.getPhone())== 0)
{
flag = 1;
disFormat();
s.disAll();
}
f3.read((char *)&s,sizeof(s));
}
if (flag==0)
cout << "\tSearch Query not found !!!!\n";
int q = exitFormat();
if (flag == 1)
goto start;
f3.close();
}
break;
}
}
break;
case 4: // Ticket Modifications
{
system("clear");
cout << "\n\n\n\n\n\n\n\n";
cout << "\t\t\t****************************************************\n";
cout << "\t\t\t\tWelcome to the Modifications Portal\n";
cout << "\t\t\t****************************************************\n";
AIRLINE mod;
cout << "\n\t\t\tTo edit/update your INFO , please enter your unique booking ID :- ";
int query;
cin >> query;
fstream fr,fw;
fr.open("booking.dat",ios::in|ios::binary|ios::app);
fw.open("mod.dat",ios::in|ios::binary|ios::app);
fr.read((char *)&mod,sizeof(mod));
fr.seekg(0,ios::beg);
int flag = 0;
while (fr.eof() != 1)
{
if(query == mod.getBookingId())
{
flag = 1;
cout << "\n\tyou want to modify the following record\n";
disFormat();
mod.disAll();
break;
}
fr.read((char *)&mod,sizeof(mod));
}
if(flag == 0)
{
cout << "\t\t!!! search query not found !!!";
cout << "\t\twe are sending you back to home screen\n";
goto start;
}
else
{
char ch;
cout << "\t\tbooking id matched as in the records\n";
cout << "\tto proceed press 'y'/'y' ,or to abort press 'q'/'q'\n";
cin >> ch;
if (ch != 'y' && ch != 'y')
goto start;
}
// modifications menu
cout << "\n\tplease choose among the following modifications criteria \n";
cout << "\t\t1. name\t\t\t2. email\n";
cout << "\t\t3. address\t\t4. phone no.\n";
cout << "Enter your Choice :- ";
int choice;
cin >> choice;
fr.seekg(0,ios::beg);
fr.read((char *)&mod,sizeof(mod));
switch (choice)
{
case 1: // Editing the Passenger's Name
{
while(fr.eof() != 1)
{
if(query == mod.getBookingId())
{
mod.setName();
cout << "\t\tName Successfully Modified\n";
fw.write((char *)&mod,sizeof(mod));
cout << "\tNew Record is :-\n";
disFormat();
mod.disAll();
fr.read((char *)&mod,sizeof(mod));
}
else
{
fw.write((char *)&mod,sizeof(mod));
fr.read((char *)&mod,sizeof(mod));
}
}
remove ("booking.dat");
rename("mod.dat","booking.dat");
fr.close();
fw.close();
int q = exitFormat();
if (q == 1)
goto start;
}
break;
case 2:
{
while(fr.eof() != 1)
{
if(query == mod.getBookingId())
{
cin.get();
mod.setEmail();
cout << "\t\tEmail Successfully Modified\n";
fw.write((char *)&mod,sizeof(mod));
cout << "New Record is :- \n";
disFormat();
mod.disAll();
fr.read((char *)&mod,sizeof(mod));
}
else
{
fw.write((char *)&mod,sizeof(mod));
fr.read((char *)&mod,sizeof(mod));
}
}
remove("booking.dat");
rename("mod.dat","booking.dat");
fr.close();
fw.close();
int q = exitFormat();
if (q == 1)
goto start;
}
break;
case 3:
{
while(fr.eof() != 1)
{
if(query == mod.getBookingId())
{
mod.setAddress();
cout << "\t\tAddress Successfully Modified\n";
fw.write((char *)&mod,sizeof(mod));
cout << "\tNew Record is :-\n";
disFormat();
mod.disAll();
fr.read((char *)&mod,sizeof(mod));
}
else
{
fw.write((char *)&mod,sizeof(mod));
fr.read((char *)&mod,sizeof(mod));
}
}
remove ("booking.dat");
rename("mod.dat","booking.dat");
fr.close();
fw.close();
int q = exitFormat();
if (q == 1)
goto start;
}
break;
case 4:
{
while(fr.eof() != 1)
{
if(query == mod.getBookingId())
{
mod.setPhone();
cout << "\t\tPhone Number Successfully Modified\n";
fw.write((char *)&mod,sizeof(mod));
cout << "\tNew Record is :-\n";
disFormat();
mod.disAll();
fr.read((char *)&mod,sizeof(mod));
}
else
{
fw.write((char *)&mod,sizeof(mod));
fr.read((char *)&mod,sizeof(mod));
}
}
remove ("booking.dat");
rename("mod.dat","booking.dat");
fr.close();
fw.close();
int q = exitFormat();
if (q == 1)
goto start;
}
break;
}
}
break;
case 5: // TICKET Cancellation
{
system("clear");
cout <<"\n\n\n\n\n\n\n";
cout << "\t\t\t********************************************************\n";
cout << "\t\t\t\tWelcome to the Ticket Cancellation System\n";
cout << "\t\t\t*********************************************************\n";
AIRLINE c;
int query;
int flag;
cout << "\n\t\tEnter the Booking ID of the ticket which you want to cancel :- ";
cin >> query;
fstream fr,fw;
fr.open("booking.dat",ios::in|ios::app|ios::binary);
fw.open("temp.dat",ios::in|ios::binary|ios::app);
fr.seekg(0,ios::beg);
fr.read((char *)&c,sizeof(c));
while (fr.eof() != 1)
{
if (query == c.getBookingId())
{
flag = 1;
disFormat();
c.disAll();
cout << "\tThis Ticket is going to be cancelled\n";
cout << "\t\t To Proceed , press 'y'/'Y' or To Abort press 'q'/'Q' \n";
char ch;
cin >> ch;
if (ch == 'q' || ch == 'Q')
goto start;
else {
c.incSeatNum(c.getTravelClassChar() , c.getUserFlightNo());
goto del;
}
}
fr.read((char *)&c,sizeof(c));
}
del:
fr.seekg(0,ios::beg);
fr.read((char *)&c,sizeof(c));
while(fr.eof() != 1)
{
if(query != c.getBookingId())
{
fw.write((char*)&c,sizeof(c));
}
fr.read((char *)&c,sizeof(c));
}
if (flag == 0)
{
cout << "\t!!!! Search query not found !!! You are being sent to Home Screen >>>> \n";
goto start;
}
remove("booking.dat");
rename("temp.dat","booking.dat");
fr.close();
fw.close();
cout << "\t\t!!! Ticket Successfully Cancelled !!! \n";
int q = exitFormat();
if (q == 1)
goto start;
}
break;
case 6: // Passenger's List
{
system("clear");
AIRLINE p;
int count = 0;
fstream f6;
f6.open("booking.dat",ios::in|ios::out|ios::binary|ios::app);
f6.seekg(0,ios::beg);
f6.read((char *)&p,sizeof(p));
cout << "\t\t\tPASSENGER'S DETAIL\n";
disFormat();
while(f6.eof() != 1)
{
p.disAll();
count++;
f6.read((char *)&p,sizeof(p));
}
f6.close();
cout << "\t\t\tTotal Number of Passengers is "<<count<<endl;
int q = exitFormat();
if (q == 1)
goto start;
}
break;
case 7:
{
system("clear");
cout <<"\n\n\n\n\n\n\n";
cout << "\t\t\t\tWelcome to The Ticket Printing Facility\n\n\n";
cout << "\t\t\tEnter the Booking Id for which TICKET is to be printed : ";
int ticket_id;
cin >> ticket_id;
AIRLINE ticket;
fstream search_id("booking.dat");
search_id.seekg(0,ios::beg);
search_id.read((char *) &ticket , sizeof(ticket));
int flag = 0;
while (search_id.eof() != 1) {
if (ticket_id == ticket.getBookingId()) {
flag = 1;
cout << "\n\t\t\tHere comes your Ticket :\n";
ticket.printTicket();
}
search_id.read((char *) &ticket , sizeof(ticket));
}
if (flag == 0)
cout << "\t\t\t\tThe Booking ID you entered doesn't exist in our Database\n";
cout << endl;
int q = exitFormat();
if (q == 1)
goto start;
}
break;
case 8:
{
cout << "\t\tGood Bye !!!! , We hope you enjoyed our Services \n";
exit(EXIT_SUCCESS);
}
}
}
|
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "wallet/wallet.h"
#include <QDebug>
#include <QFont>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
struct AddressTableEntry {
enum Type {
Sending,
Receiving,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
AddressTableEntry() {}
AddressTableEntry(Type _type, const QString& _label, const QString& _address) : type(_type), label(_label), address(_address) {}
};
struct AddressTableEntryLessThan {
bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry& a, const QString& b) const
{
return a.address < b;
}
bool operator()(const QString& a, const AddressTableEntry& b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet* wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel* parent;
AddressTablePriv(CWallet* _wallet, AddressTableModel* _parent) : wallet(_wallet), parent(_parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
for (const std::pair<CTxDestination, CAddressBookData>& item : wallet->mapAddressBook) {
const CDietBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(address.ToString())));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry* index(int idx)
{
if (idx >= 0 && idx < cachedAddressTable.size()) {
return &cachedAddressTable[idx];
} else {
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet* _wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(_wallet), priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case Label:
if (rec->label.isEmpty() && role == Qt::DisplayRole) {
return tr("(no label)");
} else {
return rec->label;
}
case Address:
return rec->address;
}
} else if (role == Qt::FontRole) {
QFont font;
if (index.column() == Address) {
font = GUIUtil::fixedPitchFont();
}
return font;
} else if (role == TypeRole) {
switch (rec->type) {
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default:
break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if (role == Qt::EditRole) {
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = CDietBitcoinAddress(rec->address.toStdString()).Get();
if (index.column() == Label) {
// Do nothing, if old label == new label
if (rec->label == value.toString()) {
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if (index.column() == Address) {
CTxDestination newAddress = CDietBitcoinAddress(value.toString().toStdString()).Get();
// Refuse to set invalid address, set error status and return false
if (boost::get<CNoDestination>(&newAddress)) {
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if (newAddress == curAddress) {
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if (wallet->mapAddressBook.count(newAddress)) {
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if (rec->type == AddressTableEntry::Sending) {
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole && section < columns.size()) {
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return 0;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if (rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column() == Label)) {
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
AddressTableEntry* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
} else {
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString& address,
const QString& label,
bool isMine,
const QString& purpose,
int status)
{
// Update address book model from DietBitcoin core
priv->updateEntry(address, label, isMine, purpose, status);
}
QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if (type == Send) {
if (!walletModel->validateAddress(address)) {
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if (wallet->mapAddressBook.count(CDietBitcoinAddress(strAddress).Get())) {
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
} else if (type == Receive) {
// Generate a new address to associate with given label
CPubKey newKey;
if (!wallet->GetKeyFromPool(newKey)) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock());
if (!ctx.isValid()) {
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if (!wallet->GetKeyFromPool(newKey)) {
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = CDietBitcoinAddress(newKey.GetID()).ToString();
} else {
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(CDietBitcoinAddress(strAddress).Get(), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent)
{
Q_UNUSED(parent);
AddressTableEntry* rec = priv->index(row);
if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) {
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(CDietBitcoinAddress(rec->address.toStdString()).Get());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString& address) const
{
{
LOCK(wallet->cs_wallet);
CDietBitcoinAddress address_parsed(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
if (mi != wallet->mapAddressBook.end()) {
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString& address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if (lst.isEmpty()) {
return -1;
} else {
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex()));
}
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define gcd(a,b) __gcd(a,b)
const int mod = 1e9+7;
int primes[] = {2,3,5,7};
int n;
int arr[100005];
ll arr1[100005];
ll dp[100005][4][1<<5];
//std::map<ll,ll>h;
ll f(int i,int cnt,int mask){
if(i==n){
return cnt==3;
}
if(cnt==3) return 1;
if(dp[i][cnt][mask]!=-1) return dp[i][cnt][mask];
ll ans = 0;
if(mask&arr[i]){
ans += f(i+1,cnt+1,mask&arr[i]);
ans += f(i+1,cnt,mask);
}
else ans += f(i+1,cnt,mask);
return dp[i][cnt][mask]=ans;
}
int main(int argc, char const *argv[])
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin>>n;
ll d;
map<int,int>m;
m[2] = 0;
m[3] = 1;
m[5] = 2;
m[7] = 3;
int idx=0;
for (int i = 0; i < n; ++i)
{
cin>>d;
//h[d]+=1;
//if(h[d]>1) continue;
//arr1[idx] = d;
int val = 0;
while(d){
int y = d%10;
d /= 10;
if(m.count(y)) val |= (1<<m[y]);
}
arr[i] = val;
//idx++;
}
memset(dp,-1,sizeof(dp));
//n = idx;
//cout<<n<<endl;
cout<<f(0,0,(1<<4)-1);
//cout<<ans;
return 0;
}
|
// MFEM Mesh Optimizer Miniapp - Serial/Parallel Shared Code
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace mfem;
using namespace std;
double discrete_size_2d(const Vector &x)
{
int opt = 2;
const double small = 0.001, big = 0.01;
double val = 0.;
if (opt == 1) // sine wave.
{
const double X = x(0), Y = x(1);
val = std::tanh((10*(Y-0.5) + std::sin(4.0*M_PI*X)) + 1) -
std::tanh((10*(Y-0.5) + std::sin(4.0*M_PI*X)) - 1);
}
else if (opt == 2) // semi-circle
{
const double xc = x(0) - 0.0, yc = x(1) - 0.5;
const double r = sqrt(xc*xc + yc*yc);
double r1 = 0.45; double r2 = 0.55; double sf=30.0;
val = 0.5*(1+std::tanh(sf*(r-r1))) - 0.5*(1+std::tanh(sf*(r-r2)));
}
val = std::max(0.,val);
val = std::min(1.,val);
return val * small + (1.0 - val) * big;
}
double material_indicator_2d(const Vector &x)
{
double xc = x(0)-0.5, yc = x(1)-0.5;
double th = 22.5*M_PI/180.;
double xn = cos(th)*xc + sin(th)*yc;
double yn = -sin(th)*xc + cos(th)*yc;
double th2 = (th > 45.*M_PI/180) ? M_PI/2 - th : th;
double stretch = 1/cos(th2);
xc = xn/stretch; yc = yn/stretch;
double tfac = 20;
double s1 = 3;
double s2 = 3;
double wgt = std::tanh((tfac*(yc) + s2*std::sin(s1*M_PI*xc)) + 1);
if (wgt > 1) { wgt = 1; }
if (wgt < 0) { wgt = 0; }
return wgt;
}
double discrete_ori_2d(const Vector &x)
{
return M_PI * x(1) * (1.0 - x(1)) * cos(2 * M_PI * x(0));
}
double discrete_aspr_2d(const Vector &x)
{
double xc = x(0)-0.5, yc = x(1)-0.5;
double th = 22.5*M_PI/180.;
double xn = cos(th)*xc + sin(th)*yc;
double yn = -sin(th)*xc + cos(th)*yc;
//double th2 = (th > 45.*M_PI/180) ? M_PI/2 - th : th;
//double stretch = 1/cos(th2);
xc = xn; yc = yn;
double tfac = 20;
double s1 = 3;
double s2 = 2;
double wgt = std::tanh((tfac*(yc) + s2*std::sin(s1*M_PI*xc)) + 1)
- std::tanh((tfac*(yc) + s2*std::sin(s1*M_PI*xc)) - 1);
if (wgt > 1) { wgt = 1; }
if (wgt < 0) { wgt = 0; }
return 0.1 + 1*(1-wgt)*(1-wgt);
}
void discrete_aspr_3d(const Vector &x, Vector &v)
{
int dim = x.Size();
v.SetSize(dim);
double l1, l2, l3;
l1 = 1.;
l2 = 1. + 5*x(1);
l3 = 1. + 10*x(2);
v[0] = l1/pow(l2*l3,0.5);
v[1] = l2/pow(l1*l3,0.5);
v[2] = l3/pow(l2*l1,0.5);
}
class HessianCoefficient : public MatrixCoefficient
{
private:
int metric;
public:
HessianCoefficient(int dim, int metric_id)
: MatrixCoefficient(dim), metric(metric_id) { }
virtual void Eval(DenseMatrix &K, ElementTransformation &T,
const IntegrationPoint &ip)
{
Vector pos(3);
T.Transform(ip, pos);
if (metric != 14 && metric != 87)
{
const double xc = pos(0) - 0.5, yc = pos(1) - 0.5;
const double r = sqrt(xc*xc + yc*yc);
double r1 = 0.15; double r2 = 0.35; double sf=30.0;
const double eps = 0.5;
const double tan1 = std::tanh(sf*(r-r1)),
tan2 = std::tanh(sf*(r-r2));
K(0, 0) = eps + 1.0 * (tan1 - tan2);
K(0, 1) = 0.0;
K(1, 0) = 0.0;
K(1, 1) = 1.0;
}
else if (metric == 14) // Size + Alignment
{
const double xc = pos(0), yc = pos(1);
double theta = M_PI * yc * (1.0 - yc) * cos(2 * M_PI * xc);
double alpha_bar = 0.1;
K(0, 0) = cos(theta);
K(1, 0) = sin(theta);
K(0, 1) = -sin(theta);
K(1, 1) = cos(theta);
K *= alpha_bar;
}
else if (metric == 87) // Shape + Alignment
{
Vector x = pos;
double xc = x(0)-0.5, yc = x(1)-0.5;
double th = 22.5*M_PI/180.;
double xn = cos(th)*xc + sin(th)*yc;
double yn = -sin(th)*xc + cos(th)*yc;
xc = xn; yc=yn;
double tfac = 20;
double s1 = 3;
double s2 = 2;
double wgt = std::tanh((tfac*(yc) + s2*std::sin(s1*M_PI*xc)) + 1)
- std::tanh((tfac*(yc) + s2*std::sin(s1*M_PI*xc)) - 1);
if (wgt > 1) { wgt = 1; }
if (wgt < 0) { wgt = 0; }
xc = pos(0), yc = pos(1);
double theta = M_PI * (yc) * (1.0 - yc) * cos(2 * M_PI * xc);
K(0, 0) = cos(theta);
K(1, 0) = sin(theta);
K(0, 1) = -sin(theta);
K(1, 1) = cos(theta);
double asp_ratio_tar = 0.1 + 1*(1-wgt)*(1-wgt);
K(0, 0) *= 1/pow(asp_ratio_tar,0.5);
K(1, 0) *= 1/pow(asp_ratio_tar,0.5);
K(0, 1) *= pow(asp_ratio_tar,0.5);
K(1, 1) *= pow(asp_ratio_tar,0.5);
}
}
};
// Additional IntegrationRules that can be used with the --quad-type option.
IntegrationRules IntRulesLo(0, Quadrature1D::GaussLobatto);
IntegrationRules IntRulesCU(0, Quadrature1D::ClosedUniform);
// Defined with respect to the icf mesh.
double weight_fun(const Vector &x)
{
const double r = sqrt(x(0)*x(0) + x(1)*x(1) + 1e-12);
const double den = 0.002;
double l2 = 0.2 + 0.5*std::tanh((r-0.16)/den) - 0.5*std::tanh((r-0.17)/den)
+ 0.5*std::tanh((r-0.23)/den) - 0.5*std::tanh((r-0.24)/den);
return l2;
}
// Used for the adaptive limiting examples.
double adapt_lim_fun(const Vector &x)
{
const double xc = x(0) - 0.1, yc = x(1) - 0.2;
const double r = sqrt(xc*xc + yc*yc);
double r1 = 0.45; double r2 = 0.55; double sf=30.0;
double val = 0.5*(1+std::tanh(sf*(r-r1))) - 0.5*(1+std::tanh(sf*(r-r2)));
val = std::max(0.,val);
val = std::min(1.,val);
return val;
}
void DiffuseField(GridFunction &field, int smooth_steps)
{
//Setup the Laplacian operator
BilinearForm *Lap = new BilinearForm(field.FESpace());
Lap->AddDomainIntegrator(new DiffusionIntegrator());
Lap->Assemble();
Lap->Finalize();
//Setup the smoothing operator
DSmoother *S = new DSmoother(0,1.0,smooth_steps);
S->iterative_mode = true;
S->SetOperator(Lap->SpMat());
Vector tmp(field.Size());
tmp = 0.0;
S->Mult(tmp, field);
delete S;
delete Lap;
}
#ifdef MFEM_USE_MPI
void DiffuseField(ParGridFunction &field, int smooth_steps)
{
//Setup the Laplacian operator
ParBilinearForm *Lap = new ParBilinearForm(field.ParFESpace());
Lap->AddDomainIntegrator(new DiffusionIntegrator());
Lap->Assemble();
Lap->Finalize();
HypreParMatrix *A = Lap->ParallelAssemble();
HypreSmoother *S = new HypreSmoother(*A,0,smooth_steps);
S->iterative_mode = true;
Vector tmp(A->Width());
field.SetTrueVector();
Vector fieldtrue = field.GetTrueVector();
tmp = 0.0;
S->Mult(tmp, fieldtrue);
field.SetFromTrueDofs(fieldtrue);
delete S;
delete Lap;
}
#endif
|
// Time: O(m * n)
// Space: O(m)
// DP Solution with rolling window
class Solution {
public:
/**
* @param s: A string
* @param p: A string includes "?" and "*"
* @return: A boolean
*/
bool isMatch(const char *s, const char *p) {
const size_t s_len = strlen(s);
const size_t p_len = strlen(p);
// match[i][j] denotes as:
// s[0, i - 1] matches p[0, j - 1] or not.
vector<vector<bool>> match(s_len + 1, vector<bool>(p_len + 1));
match[0][0] = true;
for (int i = 2; i <= p_len; ++i) {
if (p[i - 1] == '*') {
match[0 % 2][i] = match[0 % 2][i - 2];
}
}
for (int i = 1; i <= s_len; ++i) {
match[i % 2][0] = false;
for (int j = 1; j <= p_len; ++j) {
if (p[j - 1] != '*') {
match[i % 2][j] = match[(i - 1) % 2][j - 1] && (p[j - 1] == s[i - 1] || p[j - 1] == '.');
} else {
match[i % 2][j] = j >= 2 && (match[i % 2][j - 2] || (match[(i - 1) % 2][j] && (p[j - 2] == s[i - 1] || p[j - 2]=='.')));
}
}
}
return match[s_len % 2][p_len];
}
};
// Time: O(m * n)
// Space: O(m * n)
// DP Solution
class Solution2 {
public:
/**
* @param s: A string
* @param p: A string includes "?" and "*"
* @return: A boolean
*/
bool isMatch(const char *s, const char *p) {
const size_t s_len = strlen(s);
const size_t p_len = strlen(p);
// match[i][j] denotes as:
// s[0, i - 1] matches p[0, j - 1] or not.
vector<vector<bool>> match(s_len + 1, vector<bool>(p_len + 1));
match[0][0] = true;
for (int i = 2; i <= p_len; ++i) {
if (p[i - 1] == '*') {
match[0][i] = match[0][i - 2];
}
}
for (int i = 1; i <= s_len; ++i) {
match[i][0] = false;
for (int j = 1; j <= p_len; ++j) {
if (p[j - 1] != '*') {
match[i][j] = match[i - 1][j - 1] && (p[j - 1] == s[i - 1] || p[j - 1] == '.');
} else {
match[i][j] = j >= 2 && (match[i][j - 2] || (match[i - 1][j] && (p[j - 2] == s[i - 1] || p[j - 2] == '.')));
}
}
}
return match[s_len][p_len];
}
};
// Time: O(m * n^2)
// Space: O(m + n)
// Recursion solution
class Solution3 {
public:
/**
* @param s: A string
* @param p: A string includes "?" and "*"
* @return: A boolean
*/
bool isMatch(const char *s, const char *p) {
if (*s == 0 || *p == 0) {
return *s == 0 && *p == 0;
}
if (*(p + 1) == 0 || p[1] != '*') {
if (*s != 0 && (p[0] == s[0] || p[0] == '.')) {
// Matched a char.
return isMatch(s + 1, p + 1);
} else {
return false;
}
} else {
// Try all possible matches with '*' in p.
while (*s != 0 && (p[0] == s[0] || p[0] == '.')) {
if (isMatch(s, p + 2)) {
return true;
}
++s;
}
return isMatch(s, p + 2);
}
}
};
// Time: O(?)
// Space: O(?)
// Iteration solution (Greedy not work)
class Solution4 {
public:
/**
* @param s: A string
* @param p: A string includes "." and "*"
* @return: A boolean
*/
bool isMatch(const char *s, const char *p) {
int p_pos = 0, s_pos = 0;
int last_s_pos = -1, last_p_pos = -1;
const int s_len = strlen(s), p_len = strlen(p);
stack<pair<int, int>> last_pos;
while (s_pos < s_len) {
if (p_pos < p_len && (p_pos == p_len - 1 || p[p_pos + 1] != '*') &&
(s_pos < s_len && (p[p_pos] == s[s_pos] || p[p_pos] == '.'))) {
// Matched a char.
++s_pos;
++p_pos;
} else if (p_pos < p_len && (p_pos != p_len - 1 && p[p_pos + 1] == '*')) {
// Matched '*'.
p_pos += 2;
last_pos.emplace({s_pos, p_pos});
} else if (!last_pos.empty()) {
// Rollback to the last position of '*' plus 2.
// And try next position of last matched one.
tie<int, int>(last_s_pos, last_p_pos) = last_pos.top();
last_pos.pop();
while (!last_pos.empty() && p[last_p_pos - 2] != s[last_s_pos] && p[last_p_pos - 2] != '.') {
tie<int, int>(last_s_pos, last_p_pos) = last_pos.top();
last_pos.pop();
}
if (p[last_p_pos - 2] == s[last_s_pos] || p[last_p_pos - 2] == '.') {
++last_s_pos;
s_pos = last_s_pos;
p_pos = last_p_pos;
last_pos.emplace({s_pos, p_pos});
}
else {
return false;
}
} else {
// s_pos < s_len && no matched p, no position to retry.
return false;
}
}
// Skip '*' in p.
while (p_pos < p_len - 1 && p[p_pos] == '.' && p[p_pos + 1] == '*') {
p_pos += 2;
}
// Check if pattern is all matched.
return p_pos == p_len;
}
};
|
//
// $Id$
//
//
// Original author: Darren Kessner <darren@proteowizard.org>
//
// Copyright 2008 Spielberg Family Center for Applied Proteomics
// Cedars-Sinai Medical Center, Los Angeles, California 90048
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef _MSDATACACHE_HPP_
#define _MSDATACACHE_HPP_
#include "pwiz/utility/misc/Export.hpp"
#include "pwiz/data/msdata/SpectrumInfo.hpp"
#include "MSDataAnalyzer.hpp"
namespace pwiz {
namespace analysis {
using namespace msdata;
///
/// simple memory cache for common MSData info
///
/// Memory caching is useful to minimize data retrieval expenses:
/// - disk I/O and decoding of binary data
/// - indirection and pointer validation
/// - parameter list searching
/// - lexical casting
///
/// MSDataCache is a vector of SpectrumInfo objects, but also implements the
/// MSDataAnalyzer interface. It can be used in two ways:
/// 1) Updated from the outside via MSDataAnalyzer interface
/// 2) Automatic updating via spectrumInfo() access method
///
/// Spectrum binary data (SpectrumInfo::data) is
/// freed from the cache using a LRU (least recently used) algorithm.
/// Binary data will be freed only to make room for a new update. The
/// default cache size is 1, i.e. only the most recently updated binary
/// data array is stored. Note that modifying the SpectrumInfo objects
/// directly through the vector interface circumvents the LRU mechanism.
///
/// Usage #1: MSDataCache should be placed first in an
/// MSDataAnalyzerContainer, so that it receives update() first. Other
/// analyzers may then use it (preferably as const MSDataCache&) to access
/// spectrum data when they receive update(). On updateRequested(),
/// MSDataCache returns UpdateRequest_Ok to indicate that it should
/// receive any updates that are requested by other analyzers. If no
/// other analyzer requests an update, the cache will not be updated.
///
/// Usage #2: Instantiate independently and call open() to set reference to an
/// MSData object. Calls to spectrumInfo() will return the requested SpectrumInfo,
/// automatically updating the cache via call to SpectrumList::spectrum() if
/// necessary.
///
class PWIZ_API_DECL MSDataCache : public std::vector<SpectrumInfo>,
public MSDataAnalyzer
{
public:
/// MSDataCache configuration
struct PWIZ_API_DECL Config
{
size_t binaryDataCacheSize;
Config(size_t cacheSize = 1) : binaryDataCacheSize(cacheSize) {}
};
MSDataCache(const Config& config = Config());
/// \name MSDataAnalyzer interface
//@{
virtual void open(const DataInfo& dataInfo);
virtual UpdateRequest updateRequested(const DataInfo& dataInfo,
const SpectrumIdentity& spectrumIdentity) const
{
// receive update() only if requested by another analyzer
return MSDataAnalyzer::UpdateRequest_Ok;
}
virtual void update(const DataInfo& dataInfo,
const Spectrum& spectrum);
//@}
/// access to SpectrumInfo with automatic update (open() must be called first)
const SpectrumInfo& spectrumInfo(size_t index, bool getBinaryData = false);
private:
struct Impl;
boost::shared_ptr<Impl> impl_;
MSDataCache(MSDataCache&);
MSDataCache& operator=(MSDataCache&);
};
} // namespace analysis
} // namespace pwiz
#endif // _MSDATACACHE_HPP_
|
/*
Copyright (c) 2005-2019, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
#include "Hdf5ToXdmfConverter.hpp"
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM>
Hdf5ToXdmfConverter<ELEMENT_DIM, SPACE_DIM>::Hdf5ToXdmfConverter(const FileFinder& rInputDirectory,
const std::string& rFileBaseName,
AbstractTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh)
: AbstractHdf5Converter<ELEMENT_DIM,SPACE_DIM>(rInputDirectory, rFileBaseName, pMesh, "xdmf_output", 0u),
XdmfMeshWriter<ELEMENT_DIM,SPACE_DIM>(rInputDirectory.GetRelativePath(FileFinder("", RelativeTo::ChasteTestOutput)) + "/xdmf_output",
rFileBaseName, false /* Not cleaning directory*/)
{
// Set number of time steps
std::vector<double> time_values = this->mpReader->GetUnlimitedDimensionValues();
unsigned num_timesteps = time_values.size();
this->mNumberOfTimePoints = num_timesteps;
// Set time step size
if (num_timesteps > 1)
{
this->mTimeStep = time_values[1] - time_values[0];
}
// Write
this->WriteFilesUsingMesh(*pMesh);
}
#ifndef _MSC_VER
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void Hdf5ToXdmfConverter<ELEMENT_DIM, SPACE_DIM>::AddDataOnNodes(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* pGridElement,
XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDomDocument,
unsigned timeStep)
{
// Use xerces namespace for convenience
XERCES_CPP_NAMESPACE_USE
unsigned num_timesteps = this->mpReader->GetUnlimitedDimensionValues().size();
// Loop over variables
for (unsigned var_index=0; var_index<this->mNumVariables; var_index++)
{
std::string variable_name = this->mpReader->GetVariableNames()[var_index];
/*
* e.g. <Attribute Center="Node" Name="V">
*/
DOMElement* p_attr_element = pDomDocument->createElement(X("Attribute"));
p_attr_element->setAttribute(X("Name"), X(variable_name));
p_attr_element->setAttribute(X("Center"), X("Node"));
pGridElement->appendChild(p_attr_element);
/*
* e.g. <DataItem Dimensions="1 12 1" ItemType="HyperSlab">
*/
DOMElement* p_hype_element = pDomDocument->createElement(X("DataItem"));
p_hype_element->setAttribute(X("ItemType"), X("HyperSlab"));
std::stringstream dim_stream;
// First index is time value, second is number of nodes, third is variable index
///\todo #1157 Make this work in parallel
/* DistributedVectorFactory* p_factory = AbstractHdf5Converter<ELEMENT_DIM, SPACE_DIM>::mpMesh->GetDistributedVectorFactory();
dim_stream << "1 " << p_factory->GetHigh()-p_factory->GetLow() << " 1"; */
unsigned num_nodes = AbstractHdf5Converter<ELEMENT_DIM, SPACE_DIM>::mpMesh->GetNumNodes();
dim_stream << "1 " << num_nodes << " 1";
p_hype_element->setAttribute(X("Dimensions"), X(dim_stream.str()));
p_attr_element->appendChild(p_hype_element);
/*
* e.g. <DataItem Dimensions="3 3" Format="XML">
*/
DOMElement* p_xml_element = pDomDocument->createElement(X("DataItem"));
p_xml_element->setAttribute(X("Format"), X("XML"));
p_xml_element->setAttribute(X("Dimensions"), X("3 3"));
p_hype_element->appendChild(p_xml_element);
/*
* e.g. 0 0 0 1 1 1 1 12 1
*/
std::stringstream XMLStream;
XMLStream << timeStep << " 0 " << var_index << " ";
XMLStream << "1 1 1 ";
/* XMLStream << "1 " << p_factory->GetHigh()-p_factory->GetLow() << " 1"; */
XMLStream << "1 " << num_nodes << " 1";
DOMText* p_xml_text = pDomDocument->createTextNode(X(XMLStream.str()));
p_xml_element->appendChild(p_xml_text);
/*
* e.g. <DataItem Dimensions="2 12 2" Format="HDF" NumberType="Float" Precision="8">
*/
DOMElement* p_hdf_element = pDomDocument->createElement(X("DataItem"));
p_hdf_element->setAttribute(X("Format"), X("HDF"));
p_hdf_element->setAttribute(X("NumberType"), X("Float"));
p_hdf_element->setAttribute(X("Precision"), X("8"));
std::stringstream hdf_dims_stream;
/* hdf_dims_stream << num_timesteps << " " << p_factory->GetHigh()-p_factory->GetLow() << " " << this->mNumVariables; */
hdf_dims_stream << num_timesteps << " " << num_nodes << " " << this->mNumVariables;
p_hdf_element->setAttribute(X("Dimensions"), X(hdf_dims_stream.str()));
p_hype_element->appendChild(p_hdf_element);
/*
* e.g. ../cube_2mm_12_elements.h5:/Data
*/
std::stringstream HDFStream;
HDFStream << "../" << AbstractHdf5Converter<ELEMENT_DIM, SPACE_DIM>::mFileBaseName << ".h5:/Data";
DOMText* p_hdf_text = pDomDocument->createTextNode(X(HDFStream.str()));
p_hdf_element->appendChild(p_hdf_text);
}
}
#endif
// Explicit instantiation
template class Hdf5ToXdmfConverter<1,1>;
template class Hdf5ToXdmfConverter<1,2>;
template class Hdf5ToXdmfConverter<2,2>;
template class Hdf5ToXdmfConverter<1,3>;
template class Hdf5ToXdmfConverter<2,3>;
template class Hdf5ToXdmfConverter<3,3>;
|
/**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <list>
#include <vector>
#include "common/common_test.h"
#include "parallel/strategy.h"
#include "parallel/ops_info/matmul_info.h"
#include "parallel/device_manager.h"
#include "parallel/step_parallel.h"
#include "parallel/auto_parallel/graph_costmodel.h"
namespace mindspore {
namespace parallel {
class MatMulInfo;
using MatMulInfoPtr = std::shared_ptr<MatMulInfo>;
MatMulInfoPtr matmul1;
MatMulInfoPtr matmul2;
MatMulInfoPtr matmul3;
MatMulInfoPtr matmul4;
class TestMatmulInfo : public UT::Common {
public:
TestMatmulInfo() {}
void SetUp();
void TearDown() {}
};
void TestMatmulInfo::SetUp() {
std::vector<int32_t> dev_list;
for (int32_t i = 0; i < 1050; i++) {
dev_list.push_back(i);
}
std::vector<int32_t> stage_map;
stage_map.push_back(1024);
stage_map.push_back(26);
int32_t local_dev = 0;
// create a new g_device_manager
g_device_manager = std::make_shared<DeviceManager>();
g_device_manager->Init(dev_list, local_dev, stage_map, "hccl");
// matmul1
ValuePtr transpose_a_1 = MakeValue(false);
ValuePtr transpoce_b_1 = MakeValue(false);
std::unordered_map<std::string, ValuePtr> attr_1 = {{"transpose_a", transpose_a_1}, {"transpose_b", transpoce_b_1}};
Shapes inputs_shape_1 = {{2, 4, 8, 16}, {2, 4, 16, 32}};
Shapes outputs_shape_1 = {{2, 4, 8, 32}};
matmul1 = std::make_shared<MatMulInfo>("matmul_info", inputs_shape_1, outputs_shape_1, attr_1);
// matmul2
ValuePtr transpose_a_2 = MakeValue(false);
ValuePtr transpoce_b_2 = MakeValue(true);
std::unordered_map<std::string, ValuePtr> attr_2 = {{"transpose_a", transpose_a_2}, {"transpose_b", transpoce_b_2}};
Shapes inputs_shape_2 = {{2, 4, 8, 16}, {32, 16}};
Shapes outputs_shape_2 = {{2, 4, 8, 32}};
matmul2 = std::make_shared<MatMulInfo>("matmul_info", inputs_shape_2, outputs_shape_2, attr_2);
// matmul3
ValuePtr transpose_a_3 = MakeValue(false);
ValuePtr transpoce_b_3 = MakeValue(true);
std::unordered_map<std::string, ValuePtr> attr_3 = {{"transpose_a", transpose_a_3}, {"transpose_b", transpoce_b_3}};
Shapes inputs_shape_3 = {{8, 16}, {2, 4, 32, 16}};
Shapes outputs_shape_3 = {{2, 4, 8, 32}};
matmul3 = std::make_shared<MatMulInfo>("matmul_info", inputs_shape_3, outputs_shape_3, attr_3);
// matmul4
std::unordered_map<std::string, ValuePtr> attr_4 = {{"transpose_a", transpose_a_3}};
matmul4 = std::make_shared<MatMulInfo>("matmul_info", inputs_shape_3, outputs_shape_3, attr_4);
}
TEST_F(TestMatmulInfo, InferDevMatrixShape1) {
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul1->Init(strategy);
std::vector<int32_t> dev_matrix_shape = matmul1->dev_matrix_shape();
std::vector<int32_t> expect = {2, 4, 8, 16, 1};
ASSERT_EQ(dev_matrix_shape, expect);
}
TEST_F(TestMatmulInfo, InferDevMatrixShape2) {
std::vector<Dimensions> inputs = {{2, 4, 8, 8}, {2, 4, 8, 2}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul1->Init(strategy);
std::vector<int32_t> dev_matrix_shape = matmul1->dev_matrix_shape();
std::vector<int32_t> expect = {2, 4, 8, 8, 2};
ASSERT_EQ(dev_matrix_shape, expect);
}
// matmul2
TEST_F(TestMatmulInfo, InferDevMatrixShape3) {
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {1, 16}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul2->Init(strategy);
std::vector<int32_t> dev_matrix_shape = matmul2->dev_matrix_shape();
std::vector<int32_t> expect = {2, 4, 8, 16, 1};
ASSERT_EQ(dev_matrix_shape, expect);
}
// matmul2
TEST_F(TestMatmulInfo, InferDevMatrixShape4) {
std::vector<Dimensions> inputs = {{2, 4, 8, 8}, {2, 8}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul2->Init(strategy);
std::vector<int32_t> dev_matrix_shape = matmul2->dev_matrix_shape();
std::vector<int32_t> expect = {2, 4, 8, 8, 2};
ASSERT_EQ(dev_matrix_shape, expect);
}
// matmul3
TEST_F(TestMatmulInfo, InferDevMatrixShape5) {
std::vector<Dimensions> inputs = {{8, 16}, {2, 4, 1, 16}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul3->Init(strategy);
std::vector<int32_t> dev_matrix_shape = matmul3->dev_matrix_shape();
std::vector<int32_t> expect = {2, 4, 8, 16, 1};
ASSERT_EQ(dev_matrix_shape, expect);
}
// matmul3
TEST_F(TestMatmulInfo, InferDevMatrixShape6) {
std::vector<Dimensions> inputs = {{8, 8}, {2, 4, 2, 8}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul3->Init(strategy);
std::vector<int32_t> dev_matrix_shape = matmul3->dev_matrix_shape();
std::vector<int32_t> expect = {2, 4, 8, 8, 2};
ASSERT_EQ(dev_matrix_shape, expect);
}
TEST_F(TestMatmulInfo, InferTensorMap1) {
std::vector<Dimensions> str = {{2, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, str);
matmul1->Init(strategy);
std::vector<TensorInfo> inputs = matmul1->inputs_tensor_info();
std::vector<TensorInfo> outputs = matmul1->outputs_tensor_info();
TensorMap mat_a_expect = {4, 3, 2, 1};
TensorMap mat_b_expect = {4, 3, 1, 0};
TensorMap output_expect = {4, 3, 2, 0};
TensorInfo mat_a_tensor_info = inputs.at(0);
TensorInfo mat_b_tensor_info = inputs.at(1);
TensorInfo output_tensor_info = outputs.at(0);
Map mat_a_tensor_map = mat_a_tensor_info.tensor_layout().origin_tensor_map();
Map mat_b_tensor_map = mat_b_tensor_info.tensor_layout().origin_tensor_map();
Map output_tensor_map = output_tensor_info.tensor_layout().origin_tensor_map();
ASSERT_EQ(mat_a_tensor_map.array(), mat_a_expect);
ASSERT_EQ(mat_b_tensor_map.array(), mat_b_expect);
ASSERT_EQ(output_tensor_map.array(), output_expect);
}
// matmul2
TEST_F(TestMatmulInfo, InferTensorMap2) {
std::vector<Dimensions> str = {{2, 4, 8, 16}, {1, 16}};
StrategyPtr strategy = NewStrategy(0, str);
matmul2->Init(strategy);
std::vector<TensorInfo> inputs = matmul2->inputs_tensor_info();
std::vector<TensorInfo> outputs = matmul2->outputs_tensor_info();
TensorMap mat_a_expect = {4, 3, 2, 1};
TensorMap mat_b_expect = {0, 1};
TensorMap output_expect = {4, 3, 2, 0};
TensorInfo mat_a_tensor_info = inputs.at(0);
TensorInfo mat_b_tensor_info = inputs.at(1);
TensorInfo output_tensor_info = outputs.at(0);
Map mat_a_tensor_map = mat_a_tensor_info.tensor_layout().origin_tensor_map();
Map mat_b_tensor_map = mat_b_tensor_info.tensor_layout().origin_tensor_map();
Map output_tensor_map = output_tensor_info.tensor_layout().origin_tensor_map();
ASSERT_EQ(mat_a_tensor_map.array(), mat_a_expect);
ASSERT_EQ(mat_b_tensor_map.array(), mat_b_expect);
ASSERT_EQ(output_tensor_map.array(), output_expect);
}
// matmul3
TEST_F(TestMatmulInfo, InferTensorMap3) {
std::vector<Dimensions> str = {{8, 16}, {2, 4, 1, 16}};
StrategyPtr strategy = NewStrategy(0, str);
matmul3->Init(strategy);
std::vector<TensorInfo> inputs = matmul3->inputs_tensor_info();
std::vector<TensorInfo> outputs = matmul3->outputs_tensor_info();
TensorMap mat_a_expect = {2, 1};
TensorMap mat_b_expect = {4, 3, 0, 1};
TensorMap output_expect = {4, 3, 2, 0};
TensorInfo mat_a_tensor_info = inputs.at(0);
TensorInfo mat_b_tensor_info = inputs.at(1);
TensorInfo output_tensor_info = outputs.at(0);
Map mat_a_tensor_map = mat_a_tensor_info.tensor_layout().origin_tensor_map();
Map mat_b_tensor_map = mat_b_tensor_info.tensor_layout().origin_tensor_map();
Map output_tensor_map = output_tensor_info.tensor_layout().origin_tensor_map();
ASSERT_EQ(mat_a_tensor_map.array(), mat_a_expect);
ASSERT_EQ(mat_b_tensor_map.array(), mat_b_expect);
ASSERT_EQ(output_tensor_map.array(), output_expect);
}
TEST_F(TestMatmulInfo, InferSliceShape1) {
std::vector<Dimensions> str = {{2, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, str);
matmul1->Init(strategy);
std::vector<TensorInfo> inputs = matmul1->inputs_tensor_info();
std::vector<TensorInfo> outputs = matmul1->outputs_tensor_info();
Shape mat_a_slice_shape_expect = {1, 1, 1, 1};
Shape mat_b_slice_shape_expect = {1, 1, 1, 32};
Shape output_slice_shape_expect = {1, 1, 1, 32};
TensorInfo mat_a_tensor_info = inputs.at(0);
TensorInfo mat_b_tensor_info = inputs.at(1);
TensorInfo output_tensor_info = outputs.at(0);
Shape mat_a_slice_shape = mat_a_tensor_info.slice_shape();
Shape mat_b_slice_shape = mat_b_tensor_info.slice_shape();
Shape output_slice_shape = output_tensor_info.slice_shape();
ASSERT_EQ(mat_a_slice_shape, mat_a_slice_shape_expect);
ASSERT_EQ(mat_b_slice_shape, mat_b_slice_shape_expect);
ASSERT_EQ(output_slice_shape, output_slice_shape_expect);
}
// matmul2
TEST_F(TestMatmulInfo, InferSliceShape2) {
std::vector<Dimensions> str = {{2, 4, 8, 16}, {1, 16}};
StrategyPtr strategy = NewStrategy(0, str);
matmul2->Init(strategy);
std::vector<TensorInfo> inputs = matmul2->inputs_tensor_info();
std::vector<TensorInfo> outputs = matmul2->outputs_tensor_info();
Shape mat_a_slice_shape_expect = {1, 1, 1, 1};
Shape mat_b_slice_shape_expect = {32, 1};
Shape output_slice_shape_expect = {1, 1, 1, 32};
TensorInfo mat_a_tensor_info = inputs.at(0);
TensorInfo mat_b_tensor_info = inputs.at(1);
TensorInfo output_tensor_info = outputs.at(0);
Shape mat_a_slice_shape = mat_a_tensor_info.slice_shape();
Shape mat_b_slice_shape = mat_b_tensor_info.slice_shape();
Shape output_slice_shape = output_tensor_info.slice_shape();
ASSERT_EQ(mat_a_slice_shape, mat_a_slice_shape_expect);
ASSERT_EQ(mat_b_slice_shape, mat_b_slice_shape_expect);
ASSERT_EQ(output_slice_shape, output_slice_shape_expect);
}
// matmul3
TEST_F(TestMatmulInfo, InferSliceShape3) {
std::vector<Dimensions> str = {{8, 16}, {2, 4, 1, 16}};
StrategyPtr strategy = NewStrategy(0, str);
matmul3->Init(strategy);
std::vector<TensorInfo> inputs = matmul3->inputs_tensor_info();
std::vector<TensorInfo> outputs = matmul3->outputs_tensor_info();
Shape mat_a_slice_shape_expect = {1, 1};
Shape mat_b_slice_shape_expect = {1, 1, 32, 1};
Shape output_slice_shape_expect = {1, 1, 1, 32};
TensorInfo mat_a_tensor_info = inputs.at(0);
TensorInfo mat_b_tensor_info = inputs.at(1);
TensorInfo output_tensor_info = outputs.at(0);
Shape mat_a_slice_shape = mat_a_tensor_info.slice_shape();
Shape mat_b_slice_shape = mat_b_tensor_info.slice_shape();
Shape output_slice_shape = output_tensor_info.slice_shape();
ASSERT_EQ(mat_a_slice_shape, mat_a_slice_shape_expect);
ASSERT_EQ(mat_b_slice_shape, mat_b_slice_shape_expect);
ASSERT_EQ(output_slice_shape, output_slice_shape_expect);
}
// matmul3
TEST_F(TestMatmulInfo, GetTensorLayout3) {
std::vector<Dimensions> str = {{8, 16}, {2, 4, 1, 16}};
StrategyPtr strategy = NewStrategy(0, str);
matmul3->Init(strategy);
std::vector<TensorInfo> inputs = matmul3->inputs_tensor_info();
std::vector<TensorInfo> outputs = matmul3->outputs_tensor_info();
TensorMap mat_a_expect = {2, 1};
TensorMap mat_b_expect = {4, 3, 0, 1};
TensorMap output_expect = {4, 3, 2, 0};
TensorInfo mat_a_tensor_info = inputs.at(0);
TensorInfo mat_b_tensor_info = inputs.at(1);
TensorInfo output_tensor_info = outputs.at(0);
Map mat_a_tensor_map = mat_a_tensor_info.tensor_layout().origin_tensor_map();
Map mat_b_tensor_map = mat_b_tensor_info.tensor_layout().origin_tensor_map();
Map output_tensor_map = output_tensor_info.tensor_layout().origin_tensor_map();
ASSERT_EQ(mat_a_tensor_map.array(), mat_a_expect);
ASSERT_EQ(mat_b_tensor_map.array(), mat_b_expect);
ASSERT_EQ(output_tensor_map.array(), output_expect);
}
TEST_F(TestMatmulInfo, GetForwardOp1) {
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul1->Init(strategy);
OperatorVector forward_op = matmul1->forward_op();
OperatorArgs operator_args = forward_op.at(0).second;
std::string arg0_name = operator_args.first.at(0).first;
ValuePtr arg0_value = operator_args.first.at(0).second;
std::string arg1_name = operator_args.first.at(1).first;
ValuePtr arg1_value = operator_args.first.at(1).second;
bool arg1_value_is_string = false;
if (arg1_value->isa<StringImm>()) {
arg1_value_is_string = true;
}
ASSERT_EQ(forward_op.at(0).first, "AllReduce");
ASSERT_EQ(forward_op.size(), 1);
ASSERT_EQ(arg0_name, "op");
ASSERT_EQ(arg1_name, "group");
ASSERT_EQ(arg1_value_is_string, true);
}
TEST_F(TestMatmulInfo, GetForwardOp2) {
std::vector<Dimensions> inputs = {{2, 4, 8, 1}, {2, 4, 1, 16}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul1->Init(strategy);
OperatorVector forward_op = matmul1->forward_op();
ASSERT_EQ(forward_op.size(), 0);
}
TEST_F(TestMatmulInfo, GetVirtualDivOp1) {
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul1->Init(strategy);
OperatorVector virtual_div_op = matmul1->virtual_div_op();
OperatorArgs operator_args = virtual_div_op.at(0).second;
std::string arg0_name = operator_args.first.at(0).first;
ValuePtr arg0_value = operator_args.first.at(0).second;
int32_t divisor = arg0_value->cast<Int32ImmPtr>()->value();
ASSERT_EQ(virtual_div_op.at(0).first, "_VirtualDiv");
ASSERT_EQ(virtual_div_op.size(), 1);
ASSERT_EQ(arg0_name, "divisor");
ASSERT_EQ(divisor, 16);
}
TEST_F(TestMatmulInfo, GetMirrorOPs1) {
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul1->Init(strategy);
MirrorOps mirror_ops = matmul1->mirror_ops();
OperatorVector mirror_op = mirror_ops.at(1);
OperatorArgs operator_args = mirror_op.at(0).second;
std::string arg0_name = operator_args.first.at(0).first;
ValuePtr arg0_value = operator_args.first.at(0).second;
std::string group = arg0_value->cast<StringImmPtr>()->ToString();
ASSERT_EQ(mirror_op.at(0).first, "_MirrorOperator");
ASSERT_EQ(mirror_op.size(), 1);
ASSERT_EQ(arg0_name, "group");
}
// matmul2
TEST_F(TestMatmulInfo, GetMirrorOPs2) {
std::vector<Dimensions> inputs = {{2, 4, 1, 16}, {8, 16}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul2->Init(strategy);
MirrorOps mirror_ops = matmul2->mirror_ops();
OperatorVector mirror_op = mirror_ops.at(1);
OperatorArgs operator_args = mirror_op.at(0).second;
std::string arg0_name = operator_args.first.at(0).first;
ValuePtr arg0_value = operator_args.first.at(0).second;
std::string group = arg0_value->cast<StringImmPtr>()->ToString();
ASSERT_EQ(mirror_op.at(0).first, "_MirrorOperator");
ASSERT_EQ(mirror_op.size(), 1);
ASSERT_EQ(arg0_name, "group");
}
// matmul3
TEST_F(TestMatmulInfo, GetMirrorOPs3) {
std::vector<Dimensions> inputs = {{8, 16}, {2, 4, 1, 16}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul3->Init(strategy);
MirrorOps mirror_ops = matmul3->mirror_ops();
OperatorVector mirror_op = mirror_ops.at(1);
OperatorArgs operator_args = mirror_op.at(0).second;
std::string arg0_name = operator_args.first.at(0).first;
ValuePtr arg0_value = operator_args.first.at(0).second;
ASSERT_EQ(mirror_op.at(0).first, "_MirrorOperator");
ASSERT_EQ(mirror_op.size(), 1);
ASSERT_EQ(arg0_name, "group");
}
TEST_F(TestMatmulInfo, GetMirrorOPs4) {
std::vector<Dimensions> inputs = {{2, 4, 1, 16}, {2, 4, 16, 8}};
StrategyPtr strategy = NewStrategy(0, inputs);
matmul1->Init(strategy);
MirrorOps mirror_ops = matmul1->mirror_ops();
ASSERT_EQ(mirror_ops.size(), 0); // all reduce only in -3 dim (strategy is 1);
}
TEST_F(TestMatmulInfo, InitTwice) {
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
// init twice
matmul1->Init(strategy);
matmul1->Init(strategy);
MirrorOps mirror_ops = matmul1->mirror_ops();
OperatorVector mirror_op = mirror_ops.at(1);
OperatorArgs operator_args = mirror_op.at(0).second;
std::string arg0_name = operator_args.first.at(0).first;
ValuePtr arg0_value = operator_args.first.at(0).second;
ASSERT_EQ(mirror_op.at(0).first, "_MirrorOperator");
ASSERT_EQ(mirror_op.size(), 1);
ASSERT_EQ(arg0_name, "group");
}
TEST_F(TestMatmulInfo, CheckStrategy1) {
// Success: {{2,4,8,16}, {2,4,16,1}}
std::vector<Dimensions> inputs = {{2, 2, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
Status ret = matmul1->Init(strategy);
ASSERT_EQ(ret, FAILED);
}
TEST_F(TestMatmulInfo, CheckStrategy2) {
// Success: {{2,4,8,16}, {2,4,16,1}}
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
Status ret = matmul1->Init(strategy);
ASSERT_EQ(ret, FAILED);
}
TEST_F(TestMatmulInfo, CheckStrategy3) {
// Success: {{2,4,8,16}, {2,4,16,1}}
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {2, 4, 8, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
Status ret = matmul1->Init(strategy);
ASSERT_EQ(ret, FAILED);
}
TEST_F(TestMatmulInfo, CheckStrategy4) {
// Success: {{2,4,8,16}, {2,4,16,1}}
std::vector<Dimensions> inputs = {{2, 4, 8, 16}, {2, 3, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
Status ret = matmul1->Init(strategy);
ASSERT_EQ(ret, FAILED);
}
TEST_F(TestMatmulInfo, CheckStrategy5) {
// Success: {{2,4,8,16}, {2,4,16,1}}
std::vector<Dimensions> inputs = {{0, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
Status ret = matmul1->Init(strategy);
ASSERT_EQ(ret, FAILED);
}
TEST_F(TestMatmulInfo, CheckStrategy6) {
// Success: {{2,4,8,16}, {2,4,16,1}}
std::vector<Dimensions> inputs = {{-1, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
Status ret = matmul1->Init(strategy);
ASSERT_EQ(ret, FAILED);
}
TEST_F(TestMatmulInfo, CheckStrategy7) {
// Success: {{2,4,8,16}, {2,4,16,1}}
std::vector<Dimensions> inputs = {{4, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
Status ret = matmul1->Init(strategy);
ASSERT_EQ(ret, FAILED);
}
TEST_F(TestMatmulInfo, InitFailed) {
// matmul4 attr is wrong
std::vector<Dimensions> inputs = {{4, 4, 8, 16}, {2, 4, 16, 1}};
StrategyPtr strategy = NewStrategy(0, inputs);
Status ret = matmul4->Init(strategy);
ASSERT_EQ(ret, FAILED);
}
TEST_F(TestMatmulInfo, test_GenerateStrategies1) {
// the parameter '0' indicates that the stageId = 0, there are 1024 devices in the stage 0
ASSERT_EQ(matmul1->GenerateStrategies(0), Status::SUCCESS);
std::vector<std::shared_ptr<StrategyWithCost>> sc = matmul1->GetStrategyCost();
for (const auto& swc : sc) {
StrategyPtr sp = swc->strategy_ptr;
Cost cost = *(swc->cost_list[0]);
matmul1->InitForCostModel(sp);
std::vector<TensorInfo> inputs_info = matmul1->inputs_tensor_info();
std::vector<TensorInfo> outputs_info = matmul1->outputs_tensor_info();
ASSERT_DOUBLE_EQ(matmul1->operator_cost()->GetComputationCost(inputs_info, outputs_info, sp->GetInputStage()),
cost.computation_cost_);
break;
}
}
TEST_F(TestMatmulInfo, test_GenerateStrategies2) {
// the parameter '0' indicates that the stageId = 0, there are 1024 devices in the stage 0
ASSERT_EQ(matmul3->GenerateStrategies(0), Status::SUCCESS);
std::vector<std::shared_ptr<StrategyWithCost>> sc = matmul3->GetStrategyCost();
for (const auto& swc : sc) {
StrategyPtr sp = swc->strategy_ptr;
Cost cost = *(swc->cost_list[0]);
matmul3->InitForCostModel(sp);
std::vector<TensorInfo> inputs_info = matmul3->inputs_tensor_info();
std::vector<TensorInfo> outputs_info = matmul3->outputs_tensor_info();
std::vector<TensorInfo> replica_inputs_info;
replica_inputs_info.push_back(inputs_info[0]);
// transpose the tensor B
TensorInfo input1_info = inputs_info[1];
Shape input1_shape = input1_info.shape();
Shape input1_slice_shape = input1_info.slice_shape();
TensorLayout tly;
matmul3->SwapLastTwoElements(&input1_shape);
matmul3->SwapLastTwoElements(&input1_slice_shape);
TensorInfo replica_input1_info(tly, input1_shape, input1_slice_shape);
replica_inputs_info.push_back(replica_input1_info);
ASSERT_DOUBLE_EQ(matmul3->operator_cost()->GetComputationCost(replica_inputs_info, outputs_info, sp->GetInputStage()),
cost.computation_cost_);
break;
}
}
} // namespace parallel
} // namespace mindspore
|
/*******************************************************************************
* Copyright 2016-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "c_types_map.hpp"
#include "type_helpers.hpp"
#include "mkldnn_thread.hpp"
#include "gemm_inner_product.hpp"
#include "mkldnn_os.h"
namespace mkldnn {
namespace impl {
namespace cpu {
using namespace mkldnn::impl::status;
using namespace mkldnn::impl::prop_kind;
using namespace mkldnn::impl::data_type;
using namespace mkldnn::impl::memory_format;
using namespace mkldnn::impl::primitive_kind;
template <impl::data_type_t data_type>
void gemm_inner_product_fwd_t<data_type>::execute_forward() {
auto src = reinterpret_cast<const data_t *>(this->input_memory(0));
auto weights = reinterpret_cast<const data_t *>(this->input_memory(1));
auto bias = reinterpret_cast<const data_t *>(this->input_memory(2));
auto dst = reinterpret_cast<data_t*>(this->memory());
const int MB = conf_.MB();
const int OC = conf_.OC();
const int IC = conf_.IC_total_padded();
bool wei_tr = !utils::one_of(conf_.weights_pd()->desc()->format,
hwio, dhwio, io);
const auto &post_ops = conf_.attr()->post_ops_;
const bool do_relu = post_ops.len_ == 1;
float alpha = 1.0, beta = 0.0;
extended_sgemm(wei_tr ? "T" : "N", "N", &OC, &MB, &IC, &alpha, weights,
wei_tr ? &IC : &OC, src, &IC, &beta, dst, &OC, bias);
if (do_relu) {
float nslope = post_ops.entry_[0].eltwise.alpha;
parallel_nd(MB, OC, [&](int mb, int oc) {
size_t dst_off = mb * OC + oc;
if (dst[dst_off] < 0)
dst[dst_off] *= nslope;
});
}
}
template <impl::data_type_t data_type>
void gemm_inner_product_bwd_data_t<data_type>::execute_backward_data() {
auto diff_dst = reinterpret_cast<const data_t *>(this->input_memory(0));
auto weights = reinterpret_cast<const data_t *>(this->input_memory(1));
auto diff_src = reinterpret_cast<data_t*>(this->memory());
const int MB = conf_.MB();
const int OC = conf_.OC();
const int IC = conf_.IC_total_padded();
bool wei_tr = utils::one_of(conf_.weights_pd()->desc()->format,
hwio, dhwio, io);
float alpha = 1.0, beta = 0.0;
extended_sgemm(wei_tr ? "T" : "N", "N", &IC, &MB, &OC, &alpha, weights,
wei_tr ? &OC : &IC, diff_dst, &OC, &beta, diff_src, &IC);
}
template <impl::data_type_t data_type>
void gemm_inner_product_bwd_weights_t<data_type>::execute_backward_weights() {
auto src = reinterpret_cast<const data_t *>(this->input_memory(0));
auto diff_dst = reinterpret_cast<const data_t *>(this->input_memory(1));
auto diff_weights = reinterpret_cast<data_t *>(this->memory(0));
auto diff_bias = reinterpret_cast<data_t *>(this->memory(1));
const memory_desc_wrapper diff_dst_d(conf_.diff_dst_pd());
const memory_desc_wrapper diff_bias_d(conf_.diff_weights_pd(1));
diff_dst += diff_dst_d.blocking_desc().offset_padding;
const int MB = conf_.MB();
const int OC = conf_.OC();
const int IC = conf_.IC_total_padded();
bool wei_tr = utils::one_of(conf_.diff_weights_pd()->desc()->format,
hwio, dhwio, io);
float alpha = 1.0, beta = 0.0;
if (wei_tr)
extended_sgemm("N", "T", &OC, &IC, &MB, &alpha, diff_dst, &OC, src, &IC,
&beta, diff_weights, &OC);
else
extended_sgemm("N", "T", &IC, &OC, &MB, &alpha, src, &IC, diff_dst, &OC,
&beta, diff_weights, &IC);
if (diff_bias) {
diff_bias += diff_bias_d.blocking_desc().offset_padding;
constexpr int blksize = 8;
int OC_blocks = OC / blksize;
int rem_OC = OC % blksize;
OMP(parallel)//;
{
const int ithr = omp_get_thread_num();
const int nthr = omp_get_num_threads();
int oc_st{0}, oc_e{0};
balance211(OC_blocks, nthr, ithr, oc_st, oc_e);
oc_st = oc_st * blksize;
oc_e = oc_e * blksize;
PRAGMA_OMP_SIMD()
for (int oc = oc_st; oc < oc_e; ++oc) {
diff_bias[oc] = diff_dst[oc];
}
for (int mb = 1; mb < MB; ++mb) {
PRAGMA_OMP_SIMD()
for (int oc = oc_st; oc < oc_e; ++oc) {
diff_bias[oc] += diff_dst[mb * OC + oc];
}
}
if (rem_OC != 0 && ithr == nthr-1) {
for (int oc = OC_blocks * blksize; oc < OC; oc++)
diff_bias[oc] = diff_dst[oc];
for (int mb = 1; mb < MB; ++mb) {
for (int oc = OC_blocks * blksize; oc < OC; oc++) {
diff_bias[oc] += diff_dst[mb * OC + oc];
}
}
}
}
}
}
template struct gemm_inner_product_fwd_t<data_type::f32>;
template struct gemm_inner_product_bwd_data_t<data_type::f32>;
template struct gemm_inner_product_bwd_weights_t<data_type::f32>;
}
}
}
// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
|
// Copyright (c) 2020 The DigiByte Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <chainparamsbase.h>
#include <key.h>
#include <pubkey.h>
#include <script/sigcache.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
void initialize_script_sigcache()
{
static const ECCVerifyHandle ecc_verify_handle;
ECC_Start();
SelectParams(CBaseChainParams::REGTEST);
InitSignatureCache();
}
FUZZ_TARGET_INIT(script_sigcache, initialize_script_sigcache)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const std::optional<CMutableTransaction> mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider);
const CTransaction tx{mutable_transaction ? *mutable_transaction : CMutableTransaction{}};
const unsigned int n_in = fuzzed_data_provider.ConsumeIntegral<unsigned int>();
const CAmount amount = ConsumeMoney(fuzzed_data_provider);
const bool store = fuzzed_data_provider.ConsumeBool();
PrecomputedTransactionData tx_data;
CachingTransactionSignatureChecker caching_transaction_signature_checker{mutable_transaction ? &tx : nullptr, n_in, amount, store, tx_data};
if (fuzzed_data_provider.ConsumeBool()) {
const auto random_bytes = fuzzed_data_provider.ConsumeBytes<unsigned char>(64);
const XOnlyPubKey pub_key(ConsumeUInt256(fuzzed_data_provider));
if (random_bytes.size() == 64) {
(void)caching_transaction_signature_checker.VerifySchnorrSignature(random_bytes, pub_key, ConsumeUInt256(fuzzed_data_provider));
}
} else {
const auto random_bytes = ConsumeRandomLengthByteVector(fuzzed_data_provider);
const auto pub_key = ConsumeDeserializable<CPubKey>(fuzzed_data_provider);
if (pub_key) {
if (!random_bytes.empty()) {
(void)caching_transaction_signature_checker.VerifyECDSASignature(random_bytes, *pub_key, ConsumeUInt256(fuzzed_data_provider));
}
}
}
}
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2019 Evandro de Souza
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Evandro de Souza <evandro@ualberta.ca>
* Date: 2019.05.12
* Company: University of Alberta/Canada - Computing Science
*
*/
#include "ns3-helper.h"
#define MAX_NODES 2000
using namespace std;
using namespace ns3;
int parent[MAX_NODES][MAX_NODES];
vector<vector<bool>>
ReadNodeAdjMatrix(string adjMatFileName)
{
NS_LOG_INFO("ReadNodeAdjMatrix");
memset(parent, -1, sizeof(parent));
ifstream adjMatFile;
adjMatFile.open(adjMatFileName.c_str(), std::ios::in);
if (adjMatFile.fail())
{
NS_FATAL_ERROR("File " << adjMatFileName.c_str() << " not found");
}
vector<vector<bool>> array;
int i = 0;
int n_nodes = 0;
while (!adjMatFile.eof())
{
string line;
getline(adjMatFile, line);
if (line == "")
{
NS_LOG_WARN("WARNING: Ignoring blank row in the array: " << i);
break;
}
istringstream iss(line);
bool element;
vector<bool> row;
int j = 0;
while (iss >> element)
{
row.push_back(element);
j++;
}
if (i == 0)
{
n_nodes = j;
}
if (j != n_nodes)
{
NS_LOG_ERROR("ERROR: Number of elements in line " << i << ": " << j << " not equal to number of elements in line 0: " << n_nodes);
NS_FATAL_ERROR("ERROR: The number of rows is not equal to the number of columns! in the adjacency matrix");
}
else
{
array.push_back(row);
}
i++;
}
if (i != n_nodes)
{
NS_LOG_ERROR("There are " << i << " rows and " << n_nodes << " columns.");
NS_FATAL_ERROR("ERROR: The number of rows is not equal to the number of columns! in the adjacency matrix");
}
adjMatFile.close();
return array;
}
vector<vector<double>>
loadNodeCoords(vector<vector<string>> arrayNamesCoords)
{
vector<vector<double>> arrayNodeCoords;
for (auto it = arrayNamesCoords.begin(); it != arrayNamesCoords.end(); it++)
{
vector<double> row;
row.push_back(atof((*it)[1].c_str()));
row.push_back(atof((*it)[2].c_str()));
arrayNodeCoords.push_back(row);
}
return arrayNodeCoords;
}
void PrintNodeAdjMatrix(const char *description, vector<vector<bool>> array)
{
NS_LOG_INFO("PrintNodeAdjMatrix");
cout << "**** Print file " << description << "********" << endl;
for (size_t m = 0; m < array.size(); m++)
{
for (size_t n = 0; n < array[m].size(); n++)
{
cout << array[m][n] << ' ';
}
cout << endl;
}
cout << "**** End " << description << " ********" << endl;
}
vector<vector<string>>
ReadCoordinatesFile(string nodeCoordinatesFilename)
{
NS_LOG_INFO("ReadCoordinatesFile");
vector<vector<string>> array;
ifstream node_coordinates_file;
ifstream inputFile(nodeCoordinatesFilename);
int l = 0;
while (inputFile)
{
l++;
string s;
if (!getline(inputFile, s))
break;
if (s != "")
{
istringstream ss(s);
vector<string> record;
while (ss)
{
string line;
if (!getline(ss, line, ','))
break;
//--- strip '\r'
if (!line.empty() && *line.rbegin() == '\r')
{
line.erase(line.length() - 1, 1);
}
record.push_back(line);
}
array.push_back(record);
}
}
if (!inputFile.eof())
{
cerr << "Could not read file " << nodeCoordinatesFilename << "\n";
__throw_invalid_argument("File not found.");
}
return array;
}
void PrintNamesCoordinates(const char *description, vector<vector<string>> array)
{
NS_LOG_INFO("PrintNamesCoordinates");
cout << "**** Start " << description << " ********" << endl;
for (size_t m = 0; m < array.size(); m++)
{
for (size_t n = 0; n < array[m].size(); n++)
{
cout << array[m][n] << ' ';
}
cout << endl;
}
cout << "**** End " << description << " ********" << endl;
}
vector<vector<string>>
ReadAppConnectionsFile(string appConnectionsFilename)
{
NS_LOG_INFO("ReadAppConnectionsFile");
vector<vector<string>> array;
ifstream node_coordinates_file;
ifstream inputFile(appConnectionsFilename);
int l = 0;
while (inputFile)
{
l++;
string s;
if (!getline(inputFile, s))
break;
if (s != "")
{
istringstream ss(s);
vector<string> record;
while (ss)
{
string line;
if (!getline(ss, line, ','))
break;
//--- strip '\r'
if (!line.empty() && *line.rbegin() == '\r')
{
line.erase(line.length() - 1, 1);
}
record.push_back(line);
}
array.push_back(record);
}
}
if (!inputFile.eof())
{
cerr << "Could not read file " << appConnectionsFilename << "\n";
__throw_invalid_argument("File not found.");
}
return array;
}
void PrintIpAddresses(NodeContainer nodes, string network)
{
NS_LOG_INFO("PrintIpAddresses");
cout << "**** Start Print IP Addresses ********" << endl;
string nodeName;
Ipv4InterfaceAddress v4iaddr;
Ipv6InterfaceAddress v6iaddr;
bool v4 = false;
if (network == "P2P" || network == "CSMA") v4 = true;
for (NodeList::Iterator i = NodeList::Begin(); i != NodeList::End(); ++i)
{
int ifaces;
if (v4) ifaces = (*i)->GetObject<Ipv4>()->GetNInterfaces();
else ifaces = (*i)->GetObject<Ipv6>()->GetNInterfaces();
for (int j = 1; j < ifaces; j++)
{
if (v4) v4iaddr = (*i)->GetObject<Ipv4>()->GetAddress(j, 0);
else v6iaddr = (*i)->GetObject<Ipv6>()->GetAddress(j, 1);
nodeName = Names::FindName((*i));
if (v4) cout << "Node ID: " << (*i)->GetId() << " - "
<< "Ifaces: " << (*i)->GetObject<Ipv4>()->GetNInterfaces() << " - "
<< "Name: " << nodeName << " - "
<< "IP Addr: " << v4iaddr.GetLocal() << " - "
<< "IP Mask: " << v4iaddr.GetMask() << endl;
else cout << "Node ID: " << (*i)->GetId() << " - "
<< "Ifaces: " << (*i)->GetObject<Ipv6>()->GetNInterfaces() << " - "
<< "Name: " << nodeName << " - "
<< "IP Addr: " << v6iaddr.GetAddress() << " - "
<< "IP Mask: " << v6iaddr.GetPrefix() << endl;
}
}
cout << "**** End Print IP Addresses ********" << endl;
}
map<Ipv4Address, uint32_t>
CreateMapIpv4NodeId(NodeContainer nodes)
{
NS_LOG_INFO("CreateMapIpv4NodeId");
map<Ipv4Address, uint32_t> mapIpv4NodeId;
string nodeName;
uint32_t nodeId;
Ipv4InterfaceAddress iaddr;
for (NodeList::Iterator i = NodeList::Begin(); i != NodeList::End(); ++i)
{
int ifaces = (*i)->GetObject<Ipv4>()->GetNInterfaces();
for (int j = 1; j < ifaces; j++)
{
iaddr = (*i)->GetObject<Ipv4>()->GetAddress(j, 0);
nodeId = (*i)->GetId();
nodeName = Names::FindName((*i));
mapIpv4NodeId[iaddr.GetLocal()] = nodeId;
}
}
return mapIpv4NodeId;
}
map<Ipv6Address, uint32_t>
CreateMapIpv6NodeId(NodeContainer nodes)
{
NS_LOG_INFO("CreateMapIpv6NodeId");
map<Ipv6Address, uint32_t> mapIpv6NodeId;
string nodeName;
uint32_t nodeId;
Ipv6InterfaceAddress iaddr;
for (NodeList::Iterator i = NodeList::Begin(); i != NodeList::End(); ++i)
{
int ifaces = (*i)->GetObject<Ipv6>()->GetNInterfaces();
for (int j = 1; j < ifaces; j++)
{
iaddr = (*i)->GetObject<Ipv6>()->GetAddress(j, 1);
nodeId = (*i)->GetId();
nodeName = Names::FindName((*i));
mapIpv6NodeId[iaddr.GetAddress()] = nodeId;
}
}
return mapIpv6NodeId;
}
string FindNextHop(string clt, string srv, vector<vector<bool>> array)
{
Ptr <Node> srcNode = Names::Find<Node>(clt);
Ptr <Node> desNode = Names::Find<Node>(srv);
size_t src = srcNode->GetId();
size_t des = desNode->GetId();
if(parent[des][src] != -1)
{
Ptr <Node> nextHopeNode = NodeList::GetNode(parent[des][src]);
return Names::FindName(nextHopeNode);
}
size_t nextHop;
queue <size_t> bfsQ;
// Searching in the opposite direction so that parents are
// actually next hops when des is the destination
bfsQ.push(des);
parent[des][des] = des;
while(!bfsQ.empty())
{
nextHop = bfsQ.front();
bfsQ.pop();
for (size_t m = 0; m < array[nextHop].size(); m++)
{
if(!array[nextHop][m]) continue;
if(parent[des][m] != -1) continue;
bfsQ.push(m);
parent[des][m] = nextHop;
}
}
if(parent[des][src] == -1) cerr << "The source and destination are not connected!";
Ptr <Node> nextHopeNode = NodeList::GetNode(parent[des][src]);
return Names::FindName(nextHopeNode);
}
void PrintRoutingTable (Ptr<Node>& n, bool v4)
{
if (v4)
{
Ptr<Ipv4StaticRouting> routing = 0;
Ipv4StaticRoutingHelper routingHelper;
Ptr<Ipv4> ipv4 = n->GetObject<Ipv4> ();
uint32_t nbRoutes = 0;
Ipv4RoutingTableEntry route;
routing = routingHelper.GetStaticRouting (ipv4);
std::cout << "Routing table of " << Names::FindName(n) << " : " << std::endl;
std::cout << "Destination\t\t\t\t" << "Gateway\t\t\t\t\t" << "Interface\t" << "Destination Network" << std::endl;
nbRoutes = routing->GetNRoutes ();
for (uint32_t i = 0; i < nbRoutes; i++)
{
route = routing->GetRoute (i);
std::cout << route.GetDest () << "\t"
<< route.GetGateway () << "\t"
<< route.GetInterface () << "\t"
<< route.GetDestNetwork () << "\t"
<< route.GetDestNetworkMask () << "\t"
<< std::endl;
}
}
else
{
Ptr<Ipv6StaticRouting> routing = 0;
Ipv6StaticRoutingHelper routingHelper;
Ptr<Ipv6> ipv6 = n->GetObject<Ipv6> ();
uint32_t nbRoutes = 0;
Ipv6RoutingTableEntry route;
routing = routingHelper.GetStaticRouting (ipv6);
std::cout << "Routing table of " << Names::FindName(n) << " : " << std::endl;
std::cout << "Destination\t\t\t\t" << "Gateway\t\t\t\t\t" << "Interface\t" << "Prefix to use" << std::endl;
nbRoutes = routing->GetNRoutes ();
for (uint32_t i = 0; i < nbRoutes; i++)
{
route = routing->GetRoute (i);
std::cout << route.GetDest () << "\t"
<< route.GetGateway () << "\t"
<< route.GetInterface () << "\t"
<< route.GetPrefixToUse () << "\t"
<< std::endl;
}
}
}
bool isSecondary(string nodeName)
{
int s_size = nodeName.size();
/// Secondary node name has to be a number
for(int i=0; i<s_size; i++)
if(!isdigit(nodeName[i])) return false;
/// There can be at most 999 primary nodes (for now)
if(s_size < 4) return false;
return true;
}
|
/*
//@HEADER
// ************************************************************************
//
// KokkosKernels 0.9: Linear Algebra and Graph Kernels
// Copyright 2017 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#define KOKKOSKERNELS_IMPL_COMPILE_LIBRARY true
#include "KokkosKernels_config.h"
#if defined (KOKKOSKERNELS_INST_DOUBLE) \
&& defined (KOKKOSKERNELS_INST_LAYOUTLEFT) \
&& defined (KOKKOSKERNELS_INST_EXECSPACE_SERIAL) \
&& defined (KOKKOSKERNELS_INST_MEMSPACE_HOSTSPACE) \
&& defined (KOKKOSKERNELS_INST_ORDINAL_INT) \
&& defined (KOKKOSKERNELS_INST_OFFSET_SIZE_T)
#include "KokkosSparse_spmv_struct_spec.hpp"
namespace KokkosSparse {
namespace Impl {
KOKKOSSPARSE_SPMV_STRUCT_ETI_SPEC_INST(double, int, size_t, Kokkos::LayoutLeft, Kokkos::Serial, Kokkos::HostSpace)
} // Impl
} // KokkosSparse
#endif
|
extern "C"
{
__declspec(dllexport) float __stdcall InvertSqrt(float x) {
float xhalf = 0.5f * x;
int i = *(int*)&x;
i = 0x5f3759df - (i >> 1);
x = *(float*)&i;
x = x * (1.5f - xhalf * x * x);
return x;
}
}
extern "C"
{
__declspec(dllexport) int __stdcall power2(int num, int power)
{
__asm
{
mov eax, num ; Get first argument
mov ecx, power ; Get second argument
shl eax, cl ; EAX = EAX * (2 to the power of CL)
}
//return with result in EAX;
}
}
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "backend/plain/peer.hpp"
using namespace shared_model;
using namespace shared_model::plain;
Peer::Peer(const interface::types::AddressType &address,
const interface::types::PubkeyType &public_key,
const boost::optional<interface::types::TLSCertificateType>
&tls_certificate)
: address_(address),
public_key_(public_key),
tls_certificate_(tls_certificate) {}
const shared_model::interface::types::AddressType &Peer::address() const {
return address_;
}
const shared_model::interface::types::PubkeyType &Peer::pubkey() const {
return public_key_;
}
const boost::optional<shared_model::interface::types::TLSCertificateType>
&Peer::tlsCertificate() const {
return tls_certificate_;
}
|
#pragma once
#include <array>
#include <cstdint>
#include <string_view>
#include <RED4ext/CName.hpp>
#include <RED4ext/CString.hpp>
#include <RED4ext/Common.hpp>
#include <RED4ext/HashMap.hpp>
#include <RED4ext/InstanceType.hpp>
#include <RED4ext/Unks.hpp>
namespace RED4ext
{
struct CBaseRTTIType;
struct CDateTime
{
int64_t unk00; // 00
};
RED4EXT_ASSERT_SIZE(CDateTime, 0x8);
struct CGUID
{
int64_t unk00; // 00
int64_t unk08; // 08
};
RED4EXT_ASSERT_SIZE(CGUID, 0x10);
struct CRUID
{
int64_t unk00; // 00
};
RED4EXT_ASSERT_SIZE(CRUID, 0x8);
struct CRUIDRef
{
int64_t unk00; // 00
};
RED4EXT_ASSERT_SIZE(CRUIDRef, 0x8);
struct TweakDBID
{
#pragma pack(push, 1)
union
{
uint64_t value = 0;
struct
{
uint32_t nameHash; // 00 CRC32
uint8_t nameLength; // 04
uint8_t tdbOffsetBE[3]; // 05 - Big Endian
};
};
#pragma pack(pop)
TweakDBID() noexcept = default;
TweakDBID(uint64_t aValue) noexcept;
TweakDBID(uint32_t aNameHash, uint8_t aNameLength) noexcept;
TweakDBID(const std::string_view aName) noexcept;
TweakDBID(const TweakDBID& aBase, const std::string_view aName) noexcept;
bool IsValid() const;
bool HasTDBOffset() const;
int32_t ToTDBOffset() const;
void SetTDBOffset(int32_t aTDBOffset);
operator uint64_t() const noexcept;
TweakDBID& operator=(const std::string_view aName) noexcept;
TweakDBID operator+(const std::string_view aName) const noexcept;
bool operator<(const TweakDBID& aDBID) const noexcept;
bool operator>(const TweakDBID& aDBID) const noexcept;
bool operator==(const TweakDBID& aDBID) const noexcept;
bool operator!=(const TweakDBID& aDBID) const noexcept;
};
RED4EXT_ASSERT_SIZE(TweakDBID, 0x8);
struct ItemID
{
TweakDBID tdbid; // 00
uint32_t rngSeed; // 08
uint16_t unk0C; // 0C
uint8_t unk0E; // 0E
uint8_t pad0F; // 0F
};
RED4EXT_ASSERT_SIZE(ItemID, 0x10);
struct EditorObjectID
{
int64_t unk00; // 00
int64_t unk08; // 08
int64_t unk10; // 10
int64_t unk18; // 18
};
RED4EXT_ASSERT_SIZE(EditorObjectID, 0x20);
struct Variant
{
static constexpr uint32_t InlineSize = 16;
static constexpr uint32_t InlineAlignment = 8;
static constexpr uintptr_t InlineFlag = 1;
static constexpr uintptr_t TypeMask = ~InlineFlag;
Variant() noexcept = default;
Variant(const CBaseRTTIType* aType);
Variant(const CBaseRTTIType* aType, const ScriptInstance aData);
Variant(const CName& aTypeName, const ScriptInstance aData);
Variant(const Variant& aOther);
~Variant();
bool IsEmpty() const noexcept;
bool IsInlined() const noexcept;
CBaseRTTIType* GetType() const noexcept;
ScriptInstance GetDataPtr() const noexcept;
bool Init(const CBaseRTTIType* aType);
bool Fill(const CBaseRTTIType* aType, const ScriptInstance aData);
bool Extract(ScriptInstance aBuffer);
void Free();
static bool CanBeInlined(const CBaseRTTIType* aType) noexcept;
const CBaseRTTIType* type{ nullptr };
union
{
uint8_t inlined[InlineSize]{ 0 };
ScriptInstance instance;
};
};
RED4EXT_ASSERT_SIZE(Variant, 0x18);
struct RawBuffer
{
void* data; // 00
uint32_t size; // 08
uint32_t alignment; // 0C
Unk530 unk10; // 10
};
RED4EXT_ASSERT_SIZE(RawBuffer, 0x20);
struct DataBuffer
{
RawBuffer buffer; // 00
uint64_t unk20; // 20 - Pointer to something
};
RED4EXT_ASSERT_SIZE(DataBuffer, 0x28);
struct SharedDataBuffer
{
int64_t unk00; // 00
};
RED4EXT_ASSERT_SIZE(SharedDataBuffer, 0x8);
struct DeferredDataBuffer
{
int64_t unk00; // 00
int64_t unk08; // 08
RawBuffer buffer; // 10
int64_t unk30; // 30
int8_t unk38; // 38
int64_t unk40; // 40
int64_t unk48; // 48
int64_t unk50; // 50
};
RED4EXT_ASSERT_SIZE(DeferredDataBuffer, 0x58);
struct gamedataLocKeyWrapper
{
int64_t unk00; // 00
};
RED4EXT_ASSERT_SIZE(gamedataLocKeyWrapper, 0x8);
struct LocalizationString
{
int64_t unk00; // 00
CString unk08; // 08
};
RED4EXT_ASSERT_SIZE(LocalizationString, 0x28);
struct MessageResourcePath
{
int64_t unk00; // 00
};
RED4EXT_ASSERT_SIZE(MessageResourcePath, 0x8);
struct NodeRef
{
int64_t unk00; // 00
};
RED4EXT_ASSERT_SIZE(NodeRef, 0x8);
struct RuntimeEntityRef
{
int64_t unk00; // 00
};
RED4EXT_ASSERT_SIZE(RuntimeEntityRef, 0x8);
template<typename T>
struct ResourceAsyncReference
{
T* ref; // 00
};
RED4EXT_ASSERT_SIZE(ResourceAsyncReference<void>, 0x8);
template<typename T>
using RaRef = ResourceAsyncReference<T>;
template<typename T>
struct ResourceReference
{
T* ref; // 00
uintptr_t unk08; // 08
uintptr_t unk10; // 10
};
RED4EXT_ASSERT_SIZE(ResourceReference<void>, 0x18);
template<typename T>
using Ref = ResourceReference<T>;
template<typename T, uint32_t MAX_LEN>
struct StaticArray
{
T entries[MAX_LEN]; // 00
uint32_t size;
};
static_assert(sizeof(StaticArray<std::array<uint8_t, 5>, 32>) ==
164); // StaticArray<GpuWrapApiVertexPackingPackingElement, 32>
template<typename T, uint32_t MAX_LEN>
using NativeArray = std::array<T, MAX_LEN>;
template<typename T>
struct CurveData
{
uint64_t unk00; // 00
uint64_t unk08; // 08
uint64_t unk10; // 10
uint64_t unk18; // 18
uint64_t unk20; // 20
uint64_t unk28; // 28
uint64_t unk30; // 30
};
RED4EXT_ASSERT_SIZE(CurveData<float>, 0x38);
template<typename T>
struct ScriptRef
{
uint8_t unk00[0x10]; // 00
CBaseRTTIType* innerType; // 10
T* ref; // 18
CName hash; // 20
};
RED4EXT_ASSERT_SIZE(ScriptRef<void>, 0x28);
template<typename T>
struct HashMapHash<T, std::enable_if_t<std::is_same_v<T, TweakDBID>>>
{
uint32_t operator()(const T& aKey) const noexcept
{
return static_cast<uint32_t>(aKey);
}
};
} // namespace RED4ext
#ifdef RED4EXT_HEADER_ONLY
#include <RED4ext/NativeTypes-inl.hpp>
#endif
|
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/detail/overload.hpp>
#include <eve/function/all.hpp>
#include <eve/function/is_nltz.hpp>
#include <type_traits>
namespace eve
{
//================================================================================================
//! @addtogroup trigonometric
//! @{
//! @var rempio2
//!
//! @brief Callable object computing the rempio2 value.
//!
//! **Required header:** `#include <eve/function/rempio2.hpp>`
//!
//! #### Members Functions
//!
//! | Member | Effect |
//! |:-------------|:-----------------------------------------------------------|
//! | `operator()` | the computation of the rempio2 value |
//!
//! ---
//!
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
//! template< floating_value T> auto operator()( T x ) const noexcept;
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//!
//! **Parameters**
//!
//!`x`: [floating real value](@ref eve::floating_real_value).
//!
//! **Return value**
//!
//! A tuple consisting of an [flint](@ref eve::is_flint) value designing the quadrant and two
//! floating values of type `T` giving the remainder of `x` modulo \f$\pi/2\f$ and a corrective
//! to the rounding error on the first result.
//!
//! ---
//!
//! #### Supported decorators
//!
//! no decorators are supported
//!
//! #### Example
//!
//! @godbolt{doc/core/rempio2.cpp}
//!
//! @}
//================================================================================================
namespace tag { struct rempio2_; }
namespace detail
{
template<typename T, typename U>
EVE_FORCEINLINE void check(EVE_MATCH_CALL(eve::tag::rempio2_), [[maybe_unused]] T const& x)
{
EVE_ASSERT(eve::all(is_nltz(x)), "[eve::rempio2] : parameter must be positive or nan, found:" << x);
}
}
namespace tag { struct rempio2_; }
template<> struct supports_conditional<tag::rempio2_> : std::false_type {};
EVE_MAKE_CALLABLE(rempio2_, rempio2);
}
#include <eve/module/real/math/function/regular/generic/rempio2.hpp>
|
//=================================================================================================
/*!
// \file src/mathtest/operations/dvecdveckron/V3aVUa.cpp
// \brief Source file for the V3aVUa dense vector/dense vector Kronecker product math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticVector.h>
#include <blaze/math/UniformVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/dvecdveckron/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'V3aVUa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Vector type definitions
using V3a = blaze::StaticVector<TypeA,3UL>;
using VUa = blaze::UniformVector<TypeA>;
// Creator type definitions
using CV3a = blazetest::Creator<V3a>;
using CVUa = blazetest::Creator<VUa>;
// Running tests with small vectors
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_DVECDVECKRON_OPERATION_TEST( CV3a(), CVUa( i ) );
}
// Running tests with large vectors
RUN_DVECDVECKRON_OPERATION_TEST( CV3a(), CVUa( 17UL ) );
RUN_DVECDVECKRON_OPERATION_TEST( CV3a(), CVUa( 32UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector Kronecker product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>> &points, int K) {
vector<vector<int>> ret;
sort(points.begin(), points.end(), [](vector<int> &v1, vector<int> v2) {
return (pow(v1[0], 2) + pow(v1[1], 2)) < (pow(v2[0], 2) + pow(v2[1], 2));
});
for (int i = 0; i < K; ++i)
ret.push_back(points[i]);
return ret;
}
};
|
#pragma once
#ifndef JM_UNITS_CORE_SCALES_HPP
#define JM_UNITS_CORE_SCALES_HPP
#include <cstdint> // INTMAX_MAX
#include <ratio>
#if INTMAX_MAX / 1000000000000000000 >= 1000
#define JM_UNITS_ZT_AVAILABLE
#endif
#if INTMAX_MAX / 1000000000000000000 >= 1000000
#define JM_UNITS_YT_AVAILABLE
#endif
namespace JadeMatrix { namespace units
{
using unit_scale = std::ratio< 1, 1 >;
using dozen_scale = std::ratio< 12, 1 >;
using bi_scale = std::ratio< 2, 1 >;
using semi_scale = std::ratio< 1, 2 >;
using exa_scale = std:: exa;
using peta_scale = std:: peta;
using tera_scale = std:: tera;
using giga_scale = std:: giga;
using mega_scale = std:: mega;
using kilo_scale = std:: kilo;
using hecto_scale = std::hecto;
using deca_scale = std:: deca;
using deci_scale = std:: deci;
using centi_scale = std::centi;
using milli_scale = std::milli;
using micro_scale = std::micro;
using nano_scale = std:: nano;
using pico_scale = std:: pico;
using femto_scale = std::femto;
using atto_scale = std:: atto;
using exbi_scale = std::ratio< ( 2L << ( 60 - 1 ) ), 1 >;
using pebi_scale = std::ratio< ( 2L << ( 50 - 1 ) ), 1 >;
using tebi_scale = std::ratio< ( 2L << ( 40 - 1 ) ), 1 >;
using gibi_scale = std::ratio< ( 2L << ( 30 - 1 ) ), 1 >;
using mebi_scale = std::ratio< ( 2L << ( 20 - 1 ) ), 1 >;
using kibi_scale = std::ratio< ( 2L << ( 10 - 1 ) ), 1 >;
#if defined JM_UNITS_ZT_AVAILABLE
using zepto_scale = std::zepto;
using zetta_scale = std::zetta;
using zebi_scale = std::ratio< ( 2L << ( 70 - 1 ) ), 1 >;
#endif
#if defined JM_UNITS_YT_AVAILABLE
using yocto_scale = std::yocto;
using yotta_scale = std::yotta;
using yobi_scale = std::ratio< ( 2L << ( 80 - 1 ) ), 1 >;
#endif
} }
#endif
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_int_realloc_07.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml
Template File: sources-sinks-07.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: realloc Allocate data using realloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 07 Control flow: if(static_five==5) and if(static_five!=5)
*
* */
#include "std_testcase.h"
/* The variable below is not declared "const", but is never assigned
any other value so a tool should be able to identify that reads of
this will always give its initialized value. */
static int static_five = 5;
namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_int_realloc_07
{
#ifndef OMITBAD
void bad()
{
int * data;
/* Initialize data*/
data = NULL;
if(static_five==5)
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int *)realloc(data, 100*sizeof(int));
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Allocate memory using new [] */
data = new int[100];
}
if(static_five==5)
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Free memory using free() */
free(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second static_five==5 to static_five!=5 */
static void goodB2G1()
{
int * data;
/* Initialize data*/
data = NULL;
if(static_five==5)
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int *)realloc(data, 100*sizeof(int));
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Allocate memory using new [] */
data = new int[100];
}
if(static_five!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
else
{
/* FIX: Free memory using free() */
free(data);
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
int * data;
/* Initialize data*/
data = NULL;
if(static_five==5)
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int *)realloc(data, 100*sizeof(int));
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Allocate memory using new [] */
data = new int[100];
}
if(static_five==5)
{
/* FIX: Free memory using free() */
free(data);
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
}
/* goodG2B1() - use goodsource and badsink by changing the first static_five==5 to static_five!=5 */
static void goodG2B1()
{
int * data;
/* Initialize data*/
data = NULL;
if(static_five!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int *)realloc(data, 100*sizeof(int));
}
else
{
/* FIX: Allocate memory using new [] */
data = new int[100];
}
if(static_five==5)
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Free memory using free() */
free(data);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
int * data;
/* Initialize data*/
data = NULL;
if(static_five==5)
{
/* FIX: Allocate memory using new [] */
data = new int[100];
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (int *)realloc(data, 100*sizeof(int));
}
if(static_five==5)
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
else
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Free memory using free() */
free(data);
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} // close namespace
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_int_realloc_07; // so that we can use good and bad easily
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdlib> // to force __GLIBCXX__ define reference
#if defined(__GNUC__) && defined(__GLIBCXX__)
#include <cxxabi.h>
#elif qPlatform_Windows
#include <Windows.h>
#include <Dbghelp.h>
#endif
#include "../Execution/Finally.h"
#include "Demangle.h"
using namespace Stroika::Foundation;
#if qPlatform_Windows
// otherwise modules linking with this code will tend to get link errors without explicitly linking
// to this module...
#pragma comment(lib, "Dbghelp.lib")
#endif
/*
********************************************************************************
************************ Debug::DropIntoDebuggerIfPresent **********************
********************************************************************************
*/
Characters::String Debug::Demangle (const Characters::String& originalName)
{
#if defined(__GNUC__) && defined(__GLIBCXX__)
int status{};
char* realname = abi::__cxa_demangle (originalName.AsNarrowSDKString ().c_str (), 0, 0, &status);
[[maybe_unused]] auto&& cleanup = Execution::Finally ([&realname] () { if (realname != nullptr) { ::free (realname); } });
if (status == 0) {
return Characters::String::FromNarrowSDKString (realname);
}
#elif qPlatform_Windows
char resultBuf[10 * 1024];
if (::UnDecorateSymbolName (originalName.AsNarrowSDKString ().c_str (), resultBuf, sizeof (resultBuf), UNDNAME_COMPLETE) != 0) {
return Characters::String::FromNarrowSDKString (resultBuf);
}
#endif
return originalName;
}
|
/*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "JSHTMLLIElement.h"
#include "HTMLLIElement.h"
#include "HTMLNames.h"
#include "KURL.h"
#include <runtime/JSNumberCell.h>
#include <runtime/JSString.h>
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSHTMLLIElement);
/* Hash table */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSHTMLLIElementTableValues[4] =
{
{ "type", DontDelete, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsHTMLLIElementType), (intptr_t)setJSHTMLLIElementType THUNK_GENERATOR(0) },
{ "value", DontDelete, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsHTMLLIElementValue), (intptr_t)setJSHTMLLIElementValue THUNK_GENERATOR(0) },
{ "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsHTMLLIElementConstructor), (intptr_t)0 THUNK_GENERATOR(0) },
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSHTMLLIElementTable = { 9, 7, JSHTMLLIElementTableValues, 0 };
/* Hash table for constructor */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSHTMLLIElementConstructorTableValues[1] =
{
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSHTMLLIElementConstructorTable = { 1, 0, JSHTMLLIElementConstructorTableValues, 0 };
class JSHTMLLIElementConstructor : public DOMConstructorObject {
public:
JSHTMLLIElementConstructor(JSC::ExecState*, JSDOMGlobalObject*);
virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);
virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);
static const JSC::ClassInfo s_info;
static PassRefPtr<JSC::Structure> createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)
{
return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);
}
protected:
static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;
};
const ClassInfo JSHTMLLIElementConstructor::s_info = { "HTMLLIElementConstructor", &DOMConstructorObject::s_info, &JSHTMLLIElementConstructorTable, 0 };
JSHTMLLIElementConstructor::JSHTMLLIElementConstructor(ExecState* exec, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(JSHTMLLIElementConstructor::createStructure(globalObject->globalData(), globalObject->objectPrototype()), globalObject)
{
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSHTMLLIElementPrototype::self(exec, globalObject), DontDelete | ReadOnly);
}
bool JSHTMLLIElementConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSHTMLLIElementConstructor, DOMObject>(exec, &JSHTMLLIElementConstructorTable, this, propertyName, slot);
}
bool JSHTMLLIElementConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSHTMLLIElementConstructor, DOMObject>(exec, &JSHTMLLIElementConstructorTable, this, propertyName, descriptor);
}
/* Hash table for prototype */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif
static const HashTableValue JSHTMLLIElementPrototypeTableValues[1] =
{
{ 0, 0, 0, 0 THUNK_GENERATOR(0) }
};
#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSHTMLLIElementPrototypeTable = { 1, 0, JSHTMLLIElementPrototypeTableValues, 0 };
const ClassInfo JSHTMLLIElementPrototype::s_info = { "HTMLLIElementPrototype", &JSC::JSObjectWithGlobalObject::s_info, &JSHTMLLIElementPrototypeTable, 0 };
JSObject* JSHTMLLIElementPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSHTMLLIElement>(exec, globalObject);
}
const ClassInfo JSHTMLLIElement::s_info = { "HTMLLIElement", &JSHTMLElement::s_info, &JSHTMLLIElementTable, 0 };
JSHTMLLIElement::JSHTMLLIElement(NonNullPassRefPtr<Structure> structure, JSDOMGlobalObject* globalObject, PassRefPtr<HTMLLIElement> impl)
: JSHTMLElement(structure, globalObject, impl)
{
ASSERT(inherits(&s_info));
}
JSObject* JSHTMLLIElement::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return new (exec) JSHTMLLIElementPrototype(globalObject, JSHTMLLIElementPrototype::createStructure(exec->globalData(), JSHTMLElementPrototype::self(exec, globalObject)));
}
bool JSHTMLLIElement::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSHTMLLIElement, Base>(exec, &JSHTMLLIElementTable, this, propertyName, slot);
}
bool JSHTMLLIElement::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSHTMLLIElement, Base>(exec, &JSHTMLLIElementTable, this, propertyName, descriptor);
}
JSValue jsHTMLLIElementType(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSHTMLLIElement* castedThis = static_cast<JSHTMLLIElement*>(asObject(slotBase));
UNUSED_PARAM(exec);
HTMLLIElement* imp = static_cast<HTMLLIElement*>(castedThis->impl());
JSValue result = jsString(exec, imp->getAttribute(WebCore::HTMLNames::typeAttr));
return result;
}
JSValue jsHTMLLIElementValue(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSHTMLLIElement* castedThis = static_cast<JSHTMLLIElement*>(asObject(slotBase));
UNUSED_PARAM(exec);
HTMLLIElement* imp = static_cast<HTMLLIElement*>(castedThis->impl());
JSValue result = jsNumber(imp->getIntegralAttribute(WebCore::HTMLNames::valueAttr));
return result;
}
JSValue jsHTMLLIElementConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSHTMLLIElement* domObject = static_cast<JSHTMLLIElement*>(asObject(slotBase));
return JSHTMLLIElement::getConstructor(exec, domObject->globalObject());
}
void JSHTMLLIElement::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)
{
lookupPut<JSHTMLLIElement, Base>(exec, propertyName, value, &JSHTMLLIElementTable, this, slot);
}
void setJSHTMLLIElementType(ExecState* exec, JSObject* thisObject, JSValue value)
{
JSHTMLLIElement* castedThis = static_cast<JSHTMLLIElement*>(thisObject);
HTMLLIElement* imp = static_cast<HTMLLIElement*>(castedThis->impl());
imp->setAttribute(WebCore::HTMLNames::typeAttr, valueToStringWithNullCheck(exec, value));
}
void setJSHTMLLIElementValue(ExecState* exec, JSObject* thisObject, JSValue value)
{
JSHTMLLIElement* castedThis = static_cast<JSHTMLLIElement*>(thisObject);
HTMLLIElement* imp = static_cast<HTMLLIElement*>(castedThis->impl());
imp->setIntegralAttribute(WebCore::HTMLNames::valueAttr, value.toInt32(exec));
}
JSValue JSHTMLLIElement::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMConstructor<JSHTMLLIElementConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}
}
|
// fts_index_format.cpp
/**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <third_party/murmurhash3/MurmurHash3.h>
#include "mongo/base/init.h"
#include "mongo/db/fts/fts_index_format.h"
#include "mongo/db/fts/fts_spec.h"
#include "mongo/util/hex.h"
#include "mongo/util/mongoutils/str.h"
namespace mongo {
namespace fts {
using std::string;
using std::vector;
namespace {
BSONObj nullObj;
BSONElement nullElt;
// New in textIndexVersion 2.
// If the term is longer than 32 characters, it may
// result in the generated key being too large
// for the index. In that case, we generate a 64-character key
// from the concatenation of the first 32 characters
// and the hex string of the murmur3 hash value of the entire
// term value.
const size_t termKeyPrefixLength = 32U;
// 128-bit hash value expressed in hex = 32 characters
const size_t termKeySuffixLength = 32U;
const size_t termKeyLength = termKeyPrefixLength + termKeySuffixLength;
/**
* Returns size of buffer required to store term in index key.
* In version 1, terms are stored verbatim in key.
* In version 2, terms longer than 32 characters are hashed and combined
* with a prefix.
*/
int guessTermSize(const std::string& term, TextIndexVersion textIndexVersion) {
if (TEXT_INDEX_VERSION_1 == textIndexVersion) {
return term.size();
} else {
invariant(TEXT_INDEX_VERSION_2 == textIndexVersion);
if (term.size() <= termKeyPrefixLength) {
return term.size();
}
return termKeyLength;
}
}
}
MONGO_INITIALIZER(FTSIndexFormat)(InitializerContext* context) {
BSONObjBuilder b;
b.appendNull("");
nullObj = b.obj();
nullElt = nullObj.firstElement();
return Status::OK();
}
void FTSIndexFormat::getKeys(const FTSSpec& spec, const BSONObj& obj, BSONObjSet* keys) {
int extraSize = 0;
vector<BSONElement> extrasBefore;
vector<BSONElement> extrasAfter;
// compute the non FTS key elements
for (unsigned i = 0; i < spec.numExtraBefore(); i++) {
BSONElement e = obj.getFieldDotted(spec.extraBefore(i));
if (e.eoo())
e = nullElt;
uassert(16675, "cannot have a multi-key as a prefix to a text index", e.type() != Array);
extrasBefore.push_back(e);
extraSize += e.size();
}
for (unsigned i = 0; i < spec.numExtraAfter(); i++) {
BSONElement e = obj.getFieldDotted(spec.extraAfter(i));
if (e.eoo())
e = nullElt;
extrasAfter.push_back(e);
extraSize += e.size();
}
TermFrequencyMap term_freqs;
spec.scoreDocument(obj, &term_freqs);
// create index keys from raw scores
// only 1 per string
uassert(16732,
mongoutils::str::stream() << "too many unique keys for a single document to"
<< " have a text index, max is " << term_freqs.size()
<< obj["_id"],
term_freqs.size() <= 400000);
long long keyBSONSize = 0;
const int MaxKeyBSONSizeMB = 4;
for (TermFrequencyMap::const_iterator i = term_freqs.begin(); i != term_freqs.end(); ++i) {
const string& term = i->first;
double weight = i->second;
// guess the total size of the btree entry based on the size of the weight, term tuple
int guess = 5 /* bson overhead */ + 10 /* weight */ + 8 /* term overhead */ +
/* term size (could be truncated/hashed) */
guessTermSize(term, spec.getTextIndexVersion()) + extraSize;
BSONObjBuilder b(guess); // builds a BSON object with guess length.
for (unsigned k = 0; k < extrasBefore.size(); k++) {
b.appendAs(extrasBefore[k], "");
}
_appendIndexKey(b, weight, term, spec.getTextIndexVersion());
for (unsigned k = 0; k < extrasAfter.size(); k++) {
b.appendAs(extrasAfter[k], "");
}
BSONObj res = b.obj();
verify(guess >= res.objsize());
keys->insert(res);
keyBSONSize += res.objsize();
uassert(16733,
mongoutils::str::stream()
<< "trying to index text where term list is too big, max is "
<< MaxKeyBSONSizeMB << "mb " << obj["_id"],
keyBSONSize <= (MaxKeyBSONSizeMB * 1024 * 1024));
}
}
BSONObj FTSIndexFormat::getIndexKey(double weight,
const string& term,
const BSONObj& indexPrefix,
TextIndexVersion textIndexVersion) {
BSONObjBuilder b;
BSONObjIterator i(indexPrefix);
while (i.more()) {
b.appendAs(i.next(), "");
}
_appendIndexKey(b, weight, term, textIndexVersion);
return b.obj();
}
void FTSIndexFormat::_appendIndexKey(BSONObjBuilder& b,
double weight,
const string& term,
TextIndexVersion textIndexVersion) {
verify(weight >= 0 && weight <= MAX_WEIGHT); // FTSmaxweight = defined in fts_header
// Terms are added to index key verbatim.
if (TEXT_INDEX_VERSION_1 == textIndexVersion) {
b.append("", term);
b.append("", weight);
}
// See comments at the top of file for termKeyPrefixLength.
// Apply hash for text index version 2 to long terms (longer than 32 characters).
else {
invariant(TEXT_INDEX_VERSION_2 == textIndexVersion);
if (term.size() <= termKeyPrefixLength) {
b.append("", term);
} else {
union {
uint64_t hash[2];
char data[16];
} t;
uint32_t seed = 0;
MurmurHash3_x64_128(term.data(), term.size(), seed, t.hash);
string keySuffix = mongo::toHexLower(t.data, sizeof(t.data));
invariant(termKeySuffixLength == keySuffix.size());
b.append("", term.substr(0, termKeyPrefixLength) + keySuffix);
}
b.append("", weight);
}
}
}
}
|
//---------------------------------------------------------------------------//
// Copyright (c) 2016 Jason Rhinelander <jason@imaginary.ca>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//
#define BOOST_TEST_MODULE TestLiteralConversion
#include <boost/test/unit_test.hpp>
#include <string>
#include <sstream>
#include <vector>
#include <boost/compute/detail/literal.hpp>
BOOST_AUTO_TEST_CASE(literal_conversion_float)
{
std::vector<float> values, roundtrip;
values.push_back(1.2345679f);
values.push_back(1.2345680f);
values.push_back(1.2345681f);
for (size_t i = 0; i < values.size(); i++) {
std::string literal = boost::compute::detail::make_literal(values[i]);
// Check that we got something in the literal, and that at least the first
// 6 characters (5 digits) look good
BOOST_CHECK_EQUAL(literal.substr(0, 6), "1.2345");
// libc++ stream extraction fails on a value such as "1.2f" rather than extracting 1.2
// and leaving the f; so check the "f", then slice it off for the extraction below:
BOOST_CHECK_EQUAL(literal.substr(literal.length()-1), "f");
std::istringstream iss(literal.substr(0, literal.length()-1));
float x;
iss >> x;
roundtrip.push_back(x);
}
BOOST_CHECK_EQUAL(values[0], roundtrip[0]);
BOOST_CHECK_EQUAL(values[1], roundtrip[1]);
BOOST_CHECK_EQUAL(values[2], roundtrip[2]);
}
BOOST_AUTO_TEST_CASE(literal_conversion_double)
{
std::vector<double> values, roundtrip;
values.push_back(1.2345678901234567);
values.push_back(1.2345678901234569);
values.push_back(1.2345678901234571);
for (size_t i = 0; i < values.size(); i++) {
std::string literal = boost::compute::detail::make_literal(values[i]);
// Check that we got something in the literal, and that at least the first
// 11 characters (10 digits) look good
BOOST_CHECK_EQUAL(literal.substr(0, 11), "1.234567890");
// Stuff the literal into a stream then extract it, and make sure we get a numerically
// identical result. (Since there is no suffix, we don't have to worry about removing the
// suffix like we have to above, for float--but we also check to make sure there is no
// (unextracted) suffix).
std::istringstream iss(literal);
double x;
std::string suffix;
iss >> x >> suffix;
BOOST_CHECK_EQUAL(suffix, "");
roundtrip.push_back(x);
}
BOOST_CHECK_EQUAL(values[0], roundtrip[0]);
BOOST_CHECK_EQUAL(values[1], roundtrip[1]);
BOOST_CHECK_EQUAL(values[2], roundtrip[2]);
}
|
#pragma once
#include "../../sk_math.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace flexbuffers {
class Map;
}
namespace StardustXRFusion {
class Datamap {
public:
explicit Datamap(const flexbuffers::Map &flexDatamap);
std::vector<std::string> keys() const;
bool exists(std::string key) const;
bool getBool(std::string key) const;
int32_t getInt(std::string key) const;
float getFloat(std::string key) const;
SKMath::vec2 getVec2(std::string key) const;
SKMath::vec3 getVec3(std::string key) const;
private:
const flexbuffers::Map *flexDatamap;
};
} // namespace StardustXRFusion
|
//Copyright 2020 Iris Technologies, All Rights Reserved
#pragma once
#include <string>
#include <vector>
using namespace std;
namespace ProjectIris
{
namespace Hashes
{
constexpr size_t InitApp = 4229616916362953318;//initapp
constexpr size_t IsConsole = 4280226163429640506;//isconsole
constexpr size_t Natlib = 2283687954489727723;//natlib
constexpr size_t Ignore = 12181781538219395523;//ignore
constexpr size_t UseVisualDebugger = 4970868739992279183;//usevisualdebugger
constexpr size_t MeasureType = 9985186892661743463;//measuretype
constexpr size_t ReportPupil = 15381437785649700129;//reportpupil
constexpr size_t Name = 14176396743819860870;//name
constexpr size_t Type = 12075340201627130925;//type
constexpr size_t Executable = 13678059843563106925;//executable
constexpr size_t Library = 16152639334691645584;//library
constexpr size_t Sandbox = 3331646911590050372;//sandbox
constexpr size_t Nanoseconds = 626911876451167078;//ns
constexpr size_t Microseconds = 582730275372608502;//mcs
constexpr size_t Milliseconds = 624114718869565969;//ms
constexpr size_t Off = 1883801076392705514;//off
constexpr size_t Sldown = 5780042772118102530;//sldown
constexpr size_t Stop = 12618894948741332165;//stop
constexpr size_t Module = 4892776386767805149;//module
constexpr size_t Using = 15689622396028117031;//using
constexpr size_t Function = 619343937915704565;//fn
constexpr size_t Main = 2258945139493307336;//main
constexpr size_t In = 628032278800124862;//in
constexpr size_t Out = 1871134702438174719;//out
constexpr size_t Inout = 4023996569761782818;//inout
constexpr size_t Const = 7334518323283222324;//const
constexpr size_t Class = 15066323702654938015;//class
constexpr size_t OperatorPlus = 5084307088801188994;//operator+
constexpr size_t OperatorMinus = 5084300491731419728;//operator-
constexpr size_t OperatorEqual = 5084282899545368352;//operator=
constexpr size_t OperatorMultiplication = 5084308188312817205;//operator*
constexpr size_t OperatorDivision = 5084302690754676150;//operator/
constexpr size_t OperatorIncrement = 16424530381718799147;//operator++
constexpr size_t OperatorDecrement = 16418797528090442343;//operator--
constexpr size_t OperatorPlusEqual = 16424554570974619789;//operator+=
constexpr size_t OperatorMinusEqual = 16418779935904390967;//operator-=
constexpr size_t OperatorMultiplicationEqual = 16425394597858383768; //operator*=
constexpr size_t OperatorDivisionEqual = 16420613921299868465;//operator/=
constexpr size_t Equal = 12638138822044000712;//=
constexpr size_t S8 = 637547452428770606;//s8
}
namespace Opcodes
{
constexpr unsigned short Nothing = 0;
constexpr unsigned short NewFile = 1;
constexpr unsigned short StartModule = 2;
constexpr unsigned short EndModule = 3;
constexpr unsigned short Using = 4;
constexpr unsigned short StartFunction = 5;
constexpr unsigned short EndFunction = 6;
constexpr unsigned short InArgument = 7;
constexpr unsigned short InoutArgument = 8;
constexpr unsigned short OutArgument = 9;
constexpr unsigned short ArgumentType = 10;
constexpr unsigned short ArgumentName = 11;
constexpr unsigned short FunctionBody = 12;
constexpr unsigned short LvalueKeyword = 13;
constexpr unsigned short EqualOperation = 14;
constexpr unsigned short RvalueKeyword = 15;
constexpr unsigned short LocalVariableType = 16;
constexpr unsigned short LocalVariableName = 17;
constexpr unsigned short StartClass = 18;
constexpr unsigned short Main = 19;
}
struct Bytes8
{
unsigned char a, b, c, d, e, f, g, h;
};
struct Bytes4
{
unsigned char a, b, c, d;
};
struct Bytes2
{
unsigned char a, b;
};
struct PESection
{
unsigned int PointerToRawData, VirtualEnd, VirtualAddress;//VirtualEnd = VirtualAddress + VirtualSize
};
struct PENativeSection
{
unsigned int PointerToRawData, SizeOfRawData, VirtualAddress, VirtualSize;
};
enum class OperatingSystem : unsigned char
{
Windows,
Xbox,
};
struct ErrorPoint
{
size_t Line, Character;
string File, Message;
__forceinline void clear() noexcept
{
File.clear();
Message.clear();
}
};
struct NativeLibrary
{
size_t Line, Character;
string Name;
};
enum class MeasureTypes : unsigned char
{
Nanoseconds,
Microseconds,
Milliseconds
};
enum class ProjectType : unsigned char
{
Sandbox,
Library,
Executable
};
struct IgnoredFile
{
size_t Line, Character;
string Name;
};
enum class ArgumentDirection : unsigned char
{
In,
Out,
Inout
};
struct Argument
{
size_t Type;
ArgumentDirection Direction;
};
struct FunctionPrototype
{
size_t Name, Character, Line;
vector<Argument> Arguments;
};
struct PupilFInstruction
{
bool IsLiteral = false;
unsigned short Opcode;
size_t Pointer, Module, Name, Line, Character;
};
struct RegisterAliasing
{
size_t VarName;
char Register;
};
}
|
#include <iostream>
#include <list>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
typedef map<int,list<int> >::iterator IteratorM;
typedef list<int>::iterator IteratorL;
int main (int argc, char *argv[])
{
map<int,list<int> > m;
list<int> l1, l2;
l1.push_back(1);
l1.push_back(0);
l1.push_back(3);
l1.push_back(7);
m[0] = l1;
l2.push_back(10);
l2.push_back(20);
l2.push_back(30);
l2.push_back(70);
m[1] = l2;
for(IteratorM i = m.begin();i != m.end(); i++) {
cout << i->first << endl;
for(IteratorL j = i->second.begin(); j != i->second.end(); j++) {
cout << (*j) << " DISTANCE: " << distance(i->second.begin(),j) << endl;
}
cout << "-----------------" << endl;
}
}
|
#include "SymbolsLookup.hpp"
namespace Helpers
{
void SymbolsLookup::Put(const SymbolInfo& aSymbolInfo)
{
const auto& code = aSymbolInfo.Code;
if (!code.Length)
{
return;
}
mLengthsIndex[code.Length][code.Value] = aSymbolInfo.Symbol;
}
SymbolsLookup::FindResult SymbolsLookup::Find(int aValue, int aLength) const
{
static FindResult notFound{false};
auto lit = mLengthsIndex.find(aLength);
if (lit == mLengthsIndex.end())
{
return notFound;
}
const auto& symbols = lit->second;
auto sit = symbols.find(aValue);
if (sit == symbols.end())
{
return notFound;
}
return FindResult{true, sit->second};
}
size_t SymbolsLookup::Size() const
{
size_t size = 0;
for (const auto& index : mLengthsIndex)
{
size += index.second.size();
}
return size;
}
}
|
/*****************************************************************************
Copyright (c) 1995, 2015, Oracle and/or its affiliates. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
*****************************************************************************/
/**************************************************//**
@file buf/buf0lru.cc
The database buffer replacement algorithm
Created 11/5/1995 Heikki Tuuri
*******************************************************/
#include "buf0lru.h"
#ifdef UNIV_NONINL
#include "buf0lru.ic"
#endif /* UNIV_NOINL */
#ifndef UNIV_HOTBACKUP
#include "ut0byte.h"
#include "ut0rnd.h"
#include "sync0rw.h"
#include "hash0hash.h"
#include "os0event.h"
#include "fil0fil.h"
#include "btr0btr.h"
#include "buf0buddy.h"
#include "buf0buf.h"
#include "buf0dblwr.h"
#include "buf0flu.h"
#include "buf0rea.h"
#include "btr0sea.h"
#include "ibuf0ibuf.h"
#include "os0file.h"
#include "page0zip.h"
#include "log0recv.h"
#include "srv0srv.h"
#include "srv0mon.h"
#include "lock0lock.h"
/** The number of blocks from the LRU_old pointer onward, including
the block pointed to, must be buf_pool->LRU_old_ratio/BUF_LRU_OLD_RATIO_DIV
of the whole LRU list length, except that the tolerance defined below
is allowed. Note that the tolerance must be small enough such that for
even the BUF_LRU_OLD_MIN_LEN long LRU list, the LRU_old pointer is not
allowed to point to either end of the LRU list. */
static const ulint BUF_LRU_OLD_TOLERANCE = 20;
/** The minimum amount of non-old blocks when the LRU_old list exists
(that is, when there are more than BUF_LRU_OLD_MIN_LEN blocks).
@see buf_LRU_old_adjust_len */
#define BUF_LRU_NON_OLD_MIN_LEN 5
#if BUF_LRU_NON_OLD_MIN_LEN >= BUF_LRU_OLD_MIN_LEN
# error "BUF_LRU_NON_OLD_MIN_LEN >= BUF_LRU_OLD_MIN_LEN"
#endif
/** When dropping the search hash index entries before deleting an ibd
file, we build a local array of pages belonging to that tablespace
in the buffer pool. Following is the size of that array.
We also release buf_pool->mutex after scanning this many pages of the
flush_list when dropping a table. This is to ensure that other threads
are not blocked for extended period of time when using very large
buffer pools. */
static const ulint BUF_LRU_DROP_SEARCH_SIZE = 1024;
/** We scan these many blocks when looking for a clean page to evict
during LRU eviction. */
static const ulint BUF_LRU_SEARCH_SCAN_THRESHOLD = 100;
/** If we switch on the InnoDB monitor because there are too few available
frames in the buffer pool, we set this to TRUE */
static bool buf_lru_switched_on_innodb_mon = false;
/******************************************************************//**
These statistics are not 'of' LRU but 'for' LRU. We keep count of I/O
and page_zip_decompress() operations. Based on the statistics,
buf_LRU_evict_from_unzip_LRU() decides if we want to evict from
unzip_LRU or the regular LRU. From unzip_LRU, we will only evict the
uncompressed frame (meaning we can evict dirty blocks as well). From
the regular LRU, we will evict the entire block (i.e.: both the
uncompressed and compressed data), which must be clean. */
/* @{ */
/** Number of intervals for which we keep the history of these stats.
Each interval is 1 second, defined by the rate at which
srv_error_monitor_thread() calls buf_LRU_stat_update(). */
static const ulint BUF_LRU_STAT_N_INTERVAL = 50;
/** Co-efficient with which we multiply I/O operations to equate them
with page_zip_decompress() operations. */
static const ulint BUF_LRU_IO_TO_UNZIP_FACTOR = 50;
/** Sampled values buf_LRU_stat_cur.
Not protected by any mutex. Updated by buf_LRU_stat_update(). */
static buf_LRU_stat_t buf_LRU_stat_arr[BUF_LRU_STAT_N_INTERVAL];
/** Cursor to buf_LRU_stat_arr[] that is updated in a round-robin fashion. */
static ulint buf_LRU_stat_arr_ind;
/** Current operation counters. Not protected by any mutex. Cleared
by buf_LRU_stat_update(). */
buf_LRU_stat_t buf_LRU_stat_cur;
/** Running sum of past values of buf_LRU_stat_cur.
Updated by buf_LRU_stat_update(). Not Protected by any mutex. */
buf_LRU_stat_t buf_LRU_stat_sum;
/* @} */
/** @name Heuristics for detecting index scan @{ */
/** Move blocks to "new" LRU list only if the first access was at
least this many milliseconds ago. Not protected by any mutex or latch. */
uint buf_LRU_old_threshold_ms;
/* @} */
/******************************************************************//**
Takes a block out of the LRU list and page hash table.
If the block is compressed-only (BUF_BLOCK_ZIP_PAGE),
the object will be freed.
The caller must hold buf_pool->mutex, the buf_page_get_mutex() mutex
and the appropriate hash_lock. This function will release the
buf_page_get_mutex() and the hash_lock.
If a compressed page is freed other compressed pages may be relocated.
@retval true if BUF_BLOCK_FILE_PAGE was removed from page_hash. The
caller needs to free the page to the free list
@retval false if BUF_BLOCK_ZIP_PAGE was removed from page_hash. In
this case the block is already returned to the buddy allocator. */
static __attribute__((warn_unused_result))
bool
buf_LRU_block_remove_hashed(
/*========================*/
buf_page_t* bpage, /*!< in: block, must contain a file page and
be in a state where it can be freed; there
may or may not be a hash index to the page */
bool zip); /*!< in: true if should remove also the
compressed page of an uncompressed page */
/******************************************************************//**
Puts a file page whose has no hash index to the free list. */
static
void
buf_LRU_block_free_hashed_page(
/*===========================*/
buf_block_t* block); /*!< in: block, must contain a file page and
be in a state where it can be freed */
/******************************************************************//**
Increases LRU size in bytes with page size inline function */
static inline
void
incr_LRU_size_in_bytes(
/*===================*/
buf_page_t* bpage, /*!< in: control block */
buf_pool_t* buf_pool) /*!< in: buffer pool instance */
{
ut_ad(buf_pool_mutex_own(buf_pool));
buf_pool->stat.LRU_bytes += bpage->size.physical();
ut_ad(buf_pool->stat.LRU_bytes <= buf_pool->curr_pool_size);
}
/******************************************************************//**
Determines if the unzip_LRU list should be used for evicting a victim
instead of the general LRU list.
@return TRUE if should use unzip_LRU */
ibool
buf_LRU_evict_from_unzip_LRU(
/*=========================*/
buf_pool_t* buf_pool)
{
ut_ad(buf_pool_mutex_own(buf_pool));
/* If the unzip_LRU list is empty, we can only use the LRU. */
if (UT_LIST_GET_LEN(buf_pool->unzip_LRU) == 0) {
return(FALSE);
}
/* If unzip_LRU is at most 10% of the size of the LRU list,
then use the LRU. This slack allows us to keep hot
decompressed pages in the buffer pool. */
if (UT_LIST_GET_LEN(buf_pool->unzip_LRU)
<= UT_LIST_GET_LEN(buf_pool->LRU) / 10) {
return(FALSE);
}
/* If eviction hasn't started yet, we assume by default
that a workload is disk bound. */
if (buf_pool->freed_page_clock == 0) {
return(TRUE);
}
/* Calculate the average over past intervals, and add the values
of the current interval. */
ulint io_avg = buf_LRU_stat_sum.io / BUF_LRU_STAT_N_INTERVAL
+ buf_LRU_stat_cur.io;
ulint unzip_avg = buf_LRU_stat_sum.unzip / BUF_LRU_STAT_N_INTERVAL
+ buf_LRU_stat_cur.unzip;
/* Decide based on our formula. If the load is I/O bound
(unzip_avg is smaller than the weighted io_avg), evict an
uncompressed frame from unzip_LRU. Otherwise we assume that
the load is CPU bound and evict from the regular LRU. */
return(unzip_avg <= io_avg * BUF_LRU_IO_TO_UNZIP_FACTOR);
}
/** Attempts to drop page hash index on a batch of pages belonging to a
particular space id.
@param[in] space_id space id
@param[in] page_size page size
@param[in] arr array of page_no
@param[in] count number of entries in array */
static
void
buf_LRU_drop_page_hash_batch(
ulint space_id,
const page_size_t& page_size,
const ulint* arr,
ulint count)
{
ut_ad(count <= BUF_LRU_DROP_SEARCH_SIZE);
for (ulint i = 0; i < count; ++i, ++arr) {
/* While our only caller
buf_LRU_drop_page_hash_for_tablespace()
is being executed for DROP TABLE or similar,
the table cannot be evicted from the buffer pool.
Note: this should not be executed for DROP TABLESPACE,
because DROP TABLESPACE would be refused if tables existed
in the tablespace, and a previous DROP TABLE would have
already removed the AHI entries. */
btr_search_drop_page_hash_when_freed(
page_id_t(space_id, *arr), page_size);
}
}
/******************************************************************//**
When doing a DROP TABLE/DISCARD TABLESPACE we have to drop all page
hash index entries belonging to that table. This function tries to
do that in batch. Note that this is a 'best effort' attempt and does
not guarantee that ALL hash entries will be removed. */
static
void
buf_LRU_drop_page_hash_for_tablespace(
/*==================================*/
buf_pool_t* buf_pool, /*!< in: buffer pool instance */
ulint id) /*!< in: space id */
{
bool found;
const page_size_t page_size(fil_space_get_page_size(id, &found));
if (!found) {
/* Somehow, the tablespace does not exist. Nothing to drop. */
ut_ad(0);
return;
}
ulint* page_arr = static_cast<ulint*>(ut_malloc_nokey(
sizeof(ulint) * BUF_LRU_DROP_SEARCH_SIZE));
ulint num_entries = 0;
buf_pool_mutex_enter(buf_pool);
scan_again:
for (buf_page_t* bpage = UT_LIST_GET_LAST(buf_pool->LRU);
bpage != NULL;
/* No op */) {
buf_page_t* prev_bpage = UT_LIST_GET_PREV(LRU, bpage);
ut_a(buf_page_in_file(bpage));
if (buf_page_get_state(bpage) != BUF_BLOCK_FILE_PAGE
|| bpage->id.space() != id
|| bpage->io_fix != BUF_IO_NONE) {
/* Compressed pages are never hashed.
Skip blocks of other tablespaces.
Skip I/O-fixed blocks (to be dealt with later). */
next_page:
bpage = prev_bpage;
continue;
}
mutex_enter(&((buf_block_t*) bpage)->mutex);
{
bool skip = bpage->buf_fix_count > 0
|| !((buf_block_t*) bpage)->index;
mutex_exit(&((buf_block_t*) bpage)->mutex);
if (skip) {
/* Skip this block, because there are
no adaptive hash index entries
pointing to it, or because we cannot
drop them due to the buffer-fix. */
goto next_page;
}
}
/* Store the page number so that we can drop the hash
index in a batch later. */
page_arr[num_entries] = bpage->id.page_no();
ut_a(num_entries < BUF_LRU_DROP_SEARCH_SIZE);
++num_entries;
if (num_entries < BUF_LRU_DROP_SEARCH_SIZE) {
goto next_page;
}
/* Array full. We release the buf_pool->mutex to obey
the latching order. */
buf_pool_mutex_exit(buf_pool);
buf_LRU_drop_page_hash_batch(
id, page_size, page_arr, num_entries);
num_entries = 0;
buf_pool_mutex_enter(buf_pool);
/* Note that we released the buf_pool mutex above
after reading the prev_bpage during processing of a
page_hash_batch (i.e.: when the array was full).
Because prev_bpage could belong to a compressed-only
block, it may have been relocated, and thus the
pointer cannot be trusted. Because bpage is of type
buf_block_t, it is safe to dereference.
bpage can change in the LRU list. This is OK because
this function is a 'best effort' to drop as many
search hash entries as possible and it does not
guarantee that ALL such entries will be dropped. */
/* If, however, bpage has been removed from LRU list
to the free list then we should restart the scan.
bpage->state is protected by buf_pool mutex. */
if (bpage != NULL
&& buf_page_get_state(bpage) != BUF_BLOCK_FILE_PAGE) {
goto scan_again;
}
}
buf_pool_mutex_exit(buf_pool);
/* Drop any remaining batch of search hashed pages. */
buf_LRU_drop_page_hash_batch(id, page_size, page_arr, num_entries);
ut_free(page_arr);
}
/******************************************************************//**
While flushing (or removing dirty) pages from a tablespace we don't
want to hog the CPU and resources. Release the buffer pool and block
mutex and try to force a context switch. Then reacquire the same mutexes.
The current page is "fixed" before the release of the mutexes and then
"unfixed" again once we have reacquired the mutexes. */
static
void
buf_flush_yield(
/*============*/
buf_pool_t* buf_pool, /*!< in/out: buffer pool instance */
buf_page_t* bpage) /*!< in/out: current page */
{
BPageMutex* block_mutex;
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(buf_page_in_file(bpage));
block_mutex = buf_page_get_mutex(bpage);
mutex_enter(block_mutex);
/* "Fix" the block so that the position cannot be
changed after we release the buffer pool and
block mutexes. */
buf_page_set_sticky(bpage);
/* Now it is safe to release the buf_pool->mutex. */
buf_pool_mutex_exit(buf_pool);
mutex_exit(block_mutex);
/* Try and force a context switch. */
os_thread_yield();
buf_pool_mutex_enter(buf_pool);
mutex_enter(block_mutex);
/* "Unfix" the block now that we have both the
buffer pool and block mutex again. */
buf_page_unset_sticky(bpage);
mutex_exit(block_mutex);
}
/******************************************************************//**
If we have hogged the resources for too long then release the buffer
pool and flush list mutex and do a thread yield. Set the current page
to "sticky" so that it is not relocated during the yield.
@return true if yielded */
static __attribute__((warn_unused_result))
bool
buf_flush_try_yield(
/*================*/
buf_pool_t* buf_pool, /*!< in/out: buffer pool instance */
buf_page_t* bpage, /*!< in/out: bpage to remove */
ulint processed) /*!< in: number of pages processed */
{
/* Every BUF_LRU_DROP_SEARCH_SIZE iterations in the
loop we release buf_pool->mutex to let other threads
do their job but only if the block is not IO fixed. This
ensures that the block stays in its position in the
flush_list. */
if (bpage != NULL
&& processed >= BUF_LRU_DROP_SEARCH_SIZE
&& buf_page_get_io_fix(bpage) == BUF_IO_NONE) {
buf_flush_list_mutex_exit(buf_pool);
/* Release the buffer pool and block mutex
to give the other threads a go. */
buf_flush_yield(buf_pool, bpage);
buf_flush_list_mutex_enter(buf_pool);
/* Should not have been removed from the flush
list during the yield. However, this check is
not sufficient to catch a remove -> add. */
ut_ad(bpage->in_flush_list);
return(true);
}
return(false);
}
/******************************************************************//**
Removes a single page from a given tablespace inside a specific
buffer pool instance.
@return true if page was removed. */
static __attribute__((warn_unused_result))
bool
buf_flush_or_remove_page(
/*=====================*/
buf_pool_t* buf_pool, /*!< in/out: buffer pool instance */
buf_page_t* bpage, /*!< in/out: bpage to remove */
bool flush) /*!< in: flush to disk if true but
don't remove else remove without
flushing to disk */
{
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(buf_flush_list_mutex_own(buf_pool));
/* bpage->space and bpage->io_fix are protected by
buf_pool->mutex and block_mutex. It is safe to check
them while holding buf_pool->mutex only. */
if (buf_page_get_io_fix(bpage) != BUF_IO_NONE) {
/* We cannot remove this page during this scan
yet; maybe the system is currently reading it
in, or flushing the modifications to the file */
return(false);
}
BPageMutex* block_mutex;
bool processed = false;
block_mutex = buf_page_get_mutex(bpage);
/* We have to release the flush_list_mutex to obey the
latching order. We are however guaranteed that the page
will stay in the flush_list and won't be relocated because
buf_flush_remove() and buf_flush_relocate_on_flush_list()
need buf_pool->mutex as well. */
buf_flush_list_mutex_exit(buf_pool);
mutex_enter(block_mutex);
ut_ad(bpage->oldest_modification != 0);
if (!flush) {
buf_flush_remove(bpage);
mutex_exit(block_mutex);
processed = true;
} else if (buf_flush_ready_for_flush(bpage, BUF_FLUSH_SINGLE_PAGE)) {
/* The following call will release the buffer pool
and block mutex. */
processed = buf_flush_page(
buf_pool, bpage, BUF_FLUSH_SINGLE_PAGE, false);
if (processed) {
/* Wake possible simulated aio thread to actually
post the writes to the operating system */
os_aio_simulated_wake_handler_threads();
buf_pool_mutex_enter(buf_pool);
} else {
mutex_exit(block_mutex);
}
} else {
mutex_exit(block_mutex);
}
buf_flush_list_mutex_enter(buf_pool);
ut_ad(!mutex_own(block_mutex));
ut_ad(buf_pool_mutex_own(buf_pool));
return(processed);
}
/******************************************************************//**
Remove all dirty pages belonging to a given tablespace inside a specific
buffer pool instance when we are deleting the data file(s) of that
tablespace. The pages still remain a part of LRU and are evicted from
the list as they age towards the tail of the LRU.
@retval DB_SUCCESS if all freed
@retval DB_FAIL if not all freed
@retval DB_INTERRUPTED if the transaction was interrupted */
static __attribute__((warn_unused_result))
dberr_t
buf_flush_or_remove_pages(
/*======================*/
buf_pool_t* buf_pool, /*!< buffer pool instance */
ulint id, /*!< in: target space id for which
to remove or flush pages */
FlushObserver* observer, /*!< in: flush observer */
bool flush, /*!< in: flush to disk if true but
don't remove else remove without
flushing to disk */
const trx_t* trx) /*!< to check if the operation must
be interrupted, can be 0 */
{
buf_page_t* prev;
buf_page_t* bpage;
ulint processed = 0;
buf_flush_list_mutex_enter(buf_pool);
rescan:
bool all_freed = true;
for (bpage = UT_LIST_GET_LAST(buf_pool->flush_list);
bpage != NULL;
bpage = prev) {
ut_a(buf_page_in_file(bpage));
/* Save the previous link because once we free the
page we can't rely on the links. */
prev = UT_LIST_GET_PREV(list, bpage);
/* If flush observer is NULL, flush page for space id,
or flush page for flush observer. */
if ((observer != NULL && observer != bpage->flush_observer)
|| (observer == NULL && id != bpage->id.space())) {
/* Skip this block, as it does not belong to
the target space. */
} else if (!buf_flush_or_remove_page(buf_pool, bpage, flush)) {
/* Remove was unsuccessful, we have to try again
by scanning the entire list from the end.
This also means that we never released the
buf_pool mutex. Therefore we can trust the prev
pointer.
buf_flush_or_remove_page() released the
flush list mutex but not the buf_pool mutex.
Therefore it is possible that a new page was
added to the flush list. For example, in case
where we are at the head of the flush list and
prev == NULL. That is OK because we have the
tablespace quiesced and no new pages for this
space-id should enter flush_list. This is
because the only callers of this function are
DROP TABLE and FLUSH TABLE FOR EXPORT.
We know that we'll have to do at least one more
scan but we don't break out of loop here and
try to do as much work as we can in this
iteration. */
all_freed = false;
} else if (flush) {
/* The processing was successful. And during the
processing we have released the buf_pool mutex
when calling buf_page_flush(). We cannot trust
prev pointer. */
goto rescan;
}
++processed;
/* Yield if we have hogged the CPU and mutexes for too long. */
if (buf_flush_try_yield(buf_pool, prev, processed)) {
/* Reset the batch size counter if we had to yield. */
processed = 0;
}
#ifdef DBUG_OFF
if (flush) {
DBUG_EXECUTE_IF("ib_export_flush_crash",
static ulint n_pages;
if (++n_pages == 4) {DBUG_SUICIDE();});
}
#endif /* DBUG_OFF */
/* The check for trx is interrupted is expensive, we want
to check every N iterations. */
if (!processed && trx && trx_is_interrupted(trx)) {
if (trx->flush_observer != NULL) {
if (flush) {
trx->flush_observer->interrupted();
} else {
/* We should remove all pages with the
the flush observer. */
continue;
}
}
buf_flush_list_mutex_exit(buf_pool);
return(DB_INTERRUPTED);
}
}
buf_flush_list_mutex_exit(buf_pool);
return(all_freed ? DB_SUCCESS : DB_FAIL);
}
/******************************************************************//**
Remove or flush all the dirty pages that belong to a given tablespace
inside a specific buffer pool instance. The pages will remain in the LRU
list and will be evicted from the LRU list as they age and move towards
the tail of the LRU list. */
static
void
buf_flush_dirty_pages(
/*==================*/
buf_pool_t* buf_pool, /*!< buffer pool instance */
ulint id, /*!< in: space id */
FlushObserver* observer, /*!< in: flush observer */
bool flush, /*!< in: flush to disk if true otherwise
remove the pages without flushing */
const trx_t* trx) /*!< to check if the operation must
be interrupted */
{
dberr_t err;
do {
buf_pool_mutex_enter(buf_pool);
err = buf_flush_or_remove_pages(
buf_pool, id, observer, flush, trx);
buf_pool_mutex_exit(buf_pool);
ut_ad(buf_flush_validate(buf_pool));
if (err == DB_FAIL) {
os_thread_sleep(2000);
}
if (err == DB_INTERRUPTED && observer != NULL) {
ut_a(flush);
flush = false;
err = DB_FAIL;
}
/* DB_FAIL is a soft error, it means that the task wasn't
completed, needs to be retried. */
ut_ad(buf_flush_validate(buf_pool));
} while (err == DB_FAIL);
ut_ad(err == DB_INTERRUPTED
|| buf_pool_get_dirty_pages_count(buf_pool, id, observer) == 0);
}
/******************************************************************//**
Remove all pages that belong to a given tablespace inside a specific
buffer pool instance when we are DISCARDing the tablespace. */
static
void
buf_LRU_remove_all_pages(
/*=====================*/
buf_pool_t* buf_pool, /*!< buffer pool instance */
ulint id) /*!< in: space id */
{
buf_page_t* bpage;
ibool all_freed;
scan_again:
buf_pool_mutex_enter(buf_pool);
all_freed = TRUE;
for (bpage = UT_LIST_GET_LAST(buf_pool->LRU);
bpage != NULL;
/* No op */) {
rw_lock_t* hash_lock;
buf_page_t* prev_bpage;
BPageMutex* block_mutex;
ut_a(buf_page_in_file(bpage));
ut_ad(bpage->in_LRU_list);
prev_bpage = UT_LIST_GET_PREV(LRU, bpage);
/* bpage->id.space() and bpage->io_fix are protected by
buf_pool->mutex and the block_mutex. It is safe to check
them while holding buf_pool->mutex only. */
if (bpage->id.space() != id) {
/* Skip this block, as it does not belong to
the space that is being invalidated. */
goto next_page;
} else if (buf_page_get_io_fix(bpage) != BUF_IO_NONE) {
/* We cannot remove this page during this scan
yet; maybe the system is currently reading it
in, or flushing the modifications to the file */
all_freed = FALSE;
goto next_page;
} else {
hash_lock = buf_page_hash_lock_get(buf_pool, bpage->id);
rw_lock_x_lock(hash_lock);
block_mutex = buf_page_get_mutex(bpage);
mutex_enter(block_mutex);
if (bpage->buf_fix_count > 0) {
mutex_exit(block_mutex);
rw_lock_x_unlock(hash_lock);
/* We cannot remove this page during
this scan yet; maybe the system is
currently reading it in, or flushing
the modifications to the file */
all_freed = FALSE;
goto next_page;
}
}
ut_ad(mutex_own(block_mutex));
DBUG_PRINT("ib_buf", ("evict page " UINT32PF ":" UINT32PF
" state %u",
bpage->id.space(),
bpage->id.page_no(),
bpage->state));
if (buf_page_get_state(bpage) != BUF_BLOCK_FILE_PAGE) {
/* Do nothing, because the adaptive hash index
covers uncompressed pages only. */
} else if (((buf_block_t*) bpage)->index) {
buf_pool_mutex_exit(buf_pool);
rw_lock_x_unlock(hash_lock);
mutex_exit(block_mutex);
/* Note that the following call will acquire
and release block->lock X-latch.
Note that the table cannot be evicted during
the execution of ALTER TABLE...DISCARD TABLESPACE
because MySQL is keeping the table handle open. */
btr_search_drop_page_hash_when_freed(
bpage->id, bpage->size);
goto scan_again;
}
if (bpage->oldest_modification != 0) {
buf_flush_remove(bpage);
}
ut_ad(!bpage->in_flush_list);
/* Remove from the LRU list. */
if (buf_LRU_block_remove_hashed(bpage, true)) {
buf_LRU_block_free_hashed_page((buf_block_t*) bpage);
} else {
ut_ad(block_mutex == &buf_pool->zip_mutex);
}
ut_ad(!mutex_own(block_mutex));
/* buf_LRU_block_remove_hashed() releases the hash_lock */
ut_ad(!rw_lock_own(hash_lock, RW_LOCK_X));
ut_ad(!rw_lock_own(hash_lock, RW_LOCK_S));
next_page:
bpage = prev_bpage;
}
buf_pool_mutex_exit(buf_pool);
if (!all_freed) {
os_thread_sleep(20000);
goto scan_again;
}
}
/******************************************************************//**
Remove pages belonging to a given tablespace inside a specific
buffer pool instance when we are deleting the data file(s) of that
tablespace. The pages still remain a part of LRU and are evicted from
the list as they age towards the tail of the LRU only if buf_remove
is BUF_REMOVE_FLUSH_NO_WRITE. */
static
void
buf_LRU_remove_pages(
/*=================*/
buf_pool_t* buf_pool, /*!< buffer pool instance */
ulint id, /*!< in: space id */
buf_remove_t buf_remove, /*!< in: remove or flush strategy */
const trx_t* trx) /*!< to check if the operation must
be interrupted */
{
FlushObserver* observer = (trx == NULL) ? NULL : trx->flush_observer;
switch (buf_remove) {
case BUF_REMOVE_ALL_NO_WRITE:
buf_LRU_remove_all_pages(buf_pool, id);
break;
case BUF_REMOVE_FLUSH_NO_WRITE:
/* Pass trx as NULL to avoid interruption check. */
buf_flush_dirty_pages(buf_pool, id, observer, false, NULL);
break;
case BUF_REMOVE_FLUSH_WRITE:
buf_flush_dirty_pages(buf_pool, id, observer, true, trx);
if (observer == NULL) {
/* Ensure that all asynchronous IO is completed. */
os_aio_wait_until_no_pending_writes();
fil_flush(id);
}
break;
}
}
/******************************************************************//**
Flushes all dirty pages or removes all pages belonging
to a given tablespace. A PROBLEM: if readahead is being started, what
guarantees that it will not try to read in pages after this operation
has completed? */
void
buf_LRU_flush_or_remove_pages(
/*==========================*/
ulint id, /*!< in: space id */
buf_remove_t buf_remove, /*!< in: remove or flush strategy */
const trx_t* trx) /*!< to check if the operation must
be interrupted */
{
ulint i;
/* Before we attempt to drop pages one by one we first
attempt to drop page hash index entries in batches to make
it more efficient. The batching attempt is a best effort
attempt and does not guarantee that all pages hash entries
will be dropped. We get rid of remaining page hash entries
one by one below. */
for (i = 0; i < srv_buf_pool_instances; i++) {
buf_pool_t* buf_pool;
buf_pool = buf_pool_from_array(i);
switch (buf_remove) {
case BUF_REMOVE_ALL_NO_WRITE:
buf_LRU_drop_page_hash_for_tablespace(buf_pool, id);
break;
case BUF_REMOVE_FLUSH_NO_WRITE:
/* It is a DROP TABLE for a single table
tablespace. No AHI entries exist because
we already dealt with them when freeing up
extents. */
case BUF_REMOVE_FLUSH_WRITE:
/* We allow read-only queries against the
table, there is no need to drop the AHI entries. */
break;
}
buf_LRU_remove_pages(buf_pool, id, buf_remove, trx);
}
}
#if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
/********************************************************************//**
Insert a compressed block into buf_pool->zip_clean in the LRU order. */
void
buf_LRU_insert_zip_clean(
/*=====================*/
buf_page_t* bpage) /*!< in: pointer to the block in question */
{
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(buf_page_get_state(bpage) == BUF_BLOCK_ZIP_PAGE);
/* Find the first successor of bpage in the LRU list
that is in the zip_clean list. */
buf_page_t* b = bpage;
do {
b = UT_LIST_GET_NEXT(LRU, b);
} while (b && buf_page_get_state(b) != BUF_BLOCK_ZIP_PAGE);
/* Insert bpage before b, i.e., after the predecessor of b. */
if (b != NULL) {
b = UT_LIST_GET_PREV(list, b);
}
if (b != NULL) {
UT_LIST_INSERT_AFTER(buf_pool->zip_clean, b, bpage);
} else {
UT_LIST_ADD_FIRST(buf_pool->zip_clean, bpage);
}
}
#endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
/******************************************************************//**
Try to free an uncompressed page of a compressed block from the unzip
LRU list. The compressed page is preserved, and it need not be clean.
@return true if freed */
static
bool
buf_LRU_free_from_unzip_LRU_list(
/*=============================*/
buf_pool_t* buf_pool, /*!< in: buffer pool instance */
bool scan_all) /*!< in: scan whole LRU list
if true, otherwise scan only
srv_LRU_scan_depth / 2 blocks. */
{
ut_ad(buf_pool_mutex_own(buf_pool));
if (!buf_LRU_evict_from_unzip_LRU(buf_pool)) {
return(false);
}
ulint scanned = 0;
bool freed = false;
for (buf_block_t* block = UT_LIST_GET_LAST(buf_pool->unzip_LRU);
block != NULL
&& !freed
&& (scan_all || scanned < srv_LRU_scan_depth);
++scanned) {
buf_block_t* prev_block;
prev_block = UT_LIST_GET_PREV(unzip_LRU, block);
ut_ad(buf_block_get_state(block) == BUF_BLOCK_FILE_PAGE);
ut_ad(block->in_unzip_LRU_list);
ut_ad(block->page.in_LRU_list);
freed = buf_LRU_free_page(&block->page, false);
block = prev_block;
}
if (scanned) {
MONITOR_INC_VALUE_CUMULATIVE(
MONITOR_LRU_UNZIP_SEARCH_SCANNED,
MONITOR_LRU_UNZIP_SEARCH_SCANNED_NUM_CALL,
MONITOR_LRU_UNZIP_SEARCH_SCANNED_PER_CALL,
scanned);
}
return(freed);
}
/******************************************************************//**
Try to free a clean page from the common LRU list.
@return true if freed */
static
bool
buf_LRU_free_from_common_LRU_list(
/*==============================*/
buf_pool_t* buf_pool, /*!< in: buffer pool instance */
bool scan_all) /*!< in: scan whole LRU list
if true, otherwise scan only
up to BUF_LRU_SEARCH_SCAN_THRESHOLD */
{
ut_ad(buf_pool_mutex_own(buf_pool));
ulint scanned = 0;
bool freed = false;
for (buf_page_t* bpage = buf_pool->lru_scan_itr.start();
bpage != NULL
&& !freed
&& (scan_all || scanned < BUF_LRU_SEARCH_SCAN_THRESHOLD);
++scanned, bpage = buf_pool->lru_scan_itr.get()) {
buf_page_t* prev = UT_LIST_GET_PREV(LRU, bpage);
BPageMutex* mutex = buf_page_get_mutex(bpage);
buf_pool->lru_scan_itr.set(prev);
mutex_enter(mutex);
ut_ad(buf_page_in_file(bpage));
ut_ad(bpage->in_LRU_list);
unsigned accessed = buf_page_is_accessed(bpage);
if (buf_flush_ready_for_replace(bpage)) {
mutex_exit(mutex);
freed = buf_LRU_free_page(bpage, true);
} else {
mutex_exit(mutex);
}
if (freed && !accessed) {
/* Keep track of pages that are evicted without
ever being accessed. This gives us a measure of
the effectiveness of readahead */
++buf_pool->stat.n_ra_pages_evicted;
}
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(!mutex_own(mutex));
}
if (scanned) {
MONITOR_INC_VALUE_CUMULATIVE(
MONITOR_LRU_SEARCH_SCANNED,
MONITOR_LRU_SEARCH_SCANNED_NUM_CALL,
MONITOR_LRU_SEARCH_SCANNED_PER_CALL,
scanned);
}
return(freed);
}
/******************************************************************//**
Try to free a replaceable block.
@return true if found and freed */
bool
buf_LRU_scan_and_free_block(
/*========================*/
buf_pool_t* buf_pool, /*!< in: buffer pool instance */
bool scan_all) /*!< in: scan whole LRU list
if true, otherwise scan only
BUF_LRU_SEARCH_SCAN_THRESHOLD
blocks. */
{
ut_ad(buf_pool_mutex_own(buf_pool));
return(buf_LRU_free_from_unzip_LRU_list(buf_pool, scan_all)
|| buf_LRU_free_from_common_LRU_list(buf_pool, scan_all));
}
/******************************************************************//**
Returns TRUE if less than 25 % of the buffer pool in any instance is
available. This can be used in heuristics to prevent huge transactions
eating up the whole buffer pool for their locks.
@return TRUE if less than 25 % of buffer pool left */
ibool
buf_LRU_buf_pool_running_out(void)
/*==============================*/
{
ibool ret = FALSE;
for (ulint i = 0; i < srv_buf_pool_instances && !ret; i++) {
buf_pool_t* buf_pool;
buf_pool = buf_pool_from_array(i);
buf_pool_mutex_enter(buf_pool);
if (!recv_recovery_is_on()
&& UT_LIST_GET_LEN(buf_pool->free)
+ UT_LIST_GET_LEN(buf_pool->LRU)
< ut_min(buf_pool->curr_size,
buf_pool->old_size) / 4) {
ret = TRUE;
}
buf_pool_mutex_exit(buf_pool);
}
return(ret);
}
/******************************************************************//**
Returns a free block from the buf_pool. The block is taken off the
free list. If it is empty, returns NULL.
@return a free control block, or NULL if the buf_block->free list is empty */
buf_block_t*
buf_LRU_get_free_only(
/*==================*/
buf_pool_t* buf_pool)
{
buf_block_t* block;
ut_ad(buf_pool_mutex_own(buf_pool));
block = reinterpret_cast<buf_block_t*>(
UT_LIST_GET_FIRST(buf_pool->free));
while (block != NULL) {
ut_ad(block->page.in_free_list);
ut_d(block->page.in_free_list = FALSE);
ut_ad(!block->page.in_flush_list);
ut_ad(!block->page.in_LRU_list);
ut_a(!buf_page_in_file(&block->page));
UT_LIST_REMOVE(buf_pool->free, &block->page);
if (buf_pool->curr_size >= buf_pool->old_size
|| UT_LIST_GET_LEN(buf_pool->withdraw)
>= buf_pool->withdraw_target
|| !buf_block_will_withdrawn(buf_pool, block)) {
/* found valid free block */
buf_page_mutex_enter(block);
buf_block_set_state(block, BUF_BLOCK_READY_FOR_USE);
UNIV_MEM_ALLOC(block->frame, UNIV_PAGE_SIZE);
ut_ad(buf_pool_from_block(block) == buf_pool);
buf_page_mutex_exit(block);
break;
}
/* This should be withdrawn */
UT_LIST_ADD_LAST(
buf_pool->withdraw,
&block->page);
ut_d(block->in_withdraw_list = TRUE);
block = reinterpret_cast<buf_block_t*>(
UT_LIST_GET_FIRST(buf_pool->free));
}
return(block);
}
/******************************************************************//**
Checks how much of buf_pool is occupied by non-data objects like
AHI, lock heaps etc. Depending on the size of non-data objects this
function will either assert or issue a warning and switch on the
status monitor. */
static
void
buf_LRU_check_size_of_non_data_objects(
/*===================================*/
const buf_pool_t* buf_pool) /*!< in: buffer pool instance */
{
ut_ad(buf_pool_mutex_own(buf_pool));
if (!recv_recovery_is_on()
&& buf_pool->curr_size == buf_pool->old_size
&& UT_LIST_GET_LEN(buf_pool->free)
+ UT_LIST_GET_LEN(buf_pool->LRU) < buf_pool->curr_size / 20) {
ib::fatal() << "Over 95 percent of the buffer pool is"
" occupied by lock heaps or the adaptive hash index!"
" Check that your transactions do not set too many"
" row locks. Your buffer pool size is "
<< (buf_pool->curr_size
/ (1024 * 1024 / UNIV_PAGE_SIZE)) << " MB."
" Maybe you should make the buffer pool bigger?"
" We intentionally generate a seg fault to print"
" a stack trace on Linux!";
} else if (!recv_recovery_is_on()
&& buf_pool->curr_size == buf_pool->old_size
&& (UT_LIST_GET_LEN(buf_pool->free)
+ UT_LIST_GET_LEN(buf_pool->LRU))
< buf_pool->curr_size / 3) {
if (!buf_lru_switched_on_innodb_mon) {
/* Over 67 % of the buffer pool is occupied by lock
heaps or the adaptive hash index. This may be a memory
leak! */
ib::warn() << "Over 67 percent of the buffer pool is"
" occupied by lock heaps or the adaptive hash"
" index! Check that your transactions do not"
" set too many row locks. Your buffer pool"
" size is "
<< (buf_pool->curr_size
/ (1024 * 1024 / UNIV_PAGE_SIZE))
<< " MB. Maybe you should make the buffer pool"
" bigger?. Starting the InnoDB Monitor to print"
" diagnostics, including lock heap and hash"
" index sizes.";
buf_lru_switched_on_innodb_mon = true;
srv_print_innodb_monitor = TRUE;
os_event_set(lock_sys->timeout_event);
}
} else if (buf_lru_switched_on_innodb_mon) {
/* Switch off the InnoDB Monitor; this is a simple way
to stop the monitor if the situation becomes less urgent,
but may also surprise users if the user also switched on the
monitor! */
buf_lru_switched_on_innodb_mon = false;
srv_print_innodb_monitor = FALSE;
}
}
/******************************************************************//**
Returns a free block from the buf_pool. The block is taken off the
free list. If free list is empty, blocks are moved from the end of the
LRU list to the free list.
This function is called from a user thread when it needs a clean
block to read in a page. Note that we only ever get a block from
the free list. Even when we flush a page or find a page in LRU scan
we put it to free list to be used.
* iteration 0:
* get a block from free list, success:done
* if buf_pool->try_LRU_scan is set
* scan LRU up to srv_LRU_scan_depth to find a clean block
* the above will put the block on free list
* success:retry the free list
* flush one dirty page from tail of LRU to disk
* the above will put the block on free list
* success: retry the free list
* iteration 1:
* same as iteration 0 except:
* scan whole LRU list
* scan LRU list even if buf_pool->try_LRU_scan is not set
* iteration > 1:
* same as iteration 1 but sleep 10ms
@return the free control block, in state BUF_BLOCK_READY_FOR_USE */
buf_block_t*
buf_LRU_get_free_block(
/*===================*/
buf_pool_t* buf_pool) /*!< in/out: buffer pool instance */
{
buf_block_t* block = NULL;
bool freed = false;
ulint n_iterations = 0;
ulint flush_failures = 0;
bool mon_value_was = false;
bool started_monitor = false;
MONITOR_INC(MONITOR_LRU_GET_FREE_SEARCH);
loop:
buf_pool_mutex_enter(buf_pool);
buf_LRU_check_size_of_non_data_objects(buf_pool);
/* If there is a block in the free list, take it */
block = buf_LRU_get_free_only(buf_pool);
if (block != NULL) {
buf_pool_mutex_exit(buf_pool);
ut_ad(buf_pool_from_block(block) == buf_pool);
memset(&block->page.zip, 0, sizeof block->page.zip);
if (started_monitor) {
srv_print_innodb_monitor =
static_cast<my_bool>(mon_value_was);
}
block->skip_flush_check = false;
block->page.flush_observer = NULL;
return(block);
}
MONITOR_INC( MONITOR_LRU_GET_FREE_LOOPS );
freed = false;
if (buf_pool->try_LRU_scan || n_iterations > 0) {
/* If no block was in the free list, search from the
end of the LRU list and try to free a block there.
If we are doing for the first time we'll scan only
tail of the LRU list otherwise we scan the whole LRU
list. */
freed = buf_LRU_scan_and_free_block(
buf_pool, n_iterations > 0);
if (!freed && n_iterations == 0) {
/* Tell other threads that there is no point
in scanning the LRU list. This flag is set to
TRUE again when we flush a batch from this
buffer pool. */
buf_pool->try_LRU_scan = FALSE;
}
}
buf_pool_mutex_exit(buf_pool);
if (freed) {
goto loop;
}
if (n_iterations > 20
&& srv_buf_pool_old_size == srv_buf_pool_size) {
ib::warn() << "Difficult to find free blocks in the buffer pool"
" (" << n_iterations << " search iterations)! "
<< flush_failures << " failed attempts to"
" flush a page! Consider increasing the buffer pool"
" size. It is also possible that in your Unix version"
" fsync is very slow, or completely frozen inside"
" the OS kernel. Then upgrading to a newer version"
" of your operating system may help. Look at the"
" number of fsyncs in diagnostic info below."
" Pending flushes (fsync) log: "
<< fil_n_pending_log_flushes
<< "; buffer pool: "
<< fil_n_pending_tablespace_flushes
<< ". " << os_n_file_reads << " OS file reads, "
<< os_n_file_writes << " OS file writes, "
<< os_n_fsyncs
<< " OS fsyncs. Starting InnoDB Monitor to print"
" further diagnostics to the standard output.";
mon_value_was = srv_print_innodb_monitor;
started_monitor = true;
srv_print_innodb_monitor = true;
os_event_set(lock_sys->timeout_event);
}
/* If we have scanned the whole LRU and still are unable to
find a free block then we should sleep here to let the
page_cleaner do an LRU batch for us. */
if (!srv_read_only_mode) {
os_event_set(buf_flush_event);
}
if (n_iterations > 1) {
MONITOR_INC( MONITOR_LRU_GET_FREE_WAITS );
os_thread_sleep(10000);
}
/* No free block was found: try to flush the LRU list.
This call will flush one page from the LRU and put it on the
free list. That means that the free block is up for grabs for
all user threads.
TODO: A more elegant way would have been to return the freed
up block to the caller here but the code that deals with
removing the block from page_hash and LRU_list is fairly
involved (particularly in case of compressed pages). We
can do that in a separate patch sometime in future. */
if (!buf_flush_single_page_from_LRU(buf_pool)) {
MONITOR_INC(MONITOR_LRU_SINGLE_FLUSH_FAILURE_COUNT);
++flush_failures;
}
srv_stats.buf_pool_wait_free.add(n_iterations, 1);
n_iterations++;
goto loop;
}
/*******************************************************************//**
Moves the LRU_old pointer so that the length of the old blocks list
is inside the allowed limits. */
UNIV_INLINE
void
buf_LRU_old_adjust_len(
/*===================*/
buf_pool_t* buf_pool) /*!< in: buffer pool instance */
{
ulint old_len;
ulint new_len;
ut_a(buf_pool->LRU_old);
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(buf_pool->LRU_old_ratio >= BUF_LRU_OLD_RATIO_MIN);
ut_ad(buf_pool->LRU_old_ratio <= BUF_LRU_OLD_RATIO_MAX);
#if BUF_LRU_OLD_RATIO_MIN * BUF_LRU_OLD_MIN_LEN <= BUF_LRU_OLD_RATIO_DIV * (BUF_LRU_OLD_TOLERANCE + 5)
# error "BUF_LRU_OLD_RATIO_MIN * BUF_LRU_OLD_MIN_LEN <= BUF_LRU_OLD_RATIO_DIV * (BUF_LRU_OLD_TOLERANCE + 5)"
#endif
#ifdef UNIV_LRU_DEBUG
/* buf_pool->LRU_old must be the first item in the LRU list
whose "old" flag is set. */
ut_a(buf_pool->LRU_old->old);
ut_a(!UT_LIST_GET_PREV(LRU, buf_pool->LRU_old)
|| !UT_LIST_GET_PREV(LRU, buf_pool->LRU_old)->old);
ut_a(!UT_LIST_GET_NEXT(LRU, buf_pool->LRU_old)
|| UT_LIST_GET_NEXT(LRU, buf_pool->LRU_old)->old);
#endif /* UNIV_LRU_DEBUG */
old_len = buf_pool->LRU_old_len;
new_len = ut_min(UT_LIST_GET_LEN(buf_pool->LRU)
* buf_pool->LRU_old_ratio / BUF_LRU_OLD_RATIO_DIV,
UT_LIST_GET_LEN(buf_pool->LRU)
- (BUF_LRU_OLD_TOLERANCE
+ BUF_LRU_NON_OLD_MIN_LEN));
for (;;) {
buf_page_t* LRU_old = buf_pool->LRU_old;
ut_a(LRU_old);
ut_ad(LRU_old->in_LRU_list);
#ifdef UNIV_LRU_DEBUG
ut_a(LRU_old->old);
#endif /* UNIV_LRU_DEBUG */
/* Update the LRU_old pointer if necessary */
if (old_len + BUF_LRU_OLD_TOLERANCE < new_len) {
buf_pool->LRU_old = LRU_old = UT_LIST_GET_PREV(
LRU, LRU_old);
#ifdef UNIV_LRU_DEBUG
ut_a(!LRU_old->old);
#endif /* UNIV_LRU_DEBUG */
old_len = ++buf_pool->LRU_old_len;
buf_page_set_old(LRU_old, TRUE);
} else if (old_len > new_len + BUF_LRU_OLD_TOLERANCE) {
buf_pool->LRU_old = UT_LIST_GET_NEXT(LRU, LRU_old);
old_len = --buf_pool->LRU_old_len;
buf_page_set_old(LRU_old, FALSE);
} else {
return;
}
}
}
/*******************************************************************//**
Initializes the old blocks pointer in the LRU list. This function should be
called when the LRU list grows to BUF_LRU_OLD_MIN_LEN length. */
static
void
buf_LRU_old_init(
/*=============*/
buf_pool_t* buf_pool)
{
ut_ad(buf_pool_mutex_own(buf_pool));
ut_a(UT_LIST_GET_LEN(buf_pool->LRU) == BUF_LRU_OLD_MIN_LEN);
/* We first initialize all blocks in the LRU list as old and then use
the adjust function to move the LRU_old pointer to the right
position */
for (buf_page_t* bpage = UT_LIST_GET_LAST(buf_pool->LRU);
bpage != NULL;
bpage = UT_LIST_GET_PREV(LRU, bpage)) {
ut_ad(bpage->in_LRU_list);
ut_ad(buf_page_in_file(bpage));
/* This loop temporarily violates the
assertions of buf_page_set_old(). */
bpage->old = TRUE;
}
buf_pool->LRU_old = UT_LIST_GET_FIRST(buf_pool->LRU);
buf_pool->LRU_old_len = UT_LIST_GET_LEN(buf_pool->LRU);
buf_LRU_old_adjust_len(buf_pool);
}
/******************************************************************//**
Remove a block from the unzip_LRU list if it belonged to the list. */
static
void
buf_unzip_LRU_remove_block_if_needed(
/*=================================*/
buf_page_t* bpage) /*!< in/out: control block */
{
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
ut_ad(buf_page_in_file(bpage));
ut_ad(buf_pool_mutex_own(buf_pool));
if (buf_page_belongs_to_unzip_LRU(bpage)) {
buf_block_t* block = reinterpret_cast<buf_block_t*>(bpage);
ut_ad(block->in_unzip_LRU_list);
ut_d(block->in_unzip_LRU_list = FALSE);
UT_LIST_REMOVE(buf_pool->unzip_LRU, block);
}
}
/******************************************************************//**
Adjust LRU hazard pointers if needed. */
void
buf_LRU_adjust_hp(
/*==============*/
buf_pool_t* buf_pool,/*!< in: buffer pool instance */
const buf_page_t* bpage) /*!< in: control block */
{
buf_pool->lru_hp.adjust(bpage);
buf_pool->lru_scan_itr.adjust(bpage);
buf_pool->single_scan_itr.adjust(bpage);
}
/******************************************************************//**
Removes a block from the LRU list. */
UNIV_INLINE
void
buf_LRU_remove_block(
/*=================*/
buf_page_t* bpage) /*!< in: control block */
{
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
ut_ad(buf_pool_mutex_own(buf_pool));
ut_a(buf_page_in_file(bpage));
ut_ad(bpage->in_LRU_list);
/* Important that we adjust the hazard pointers before removing
bpage from the LRU list. */
buf_LRU_adjust_hp(buf_pool, bpage);
/* If the LRU_old pointer is defined and points to just this block,
move it backward one step */
if (bpage == buf_pool->LRU_old) {
/* Below: the previous block is guaranteed to exist,
because the LRU_old pointer is only allowed to differ
by BUF_LRU_OLD_TOLERANCE from strict
buf_pool->LRU_old_ratio/BUF_LRU_OLD_RATIO_DIV of the LRU
list length. */
buf_page_t* prev_bpage = UT_LIST_GET_PREV(LRU, bpage);
ut_a(prev_bpage);
#ifdef UNIV_LRU_DEBUG
ut_a(!prev_bpage->old);
#endif /* UNIV_LRU_DEBUG */
buf_pool->LRU_old = prev_bpage;
buf_page_set_old(prev_bpage, TRUE);
buf_pool->LRU_old_len++;
}
/* Remove the block from the LRU list */
UT_LIST_REMOVE(buf_pool->LRU, bpage);
ut_d(bpage->in_LRU_list = FALSE);
buf_pool->stat.LRU_bytes -= bpage->size.physical();
buf_unzip_LRU_remove_block_if_needed(bpage);
/* If the LRU list is so short that LRU_old is not defined,
clear the "old" flags and return */
if (UT_LIST_GET_LEN(buf_pool->LRU) < BUF_LRU_OLD_MIN_LEN) {
for (buf_page_t* bpage = UT_LIST_GET_FIRST(buf_pool->LRU);
bpage != NULL;
bpage = UT_LIST_GET_NEXT(LRU, bpage)) {
/* This loop temporarily violates the
assertions of buf_page_set_old(). */
bpage->old = FALSE;
}
buf_pool->LRU_old = NULL;
buf_pool->LRU_old_len = 0;
return;
}
ut_ad(buf_pool->LRU_old);
/* Update the LRU_old_len field if necessary */
if (buf_page_is_old(bpage)) {
buf_pool->LRU_old_len--;
}
/* Adjust the length of the old block list if necessary */
buf_LRU_old_adjust_len(buf_pool);
}
/******************************************************************//**
Adds a block to the LRU list of decompressed zip pages. */
void
buf_unzip_LRU_add_block(
/*====================*/
buf_block_t* block, /*!< in: control block */
ibool old) /*!< in: TRUE if should be put to the end
of the list, else put to the start */
{
buf_pool_t* buf_pool = buf_pool_from_block(block);
ut_ad(buf_pool_mutex_own(buf_pool));
ut_a(buf_page_belongs_to_unzip_LRU(&block->page));
ut_ad(!block->in_unzip_LRU_list);
ut_d(block->in_unzip_LRU_list = TRUE);
if (old) {
UT_LIST_ADD_LAST(buf_pool->unzip_LRU, block);
} else {
UT_LIST_ADD_FIRST(buf_pool->unzip_LRU, block);
}
}
/******************************************************************//**
Adds a block to the LRU list end. Please make sure that the page_size is
already set when invoking the function, so that we can get correct
page_size from the buffer page when adding a block into LRU */
static
void
buf_LRU_add_block_to_end_low(
/*=========================*/
buf_page_t* bpage) /*!< in: control block */
{
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
ut_ad(buf_pool_mutex_own(buf_pool));
ut_a(buf_page_in_file(bpage));
ut_ad(!bpage->in_LRU_list);
UT_LIST_ADD_LAST(buf_pool->LRU, bpage);
ut_d(bpage->in_LRU_list = TRUE);
incr_LRU_size_in_bytes(bpage, buf_pool);
if (UT_LIST_GET_LEN(buf_pool->LRU) > BUF_LRU_OLD_MIN_LEN) {
ut_ad(buf_pool->LRU_old);
/* Adjust the length of the old block list if necessary */
buf_page_set_old(bpage, TRUE);
buf_pool->LRU_old_len++;
buf_LRU_old_adjust_len(buf_pool);
} else if (UT_LIST_GET_LEN(buf_pool->LRU) == BUF_LRU_OLD_MIN_LEN) {
/* The LRU list is now long enough for LRU_old to become
defined: init it */
buf_LRU_old_init(buf_pool);
} else {
buf_page_set_old(bpage, buf_pool->LRU_old != NULL);
}
/* If this is a zipped block with decompressed frame as well
then put it on the unzip_LRU list */
if (buf_page_belongs_to_unzip_LRU(bpage)) {
buf_unzip_LRU_add_block((buf_block_t*) bpage, TRUE);
}
}
/******************************************************************//**
Adds a block to the LRU list. Please make sure that the page_size is
already set when invoking the function, so that we can get correct
page_size from the buffer page when adding a block into LRU */
UNIV_INLINE
void
buf_LRU_add_block_low(
/*==================*/
buf_page_t* bpage, /*!< in: control block */
ibool old) /*!< in: TRUE if should be put to the old blocks
in the LRU list, else put to the start; if the
LRU list is very short, the block is added to
the start, regardless of this parameter */
{
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
ut_ad(buf_pool_mutex_own(buf_pool));
ut_a(buf_page_in_file(bpage));
ut_ad(!bpage->in_LRU_list);
if (!old || (UT_LIST_GET_LEN(buf_pool->LRU) < BUF_LRU_OLD_MIN_LEN)) {
UT_LIST_ADD_FIRST(buf_pool->LRU, bpage);
bpage->freed_page_clock = buf_pool->freed_page_clock;
} else {
#ifdef UNIV_LRU_DEBUG
/* buf_pool->LRU_old must be the first item in the LRU list
whose "old" flag is set. */
ut_a(buf_pool->LRU_old->old);
ut_a(!UT_LIST_GET_PREV(LRU, buf_pool->LRU_old)
|| !UT_LIST_GET_PREV(LRU, buf_pool->LRU_old)->old);
ut_a(!UT_LIST_GET_NEXT(LRU, buf_pool->LRU_old)
|| UT_LIST_GET_NEXT(LRU, buf_pool->LRU_old)->old);
#endif /* UNIV_LRU_DEBUG */
UT_LIST_INSERT_AFTER(buf_pool->LRU, buf_pool->LRU_old,
bpage);
buf_pool->LRU_old_len++;
}
ut_d(bpage->in_LRU_list = TRUE);
incr_LRU_size_in_bytes(bpage, buf_pool);
if (UT_LIST_GET_LEN(buf_pool->LRU) > BUF_LRU_OLD_MIN_LEN) {
ut_ad(buf_pool->LRU_old);
/* Adjust the length of the old block list if necessary */
buf_page_set_old(bpage, old);
buf_LRU_old_adjust_len(buf_pool);
} else if (UT_LIST_GET_LEN(buf_pool->LRU) == BUF_LRU_OLD_MIN_LEN) {
/* The LRU list is now long enough for LRU_old to become
defined: init it */
buf_LRU_old_init(buf_pool);
} else {
buf_page_set_old(bpage, buf_pool->LRU_old != NULL);
}
/* If this is a zipped block with decompressed frame as well
then put it on the unzip_LRU list */
if (buf_page_belongs_to_unzip_LRU(bpage)) {
buf_unzip_LRU_add_block((buf_block_t*) bpage, old);
}
}
/******************************************************************//**
Adds a block to the LRU list. Please make sure that the page_size is
already set when invoking the function, so that we can get correct
page_size from the buffer page when adding a block into LRU */
void
buf_LRU_add_block(
/*==============*/
buf_page_t* bpage, /*!< in: control block */
ibool old) /*!< in: TRUE if should be put to the old
blocks in the LRU list, else put to the start;
if the LRU list is very short, the block is
added to the start, regardless of this
parameter */
{
buf_LRU_add_block_low(bpage, old);
}
/******************************************************************//**
Moves a block to the start of the LRU list. */
void
buf_LRU_make_block_young(
/*=====================*/
buf_page_t* bpage) /*!< in: control block */
{
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
ut_ad(buf_pool_mutex_own(buf_pool));
if (bpage->old) {
buf_pool->stat.n_pages_made_young++;
}
buf_LRU_remove_block(bpage);
buf_LRU_add_block_low(bpage, FALSE);
}
/******************************************************************//**
Moves a block to the end of the LRU list. */
void
buf_LRU_make_block_old(
/*===================*/
buf_page_t* bpage) /*!< in: control block */
{
buf_LRU_remove_block(bpage);
buf_LRU_add_block_to_end_low(bpage);
}
/******************************************************************//**
Try to free a block. If bpage is a descriptor of a compressed-only
page, the descriptor object will be freed as well.
NOTE: If this function returns true, it will temporarily
release buf_pool->mutex. Furthermore, the page frame will no longer be
accessible via bpage.
The caller must hold buf_pool->mutex and must not hold any
buf_page_get_mutex() when calling this function.
@return true if freed, false otherwise. */
bool
buf_LRU_free_page(
/*===============*/
buf_page_t* bpage, /*!< in: block to be freed */
bool zip) /*!< in: true if should remove also the
compressed page of an uncompressed page */
{
buf_page_t* b = NULL;
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
rw_lock_t* hash_lock = buf_page_hash_lock_get(buf_pool, bpage->id);
BPageMutex* block_mutex = buf_page_get_mutex(bpage);
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(buf_page_in_file(bpage));
ut_ad(bpage->in_LRU_list);
rw_lock_x_lock(hash_lock);
mutex_enter(block_mutex);
if (!buf_page_can_relocate(bpage)) {
/* Do not free buffer fixed and I/O-fixed blocks. */
goto func_exit;
}
#ifdef UNIV_IBUF_COUNT_DEBUG
ut_a(ibuf_count_get(bpage->id) == 0);
#endif /* UNIV_IBUF_COUNT_DEBUG */
if (zip || !bpage->zip.data) {
/* This would completely free the block. */
/* Do not completely free dirty blocks. */
if (bpage->oldest_modification) {
goto func_exit;
}
} else if (bpage->oldest_modification > 0
&& buf_page_get_state(bpage) != BUF_BLOCK_FILE_PAGE) {
ut_ad(buf_page_get_state(bpage) == BUF_BLOCK_ZIP_DIRTY);
func_exit:
rw_lock_x_unlock(hash_lock);
mutex_exit(block_mutex);
return(false);
} else if (buf_page_get_state(bpage) == BUF_BLOCK_FILE_PAGE) {
b = buf_page_alloc_descriptor();
ut_a(b);
memcpy(b, bpage, sizeof *b);
}
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(buf_page_in_file(bpage));
ut_ad(bpage->in_LRU_list);
ut_ad(!bpage->in_flush_list == !bpage->oldest_modification);
DBUG_PRINT("ib_buf", ("free page " UINT32PF ":" UINT32PF,
bpage->id.space(), bpage->id.page_no()));
ut_ad(rw_lock_own(hash_lock, RW_LOCK_X));
ut_ad(buf_page_can_relocate(bpage));
if (!buf_LRU_block_remove_hashed(bpage, zip)) {
return(true);
}
/* buf_LRU_block_remove_hashed() releases the hash_lock */
ut_ad(!rw_lock_own(hash_lock, RW_LOCK_X)
&& !rw_lock_own(hash_lock, RW_LOCK_S));
/* We have just freed a BUF_BLOCK_FILE_PAGE. If b != NULL
then it was a compressed page with an uncompressed frame and
we are interested in freeing only the uncompressed frame.
Therefore we have to reinsert the compressed page descriptor
into the LRU and page_hash (and possibly flush_list).
if b == NULL then it was a regular page that has been freed */
if (b != NULL) {
buf_page_t* prev_b = UT_LIST_GET_PREV(LRU, b);
rw_lock_x_lock(hash_lock);
mutex_enter(block_mutex);
ut_a(!buf_page_hash_get_low(buf_pool, b->id));
b->state = b->oldest_modification
? BUF_BLOCK_ZIP_DIRTY
: BUF_BLOCK_ZIP_PAGE;
ut_ad(b->size.is_compressed());
UNIV_MEM_DESC(b->zip.data, b->size.physical());
/* The fields in_page_hash and in_LRU_list of
the to-be-freed block descriptor should have
been cleared in
buf_LRU_block_remove_hashed(), which
invokes buf_LRU_remove_block(). */
ut_ad(!bpage->in_page_hash);
ut_ad(!bpage->in_LRU_list);
/* bpage->state was BUF_BLOCK_FILE_PAGE because
b != NULL. The type cast below is thus valid. */
ut_ad(!((buf_block_t*) bpage)->in_unzip_LRU_list);
/* The fields of bpage were copied to b before
buf_LRU_block_remove_hashed() was invoked. */
ut_ad(!b->in_zip_hash);
ut_ad(b->in_page_hash);
ut_ad(b->in_LRU_list);
HASH_INSERT(buf_page_t, hash, buf_pool->page_hash,
b->id.fold(), b);
/* Insert b where bpage was in the LRU list. */
if (prev_b != NULL) {
ulint lru_len;
ut_ad(prev_b->in_LRU_list);
ut_ad(buf_page_in_file(prev_b));
UT_LIST_INSERT_AFTER(buf_pool->LRU, prev_b, b);
incr_LRU_size_in_bytes(b, buf_pool);
if (buf_page_is_old(b)) {
buf_pool->LRU_old_len++;
if (buf_pool->LRU_old
== UT_LIST_GET_NEXT(LRU, b)) {
buf_pool->LRU_old = b;
}
}
lru_len = UT_LIST_GET_LEN(buf_pool->LRU);
if (lru_len > BUF_LRU_OLD_MIN_LEN) {
ut_ad(buf_pool->LRU_old);
/* Adjust the length of the
old block list if necessary */
buf_LRU_old_adjust_len(buf_pool);
} else if (lru_len == BUF_LRU_OLD_MIN_LEN) {
/* The LRU list is now long
enough for LRU_old to become
defined: init it */
buf_LRU_old_init(buf_pool);
}
#ifdef UNIV_LRU_DEBUG
/* Check that the "old" flag is consistent
in the block and its neighbours. */
buf_page_set_old(b, buf_page_is_old(b));
#endif /* UNIV_LRU_DEBUG */
} else {
ut_d(b->in_LRU_list = FALSE);
buf_LRU_add_block_low(b, buf_page_is_old(b));
}
if (b->state == BUF_BLOCK_ZIP_PAGE) {
#if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
buf_LRU_insert_zip_clean(b);
#endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
} else {
/* Relocate on buf_pool->flush_list. */
buf_flush_relocate_on_flush_list(bpage, b);
}
bpage->zip.data = NULL;
page_zip_set_size(&bpage->zip, 0);
bpage->size.copy_from(page_size_t(bpage->size.logical(),
bpage->size.logical(),
false));
mutex_exit(block_mutex);
/* Prevent buf_page_get_gen() from
decompressing the block while we release
buf_pool->mutex and block_mutex. */
block_mutex = buf_page_get_mutex(b);
mutex_enter(block_mutex);
buf_page_set_sticky(b);
mutex_exit(block_mutex);
rw_lock_x_unlock(hash_lock);
}
buf_pool_mutex_exit(buf_pool);
/* Remove possible adaptive hash index on the page.
The page was declared uninitialized by
buf_LRU_block_remove_hashed(). We need to flag
the contents of the page valid (which it still is) in
order to avoid bogus Valgrind warnings.*/
UNIV_MEM_VALID(((buf_block_t*) bpage)->frame,
UNIV_PAGE_SIZE);
btr_search_drop_page_hash_index((buf_block_t*) bpage);
UNIV_MEM_INVALID(((buf_block_t*) bpage)->frame,
UNIV_PAGE_SIZE);
if (b != NULL) {
/* Compute and stamp the compressed page
checksum while not holding any mutex. The
block is already half-freed
(BUF_BLOCK_REMOVE_HASH) and removed from
buf_pool->page_hash, thus inaccessible by any
other thread. */
ut_ad(b->size.is_compressed());
const uint32_t checksum = page_zip_calc_checksum(
b->zip.data,
b->size.physical(),
static_cast<srv_checksum_algorithm_t>(
srv_checksum_algorithm));
mach_write_to_4(b->zip.data + FIL_PAGE_SPACE_OR_CHKSUM,
checksum);
}
buf_pool_mutex_enter(buf_pool);
if (b != NULL) {
mutex_enter(block_mutex);
buf_page_unset_sticky(b);
mutex_exit(block_mutex);
}
buf_LRU_block_free_hashed_page((buf_block_t*) bpage);
return(true);
}
/******************************************************************//**
Puts a block back to the free list. */
void
buf_LRU_block_free_non_file_page(
/*=============================*/
buf_block_t* block) /*!< in: block, must not contain a file page */
{
void* data;
buf_pool_t* buf_pool = buf_pool_from_block(block);
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(buf_page_mutex_own(block));
switch (buf_block_get_state(block)) {
case BUF_BLOCK_MEMORY:
case BUF_BLOCK_READY_FOR_USE:
break;
default:
ut_error;
}
#if defined UNIV_AHI_DEBUG || defined UNIV_DEBUG
ut_a(block->n_pointers == 0);
#endif /* UNIV_AHI_DEBUG || UNIV_DEBUG */
ut_ad(!block->page.in_free_list);
ut_ad(!block->page.in_flush_list);
ut_ad(!block->page.in_LRU_list);
buf_block_set_state(block, BUF_BLOCK_NOT_USED);
UNIV_MEM_ALLOC(block->frame, UNIV_PAGE_SIZE);
#ifdef UNIV_DEBUG
/* Wipe contents of page to reveal possible stale pointers to it */
memset(block->frame, '\0', UNIV_PAGE_SIZE);
#else
/* Wipe page_no and space_id */
memset(block->frame + FIL_PAGE_OFFSET, 0xfe, 4);
memset(block->frame + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, 0xfe, 4);
#endif /* UNIV_DEBUG */
data = block->page.zip.data;
if (data != NULL) {
block->page.zip.data = NULL;
buf_page_mutex_exit(block);
buf_pool_mutex_exit_forbid(buf_pool);
ut_ad(block->page.size.is_compressed());
buf_buddy_free(buf_pool, data, block->page.size.physical());
buf_pool_mutex_exit_allow(buf_pool);
buf_page_mutex_enter(block);
page_zip_set_size(&block->page.zip, 0);
block->page.size.copy_from(
page_size_t(block->page.size.logical(),
block->page.size.logical(),
false));
}
if (buf_pool->curr_size < buf_pool->old_size
&& UT_LIST_GET_LEN(buf_pool->withdraw) < buf_pool->withdraw_target
&& buf_block_will_withdrawn(buf_pool, block)) {
/* This should be withdrawn */
UT_LIST_ADD_LAST(
buf_pool->withdraw,
&block->page);
ut_d(block->in_withdraw_list = TRUE);
} else {
UT_LIST_ADD_FIRST(buf_pool->free, &block->page);
ut_d(block->page.in_free_list = TRUE);
}
UNIV_MEM_ASSERT_AND_FREE(block->frame, UNIV_PAGE_SIZE);
}
/******************************************************************//**
Takes a block out of the LRU list and page hash table.
If the block is compressed-only (BUF_BLOCK_ZIP_PAGE),
the object will be freed.
The caller must hold buf_pool->mutex, the buf_page_get_mutex() mutex
and the appropriate hash_lock. This function will release the
buf_page_get_mutex() and the hash_lock.
If a compressed page is freed other compressed pages may be relocated.
@retval true if BUF_BLOCK_FILE_PAGE was removed from page_hash. The
caller needs to free the page to the free list
@retval false if BUF_BLOCK_ZIP_PAGE was removed from page_hash. In
this case the block is already returned to the buddy allocator. */
static
bool
buf_LRU_block_remove_hashed(
/*========================*/
buf_page_t* bpage, /*!< in: block, must contain a file page and
be in a state where it can be freed; there
may or may not be a hash index to the page */
bool zip) /*!< in: true if should remove also the
compressed page of an uncompressed page */
{
const buf_page_t* hashed_bpage;
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
rw_lock_t* hash_lock;
ut_ad(buf_pool_mutex_own(buf_pool));
ut_ad(mutex_own(buf_page_get_mutex(bpage)));
hash_lock = buf_page_hash_lock_get(buf_pool, bpage->id);
ut_ad(rw_lock_own(hash_lock, RW_LOCK_X));
ut_a(buf_page_get_io_fix(bpage) == BUF_IO_NONE);
ut_a(bpage->buf_fix_count == 0);
buf_LRU_remove_block(bpage);
buf_pool->freed_page_clock += 1;
switch (buf_page_get_state(bpage)) {
case BUF_BLOCK_FILE_PAGE:
UNIV_MEM_ASSERT_W(bpage, sizeof(buf_block_t));
UNIV_MEM_ASSERT_W(((buf_block_t*) bpage)->frame,
UNIV_PAGE_SIZE);
buf_block_modify_clock_inc((buf_block_t*) bpage);
if (bpage->zip.data) {
const page_t* page = ((buf_block_t*) bpage)->frame;
ut_a(!zip || bpage->oldest_modification == 0);
ut_ad(bpage->size.is_compressed());
switch (fil_page_get_type(page)) {
case FIL_PAGE_TYPE_ALLOCATED:
case FIL_PAGE_INODE:
case FIL_PAGE_IBUF_BITMAP:
case FIL_PAGE_TYPE_FSP_HDR:
case FIL_PAGE_TYPE_XDES:
/* These are essentially uncompressed pages. */
if (!zip) {
/* InnoDB writes the data to the
uncompressed page frame. Copy it
to the compressed page, which will
be preserved. */
memcpy(bpage->zip.data, page,
bpage->size.physical());
}
break;
case FIL_PAGE_TYPE_ZBLOB:
case FIL_PAGE_TYPE_ZBLOB2:
break;
case FIL_PAGE_INDEX:
case FIL_PAGE_RTREE:
#ifdef UNIV_ZIP_DEBUG
ut_a(page_zip_validate(
&bpage->zip, page,
((buf_block_t*) bpage)->index));
#endif /* UNIV_ZIP_DEBUG */
break;
default:
ib::error() << "The compressed page to be"
" evicted seems corrupt:";
ut_print_buf(stderr, page,
bpage->size.logical());
ib::error() << "Possibly older version of"
" the page:";
ut_print_buf(stderr, bpage->zip.data,
bpage->size.physical());
putc('\n', stderr);
ut_error;
}
break;
}
/* fall through */
case BUF_BLOCK_ZIP_PAGE:
ut_a(bpage->oldest_modification == 0);
if (bpage->size.is_compressed()) {
UNIV_MEM_ASSERT_W(bpage->zip.data,
bpage->size.physical());
}
break;
case BUF_BLOCK_POOL_WATCH:
case BUF_BLOCK_ZIP_DIRTY:
case BUF_BLOCK_NOT_USED:
case BUF_BLOCK_READY_FOR_USE:
case BUF_BLOCK_MEMORY:
case BUF_BLOCK_REMOVE_HASH:
ut_error;
break;
}
hashed_bpage = buf_page_hash_get_low(buf_pool, bpage->id);
if (bpage != hashed_bpage) {
ib::error() << "Page " << bpage->id
<< " not found in the hash table";
if (hashed_bpage) {
ib::error() << "In hash table we find block "
<< hashed_bpage << " of " << hashed_bpage->id
<< " which is not " << bpage;
}
#if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
mutex_exit(buf_page_get_mutex(bpage));
rw_lock_x_unlock(hash_lock);
buf_pool_mutex_exit(buf_pool);
buf_print();
buf_LRU_print();
buf_validate();
buf_LRU_validate();
#endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
ut_error;
}
ut_ad(!bpage->in_zip_hash);
ut_ad(bpage->in_page_hash);
ut_d(bpage->in_page_hash = FALSE);
HASH_DELETE(buf_page_t, hash, buf_pool->page_hash, bpage->id.fold(),
bpage);
switch (buf_page_get_state(bpage)) {
case BUF_BLOCK_ZIP_PAGE:
ut_ad(!bpage->in_free_list);
ut_ad(!bpage->in_flush_list);
ut_ad(!bpage->in_LRU_list);
ut_a(bpage->zip.data);
ut_a(bpage->size.is_compressed());
#if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
UT_LIST_REMOVE(buf_pool->zip_clean, bpage);
#endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
mutex_exit(&buf_pool->zip_mutex);
rw_lock_x_unlock(hash_lock);
buf_pool_mutex_exit_forbid(buf_pool);
buf_buddy_free(buf_pool, bpage->zip.data,
bpage->size.physical());
buf_pool_mutex_exit_allow(buf_pool);
buf_page_free_descriptor(bpage);
return(false);
case BUF_BLOCK_FILE_PAGE:
memset(((buf_block_t*) bpage)->frame
+ FIL_PAGE_OFFSET, 0xff, 4);
memset(((buf_block_t*) bpage)->frame
+ FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, 0xff, 4);
UNIV_MEM_INVALID(((buf_block_t*) bpage)->frame,
UNIV_PAGE_SIZE);
buf_page_set_state(bpage, BUF_BLOCK_REMOVE_HASH);
/* Question: If we release bpage and hash mutex here
then what protects us against:
1) Some other thread buffer fixing this page
2) Some other thread trying to read this page and
not finding it in buffer pool attempting to read it
from the disk.
Answer:
1) Cannot happen because the page is no longer in the
page_hash. Only possibility is when while invalidating
a tablespace we buffer fix the prev_page in LRU to
avoid relocation during the scan. But that is not
possible because we are holding buf_pool mutex.
2) Not possible because in buf_page_init_for_read()
we do a look up of page_hash while holding buf_pool
mutex and since we are holding buf_pool mutex here
and by the time we'll release it in the caller we'd
have inserted the compressed only descriptor in the
page_hash. */
rw_lock_x_unlock(hash_lock);
mutex_exit(&((buf_block_t*) bpage)->mutex);
if (zip && bpage->zip.data) {
/* Free the compressed page. */
void* data = bpage->zip.data;
bpage->zip.data = NULL;
ut_ad(!bpage->in_free_list);
ut_ad(!bpage->in_flush_list);
ut_ad(!bpage->in_LRU_list);
buf_pool_mutex_exit_forbid(buf_pool);
buf_buddy_free(buf_pool, data, bpage->size.physical());
buf_pool_mutex_exit_allow(buf_pool);
page_zip_set_size(&bpage->zip, 0);
bpage->size.copy_from(
page_size_t(bpage->size.logical(),
bpage->size.logical(),
false));
}
return(true);
case BUF_BLOCK_POOL_WATCH:
case BUF_BLOCK_ZIP_DIRTY:
case BUF_BLOCK_NOT_USED:
case BUF_BLOCK_READY_FOR_USE:
case BUF_BLOCK_MEMORY:
case BUF_BLOCK_REMOVE_HASH:
break;
}
ut_error;
return(false);
}
/******************************************************************//**
Puts a file page whose has no hash index to the free list. */
static
void
buf_LRU_block_free_hashed_page(
/*===========================*/
buf_block_t* block) /*!< in: block, must contain a file page and
be in a state where it can be freed */
{
buf_pool_t* buf_pool = buf_pool_from_block(block);
ut_ad(buf_pool_mutex_own(buf_pool));
buf_page_mutex_enter(block);
if (buf_pool->flush_rbt == NULL) {
block->page.id.reset(ULINT32_UNDEFINED, ULINT32_UNDEFINED);
}
buf_block_set_state(block, BUF_BLOCK_MEMORY);
buf_LRU_block_free_non_file_page(block);
buf_page_mutex_exit(block);
}
/******************************************************************//**
Remove one page from LRU list and put it to free list */
void
buf_LRU_free_one_page(
/*==================*/
buf_page_t* bpage) /*!< in/out: block, must contain a file page and
be in a state where it can be freed; there
may or may not be a hash index to the page */
{
buf_pool_t* buf_pool = buf_pool_from_bpage(bpage);
rw_lock_t* hash_lock = buf_page_hash_lock_get(buf_pool, bpage->id);
BPageMutex* block_mutex = buf_page_get_mutex(bpage);
ut_ad(buf_pool_mutex_own(buf_pool));
rw_lock_x_lock(hash_lock);
mutex_enter(block_mutex);
if (buf_LRU_block_remove_hashed(bpage, true)) {
buf_LRU_block_free_hashed_page((buf_block_t*) bpage);
}
/* buf_LRU_block_remove_hashed() releases hash_lock and block_mutex */
ut_ad(!rw_lock_own(hash_lock, RW_LOCK_X)
&& !rw_lock_own(hash_lock, RW_LOCK_S));
ut_ad(!mutex_own(block_mutex));
}
/**********************************************************************//**
Updates buf_pool->LRU_old_ratio for one buffer pool instance.
@return updated old_pct */
static
uint
buf_LRU_old_ratio_update_instance(
/*==============================*/
buf_pool_t* buf_pool,/*!< in: buffer pool instance */
uint old_pct,/*!< in: Reserve this percentage of
the buffer pool for "old" blocks. */
ibool adjust) /*!< in: TRUE=adjust the LRU list;
FALSE=just assign buf_pool->LRU_old_ratio
during the initialization of InnoDB */
{
uint ratio;
ratio = old_pct * BUF_LRU_OLD_RATIO_DIV / 100;
if (ratio < BUF_LRU_OLD_RATIO_MIN) {
ratio = BUF_LRU_OLD_RATIO_MIN;
} else if (ratio > BUF_LRU_OLD_RATIO_MAX) {
ratio = BUF_LRU_OLD_RATIO_MAX;
}
if (adjust) {
buf_pool_mutex_enter(buf_pool);
if (ratio != buf_pool->LRU_old_ratio) {
buf_pool->LRU_old_ratio = ratio;
if (UT_LIST_GET_LEN(buf_pool->LRU)
>= BUF_LRU_OLD_MIN_LEN) {
buf_LRU_old_adjust_len(buf_pool);
}
}
buf_pool_mutex_exit(buf_pool);
} else {
buf_pool->LRU_old_ratio = ratio;
}
/* the reverse of
ratio = old_pct * BUF_LRU_OLD_RATIO_DIV / 100 */
return((uint) (ratio * 100 / (double) BUF_LRU_OLD_RATIO_DIV + 0.5));
}
/**********************************************************************//**
Updates buf_pool->LRU_old_ratio.
@return updated old_pct */
uint
buf_LRU_old_ratio_update(
/*=====================*/
uint old_pct,/*!< in: Reserve this percentage of
the buffer pool for "old" blocks. */
ibool adjust) /*!< in: TRUE=adjust the LRU list;
FALSE=just assign buf_pool->LRU_old_ratio
during the initialization of InnoDB */
{
uint new_ratio = 0;
for (ulint i = 0; i < srv_buf_pool_instances; i++) {
buf_pool_t* buf_pool;
buf_pool = buf_pool_from_array(i);
new_ratio = buf_LRU_old_ratio_update_instance(
buf_pool, old_pct, adjust);
}
return(new_ratio);
}
/********************************************************************//**
Update the historical stats that we are collecting for LRU eviction
policy at the end of each interval. */
void
buf_LRU_stat_update(void)
/*=====================*/
{
buf_LRU_stat_t* item;
buf_pool_t* buf_pool;
bool evict_started = FALSE;
buf_LRU_stat_t cur_stat;
/* If we haven't started eviction yet then don't update stats. */
for (ulint i = 0; i < srv_buf_pool_instances; i++) {
buf_pool = buf_pool_from_array(i);
if (buf_pool->freed_page_clock != 0) {
evict_started = true;
break;
}
}
if (!evict_started) {
goto func_exit;
}
/* Update the index. */
item = &buf_LRU_stat_arr[buf_LRU_stat_arr_ind];
buf_LRU_stat_arr_ind++;
buf_LRU_stat_arr_ind %= BUF_LRU_STAT_N_INTERVAL;
/* Add the current value and subtract the obsolete entry.
Since buf_LRU_stat_cur is not protected by any mutex,
it can be changing between adding to buf_LRU_stat_sum
and copying to item. Assign it to local variables to make
sure the same value assign to the buf_LRU_stat_sum
and item */
cur_stat = buf_LRU_stat_cur;
buf_LRU_stat_sum.io += cur_stat.io - item->io;
buf_LRU_stat_sum.unzip += cur_stat.unzip - item->unzip;
/* Put current entry in the array. */
memcpy(item, &cur_stat, sizeof *item);
func_exit:
/* Clear the current entry. */
memset(&buf_LRU_stat_cur, 0, sizeof buf_LRU_stat_cur);
}
#if defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
/**********************************************************************//**
Validates the LRU list for one buffer pool instance. */
static
void
buf_LRU_validate_instance(
/*======================*/
buf_pool_t* buf_pool)
{
ulint old_len;
ulint new_len;
buf_pool_mutex_enter(buf_pool);
if (UT_LIST_GET_LEN(buf_pool->LRU) >= BUF_LRU_OLD_MIN_LEN) {
ut_a(buf_pool->LRU_old);
old_len = buf_pool->LRU_old_len;
new_len = ut_min(UT_LIST_GET_LEN(buf_pool->LRU)
* buf_pool->LRU_old_ratio
/ BUF_LRU_OLD_RATIO_DIV,
UT_LIST_GET_LEN(buf_pool->LRU)
- (BUF_LRU_OLD_TOLERANCE
+ BUF_LRU_NON_OLD_MIN_LEN));
ut_a(old_len >= new_len - BUF_LRU_OLD_TOLERANCE);
ut_a(old_len <= new_len + BUF_LRU_OLD_TOLERANCE);
}
CheckInLRUList::validate(buf_pool);
old_len = 0;
for (buf_page_t* bpage = UT_LIST_GET_FIRST(buf_pool->LRU);
bpage != NULL;
bpage = UT_LIST_GET_NEXT(LRU, bpage)) {
switch (buf_page_get_state(bpage)) {
case BUF_BLOCK_POOL_WATCH:
case BUF_BLOCK_NOT_USED:
case BUF_BLOCK_READY_FOR_USE:
case BUF_BLOCK_MEMORY:
case BUF_BLOCK_REMOVE_HASH:
ut_error;
break;
case BUF_BLOCK_FILE_PAGE:
ut_ad(((buf_block_t*) bpage)->in_unzip_LRU_list
== buf_page_belongs_to_unzip_LRU(bpage));
case BUF_BLOCK_ZIP_PAGE:
case BUF_BLOCK_ZIP_DIRTY:
break;
}
if (buf_page_is_old(bpage)) {
const buf_page_t* prev
= UT_LIST_GET_PREV(LRU, bpage);
const buf_page_t* next
= UT_LIST_GET_NEXT(LRU, bpage);
if (!old_len++) {
ut_a(buf_pool->LRU_old == bpage);
} else {
ut_a(!prev || buf_page_is_old(prev));
}
ut_a(!next || buf_page_is_old(next));
}
}
ut_a(buf_pool->LRU_old_len == old_len);
CheckInFreeList::validate(buf_pool);
for (buf_page_t* bpage = UT_LIST_GET_FIRST(buf_pool->free);
bpage != NULL;
bpage = UT_LIST_GET_NEXT(list, bpage)) {
ut_a(buf_page_get_state(bpage) == BUF_BLOCK_NOT_USED);
}
CheckUnzipLRUAndLRUList::validate(buf_pool);
for (buf_block_t* block = UT_LIST_GET_FIRST(buf_pool->unzip_LRU);
block != NULL;
block = UT_LIST_GET_NEXT(unzip_LRU, block)) {
ut_ad(block->in_unzip_LRU_list);
ut_ad(block->page.in_LRU_list);
ut_a(buf_page_belongs_to_unzip_LRU(&block->page));
}
buf_pool_mutex_exit(buf_pool);
}
/**********************************************************************//**
Validates the LRU list.
@return TRUE */
ibool
buf_LRU_validate(void)
/*==================*/
{
for (ulint i = 0; i < srv_buf_pool_instances; i++) {
buf_pool_t* buf_pool;
buf_pool = buf_pool_from_array(i);
buf_LRU_validate_instance(buf_pool);
}
return(TRUE);
}
#endif /* UNIV_DEBUG || UNIV_BUF_DEBUG */
#if defined UNIV_DEBUG_PRINT || defined UNIV_DEBUG || defined UNIV_BUF_DEBUG
/**********************************************************************//**
Prints the LRU list for one buffer pool instance. */
void
buf_LRU_print_instance(
/*===================*/
buf_pool_t* buf_pool)
{
buf_pool_mutex_enter(buf_pool);
for (const buf_page_t* bpage = UT_LIST_GET_FIRST(buf_pool->LRU);
bpage != NULL;
bpage = UT_LIST_GET_NEXT(LRU, bpage)) {
mutex_enter(buf_page_get_mutex(bpage));
fprintf(stderr, "BLOCK space " UINT32PF " page " UINT32PF " ",
bpage->id.space(), bpage->id.page_no());
if (buf_page_is_old(bpage)) {
fputs("old ", stderr);
}
if (bpage->buf_fix_count) {
fprintf(stderr, "buffix count %lu ",
(ulong) bpage->buf_fix_count);
}
if (buf_page_get_io_fix(bpage)) {
fprintf(stderr, "io_fix %lu ",
(ulong) buf_page_get_io_fix(bpage));
}
if (bpage->oldest_modification) {
fputs("modif. ", stderr);
}
switch (buf_page_get_state(bpage)) {
const byte* frame;
case BUF_BLOCK_FILE_PAGE:
frame = buf_block_get_frame((buf_block_t*) bpage);
fprintf(stderr, "\ntype %lu"
" index id " IB_ID_FMT "\n",
(ulong) fil_page_get_type(frame),
btr_page_get_index_id(frame));
break;
case BUF_BLOCK_ZIP_PAGE:
frame = bpage->zip.data;
fprintf(stderr, "\ntype %lu size %lu"
" index id " IB_ID_FMT "\n",
(ulong) fil_page_get_type(frame),
(ulong) bpage->size.physical(),
btr_page_get_index_id(frame));
break;
default:
fprintf(stderr, "\n!state %lu!\n",
(ulong) buf_page_get_state(bpage));
break;
}
mutex_exit(buf_page_get_mutex(bpage));
}
buf_pool_mutex_exit(buf_pool);
}
/**********************************************************************//**
Prints the LRU list. */
void
buf_LRU_print(void)
/*===============*/
{
for (ulint i = 0; i < srv_buf_pool_instances; i++) {
buf_pool_t* buf_pool;
buf_pool = buf_pool_from_array(i);
buf_LRU_print_instance(buf_pool);
}
}
#endif /* UNIV_DEBUG_PRINT || UNIV_DEBUG || UNIV_BUF_DEBUG */
#endif /* !UNIV_HOTBACKUP */
|
/*
* Copyright (c) 2019, Intel Corporation
*
* 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 "MDF_FC_common_genx.h"
_GENX_MAIN_ void Y410_444Scale16_Buf_4_Rot_180(
CURBE_INPUT_OUTPUT,
GLOBAL_BUFFER_INPUT_OUTPUT)
{
#define Y410_SUPPORT
#define BUFFER_4
#define ROTATE_180
#include "PA_Scale_Buf.h"
#undef ROTATE_180
#undef BUFFER_4
#undef Y410_SUPPORT
}
|
// MIT License (c) 2019 BYU PCCL see LICENSE file
#include "Holodeck.h"
#include "HandAgentMaxTorqueFloat.h"
void UHandAgentMaxTorqueFloat::Execute(void* const CommandArray, void* const InputCommand, float DeltaSeconds) {
float* InputCommandFloat = static_cast<float*>(InputCommand);
// Call the other controller so it can do its thing
this->TorqueControlScheme->Execute(CommandArray, InputCommand, DeltaSeconds);
// Copy out the floating directions
// Floating around is handled by the HandAgent itself
for (int i = 0; i < 3; ++i) {
static_cast<float*>(CommandArray)[AHandAgent::TOTAL_JOINT_DOF + i] =
InputCommandFloat[AHandAgent::TOTAL_JOINT_DOF + i];
}
}
void UHandAgentMaxTorqueFloat::SetTorqueControlScheme(UJointMaxTorqueControlScheme* Scheme) {
this->TorqueControlScheme = Scheme;
}
unsigned int UHandAgentMaxTorqueFloat::GetControlSchemeSizeInBytes() const {
return this->TorqueControlScheme->GetControlSchemeSizeInBytes() + 3;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/aura/root_window.h"
#include <vector>
#include "base/bind.h"
#include "base/run_loop.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/client/event_client.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/env.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/event_generator.h"
#include "ui/aura/test/test_cursor_client.h"
#include "ui/aura/test/test_event_handler.h"
#include "ui/aura/test/test_screen.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/test/test_windows.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tracker.h"
#include "ui/base/hit_test.h"
#include "ui/events/event.h"
#include "ui/events/event_handler.h"
#include "ui/events/event_utils.h"
#include "ui/events/gestures/gesture_configuration.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/transform.h"
namespace aura {
namespace {
// A delegate that always returns a non-client component for hit tests.
class NonClientDelegate : public test::TestWindowDelegate {
public:
NonClientDelegate()
: non_client_count_(0),
mouse_event_count_(0),
mouse_event_flags_(0x0) {
}
virtual ~NonClientDelegate() {}
int non_client_count() const { return non_client_count_; }
gfx::Point non_client_location() const { return non_client_location_; }
int mouse_event_count() const { return mouse_event_count_; }
gfx::Point mouse_event_location() const { return mouse_event_location_; }
int mouse_event_flags() const { return mouse_event_flags_; }
virtual int GetNonClientComponent(const gfx::Point& location) const OVERRIDE {
NonClientDelegate* self = const_cast<NonClientDelegate*>(this);
self->non_client_count_++;
self->non_client_location_ = location;
return HTTOPLEFT;
}
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
mouse_event_count_++;
mouse_event_location_ = event->location();
mouse_event_flags_ = event->flags();
event->SetHandled();
}
private:
int non_client_count_;
gfx::Point non_client_location_;
int mouse_event_count_;
gfx::Point mouse_event_location_;
int mouse_event_flags_;
DISALLOW_COPY_AND_ASSIGN(NonClientDelegate);
};
// A simple event handler that consumes key events.
class ConsumeKeyHandler : public test::TestEventHandler {
public:
ConsumeKeyHandler() {}
virtual ~ConsumeKeyHandler() {}
// Overridden from ui::EventHandler:
virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
test::TestEventHandler::OnKeyEvent(event);
event->StopPropagation();
}
private:
DISALLOW_COPY_AND_ASSIGN(ConsumeKeyHandler);
};
bool IsFocusedWindow(aura::Window* window) {
return client::GetFocusClient(window)->GetFocusedWindow() == window;
}
} // namespace
typedef test::AuraTestBase WindowEventDispatcherTest;
TEST_F(WindowEventDispatcherTest, OnHostMouseEvent) {
// Create two non-overlapping windows so we don't have to worry about which
// is on top.
scoped_ptr<NonClientDelegate> delegate1(new NonClientDelegate());
scoped_ptr<NonClientDelegate> delegate2(new NonClientDelegate());
const int kWindowWidth = 123;
const int kWindowHeight = 45;
gfx::Rect bounds1(100, 200, kWindowWidth, kWindowHeight);
gfx::Rect bounds2(300, 400, kWindowWidth, kWindowHeight);
scoped_ptr<aura::Window> window1(CreateTestWindowWithDelegate(
delegate1.get(), -1234, bounds1, root_window()));
scoped_ptr<aura::Window> window2(CreateTestWindowWithDelegate(
delegate2.get(), -5678, bounds2, root_window()));
// Send a mouse event to window1.
gfx::Point point(101, 201);
ui::MouseEvent event1(
ui::ET_MOUSE_PRESSED, point, point, ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
DispatchEventUsingWindowDispatcher(&event1);
// Event was tested for non-client area for the target window.
EXPECT_EQ(1, delegate1->non_client_count());
EXPECT_EQ(0, delegate2->non_client_count());
// The non-client component test was in local coordinates.
EXPECT_EQ(gfx::Point(1, 1), delegate1->non_client_location());
// Mouse event was received by target window.
EXPECT_EQ(1, delegate1->mouse_event_count());
EXPECT_EQ(0, delegate2->mouse_event_count());
// Event was in local coordinates.
EXPECT_EQ(gfx::Point(1, 1), delegate1->mouse_event_location());
// Non-client flag was set.
EXPECT_TRUE(delegate1->mouse_event_flags() & ui::EF_IS_NON_CLIENT);
}
TEST_F(WindowEventDispatcherTest, RepostEvent) {
// Test RepostEvent in RootWindow. It only works for Mouse Press.
EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown());
gfx::Point point(10, 10);
ui::MouseEvent event(
ui::ET_MOUSE_PRESSED, point, point, ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
dispatcher()->RepostEvent(event);
RunAllPendingInMessageLoop();
EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
}
// Check that we correctly track the state of the mouse buttons in response to
// button press and release events.
TEST_F(WindowEventDispatcherTest, MouseButtonState) {
EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown());
gfx::Point location;
scoped_ptr<ui::MouseEvent> event;
// Press the left button.
event.reset(new ui::MouseEvent(
ui::ET_MOUSE_PRESSED,
location,
location,
ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON));
DispatchEventUsingWindowDispatcher(event.get());
EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
// Additionally press the right.
event.reset(new ui::MouseEvent(
ui::ET_MOUSE_PRESSED,
location,
location,
ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON,
ui::EF_RIGHT_MOUSE_BUTTON));
DispatchEventUsingWindowDispatcher(event.get());
EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
// Release the left button.
event.reset(new ui::MouseEvent(
ui::ET_MOUSE_RELEASED,
location,
location,
ui::EF_RIGHT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON));
DispatchEventUsingWindowDispatcher(event.get());
EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
// Release the right button. We should ignore the Shift-is-down flag.
event.reset(new ui::MouseEvent(
ui::ET_MOUSE_RELEASED,
location,
location,
ui::EF_SHIFT_DOWN,
ui::EF_RIGHT_MOUSE_BUTTON));
DispatchEventUsingWindowDispatcher(event.get());
EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown());
// Press the middle button.
event.reset(new ui::MouseEvent(
ui::ET_MOUSE_PRESSED,
location,
location,
ui::EF_MIDDLE_MOUSE_BUTTON,
ui::EF_MIDDLE_MOUSE_BUTTON));
DispatchEventUsingWindowDispatcher(event.get());
EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown());
}
TEST_F(WindowEventDispatcherTest, TranslatedEvent) {
scoped_ptr<Window> w1(test::CreateTestWindowWithDelegate(NULL, 1,
gfx::Rect(50, 50, 100, 100), root_window()));
gfx::Point origin(100, 100);
ui::MouseEvent root(ui::ET_MOUSE_PRESSED, origin, origin, 0, 0);
EXPECT_EQ("100,100", root.location().ToString());
EXPECT_EQ("100,100", root.root_location().ToString());
ui::MouseEvent translated_event(
root, static_cast<Window*>(root_window()), w1.get(),
ui::ET_MOUSE_ENTERED, root.flags());
EXPECT_EQ("50,50", translated_event.location().ToString());
EXPECT_EQ("100,100", translated_event.root_location().ToString());
}
namespace {
class TestEventClient : public client::EventClient {
public:
static const int kNonLockWindowId = 100;
static const int kLockWindowId = 200;
explicit TestEventClient(Window* root_window)
: root_window_(root_window),
lock_(false) {
client::SetEventClient(root_window_, this);
Window* lock_window =
test::CreateTestWindowWithBounds(root_window_->bounds(), root_window_);
lock_window->set_id(kLockWindowId);
Window* non_lock_window =
test::CreateTestWindowWithBounds(root_window_->bounds(), root_window_);
non_lock_window->set_id(kNonLockWindowId);
}
virtual ~TestEventClient() {
client::SetEventClient(root_window_, NULL);
}
// Starts/stops locking. Locking prevents windows other than those inside
// the lock container from receiving events, getting focus etc.
void Lock() {
lock_ = true;
}
void Unlock() {
lock_ = false;
}
Window* GetLockWindow() {
return const_cast<Window*>(
static_cast<const TestEventClient*>(this)->GetLockWindow());
}
const Window* GetLockWindow() const {
return root_window_->GetChildById(kLockWindowId);
}
Window* GetNonLockWindow() {
return root_window_->GetChildById(kNonLockWindowId);
}
private:
// Overridden from client::EventClient:
virtual bool CanProcessEventsWithinSubtree(
const Window* window) const OVERRIDE {
return lock_ ?
window->Contains(GetLockWindow()) || GetLockWindow()->Contains(window) :
true;
}
virtual ui::EventTarget* GetToplevelEventTarget() OVERRIDE {
return NULL;
}
Window* root_window_;
bool lock_;
DISALLOW_COPY_AND_ASSIGN(TestEventClient);
};
} // namespace
TEST_F(WindowEventDispatcherTest, CanProcessEventsWithinSubtree) {
TestEventClient client(root_window());
test::TestWindowDelegate d;
test::TestEventHandler* nonlock_ef = new test::TestEventHandler;
test::TestEventHandler* lock_ef = new test::TestEventHandler;
client.GetNonLockWindow()->SetEventFilter(nonlock_ef);
client.GetLockWindow()->SetEventFilter(lock_ef);
Window* w1 = test::CreateTestWindowWithBounds(gfx::Rect(10, 10, 20, 20),
client.GetNonLockWindow());
w1->set_id(1);
Window* w2 = test::CreateTestWindowWithBounds(gfx::Rect(30, 30, 20, 20),
client.GetNonLockWindow());
w2->set_id(2);
scoped_ptr<Window> w3(
test::CreateTestWindowWithDelegate(&d, 3, gfx::Rect(30, 30, 20, 20),
client.GetLockWindow()));
w1->Focus();
EXPECT_TRUE(IsFocusedWindow(w1));
client.Lock();
// Since we're locked, the attempt to focus w2 will be ignored.
w2->Focus();
EXPECT_TRUE(IsFocusedWindow(w1));
EXPECT_FALSE(IsFocusedWindow(w2));
{
// Attempting to send a key event to w1 (not in the lock container) should
// cause focus to be reset.
test::EventGenerator generator(root_window());
generator.PressKey(ui::VKEY_SPACE, 0);
EXPECT_EQ(NULL, client::GetFocusClient(w1)->GetFocusedWindow());
EXPECT_FALSE(IsFocusedWindow(w1));
}
{
// Events sent to a window not in the lock container will not be processed.
// i.e. never sent to the non-lock container's event filter.
test::EventGenerator generator(root_window(), w1);
generator.ClickLeftButton();
EXPECT_EQ(0, nonlock_ef->num_mouse_events());
// Events sent to a window in the lock container will be processed.
test::EventGenerator generator3(root_window(), w3.get());
generator3.PressLeftButton();
EXPECT_EQ(1, lock_ef->num_mouse_events());
}
// Prevent w3 from being deleted by the hierarchy since its delegate is owned
// by this scope.
w3->parent()->RemoveChild(w3.get());
}
TEST_F(WindowEventDispatcherTest, IgnoreUnknownKeys) {
test::TestEventHandler* filter = new ConsumeKeyHandler;
root_window()->SetEventFilter(filter); // passes ownership
ui::KeyEvent unknown_event(ui::ET_KEY_PRESSED, ui::VKEY_UNKNOWN, 0, false);
DispatchEventUsingWindowDispatcher(&unknown_event);
EXPECT_FALSE(unknown_event.handled());
EXPECT_EQ(0, filter->num_key_events());
ui::KeyEvent known_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0, false);
DispatchEventUsingWindowDispatcher(&known_event);
EXPECT_TRUE(known_event.handled());
EXPECT_EQ(1, filter->num_key_events());
}
TEST_F(WindowEventDispatcherTest, NoDelegateWindowReceivesKeyEvents) {
scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
w1->Show();
w1->Focus();
test::TestEventHandler handler;
w1->AddPreTargetHandler(&handler);
ui::KeyEvent key_press(ui::ET_KEY_PRESSED, ui::VKEY_A, 0, false);
DispatchEventUsingWindowDispatcher(&key_press);
EXPECT_TRUE(key_press.handled());
EXPECT_EQ(1, handler.num_key_events());
w1->RemovePreTargetHandler(&handler);
}
// Tests that touch-events that are beyond the bounds of the root-window do get
// propagated to the event filters correctly with the root as the target.
TEST_F(WindowEventDispatcherTest, TouchEventsOutsideBounds) {
test::TestEventHandler* filter = new test::TestEventHandler;
root_window()->SetEventFilter(filter); // passes ownership
gfx::Point position = root_window()->bounds().origin();
position.Offset(-10, -10);
ui::TouchEvent press(ui::ET_TOUCH_PRESSED, position, 0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&press);
EXPECT_EQ(1, filter->num_touch_events());
position = root_window()->bounds().origin();
position.Offset(root_window()->bounds().width() + 10,
root_window()->bounds().height() + 10);
ui::TouchEvent release(ui::ET_TOUCH_RELEASED, position, 0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&release);
EXPECT_EQ(2, filter->num_touch_events());
}
// Tests that scroll events are dispatched correctly.
TEST_F(WindowEventDispatcherTest, ScrollEventDispatch) {
base::TimeDelta now = ui::EventTimeForNow();
test::TestEventHandler* filter = new test::TestEventHandler;
root_window()->SetEventFilter(filter);
test::TestWindowDelegate delegate;
scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate));
w1->SetBounds(gfx::Rect(20, 20, 40, 40));
// A scroll event on the root-window itself is dispatched.
ui::ScrollEvent scroll1(ui::ET_SCROLL,
gfx::Point(10, 10),
now,
0,
0, -10,
0, -10,
2);
DispatchEventUsingWindowDispatcher(&scroll1);
EXPECT_EQ(1, filter->num_scroll_events());
// Scroll event on a window should be dispatched properly.
ui::ScrollEvent scroll2(ui::ET_SCROLL,
gfx::Point(25, 30),
now,
0,
-10, 0,
-10, 0,
2);
DispatchEventUsingWindowDispatcher(&scroll2);
EXPECT_EQ(2, filter->num_scroll_events());
}
namespace {
// FilterFilter that tracks the types of events it's seen.
class EventFilterRecorder : public ui::EventHandler {
public:
typedef std::vector<ui::EventType> Events;
typedef std::vector<gfx::Point> EventLocations;
EventFilterRecorder()
: wait_until_event_(ui::ET_UNKNOWN) {
}
const Events& events() const { return events_; }
const EventLocations& mouse_locations() const { return mouse_locations_; }
gfx::Point mouse_location(int i) const { return mouse_locations_[i]; }
const EventLocations& touch_locations() const { return touch_locations_; }
void WaitUntilReceivedEvent(ui::EventType type) {
wait_until_event_ = type;
run_loop_.reset(new base::RunLoop());
run_loop_->Run();
}
Events GetAndResetEvents() {
Events events = events_;
Reset();
return events;
}
void Reset() {
events_.clear();
mouse_locations_.clear();
touch_locations_.clear();
}
// ui::EventHandler overrides:
virtual void OnEvent(ui::Event* event) OVERRIDE {
ui::EventHandler::OnEvent(event);
events_.push_back(event->type());
if (wait_until_event_ == event->type() && run_loop_) {
run_loop_->Quit();
wait_until_event_ = ui::ET_UNKNOWN;
}
}
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
mouse_locations_.push_back(event->location());
}
virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE {
touch_locations_.push_back(event->location());
}
private:
scoped_ptr<base::RunLoop> run_loop_;
ui::EventType wait_until_event_;
Events events_;
EventLocations mouse_locations_;
EventLocations touch_locations_;
DISALLOW_COPY_AND_ASSIGN(EventFilterRecorder);
};
// Converts an EventType to a string.
std::string EventTypeToString(ui::EventType type) {
switch (type) {
case ui::ET_TOUCH_RELEASED:
return "TOUCH_RELEASED";
case ui::ET_TOUCH_CANCELLED:
return "TOUCH_CANCELLED";
case ui::ET_TOUCH_PRESSED:
return "TOUCH_PRESSED";
case ui::ET_TOUCH_MOVED:
return "TOUCH_MOVED";
case ui::ET_MOUSE_PRESSED:
return "MOUSE_PRESSED";
case ui::ET_MOUSE_DRAGGED:
return "MOUSE_DRAGGED";
case ui::ET_MOUSE_RELEASED:
return "MOUSE_RELEASED";
case ui::ET_MOUSE_MOVED:
return "MOUSE_MOVED";
case ui::ET_MOUSE_ENTERED:
return "MOUSE_ENTERED";
case ui::ET_MOUSE_EXITED:
return "MOUSE_EXITED";
case ui::ET_GESTURE_SCROLL_BEGIN:
return "GESTURE_SCROLL_BEGIN";
case ui::ET_GESTURE_SCROLL_END:
return "GESTURE_SCROLL_END";
case ui::ET_GESTURE_SCROLL_UPDATE:
return "GESTURE_SCROLL_UPDATE";
case ui::ET_GESTURE_PINCH_BEGIN:
return "GESTURE_PINCH_BEGIN";
case ui::ET_GESTURE_PINCH_END:
return "GESTURE_PINCH_END";
case ui::ET_GESTURE_PINCH_UPDATE:
return "GESTURE_PINCH_UPDATE";
case ui::ET_GESTURE_TAP:
return "GESTURE_TAP";
case ui::ET_GESTURE_TAP_DOWN:
return "GESTURE_TAP_DOWN";
case ui::ET_GESTURE_TAP_CANCEL:
return "GESTURE_TAP_CANCEL";
case ui::ET_GESTURE_SHOW_PRESS:
return "GESTURE_SHOW_PRESS";
case ui::ET_GESTURE_BEGIN:
return "GESTURE_BEGIN";
case ui::ET_GESTURE_END:
return "GESTURE_END";
default:
// We should explicitly require each event type.
NOTREACHED();
break;
}
return "";
}
std::string EventTypesToString(const EventFilterRecorder::Events& events) {
std::string result;
for (size_t i = 0; i < events.size(); ++i) {
if (i != 0)
result += " ";
result += EventTypeToString(events[i]);
}
return result;
}
} // namespace
// Verifies a repost mouse event targets the window with capture (if there is
// one).
TEST_F(WindowEventDispatcherTest, RepostTargetsCaptureWindow) {
// Set capture on |window| generate a mouse event (that is reposted) and not
// over |window| and verify |window| gets it (|window| gets it because it has
// capture).
EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown());
scoped_ptr<Window> window(CreateNormalWindow(1, root_window(), NULL));
window->SetBounds(gfx::Rect(20, 20, 40, 30));
EventFilterRecorder* recorder = new EventFilterRecorder;
window->SetEventFilter(recorder); // Takes ownership.
window->SetCapture();
const ui::MouseEvent press_event(
ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
dispatcher()->RepostEvent(press_event);
RunAllPendingInMessageLoop(); // Necessitated by RepostEvent().
// Mouse moves/enters may be generated. We only care about a pressed.
EXPECT_TRUE(EventTypesToString(recorder->events()).find("MOUSE_PRESSED") !=
std::string::npos) << EventTypesToString(recorder->events());
}
TEST_F(WindowEventDispatcherTest, MouseMovesHeld) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter); // passes ownership
test::TestWindowDelegate delegate;
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
ui::MouseEvent mouse_move_event(ui::ET_MOUSE_MOVED, gfx::Point(0, 0),
gfx::Point(0, 0), 0, 0);
DispatchEventUsingWindowDispatcher(&mouse_move_event);
// Discard MOUSE_ENTER.
filter->Reset();
dispatcher()->HoldPointerMoves();
// Check that we don't immediately dispatch the MOUSE_DRAGGED event.
ui::MouseEvent mouse_dragged_event(ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0),
gfx::Point(0, 0), 0, 0);
DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
EXPECT_TRUE(filter->events().empty());
// Check that we do dispatch the held MOUSE_DRAGGED event before another type
// of event.
ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(0, 0),
gfx::Point(0, 0), 0, 0);
DispatchEventUsingWindowDispatcher(&mouse_pressed_event);
EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED",
EventTypesToString(filter->events()));
filter->Reset();
// Check that we coalesce held MOUSE_DRAGGED events.
ui::MouseEvent mouse_dragged_event2(ui::ET_MOUSE_DRAGGED, gfx::Point(10, 10),
gfx::Point(10, 10), 0, 0);
DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
DispatchEventUsingWindowDispatcher(&mouse_dragged_event2);
EXPECT_TRUE(filter->events().empty());
DispatchEventUsingWindowDispatcher(&mouse_pressed_event);
EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED",
EventTypesToString(filter->events()));
filter->Reset();
// Check that on ReleasePointerMoves, held events are not dispatched
// immediately, but posted instead.
DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
dispatcher()->ReleasePointerMoves();
EXPECT_TRUE(filter->events().empty());
RunAllPendingInMessageLoop();
EXPECT_EQ("MOUSE_DRAGGED", EventTypesToString(filter->events()));
filter->Reset();
// However if another message comes in before the dispatch of the posted
// event, check that the posted event is dispatched before this new event.
dispatcher()->HoldPointerMoves();
DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
dispatcher()->ReleasePointerMoves();
DispatchEventUsingWindowDispatcher(&mouse_pressed_event);
EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED",
EventTypesToString(filter->events()));
filter->Reset();
RunAllPendingInMessageLoop();
EXPECT_TRUE(filter->events().empty());
// Check that if the other message is another MOUSE_DRAGGED, we still coalesce
// them.
dispatcher()->HoldPointerMoves();
DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
dispatcher()->ReleasePointerMoves();
DispatchEventUsingWindowDispatcher(&mouse_dragged_event2);
EXPECT_EQ("MOUSE_DRAGGED", EventTypesToString(filter->events()));
filter->Reset();
RunAllPendingInMessageLoop();
EXPECT_TRUE(filter->events().empty());
// Check that synthetic mouse move event has a right location when issued
// while holding pointer moves.
ui::MouseEvent mouse_dragged_event3(ui::ET_MOUSE_DRAGGED, gfx::Point(28, 28),
gfx::Point(28, 28), 0, 0);
dispatcher()->HoldPointerMoves();
DispatchEventUsingWindowDispatcher(&mouse_dragged_event);
DispatchEventUsingWindowDispatcher(&mouse_dragged_event2);
window->SetBounds(gfx::Rect(15, 15, 80, 80));
DispatchEventUsingWindowDispatcher(&mouse_dragged_event3);
RunAllPendingInMessageLoop();
EXPECT_TRUE(filter->events().empty());
dispatcher()->ReleasePointerMoves();
RunAllPendingInMessageLoop();
EXPECT_EQ("MOUSE_MOVED", EventTypesToString(filter->events()));
EXPECT_EQ(gfx::Point(13, 13), filter->mouse_location(0));
filter->Reset();
}
TEST_F(WindowEventDispatcherTest, TouchMovesHeld) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter); // passes ownership
test::TestWindowDelegate delegate;
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
const gfx::Point touch_location(60, 60);
// Starting the touch and throwing out the first few events, since the system
// is going to generate synthetic mouse events that are not relevant to the
// test.
ui::TouchEvent touch_pressed_event(ui::ET_TOUCH_PRESSED, touch_location,
0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&touch_pressed_event);
filter->WaitUntilReceivedEvent(ui::ET_GESTURE_SHOW_PRESS);
filter->Reset();
dispatcher()->HoldPointerMoves();
// Check that we don't immediately dispatch the TOUCH_MOVED event.
ui::TouchEvent touch_moved_event(ui::ET_TOUCH_MOVED, touch_location,
0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&touch_moved_event);
EXPECT_TRUE(filter->events().empty());
// Check that on ReleasePointerMoves, held events are not dispatched
// immediately, but posted instead.
DispatchEventUsingWindowDispatcher(&touch_moved_event);
dispatcher()->ReleasePointerMoves();
EXPECT_TRUE(filter->events().empty());
RunAllPendingInMessageLoop();
EXPECT_EQ("TOUCH_MOVED", EventTypesToString(filter->events()));
filter->Reset();
// If another touch event occurs then the held touch should be dispatched
// immediately before it.
ui::TouchEvent touch_released_event(ui::ET_TOUCH_RELEASED, touch_location,
0, base::TimeDelta());
filter->Reset();
dispatcher()->HoldPointerMoves();
DispatchEventUsingWindowDispatcher(&touch_moved_event);
DispatchEventUsingWindowDispatcher(&touch_released_event);
EXPECT_EQ("TOUCH_MOVED TOUCH_RELEASED GESTURE_TAP_CANCEL GESTURE_END",
EventTypesToString(filter->events()));
filter->Reset();
dispatcher()->ReleasePointerMoves();
RunAllPendingInMessageLoop();
EXPECT_TRUE(filter->events().empty());
}
class HoldPointerOnScrollHandler : public test::TestEventHandler {
public:
HoldPointerOnScrollHandler(WindowEventDispatcher* dispatcher,
EventFilterRecorder* filter)
: dispatcher_(dispatcher),
filter_(filter),
holding_moves_(false) {
}
virtual ~HoldPointerOnScrollHandler() {}
private:
virtual void OnGestureEvent(ui::GestureEvent* gesture) OVERRIDE {
if (gesture->type() == ui::ET_GESTURE_SCROLL_UPDATE) {
CHECK(!holding_moves_);
holding_moves_ = true;
dispatcher_->HoldPointerMoves();
filter_->Reset();
} else if (gesture->type() == ui::ET_GESTURE_SCROLL_END) {
dispatcher_->ReleasePointerMoves();
holding_moves_ = false;
}
}
WindowEventDispatcher* dispatcher_;
EventFilterRecorder* filter_;
bool holding_moves_;
DISALLOW_COPY_AND_ASSIGN(HoldPointerOnScrollHandler);
};
// Tests that touch-move events don't contribute to an in-progress scroll
// gesture if touch-move events are being held by the dispatcher.
TEST_F(WindowEventDispatcherTest, TouchMovesHeldOnScroll) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter);
test::TestWindowDelegate delegate;
HoldPointerOnScrollHandler handler(dispatcher(), filter);
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
window->AddPreTargetHandler(&handler);
test::EventGenerator generator(root_window());
generator.GestureScrollSequence(
gfx::Point(60, 60), gfx::Point(10, 60),
base::TimeDelta::FromMilliseconds(100), 25);
// |handler| will have reset |filter| and started holding the touch-move
// events when scrolling started. At the end of the scroll (i.e. upon
// touch-release), the held touch-move event will have been dispatched first,
// along with the subsequent events (i.e. touch-release, scroll-end, and
// gesture-end).
const EventFilterRecorder::Events& events = filter->events();
EXPECT_EQ("TOUCH_MOVED TOUCH_RELEASED GESTURE_SCROLL_END GESTURE_END",
EventTypesToString(events));
ASSERT_EQ(2u, filter->touch_locations().size());
EXPECT_EQ(gfx::Point(-40, 10).ToString(),
filter->touch_locations()[0].ToString());
EXPECT_EQ(gfx::Point(-40, 10).ToString(),
filter->touch_locations()[1].ToString());
}
// Tests that synthetic mouse events are ignored when mouse
// events are disabled.
TEST_F(WindowEventDispatcherTest, DispatchSyntheticMouseEvents) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter); // passes ownership
test::TestWindowDelegate delegate;
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window()));
window->Show();
window->SetCapture();
test::TestCursorClient cursor_client(root_window());
// Dispatch a non-synthetic mouse event when mouse events are enabled.
ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, gfx::Point(10, 10),
gfx::Point(10, 10), 0, 0);
DispatchEventUsingWindowDispatcher(&mouse1);
EXPECT_FALSE(filter->events().empty());
filter->Reset();
// Dispatch a synthetic mouse event when mouse events are enabled.
ui::MouseEvent mouse2(ui::ET_MOUSE_MOVED, gfx::Point(10, 10),
gfx::Point(10, 10), ui::EF_IS_SYNTHESIZED, 0);
DispatchEventUsingWindowDispatcher(&mouse2);
EXPECT_FALSE(filter->events().empty());
filter->Reset();
// Dispatch a synthetic mouse event when mouse events are disabled.
cursor_client.DisableMouseEvents();
DispatchEventUsingWindowDispatcher(&mouse2);
EXPECT_TRUE(filter->events().empty());
}
// Tests that a mouse exit is dispatched to the last known cursor location
// when the cursor becomes invisible.
TEST_F(WindowEventDispatcherTest, DispatchMouseExitWhenCursorHidden) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter); // passes ownership
test::TestWindowDelegate delegate;
gfx::Point window_origin(7, 18);
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1234, gfx::Rect(window_origin, gfx::Size(100, 100)),
root_window()));
window->Show();
// Dispatch a mouse move event into the window.
gfx::Point mouse_location(gfx::Point(15, 25));
ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, mouse_location,
mouse_location, 0, 0);
EXPECT_TRUE(filter->events().empty());
DispatchEventUsingWindowDispatcher(&mouse1);
EXPECT_FALSE(filter->events().empty());
filter->Reset();
// Hide the cursor and verify a mouse exit was dispatched.
dispatcher()->host()->OnCursorVisibilityChanged(false);
EXPECT_FALSE(filter->events().empty());
EXPECT_EQ("MOUSE_EXITED", EventTypesToString(filter->events()));
// Verify the mouse exit was dispatched at the correct location
// (in the correct coordinate space).
int translated_x = mouse_location.x() - window_origin.x();
int translated_y = mouse_location.y() - window_origin.y();
gfx::Point translated_point(translated_x, translated_y);
EXPECT_EQ(filter->mouse_location(0).ToString(), translated_point.ToString());
}
class DeletingEventFilter : public ui::EventHandler {
public:
DeletingEventFilter()
: delete_during_pre_handle_(false) {}
virtual ~DeletingEventFilter() {}
void Reset(bool delete_during_pre_handle) {
delete_during_pre_handle_ = delete_during_pre_handle;
}
private:
// Overridden from ui::EventHandler:
virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
if (delete_during_pre_handle_)
delete event->target();
}
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
if (delete_during_pre_handle_)
delete event->target();
}
bool delete_during_pre_handle_;
DISALLOW_COPY_AND_ASSIGN(DeletingEventFilter);
};
class DeletingWindowDelegate : public test::TestWindowDelegate {
public:
DeletingWindowDelegate()
: window_(NULL),
delete_during_handle_(false),
got_event_(false) {}
virtual ~DeletingWindowDelegate() {}
void Reset(Window* window, bool delete_during_handle) {
window_ = window;
delete_during_handle_ = delete_during_handle;
got_event_ = false;
}
bool got_event() const { return got_event_; }
private:
// Overridden from WindowDelegate:
virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE {
if (delete_during_handle_)
delete window_;
got_event_ = true;
}
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
if (delete_during_handle_)
delete window_;
got_event_ = true;
}
Window* window_;
bool delete_during_handle_;
bool got_event_;
DISALLOW_COPY_AND_ASSIGN(DeletingWindowDelegate);
};
TEST_F(WindowEventDispatcherTest, DeleteWindowDuringDispatch) {
// Verifies that we can delete a window during each phase of event handling.
// Deleting the window should not cause a crash, only prevent further
// processing from occurring.
scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
DeletingWindowDelegate d11;
Window* w11 = CreateNormalWindow(11, w1.get(), &d11);
WindowTracker tracker;
DeletingEventFilter* w1_filter = new DeletingEventFilter;
w1->SetEventFilter(w1_filter);
client::GetFocusClient(w1.get())->FocusWindow(w11);
test::EventGenerator generator(root_window(), w11);
// First up, no one deletes anything.
tracker.Add(w11);
d11.Reset(w11, false);
generator.PressLeftButton();
EXPECT_TRUE(tracker.Contains(w11));
EXPECT_TRUE(d11.got_event());
generator.ReleaseLeftButton();
// Delegate deletes w11. This will prevent the post-handle step from applying.
w1_filter->Reset(false);
d11.Reset(w11, true);
generator.PressKey(ui::VKEY_A, 0);
EXPECT_FALSE(tracker.Contains(w11));
EXPECT_TRUE(d11.got_event());
// Pre-handle step deletes w11. This will prevent the delegate and the post-
// handle steps from applying.
w11 = CreateNormalWindow(11, w1.get(), &d11);
w1_filter->Reset(true);
d11.Reset(w11, false);
generator.PressLeftButton();
EXPECT_FALSE(tracker.Contains(w11));
EXPECT_FALSE(d11.got_event());
}
namespace {
// A window delegate that detaches the parent of the target's parent window when
// it receives a tap event.
class DetachesParentOnTapDelegate : public test::TestWindowDelegate {
public:
DetachesParentOnTapDelegate() {}
virtual ~DetachesParentOnTapDelegate() {}
private:
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
event->SetHandled();
return;
}
if (event->type() == ui::ET_GESTURE_TAP) {
Window* parent = static_cast<Window*>(event->target())->parent();
parent->parent()->RemoveChild(parent);
event->SetHandled();
}
}
DISALLOW_COPY_AND_ASSIGN(DetachesParentOnTapDelegate);
};
} // namespace
// Tests that the gesture recognizer is reset for all child windows when a
// window hides. No expectations, just checks that the test does not crash.
TEST_F(WindowEventDispatcherTest,
GestureRecognizerResetsTargetWhenParentHides) {
scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
DetachesParentOnTapDelegate delegate;
scoped_ptr<Window> parent(CreateNormalWindow(22, w1.get(), NULL));
Window* child = CreateNormalWindow(11, parent.get(), &delegate);
test::EventGenerator generator(root_window(), child);
generator.GestureTapAt(gfx::Point(40, 40));
}
namespace {
// A window delegate that processes nested gestures on tap.
class NestedGestureDelegate : public test::TestWindowDelegate {
public:
NestedGestureDelegate(test::EventGenerator* generator,
const gfx::Point tap_location)
: generator_(generator),
tap_location_(tap_location),
gesture_end_count_(0) {}
virtual ~NestedGestureDelegate() {}
int gesture_end_count() const { return gesture_end_count_; }
private:
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
switch (event->type()) {
case ui::ET_GESTURE_TAP_DOWN:
event->SetHandled();
break;
case ui::ET_GESTURE_TAP:
if (generator_)
generator_->GestureTapAt(tap_location_);
event->SetHandled();
break;
case ui::ET_GESTURE_END:
++gesture_end_count_;
break;
default:
break;
}
}
test::EventGenerator* generator_;
const gfx::Point tap_location_;
int gesture_end_count_;
DISALLOW_COPY_AND_ASSIGN(NestedGestureDelegate);
};
} // namespace
// Tests that gesture end is delivered after nested gesture processing.
TEST_F(WindowEventDispatcherTest, GestureEndDeliveredAfterNestedGestures) {
NestedGestureDelegate d1(NULL, gfx::Point());
scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &d1));
w1->SetBounds(gfx::Rect(0, 0, 100, 100));
test::EventGenerator nested_generator(root_window(), w1.get());
NestedGestureDelegate d2(&nested_generator, w1->bounds().CenterPoint());
scoped_ptr<Window> w2(CreateNormalWindow(1, root_window(), &d2));
w2->SetBounds(gfx::Rect(100, 0, 100, 100));
// Tap on w2 which triggers nested gestures for w1.
test::EventGenerator generator(root_window(), w2.get());
generator.GestureTapAt(w2->bounds().CenterPoint());
// Both windows should get their gesture end events.
EXPECT_EQ(1, d1.gesture_end_count());
EXPECT_EQ(1, d2.gesture_end_count());
}
// Tests whether we can repost the Tap down gesture event.
TEST_F(WindowEventDispatcherTest, RepostTapdownGestureTest) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter); // passes ownership
test::TestWindowDelegate delegate;
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
ui::GestureEventDetails details(ui::ET_GESTURE_TAP_DOWN, 0.0f, 0.0f);
gfx::Point point(10, 10);
ui::GestureEvent event(
ui::ET_GESTURE_TAP_DOWN,
point.x(),
point.y(),
0,
ui::EventTimeForNow(),
details,
0);
dispatcher()->RepostEvent(event);
RunAllPendingInMessageLoop();
// TODO(rbyers): Currently disabled - crbug.com/170987
EXPECT_FALSE(EventTypesToString(filter->events()).find("GESTURE_TAP_DOWN") !=
std::string::npos);
filter->Reset();
}
// This class inherits from the EventFilterRecorder class which provides a
// facility to record events. This class additionally provides a facility to
// repost the ET_GESTURE_TAP_DOWN gesture to the target window and records
// events after that.
class RepostGestureEventRecorder : public EventFilterRecorder {
public:
RepostGestureEventRecorder(aura::Window* repost_source,
aura::Window* repost_target)
: repost_source_(repost_source),
repost_target_(repost_target),
reposted_(false),
done_cleanup_(false) {}
virtual ~RepostGestureEventRecorder() {}
virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE {
if (reposted_ && event->type() == ui::ET_TOUCH_PRESSED) {
done_cleanup_ = true;
Reset();
}
EventFilterRecorder::OnTouchEvent(event);
}
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
EXPECT_EQ(done_cleanup_ ? repost_target_ : repost_source_, event->target());
if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
if (!reposted_) {
EXPECT_NE(repost_target_, event->target());
reposted_ = true;
repost_target_->GetDispatcher()->RepostEvent(*event);
// Ensure that the reposted gesture event above goes to the
// repost_target_;
repost_source_->GetRootWindow()->RemoveChild(repost_source_);
return;
}
}
EventFilterRecorder::OnGestureEvent(event);
}
// Ignore mouse events as they don't fire at all times. This causes
// the GestureRepostEventOrder test to fail randomly.
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {}
private:
aura::Window* repost_source_;
aura::Window* repost_target_;
// set to true if we reposted the ET_GESTURE_TAP_DOWN event.
bool reposted_;
// set true if we're done cleaning up after hiding repost_source_;
bool done_cleanup_;
DISALLOW_COPY_AND_ASSIGN(RepostGestureEventRecorder);
};
// Tests whether events which are generated after the reposted gesture event
// are received after that. In this case the scroll sequence events should
// be received after the reposted gesture event.
TEST_F(WindowEventDispatcherTest, GestureRepostEventOrder) {
// Expected events at the end for the repost_target window defined below.
const char kExpectedTargetEvents[] =
// TODO)(rbyers): Gesture event reposting is disabled - crbug.com/279039.
// "GESTURE_BEGIN GESTURE_TAP_DOWN "
"TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
"GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE TOUCH_MOVED "
"GESTURE_SCROLL_UPDATE TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED "
"GESTURE_SCROLL_END GESTURE_END";
// We create two windows.
// The first window (repost_source) is the one to which the initial tap
// gesture is sent. It reposts this event to the second window
// (repost_target).
// We then generate the scroll sequence for repost_target and look for two
// ET_GESTURE_TAP_DOWN events in the event list at the end.
test::TestWindowDelegate delegate;
scoped_ptr<aura::Window> repost_target(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
scoped_ptr<aura::Window> repost_source(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(0, 0, 50, 50), root_window()));
RepostGestureEventRecorder* repost_event_recorder =
new RepostGestureEventRecorder(repost_source.get(), repost_target.get());
root_window()->SetEventFilter(repost_event_recorder); // passes ownership
// Generate a tap down gesture for the repost_source. This will be reposted
// to repost_target.
test::EventGenerator repost_generator(root_window(), repost_source.get());
repost_generator.GestureTapAt(gfx::Point(40, 40));
RunAllPendingInMessageLoop();
test::EventGenerator scroll_generator(root_window(), repost_target.get());
scroll_generator.GestureScrollSequence(
gfx::Point(80, 80),
gfx::Point(100, 100),
base::TimeDelta::FromMilliseconds(100),
3);
RunAllPendingInMessageLoop();
int tap_down_count = 0;
for (size_t i = 0; i < repost_event_recorder->events().size(); ++i) {
if (repost_event_recorder->events()[i] == ui::ET_GESTURE_TAP_DOWN)
++tap_down_count;
}
// We expect two tap down events. One from the repost and the other one from
// the scroll sequence posted above.
// TODO(rbyers): Currently disabled - crbug.com/170987
EXPECT_EQ(1, tap_down_count);
EXPECT_EQ(kExpectedTargetEvents,
EventTypesToString(repost_event_recorder->events()));
}
class OnMouseExitDeletingEventFilter : public EventFilterRecorder {
public:
OnMouseExitDeletingEventFilter() : window_to_delete_(NULL) {}
virtual ~OnMouseExitDeletingEventFilter() {}
void set_window_to_delete(Window* window_to_delete) {
window_to_delete_ = window_to_delete;
}
private:
// Overridden from ui::EventHandler:
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
EventFilterRecorder::OnMouseEvent(event);
if (window_to_delete_) {
delete window_to_delete_;
window_to_delete_ = NULL;
}
}
Window* window_to_delete_;
DISALLOW_COPY_AND_ASSIGN(OnMouseExitDeletingEventFilter);
};
// Tests that RootWindow drops mouse-moved event that is supposed to be sent to
// a child, but the child is destroyed because of the synthesized mouse-exit
// event generated on the previous mouse_moved_handler_.
TEST_F(WindowEventDispatcherTest, DeleteWindowDuringMouseMovedDispatch) {
// Create window 1 and set its event filter. Window 1 will take ownership of
// the event filter.
scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL));
OnMouseExitDeletingEventFilter* w1_filter =
new OnMouseExitDeletingEventFilter();
w1->SetEventFilter(w1_filter);
w1->SetBounds(gfx::Rect(20, 20, 60, 60));
EXPECT_EQ(NULL, dispatcher()->mouse_moved_handler());
test::EventGenerator generator(root_window(), w1.get());
// Move mouse over window 1 to set it as the |mouse_moved_handler_| for the
// root window.
generator.MoveMouseTo(51, 51);
EXPECT_EQ(w1.get(), dispatcher()->mouse_moved_handler());
// Create window 2 under the mouse cursor and stack it above window 1.
Window* w2 = CreateNormalWindow(2, root_window(), NULL);
w2->SetBounds(gfx::Rect(30, 30, 40, 40));
root_window()->StackChildAbove(w2, w1.get());
// Set window 2 as the window that is to be deleted when a mouse-exited event
// happens on window 1.
w1_filter->set_window_to_delete(w2);
// Move mosue over window 2. This should generate a mouse-exited event for
// window 1 resulting in deletion of window 2. The original mouse-moved event
// that was targeted to window 2 should be dropped since window 2 is
// destroyed. This test passes if no crash happens.
generator.MoveMouseTo(52, 52);
EXPECT_EQ(NULL, dispatcher()->mouse_moved_handler());
// Check events received by window 1.
EXPECT_EQ("MOUSE_ENTERED MOUSE_MOVED MOUSE_EXITED",
EventTypesToString(w1_filter->events()));
}
namespace {
// Used to track if OnWindowDestroying() is invoked and if there is a valid
// RootWindow at such time.
class ValidRootDuringDestructionWindowObserver : public aura::WindowObserver {
public:
ValidRootDuringDestructionWindowObserver(bool* got_destroying,
bool* has_valid_root)
: got_destroying_(got_destroying),
has_valid_root_(has_valid_root) {
}
// WindowObserver:
virtual void OnWindowDestroying(aura::Window* window) OVERRIDE {
*got_destroying_ = true;
*has_valid_root_ = (window->GetRootWindow() != NULL);
}
private:
bool* got_destroying_;
bool* has_valid_root_;
DISALLOW_COPY_AND_ASSIGN(ValidRootDuringDestructionWindowObserver);
};
} // namespace
#if defined(USE_OZONE)
// Creating multiple WindowTreeHostOzone instances is broken.
#define MAYBE_ValidRootDuringDestruction DISABLED_ValidRootDuringDestruction
#else
#define MAYBE_ValidRootDuringDestruction ValidRootDuringDestruction
#endif
// Verifies GetRootWindow() from ~Window returns a valid root.
TEST_F(WindowEventDispatcherTest, MAYBE_ValidRootDuringDestruction) {
bool got_destroying = false;
bool has_valid_root = false;
ValidRootDuringDestructionWindowObserver observer(&got_destroying,
&has_valid_root);
{
scoped_ptr<WindowEventDispatcher> dispatcher(
new WindowEventDispatcher(
WindowEventDispatcher::CreateParams(gfx::Rect(0, 0, 100, 100))));
dispatcher->host()->InitHost();
// Owned by WindowEventDispatcher.
Window* w1 = CreateNormalWindow(1, dispatcher->window(), NULL);
w1->AddObserver(&observer);
}
EXPECT_TRUE(got_destroying);
EXPECT_TRUE(has_valid_root);
}
namespace {
// See description above DontResetHeldEvent for details.
class DontResetHeldEventWindowDelegate : public test::TestWindowDelegate {
public:
explicit DontResetHeldEventWindowDelegate(aura::Window* root)
: root_(root),
mouse_event_count_(0) {}
virtual ~DontResetHeldEventWindowDelegate() {}
int mouse_event_count() const { return mouse_event_count_; }
// TestWindowDelegate:
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 &&
mouse_event_count_++ == 0) {
ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED,
gfx::Point(10, 10), gfx::Point(10, 10),
ui::EF_SHIFT_DOWN, 0);
root_->GetDispatcher()->RepostEvent(mouse_event);
}
}
private:
Window* root_;
int mouse_event_count_;
DISALLOW_COPY_AND_ASSIGN(DontResetHeldEventWindowDelegate);
};
} // namespace
// Verifies RootWindow doesn't reset |RootWindow::held_repostable_event_| after
// dispatching. This is done by using DontResetHeldEventWindowDelegate, which
// tracks the number of events with ui::EF_SHIFT_DOWN set (all reposted events
// have EF_SHIFT_DOWN). When the first event is seen RepostEvent() is used to
// schedule another reposted event.
TEST_F(WindowEventDispatcherTest, DontResetHeldEvent) {
DontResetHeldEventWindowDelegate delegate(root_window());
scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate));
w1->SetBounds(gfx::Rect(0, 0, 40, 40));
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED,
gfx::Point(10, 10), gfx::Point(10, 10),
ui::EF_SHIFT_DOWN, 0);
root_window()->GetDispatcher()->RepostEvent(pressed);
ui::MouseEvent pressed2(ui::ET_MOUSE_PRESSED,
gfx::Point(10, 10), gfx::Point(10, 10), 0, 0);
// Dispatch an event to flush event scheduled by way of RepostEvent().
DispatchEventUsingWindowDispatcher(&pressed2);
// Delegate should have seen reposted event (identified by way of
// EF_SHIFT_DOWN). Dispatch another event to flush the second
// RepostedEvent().
EXPECT_EQ(1, delegate.mouse_event_count());
DispatchEventUsingWindowDispatcher(&pressed2);
EXPECT_EQ(2, delegate.mouse_event_count());
}
namespace {
// See description above DeleteDispatcherFromHeldMouseEvent for details.
class DeleteDispatcherFromHeldMouseEventDelegate
: public test::TestWindowDelegate {
public:
explicit DeleteDispatcherFromHeldMouseEventDelegate(
WindowEventDispatcher* dispatcher)
: dispatcher_(dispatcher),
got_mouse_event_(false),
got_destroy_(false) {
}
virtual ~DeleteDispatcherFromHeldMouseEventDelegate() {}
bool got_mouse_event() const { return got_mouse_event_; }
bool got_destroy() const { return got_destroy_; }
// TestWindowDelegate:
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
if ((event->flags() & ui::EF_SHIFT_DOWN) != 0) {
got_mouse_event_ = true;
delete dispatcher_;
}
}
virtual void OnWindowDestroyed() OVERRIDE {
got_destroy_ = true;
}
private:
WindowEventDispatcher* dispatcher_;
bool got_mouse_event_;
bool got_destroy_;
DISALLOW_COPY_AND_ASSIGN(DeleteDispatcherFromHeldMouseEventDelegate);
};
} // namespace
#if defined(USE_OZONE)
// Creating multiple WindowTreeHostOzone instances is broken.
#define MAYBE_DeleteDispatcherFromHeldMouseEvent DISABLED_DeleteDispatcherFromHeldMouseEvent
#else
#define MAYBE_DeleteDispatcherFromHeldMouseEvent DeleteDispatcherFromHeldMouseEvent
#endif
// Verifies if a RootWindow is deleted from dispatching a held mouse event we
// don't crash.
TEST_F(WindowEventDispatcherTest, MAYBE_DeleteDispatcherFromHeldMouseEvent) {
// Should be deleted by |delegate|.
WindowEventDispatcher* d2 = new WindowEventDispatcher(
WindowEventDispatcher::CreateParams(gfx::Rect(0, 0, 100, 100)));
d2->host()->InitHost();
DeleteDispatcherFromHeldMouseEventDelegate delegate(d2);
// Owned by |d2|.
Window* w1 = CreateNormalWindow(1, d2->window(), &delegate);
w1->SetBounds(gfx::Rect(0, 0, 40, 40));
ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED,
gfx::Point(10, 10), gfx::Point(10, 10),
ui::EF_SHIFT_DOWN, 0);
d2->RepostEvent(pressed);
// RunAllPendingInMessageLoop() to make sure the |pressed| is run.
RunAllPendingInMessageLoop();
EXPECT_TRUE(delegate.got_mouse_event());
EXPECT_TRUE(delegate.got_destroy());
}
TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveTouches) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter); // passes ownership
test::TestWindowDelegate delegate;
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
gfx::Point position1 = root_window()->bounds().origin();
ui::TouchEvent press(ui::ET_TOUCH_PRESSED, position1, 0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&press);
EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN",
EventTypesToString(filter->GetAndResetEvents()));
window->Hide();
EXPECT_EQ("TOUCH_CANCELLED GESTURE_TAP_CANCEL GESTURE_END",
EventTypesToString(filter->events()));
}
TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveGestures) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter); // passes ownership
test::TestWindowDelegate delegate;
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(0, 0, 100, 100), root_window()));
gfx::Point position1 = root_window()->bounds().origin();
gfx::Point position2 = root_window()->bounds().CenterPoint();
ui::TouchEvent press(ui::ET_TOUCH_PRESSED, position1, 0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&press);
ui::TouchEvent move(ui::ET_TOUCH_MOVED, position2, 0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&move);
ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, position1, 1, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&press2);
EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
"GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE "
"TOUCH_PRESSED GESTURE_BEGIN GESTURE_PINCH_BEGIN",
EventTypesToString(filter->GetAndResetEvents()));
window->Hide();
EXPECT_EQ("TOUCH_CANCELLED GESTURE_PINCH_END GESTURE_END TOUCH_CANCELLED "
"GESTURE_SCROLL_END GESTURE_END",
EventTypesToString(filter->events()));
}
// Places two windows side by side. Presses down on one window, and starts a
// scroll. Sets capture on the other window and ensures that the "ending" events
// aren't sent to the window which gained capture.
TEST_F(WindowEventDispatcherTest, EndingEventDoesntRetarget) {
scoped_ptr<Window> window1(CreateNormalWindow(1, root_window(), NULL));
window1->SetBounds(gfx::Rect(0, 0, 40, 40));
scoped_ptr<Window> window2(CreateNormalWindow(2, root_window(), NULL));
window2->SetBounds(gfx::Rect(40, 0, 40, 40));
EventFilterRecorder* filter1 = new EventFilterRecorder();
window1->SetEventFilter(filter1); // passes ownership
EventFilterRecorder* filter2 = new EventFilterRecorder();
window2->SetEventFilter(filter2); // passes ownership
gfx::Point position = window1->bounds().origin();
ui::TouchEvent press(ui::ET_TOUCH_PRESSED, position, 0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&press);
gfx::Point position2 = window1->bounds().CenterPoint();
ui::TouchEvent move(ui::ET_TOUCH_MOVED, position2, 0, base::TimeDelta());
DispatchEventUsingWindowDispatcher(&move);
window2->SetCapture();
EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED "
"GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE "
"TOUCH_CANCELLED GESTURE_SCROLL_END GESTURE_END",
EventTypesToString(filter1->events()));
EXPECT_TRUE(filter2->events().empty());
}
namespace {
// This class creates and manages a window which is destroyed as soon as
// capture is lost. This is the case for the drag and drop capture window.
class CaptureWindowTracker : public test::TestWindowDelegate {
public:
CaptureWindowTracker() {}
virtual ~CaptureWindowTracker() {}
void CreateCaptureWindow(aura::Window* root_window) {
capture_window_.reset(test::CreateTestWindowWithDelegate(
this, -1234, gfx::Rect(20, 20, 20, 20), root_window));
capture_window_->SetCapture();
}
void reset() {
capture_window_.reset();
}
virtual void OnCaptureLost() OVERRIDE {
capture_window_.reset();
}
virtual void OnWindowDestroyed() OVERRIDE {
TestWindowDelegate::OnWindowDestroyed();
capture_window_.reset();
}
aura::Window* capture_window() { return capture_window_.get(); }
private:
scoped_ptr<aura::Window> capture_window_;
DISALLOW_COPY_AND_ASSIGN(CaptureWindowTracker);
};
}
// Verifies handling loss of capture by the capture window being hidden.
TEST_F(WindowEventDispatcherTest, CaptureWindowHidden) {
CaptureWindowTracker capture_window_tracker;
capture_window_tracker.CreateCaptureWindow(root_window());
capture_window_tracker.capture_window()->Hide();
EXPECT_EQ(NULL, capture_window_tracker.capture_window());
}
// Verifies handling loss of capture by the capture window being destroyed.
TEST_F(WindowEventDispatcherTest, CaptureWindowDestroyed) {
CaptureWindowTracker capture_window_tracker;
capture_window_tracker.CreateCaptureWindow(root_window());
capture_window_tracker.reset();
EXPECT_EQ(NULL, capture_window_tracker.capture_window());
}
class ExitMessageLoopOnMousePress : public test::TestEventHandler {
public:
ExitMessageLoopOnMousePress() {}
virtual ~ExitMessageLoopOnMousePress() {}
protected:
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
test::TestEventHandler::OnMouseEvent(event);
if (event->type() == ui::ET_MOUSE_PRESSED)
base::MessageLoopForUI::current()->Quit();
}
private:
DISALLOW_COPY_AND_ASSIGN(ExitMessageLoopOnMousePress);
};
class WindowEventDispatcherTestWithMessageLoop
: public WindowEventDispatcherTest {
public:
WindowEventDispatcherTestWithMessageLoop() {}
virtual ~WindowEventDispatcherTestWithMessageLoop() {}
void RunTest() {
// Reset any event the window may have received when bringing up the window
// (e.g. mouse-move events if the mouse cursor is over the window).
handler_.Reset();
// Start a nested message-loop, post an event to be dispatched, and then
// terminate the message-loop. When the message-loop unwinds and gets back,
// the reposted event should not have fired.
ui::MouseEvent mouse(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10),
gfx::Point(10, 10), ui::EF_NONE, ui::EF_NONE);
message_loop()->PostTask(FROM_HERE,
base::Bind(&WindowEventDispatcher::RepostEvent,
base::Unretained(dispatcher()),
mouse));
message_loop()->PostTask(FROM_HERE,
message_loop()->QuitClosure());
base::MessageLoop::ScopedNestableTaskAllower allow(message_loop());
base::RunLoop loop;
loop.Run();
EXPECT_EQ(0, handler_.num_mouse_events());
// Let the current message-loop run. The event-handler will terminate the
// message-loop when it receives the reposted event.
}
base::MessageLoop* message_loop() {
return base::MessageLoopForUI::current();
}
protected:
virtual void SetUp() OVERRIDE {
WindowEventDispatcherTest::SetUp();
window_.reset(CreateNormalWindow(1, root_window(), NULL));
window_->AddPreTargetHandler(&handler_);
}
virtual void TearDown() OVERRIDE {
window_.reset();
WindowEventDispatcherTest::TearDown();
}
private:
scoped_ptr<Window> window_;
ExitMessageLoopOnMousePress handler_;
DISALLOW_COPY_AND_ASSIGN(WindowEventDispatcherTestWithMessageLoop);
};
TEST_F(WindowEventDispatcherTestWithMessageLoop, EventRepostedInNonNestedLoop) {
CHECK(!message_loop()->is_running());
// Perform the test in a callback, so that it runs after the message-loop
// starts.
message_loop()->PostTask(
FROM_HERE, base::Bind(
&WindowEventDispatcherTestWithMessageLoop::RunTest,
base::Unretained(this)));
message_loop()->Run();
}
class WindowEventDispatcherTestInHighDPI : public WindowEventDispatcherTest {
public:
WindowEventDispatcherTestInHighDPI() {}
virtual ~WindowEventDispatcherTestInHighDPI() {}
protected:
virtual void SetUp() OVERRIDE {
WindowEventDispatcherTest::SetUp();
test_screen()->SetDeviceScaleFactor(2.f);
}
};
TEST_F(WindowEventDispatcherTestInHighDPI, EventLocationTransform) {
test::TestWindowDelegate delegate;
scoped_ptr<aura::Window> child(test::CreateTestWindowWithDelegate(&delegate,
1234, gfx::Rect(20, 20, 100, 100), root_window()));
child->Show();
test::TestEventHandler handler_child;
test::TestEventHandler handler_root;
root_window()->AddPreTargetHandler(&handler_root);
child->AddPreTargetHandler(&handler_child);
{
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(30, 30), gfx::Point(30, 30),
ui::EF_NONE, ui::EF_NONE);
DispatchEventUsingWindowDispatcher(&move);
EXPECT_EQ(0, handler_child.num_mouse_events());
EXPECT_EQ(1, handler_root.num_mouse_events());
}
{
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(50, 50), gfx::Point(50, 50),
ui::EF_NONE, ui::EF_NONE);
DispatchEventUsingWindowDispatcher(&move);
// The child receives an ENTER, and a MOVED event.
EXPECT_EQ(2, handler_child.num_mouse_events());
// The root receives both the ENTER and the MOVED events dispatched to
// |child|, as well as an EXIT event.
EXPECT_EQ(3, handler_root.num_mouse_events());
}
child->RemovePreTargetHandler(&handler_child);
root_window()->RemovePreTargetHandler(&handler_root);
}
TEST_F(WindowEventDispatcherTestInHighDPI, TouchMovesHeldOnScroll) {
EventFilterRecorder* filter = new EventFilterRecorder;
root_window()->SetEventFilter(filter);
test::TestWindowDelegate delegate;
HoldPointerOnScrollHandler handler(dispatcher(), filter);
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
window->AddPreTargetHandler(&handler);
test::EventGenerator generator(root_window());
generator.GestureScrollSequence(
gfx::Point(120, 120), gfx::Point(20, 120),
base::TimeDelta::FromMilliseconds(100), 25);
// |handler| will have reset |filter| and started holding the touch-move
// events when scrolling started. At the end of the scroll (i.e. upon
// touch-release), the held touch-move event will have been dispatched first,
// along with the subsequent events (i.e. touch-release, scroll-end, and
// gesture-end).
const EventFilterRecorder::Events& events = filter->events();
EXPECT_EQ("TOUCH_MOVED TOUCH_RELEASED GESTURE_SCROLL_END GESTURE_END",
EventTypesToString(events));
ASSERT_EQ(2u, filter->touch_locations().size());
EXPECT_EQ(gfx::Point(-40, 10).ToString(),
filter->touch_locations()[0].ToString());
EXPECT_EQ(gfx::Point(-40, 10).ToString(),
filter->touch_locations()[1].ToString());
}
class SelfDestructDelegate : public test::TestWindowDelegate {
public:
SelfDestructDelegate() {}
virtual ~SelfDestructDelegate() {}
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {
window_.reset();
}
void set_window(scoped_ptr<aura::Window> window) {
window_ = window.Pass();
}
bool has_window() const { return !!window_.get(); }
private:
scoped_ptr<aura::Window> window_;
DISALLOW_COPY_AND_ASSIGN(SelfDestructDelegate);
};
TEST_F(WindowEventDispatcherTest, SynthesizedLocatedEvent) {
test::EventGenerator generator(root_window());
generator.MoveMouseTo(10, 10);
EXPECT_EQ("10,10",
Env::GetInstance()->last_mouse_location().ToString());
// Synthesized event should not update the mouse location.
ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(),
ui::EF_IS_SYNTHESIZED, 0);
generator.Dispatch(&mouseev);
EXPECT_EQ("10,10",
Env::GetInstance()->last_mouse_location().ToString());
generator.MoveMouseTo(0, 0);
EXPECT_EQ("0,0",
Env::GetInstance()->last_mouse_location().ToString());
// Make sure the location gets updated when a syntheiszed enter
// event destroyed the window.
SelfDestructDelegate delegate;
scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(
&delegate, 1, gfx::Rect(50, 50, 100, 100), root_window()));
delegate.set_window(window.Pass());
EXPECT_TRUE(delegate.has_window());
generator.MoveMouseTo(100, 100);
EXPECT_FALSE(delegate.has_window());
EXPECT_EQ("100,100",
Env::GetInstance()->last_mouse_location().ToString());
}
} // namespace aura
|
/**
* @copyright
* Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/LICENSE.txt
*/
#include "BoundaryElementsAtPoint.h"
#include "GeoLib/Point.h"
#include "MeshLib/Elements/Element.h"
#include "MeshLib/Elements/Point.h"
#include "MeshLib/Mesh.h"
#include "MeshLib/MeshSearch/ElementSearch.h"
#include "MeshLib/Node.h"
#include "MeshGeoToolsLib/MeshNodeSearcher.h"
namespace MeshGeoToolsLib
{
BoundaryElementsAtPoint::BoundaryElementsAtPoint(
MeshLib::Mesh const &mesh, MeshNodeSearcher &mshNodeSearcher,
GeoLib::Point const &point)
: _mesh(mesh), _point(point)
{
auto const node_ids = mshNodeSearcher.getMeshNodeIDs(_point);
assert(node_ids.size() == 1);
std::array<MeshLib::Node*, 1> const nodes = {{
const_cast<MeshLib::Node*>(_mesh.getNode(node_ids[0]))}};
_boundary_elements.push_back(new MeshLib::Point{nodes, node_ids[0]});
}
BoundaryElementsAtPoint::~BoundaryElementsAtPoint()
{
for (auto p : _boundary_elements)
delete p;
}
} // MeshGeoToolsLib
|
#include "Graph.h"
GGraph::GGraph() {}
GGraph::~GGraph() {}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.