hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f34302dc5b9873b155a29491bfc830d39f7f65d3 | 31,308 | cpp | C++ | vendor/dock/DockContainerWidget.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 642 | 2017-12-10T14:22:04.000Z | 2022-03-03T15:23:23.000Z | vendor/dock/DockContainerWidget.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 151 | 2017-12-21T02:08:45.000Z | 2020-07-03T14:18:51.000Z | vendor/dock/DockContainerWidget.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 30 | 2018-09-11T14:06:31.000Z | 2021-11-09T04:19:00.000Z | /*******************************************************************************
** Qt Advanced Docking System
** Copyright (C) 2017 Uwe Kindler
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
//============================================================================
/// \file DockContainerWidget.cpp
/// \author Uwe Kindler
/// \date 24.02.2017
/// \brief Implementation of CDockContainerWidget class
//============================================================================
//============================================================================
// INCLUDES
//============================================================================
#include "DockContainerWidget.h"
#include <iostream>
#include <QEvent>
#include <QGridLayout>
#include <QList>
#include <QPointer>
#include <QTextStream>
#include <QVariant>
#include <QXmlStreamWriter>
#include "DockAreaWidget.h"
#include "DockManager.h"
#include "DockOverlay.h"
#include "DockSplitter.h"
#include "DockStateSerialization.h"
#include "DockWidget.h"
#include "FloatingDockContainer.h"
#include "ads_globals.h"
namespace ads {
static unsigned int zOrderCounter = 0;
/**
* Helper function to ease insertion of dock area into splitter
*/
static void insertWidgetIntoSplitter(QSplitter *Splitter, QWidget *widget, bool Append) {
if (Append) {
Splitter->addWidget(widget);
} else {
Splitter->insertWidget(0, widget);
}
}
/**
* Private data class of CDockContainerWidget class (pimpl)
*/
struct DockContainerWidgetPrivate {
CDockContainerWidget *_this;
QPointer<CDockManager> DockManager;
unsigned int zOrderIndex = 0;
QList<CDockAreaWidget *> DockAreas;
QGridLayout *Layout = nullptr;
QSplitter *RootSplitter;
bool isFloating = false;
/**
* Private data constructor
*/
DockContainerWidgetPrivate(CDockContainerWidget *_public);
/**
* Adds dock widget to container and returns the dock area that contains
* the inserted dock widget
*/
CDockAreaWidget *dockWidgetIntoContainer(DockWidgetArea area, CDockWidget *Dockwidget);
/**
* Adds dock widget to a existing DockWidgetArea
*/
CDockAreaWidget *dockWidgetIntoDockArea(DockWidgetArea area, CDockWidget *Dockwidget,
CDockAreaWidget *TargetDockArea);
/**
* Add dock area to this container
*/
void addDockArea(CDockAreaWidget *NewDockWidget, DockWidgetArea area = CenterDockWidgetArea);
/**
* Drop floating widget into container
*/
void dropIntoContainer(CFloatingDockContainer *FloatingWidget, DockWidgetArea area);
/**
* Drop floating widget into dock area
*/
void dropIntoSection(CFloatingDockContainer *FloatingWidget, CDockAreaWidget *TargetArea, DockWidgetArea area);
/**
* Adds new dock areas to the internal dock area list
*/
void addDockAreasToList(const QList<CDockAreaWidget *> NewDockAreas);
/**
* Save state of child nodes
*/
void saveChildNodesState(QXmlStreamWriter &Stream, QWidget *Widget);
/**
* Restore state of child nodes.
* \param[in] Stream The data stream that contains the serialized state
* \param[out] CreatedWidget The widget created from parsed data or 0 if
* the parsed widget was an empty splitter
* \param[in] Testing If Testing is true, only the stream data is
* parsed without modifiying anything.
*/
bool restoreChildNodes(QXmlStreamReader &Stream, QWidget *&CreatedWidget, bool Testing);
/**
* Restores a splitter.
* \see restoreChildNodes() for details
*/
bool restoreSplitter(QXmlStreamReader &Stream, QWidget *&CreatedWidget, bool Testing);
/**
* Restores a dock area.
* \see restoreChildNodes() for details
*/
bool restoreDockArea(QXmlStreamReader &Stream, QWidget *&CreatedWidget, bool Testing);
/**
* Helper function for recursive dumping of layout
*/
void dumpRecursive(int level, QWidget *widget);
}; // struct DockContainerWidgetPrivate
//============================================================================
DockContainerWidgetPrivate::DockContainerWidgetPrivate(CDockContainerWidget *_public) : _this(_public) {}
//============================================================================
void DockContainerWidgetPrivate::dropIntoContainer(CFloatingDockContainer *FloatingWidget, DockWidgetArea area) {
auto InsertParam = internal::dockAreaInsertParameters(area);
auto NewDockAreas =
FloatingWidget->dockContainer()->findChildren<CDockAreaWidget *>(QString(), Qt::FindChildrenRecursively);
CDockWidget *DockWidget = FloatingWidget->dockContainer()->findChild<CDockWidget *>();
QSplitter *Splitter = RootSplitter;
if (DockAreas.count() <= 1) {
Splitter->setOrientation(InsertParam.orientation());
} else if (Splitter->orientation() != InsertParam.orientation()) {
QSplitter *NewSplitter = internal::newSplitter(InsertParam.orientation());
QLayoutItem *li = Layout->replaceWidget(Splitter, NewSplitter);
NewSplitter->addWidget(Splitter);
Splitter = NewSplitter;
delete li;
}
// Now we can insert the floating widget content into this container
auto FloatingSplitter = FloatingWidget->dockContainer()->rootSplitter();
if (FloatingSplitter->count() == 1) {
insertWidgetIntoSplitter(Splitter, FloatingSplitter->widget(0), InsertParam.append());
} else if (FloatingSplitter->orientation() == InsertParam.orientation()) {
while (FloatingSplitter->count()) {
insertWidgetIntoSplitter(Splitter, FloatingSplitter->widget(0), InsertParam.append());
}
} else {
insertWidgetIntoSplitter(Splitter, FloatingSplitter, InsertParam.append());
}
RootSplitter = Splitter;
addDockAreasToList(NewDockAreas);
FloatingWidget->deleteLater();
if (DockWidget) {
DockWidget->toggleView(true);
}
_this->dumpLayout();
}
//============================================================================
void DockContainerWidgetPrivate::dropIntoSection(CFloatingDockContainer *FloatingWidget,
CDockAreaWidget *TargetArea, DockWidgetArea area) {
CDockContainerWidget *FloatingContainer = FloatingWidget->dockContainer();
if (area == CenterDockWidgetArea) {
auto NewDockWidgets =
FloatingContainer->findChildren<CDockWidget *>(QString(), Qt::FindChildrenRecursively);
for (auto DockWidget : NewDockWidgets) {
TargetArea->insertDockWidget(0, DockWidget, false);
}
TargetArea->setCurrentIndex(0); // make the topmost widget active
FloatingWidget->deleteLater();
TargetArea->updateDockArea();
return;
}
auto InsertParam = internal::dockAreaInsertParameters(area);
auto NewDockAreas =
FloatingWidget->dockContainer()->findChildren<CDockAreaWidget *>(QString(), Qt::FindChildrenRecursively);
QSplitter *TargetAreaSplitter = internal::findParent<QSplitter *>(TargetArea);
if (!TargetAreaSplitter) {
QSplitter *Splitter = internal::newSplitter(InsertParam.orientation());
Layout->replaceWidget(TargetArea, Splitter);
Splitter->addWidget(TargetArea);
TargetAreaSplitter = Splitter;
}
int AreaIndex = TargetAreaSplitter->indexOf(TargetArea);
auto Widget = FloatingWidget->dockContainer()->findChild<QWidget *>(QString(), Qt::FindDirectChildrenOnly);
auto FloatingSplitter = dynamic_cast<QSplitter *>(Widget);
if (TargetAreaSplitter->orientation() == InsertParam.orientation()) {
if ((FloatingSplitter->orientation() != InsertParam.orientation()) && FloatingSplitter->count() > 1) {
TargetAreaSplitter->insertWidget(AreaIndex + InsertParam.insertOffset(), Widget);
} else {
int InsertIndex = AreaIndex + InsertParam.insertOffset();
while (FloatingSplitter->count()) {
TargetAreaSplitter->insertWidget(InsertIndex++, FloatingSplitter->widget(0));
}
}
} else {
QSplitter *NewSplitter = internal::newSplitter(InsertParam.orientation());
if ((FloatingSplitter->orientation() != InsertParam.orientation()) && FloatingSplitter->count() > 1) {
NewSplitter->addWidget(Widget);
} else {
while (FloatingSplitter->count()) {
NewSplitter->addWidget(FloatingSplitter->widget(0));
}
}
insertWidgetIntoSplitter(NewSplitter, TargetArea, !InsertParam.append());
TargetAreaSplitter->insertWidget(AreaIndex, NewSplitter);
}
FloatingWidget->deleteLater();
addDockAreasToList(NewDockAreas);
_this->dumpLayout();
}
//============================================================================
void DockContainerWidgetPrivate::addDockAreasToList(const QList<CDockAreaWidget *> NewDockAreas) {
int CountBefore = DockAreas.count();
int NewAreaCount = NewDockAreas.count();
DockAreas.append(NewDockAreas);
// We need to ensure, that the dock area title bar is visible. The title bar
// is invisible, if the dock are is a single dock area in a floating widget.
if (1 == CountBefore) {
DockAreas.at(0)->updateDockArea();
}
if (1 == NewAreaCount) {
DockAreas.last()->updateDockArea();
}
emit _this->dockAreasAdded();
}
//============================================================================
void DockContainerWidgetPrivate::saveChildNodesState(QXmlStreamWriter &s, QWidget *Widget) {
QSplitter *Splitter = dynamic_cast<QSplitter *>(Widget);
if (Splitter) {
s.writeStartElement("Splitter");
s.writeAttribute("Orientation", QString::number(Splitter->orientation()));
s.writeAttribute("Count", QString::number(Splitter->count()));
for (int i = 0; i < Splitter->count(); ++i) {
saveChildNodesState(s, Splitter->widget(i));
}
s.writeStartElement("Sizes");
for (auto Size : Splitter->sizes()) {
s.writeCharacters(QString::number(Size) + " ");
}
s.writeEndElement();
s.writeEndElement();
} else {
CDockAreaWidget *DockArea = dynamic_cast<CDockAreaWidget *>(Widget);
if (DockArea) {
DockArea->saveState(s);
}
}
}
//============================================================================
bool DockContainerWidgetPrivate::restoreSplitter(QXmlStreamReader &s, QWidget *&CreatedWidget, bool Testing) {
bool Ok;
int Orientation = s.attributes().value("Orientation").toInt(&Ok);
if (!Ok) {
return false;
}
int WidgetCount = s.attributes().value("Count").toInt(&Ok);
if (!Ok) {
return false;
}
QSplitter *Splitter = nullptr;
if (!Testing) {
Splitter = internal::newSplitter((Qt::Orientation) Orientation);
}
bool Visible = false;
QList<int> Sizes;
while (s.readNextStartElement()) {
QWidget *ChildNode = nullptr;
bool Result = true;
if (s.name() == "Splitter") {
Result = restoreSplitter(s, ChildNode, Testing);
} else if (s.name() == "DockAreaWidget") {
Result = restoreDockArea(s, ChildNode, Testing);
} else if (s.name() == "Sizes") {
QString sSizes = s.readElementText().trimmed();
QTextStream TextStream(&sSizes);
while (!TextStream.atEnd()) {
int value;
TextStream >> value;
Sizes.append(value);
}
} else {
s.skipCurrentElement();
}
if (!Result) {
return false;
}
if (Testing || !ChildNode) {
continue;
}
Splitter->addWidget(ChildNode);
Visible |= ChildNode->isVisibleTo(Splitter);
}
if (Sizes.count() != WidgetCount) {
return false;
}
if (!Testing) {
if (!Splitter->count()) {
delete Splitter;
Splitter = nullptr;
} else {
Splitter->setSizes(Sizes);
Splitter->setVisible(Visible);
}
CreatedWidget = Splitter;
} else {
CreatedWidget = nullptr;
}
return true;
}
//============================================================================
bool DockContainerWidgetPrivate::restoreDockArea(QXmlStreamReader &s, QWidget *&CreatedWidget, bool Testing) {
bool Ok;
s.attributes().value("Tabs").toInt(&Ok);
if (!Ok) {
return false;
}
int CurrentIndex = s.attributes().value("CurrentIndex").toInt(&Ok);
if (!Ok) {
return false;
}
CDockAreaWidget *DockArea = nullptr;
if (!Testing) {
DockArea = new CDockAreaWidget(DockManager, _this);
}
while (s.readNextStartElement()) {
if (s.name() != "DockWidget") {
continue;
}
auto ObjectName = s.attributes().value("ObjectName");
if (ObjectName.isEmpty()) {
return false;
}
bool Closed = s.attributes().value("Closed").toInt(&Ok);
if (!Ok) {
return false;
}
s.skipCurrentElement();
CDockWidget *DockWidget = DockManager->findDockWidget(ObjectName.toString());
if (!DockWidget || Testing) {
continue;
}
DockArea->addDockWidget(DockWidget);
DockArea->hide();
DockWidget->setToggleViewActionChecked(!Closed);
DockWidget->setProperty("closed", Closed);
DockWidget->setProperty("dirty", false);
}
if (Testing) {
return true;
}
if (!DockArea->count()) {
delete DockArea;
DockArea = nullptr;
} else {
DockArea->setProperty("currentIndex", CurrentIndex);
DockAreas.append(DockArea);
}
CreatedWidget = DockArea;
return true;
}
//============================================================================
bool DockContainerWidgetPrivate::restoreChildNodes(QXmlStreamReader &s, QWidget *&CreatedWidget, bool Testing) {
bool Result = true;
while (s.readNextStartElement()) {
if (s.name() == "Splitter") {
Result = restoreSplitter(s, CreatedWidget, Testing);
} else if (s.name() == "DockAreaWidget") {
Result = restoreDockArea(s, CreatedWidget, Testing);
} else {
s.skipCurrentElement();
}
}
return Result;
}
//============================================================================
CDockAreaWidget *DockContainerWidgetPrivate::dockWidgetIntoContainer(DockWidgetArea area, CDockWidget *Dockwidget) {
CDockAreaWidget *NewDockArea = new CDockAreaWidget(DockManager, _this);
NewDockArea->addDockWidget(Dockwidget);
addDockArea(NewDockArea, area);
return NewDockArea;
}
//============================================================================
void DockContainerWidgetPrivate::addDockArea(CDockAreaWidget *NewDockArea, DockWidgetArea area) {
auto InsertParam = internal::dockAreaInsertParameters(area);
// As long as we have only one dock area in the splitter we can adjust
// its orientation
if (DockAreas.count() <= 1) {
RootSplitter->setOrientation(InsertParam.orientation());
}
QSplitter *Splitter = RootSplitter;
if (Splitter->orientation() == InsertParam.orientation()) {
insertWidgetIntoSplitter(Splitter, NewDockArea, InsertParam.append());
} else {
QSplitter *NewSplitter = internal::newSplitter(InsertParam.orientation());
if (InsertParam.append()) {
QLayoutItem *li = Layout->replaceWidget(Splitter, NewSplitter);
NewSplitter->addWidget(Splitter);
NewSplitter->addWidget(NewDockArea);
delete li;
} else {
NewSplitter->addWidget(NewDockArea);
QLayoutItem *li = Layout->replaceWidget(Splitter, NewSplitter);
NewSplitter->addWidget(Splitter);
delete li;
}
RootSplitter = NewSplitter;
}
DockAreas.append(NewDockArea);
NewDockArea->updateDockArea();
emit _this->dockAreasAdded();
}
//============================================================================
void DockContainerWidgetPrivate::dumpRecursive(int level, QWidget *widget) {
#if defined(QT_DEBUG)
QSplitter *Splitter = dynamic_cast<QSplitter *>(widget);
QByteArray buf;
buf.fill(' ', level * 4);
if (Splitter) {
for (int i = 0; i < Splitter->count(); ++i) {
dumpRecursive(level + 1, Splitter->widget(i));
}
} else {
CDockAreaWidget *DockArea = dynamic_cast<CDockAreaWidget *>(widget);
if (!DockArea) {
return;
}
}
#else
Q_UNUSED(level);
Q_UNUSED(widget);
#endif
}
//============================================================================
CDockAreaWidget *DockContainerWidgetPrivate::dockWidgetIntoDockArea(DockWidgetArea area, CDockWidget *Dockwidget,
CDockAreaWidget *TargetDockArea) {
if (CenterDockWidgetArea == area) {
TargetDockArea->addDockWidget(Dockwidget);
return TargetDockArea;
}
CDockAreaWidget *NewDockArea = new CDockAreaWidget(DockManager, _this);
NewDockArea->addDockWidget(Dockwidget);
auto InsertParam = internal::dockAreaInsertParameters(area);
QSplitter *TargetAreaSplitter = internal::findParent<QSplitter *>(TargetDockArea);
int index = TargetAreaSplitter->indexOf(TargetDockArea);
if (TargetAreaSplitter->orientation() == InsertParam.orientation()) {
TargetAreaSplitter->insertWidget(index + InsertParam.insertOffset(), NewDockArea);
} else {
QSplitter *NewSplitter = internal::newSplitter(InsertParam.orientation());
NewSplitter->addWidget(TargetDockArea);
insertWidgetIntoSplitter(NewSplitter, NewDockArea, InsertParam.append());
TargetAreaSplitter->insertWidget(index, NewSplitter);
}
DockAreas.append(NewDockArea);
emit _this->dockAreasAdded();
return NewDockArea;
}
//============================================================================
CDockContainerWidget::CDockContainerWidget(CDockManager *DockManager, QWidget *parent)
: QFrame(parent), d(new DockContainerWidgetPrivate(this)) {
d->isFloating = dynamic_cast<CFloatingDockContainer *>(parent) != 0;
// setStyleSheet("background: green;");
d->DockManager = DockManager;
if (DockManager != this) {
d->DockManager->registerDockContainer(this);
}
d->Layout = new QGridLayout();
d->Layout->setContentsMargins(0, 1, 0, 1);
d->Layout->setSpacing(0);
setLayout(d->Layout);
d->RootSplitter = internal::newSplitter(Qt::Horizontal);
d->Layout->addWidget(d->RootSplitter);
}
//============================================================================
CDockContainerWidget::~CDockContainerWidget() {
if (d->DockManager) {
d->DockManager->removeDockContainer(this);
}
delete d;
}
//============================================================================
CDockAreaWidget *CDockContainerWidget::addDockWidget(DockWidgetArea area, CDockWidget *Dockwidget,
CDockAreaWidget *DockAreaWidget) {
CDockAreaWidget *OldDockArea = Dockwidget->dockAreaWidget();
if (OldDockArea) {
OldDockArea->removeDockWidget(Dockwidget);
}
Dockwidget->setDockManager(d->DockManager);
if (DockAreaWidget) {
return d->dockWidgetIntoDockArea(area, Dockwidget, DockAreaWidget);
} else {
return d->dockWidgetIntoContainer(area, Dockwidget);
}
}
//============================================================================
unsigned int CDockContainerWidget::zOrderIndex() const { return d->zOrderIndex; }
//============================================================================
bool CDockContainerWidget::isInFrontOf(CDockContainerWidget *Other) const {
return this->zOrderIndex() > Other->zOrderIndex();
}
//============================================================================
bool CDockContainerWidget::event(QEvent *e) {
bool Result = QWidget::event(e);
if (e->type() == QEvent::WindowActivate) {
d->zOrderIndex = ++zOrderCounter;
} else if (e->type() == QEvent::Show && !d->zOrderIndex) {
d->zOrderIndex = ++zOrderCounter;
}
return Result;
}
//============================================================================
void CDockContainerWidget::addDockArea(CDockAreaWidget *DockAreaWidget, DockWidgetArea area) {
CDockContainerWidget *Container = DockAreaWidget->dockContainer();
if (Container && Container != this) {
Container->removeDockArea(DockAreaWidget);
}
d->addDockArea(DockAreaWidget, area);
}
//============================================================================
void CDockContainerWidget::removeDockArea(CDockAreaWidget *area) {
d->DockAreas.removeAll(area);
CDockSplitter *Splitter = internal::findParent<CDockSplitter *>(area);
// Remove are from parent splitter and hide splitter if it has no visible
// content
area->setParent(0);
Splitter->setVisible(Splitter->hasVisibleContent());
// If splitter has more than 1 widgets, we are finished and can leave
if (Splitter->count() > 1) {
goto emitAndExit;
}
// If this is the RootSplitter we need to remove empty splitters to
// avoid too many empty splitters
if (Splitter == d->RootSplitter) {
// If splitter is empty, we are finished
if (!Splitter->count()) {
Splitter->hide();
goto emitAndExit;
}
QWidget *widget = Splitter->widget(0);
QSplitter *ChildSplitter = dynamic_cast<QSplitter *>(widget);
// If the one and only content widget of the splitter is not a splitter
// then we are finished
if (!ChildSplitter) {
goto emitAndExit;
}
// We replace the superfluous RootSplitter with the ChildSplitter
ChildSplitter->setParent(0);
QLayoutItem *li = d->Layout->replaceWidget(Splitter, ChildSplitter);
d->RootSplitter = ChildSplitter;
delete li;
} else if (Splitter->count() == 1) {
QWidget *widget = Splitter->widget(0);
widget->setParent(this);
QSplitter *ParentSplitter = internal::findParent<QSplitter *>(Splitter);
internal::replaceSplitterWidget(ParentSplitter, Splitter, widget);
}
delete Splitter;
emitAndExit:
dumpLayout();
emit dockAreasRemoved();
}
//============================================================================
CDockAreaWidget *CDockContainerWidget::dockAreaAt(const QPoint &GlobalPos) const {
for (const auto &DockArea : d->DockAreas) {
if (DockArea->isVisible() && DockArea->rect().contains(DockArea->mapFromGlobal(GlobalPos))) {
return DockArea;
}
}
return 0;
}
//============================================================================
CDockAreaWidget *CDockContainerWidget::dockArea(int Index) const {
return (Index < dockAreaCount()) ? d->DockAreas[Index] : 0;
}
//============================================================================
bool CDockContainerWidget::isFloating() const { return d->isFloating; }
//============================================================================
int CDockContainerWidget::dockAreaCount() const { return d->DockAreas.count(); }
//============================================================================
int CDockContainerWidget::visibleDockAreaCount() const {
// TODO Cache or precalculate this to speed it up because it is used during
// movement of floating widget
int Result = 0;
for (auto DockArea : d->DockAreas) {
Result += DockArea->isVisible() ? 1 : 0;
}
return Result;
}
//============================================================================
void CDockContainerWidget::dropFloatingWidget(CFloatingDockContainer *FloatingWidget, const QPoint &TargetPos) {
CDockAreaWidget *DockArea = dockAreaAt(TargetPos);
auto dropArea = InvalidDockWidgetArea;
auto ContainerDropArea = d->DockManager->containerOverlay()->dropAreaUnderCursor();
if (DockArea) {
auto dropOverlay = d->DockManager->dockAreaOverlay();
dropOverlay->setAllowedAreas(AllDockAreas);
dropArea = dropOverlay->showOverlay(DockArea);
if (ContainerDropArea != InvalidDockWidgetArea && ContainerDropArea != dropArea) {
dropArea = InvalidDockWidgetArea;
}
if (dropArea != InvalidDockWidgetArea) {
d->dropIntoSection(FloatingWidget, DockArea, dropArea);
}
}
// mouse is over container
if (InvalidDockWidgetArea == dropArea) {
dropArea = ContainerDropArea;
if (dropArea != InvalidDockWidgetArea) {
d->dropIntoContainer(FloatingWidget, dropArea);
}
}
}
//============================================================================
QList<CDockAreaWidget *> CDockContainerWidget::openedDockAreas() const {
QList<CDockAreaWidget *> Result;
for (auto DockArea : d->DockAreas) {
if (DockArea->isVisible()) {
Result.append(DockArea);
}
}
return Result;
}
//============================================================================
void CDockContainerWidget::saveState(QXmlStreamWriter &s) const {
s.writeStartElement("DockContainerWidget");
s.writeAttribute("Floating", QString::number(isFloating() ? 1 : 0));
if (isFloating()) {
CFloatingDockContainer *FloatingWidget = internal::findParent<CFloatingDockContainer *>(this);
QByteArray Geometry = FloatingWidget->saveGeometry();
s.writeTextElement("Geometry", Geometry.toHex(' '));
}
d->saveChildNodesState(s, d->RootSplitter);
s.writeEndElement();
}
//============================================================================
bool CDockContainerWidget::restoreState(QXmlStreamReader &s, bool Testing) {
bool IsFloating = s.attributes().value("Floating").toInt();
QWidget *NewRootSplitter{};
if (!Testing) {
d->DockAreas.clear();
}
if (IsFloating) {
if (!s.readNextStartElement() || s.name() != "Geometry") {
return false;
}
QByteArray GeometryString = s.readElementText(QXmlStreamReader::ErrorOnUnexpectedElement).toLocal8Bit();
QByteArray Geometry = QByteArray::fromHex(GeometryString);
std::cout << "Geometry: " << Geometry.toHex(' ').toStdString() << std::endl;
if (Geometry.isEmpty()) {
return false;
}
if (!Testing) {
CFloatingDockContainer *FloatingWidget = internal::findParent<CFloatingDockContainer *>(this);
FloatingWidget->restoreGeometry(Geometry);
}
}
if (!d->restoreChildNodes(s, NewRootSplitter, Testing)) {
return false;
}
if (Testing) {
return true;
}
// If the root splitter is empty, rostoreChildNodes returns a 0 pointer
// and we need to create a new empty root splitter
if (!NewRootSplitter) {
NewRootSplitter = internal::newSplitter(Qt::Horizontal);
}
d->Layout->replaceWidget(d->RootSplitter, NewRootSplitter);
QSplitter *OldRoot = d->RootSplitter;
d->RootSplitter = dynamic_cast<QSplitter *>(NewRootSplitter);
OldRoot->deleteLater();
return true;
}
//============================================================================
QSplitter *CDockContainerWidget::rootSplitter() const { return d->RootSplitter; }
//============================================================================
void CDockContainerWidget::dumpLayout() {}
} // namespace ads
//---------------------------------------------------------------------------
// EOF DockContainerWidget.cpp
| 39.086142 | 120 | 0.540118 | [
"geometry"
] |
f34629ef3c65bfbbb0c5520bff36f85bc923cc76 | 13,922 | cpp | C++ | capBAC/subject.cpp | jtracey/cuddly-fiesta | 7725f567f6eb85f7c0940c531d21d6dbd50a8767 | [
"Apache-2.0"
] | null | null | null | capBAC/subject.cpp | jtracey/cuddly-fiesta | 7725f567f6eb85f7c0940c531d21d6dbd50a8767 | [
"Apache-2.0"
] | null | null | null | capBAC/subject.cpp | jtracey/cuddly-fiesta | 7725f567f6eb85f7c0940c531d21d6dbd50a8767 | [
"Apache-2.0"
] | null | null | null | //USAGE : ./name <filename_of_instructions> <PORT_NO_ISSUER> <MODE(1/2)>
//compile with -lcrypto
//For dump_mem comparison of Digests (uncomment dump_mem and compile with base64.o,cencode.o,cdecode.o)
/*
TO-DO's :
remove read_keypair
create_keypair
In Mode1_get_token from socket write json to json_message, and remove retrieveing json from file
Remove hard-coded keys
*/
#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
#include <sstream>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>
#include <unordered_map>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "base64.h"
using namespace std;
using namespace rapidjson;
#define MACHINE_IP inet_addr("127.0.0.1")
#define TOKEN_IDENTIFIER_SIZE 17
int port_verifier;
int port_issuer;
int run_mode;
typedef unordered_map<string,string> map_tokens;
typedef std::pair<string,string> record;
map_tokens map_table;
map_tokens resource_to_json;
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
char* get_json(int fd) {
char* json;
size_t size = TOKENSIZE;
unsigned int offset;
json = (char*) realloc(NULL, sizeof(char)*size);
if(!json) {
fprintf(stdout, "get_json: Failure to realloc\n");
exit(1);
}
offset = 0;
do {
if (offset == size) {
json = (char*) realloc(json, sizeof(char)*(size += 16));
if(!json) {
fprintf(stdout, "get_json: Failure to realloc\n");
exit(1);
}
}
if(read(fd, json+offset, 1) <= 0) {
fprintf(stdout, "get_json: EOF encountered. ERROR STRING : %s \n",strerror(errno));
char c = json[offset];
json[offset] = 0;
fprintf(stdout, "story so far (%d): %s%c\n", offset, json, c);
exit(1);
}
offset++;
} while (json[offset-1] != 0);
fprintf(stdout, "DEBUG: get_json: json at %p: %s\n", json, json);
return json;
}
int get_token(const char *resource_name, EC_KEY **ec_key, char **json_message)
{
int soc;
uint16_t port = port_issuer;
BIGNUM *x, *y;
x = BN_new();
y = BN_new();
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc == -1) {
printf("Socket Failed\n");
close(soc);
return 1;
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
EC_GROUP* ec_group_new = EC_GROUP_new_by_curve_name(NID_X9_62_prime192v3);
const EC_GROUP *ec_group = ec_group_new;
const EC_POINT *ec_point = EC_KEY_get0_public_key(*ec_key);
BN_CTX *ctx;
ctx = BN_CTX_new();
EC_POINT_get_affine_coordinates_GFp(ec_group, ec_point, x, y, ctx);
char pub_key_b64[B64SIZE];
base64encode(pub_key_b64, x, y);
char *message;
message = (char *) malloc(B64SIZE + strlen(resource_name) + 2);
snprintf(message, B64SIZE+1, "%s", pub_key_b64);
strcat(message, "\n");
strcat(message,resource_name);
printf("MESSAGE: \n%s\n",message);
if(connect(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
printf("get_token: failed to connect: %s\n", strerror(errno));
}
if(write(soc, message, strlen(message)+1) < 0) {
printf("Failed to write to socket\n");
}
*json_message = get_json(soc);
close(soc);
return 0;
}
int send_token(unsigned char **sig, unsigned int *sig_len, char **json_message, size_t *json_length)
{
int soc;
unsigned char response;
uint16_t port = port_verifier;
soc = socket(AF_INET, SOCK_STREAM, 0);
if(soc < 0) {
printf("failed to create socket: %s\n", strerror(errno));
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(connect(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
printf("send_token: failed to connect: %s\n", strerror(errno));
}
printf("SEND_TOKEN : %s\n",*json_message);
if(write(soc, *json_message, (*json_length)+1) < 0) {
printf("Failed to write to socket\n");
}
if(write(soc, *sig, (*sig_len)) < 0) {
printf("Failed to write to socket\n");
}
if(read(soc, &response, 1) < 0) {
printf("Failed to read RESPONSE_LENGTH from socket\n");
}
close(soc);
cout << "RESPONSE : "<<response <<endl;
return 0;
}
int create_keypair(const char * client_name, EC_KEY **ec_key)
{
*ec_key = EC_KEY_new();
EC_GROUP* ec_group_new = EC_GROUP_new_by_curve_name(NID_X9_62_prime192v3);
const EC_GROUP *ec_group = ec_group_new;
if(!EC_KEY_set_group(*ec_key,ec_group)) {
printf("EC_KEY_set_group Error\n");
return 1;
}
if(!EC_KEY_generate_key(*ec_key)) {
printf("Generatekey Error\n");
return 1;
}
FILE *keys = fopen(client_name,"w");
//Save Private Key to File
const BIGNUM *private_key = EC_KEY_get0_private_key(*ec_key);
char *priv_hex = BN_bn2hex(private_key);
printf("%s\n",priv_hex);
fwrite(priv_hex,sizeof(char),strlen(priv_hex),keys);
fwrite("\n", sizeof(char) ,1,keys);
//Save Public Key to file
const EC_POINT *public_key = EC_KEY_get0_public_key(*ec_key);
BN_CTX *ctx;
ctx = BN_CTX_new();
char *pub_hex = EC_POINT_point2hex(ec_group, public_key, POINT_CONVERSION_COMPRESSED, ctx);
printf("%s\n",pub_hex);
fwrite(pub_hex,sizeof(char),strlen(pub_hex),keys);
// TO-DO FREE RELATED Contexts
fclose(keys);
return 0;
}
int read_keypair(const char* client_name, EC_KEY **ec_key)
{
*ec_key = EC_KEY_new();
EC_GROUP* ec_group_new = EC_GROUP_new_by_curve_name(NID_X9_62_prime192v3);
const EC_GROUP *ec_group = ec_group_new;
if(!EC_KEY_set_group(*ec_key,ec_group))
printf("EC_KEY_set_group Error\n");
BIGNUM *private_key_bn;
BN_CTX *ctx;
FILE *keys = fopen(client_name,"r");
size_t len_pub = 0, len_priv = 0;
char *private_key = NULL;
getline(&private_key, &len_priv, keys);
char *public_key = NULL;
getline(&public_key, &len_pub, keys);
ctx = BN_CTX_new();
private_key_bn = BN_new();
if(!BN_hex2bn(&private_key_bn, private_key))
printf("Hex2BN failed\n");
EC_KEY_set_private_key(*ec_key,private_key_bn);
EC_KEY_set_public_key( *ec_key,
EC_POINT_hex2point(EC_KEY_get0_group(*ec_key),public_key, NULL,ctx));
fclose(keys);
return 0;
}
int sign_token(EC_KEY **ec_key, unsigned char **sig, unsigned int *sig_len, char **json_message, size_t *json_length)
{
const EVP_MD* md;
EVP_MD_CTX* mdctx;
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
cout <<"Signing : " <<*json_message << endl;
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha256");
if(md == 0) {
printf("Unknown Message Digest\n");
return 1;
}
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, *json_message, (*json_length));
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
*sig_len = ECDSA_size(*ec_key);
*sig = (unsigned char*) OPENSSL_malloc(*sig_len);
if(! ECDSA_sign(0, md_value, md_len, *sig, sig_len, *ec_key)) {
printf("Signing Failed \n");
return 1;
}
return 0;
}
int mode1_access_resource( const char *resource_name, EC_KEY **ec_key)
{
unsigned char *sig;
unsigned int sig_len;
size_t json_length;
char *json_message;
unordered_map<string,string>::iterator iter;
if((iter = resource_to_json.find(string(resource_name))) == resource_to_json.end()) {
printf("\nNot found in map : sending for new token\n");
get_token(resource_name, ec_key, &json_message);
cout<< "\nJSON_MESSAGE_RECIEVED : " << json_message << endl;
json_length = strlen(json_message);
//record r1 = make_pair(string(resource_name), string(json_message));
string res_name = string(resource_name);
string json_token = string(json_message);
record r1 = make_pair(res_name, json_token);
resource_to_json.insert(r1);
}
else {
cout<<"\nLOAD_TOKEN_FROM_TABLE :\n";
json_message = (char *) malloc ((*iter).second.length()+1);
strcpy(json_message, (*iter).second.c_str());
json_length = strlen(json_message);
//Insert Token Expiry Validation Check here
}
sign_token(ec_key, &sig, &sig_len, &json_message, &json_length);
send_token(&sig, &sig_len, &json_message, &json_length);
return 0;
}
int mode2_send_token_identifier(char **token_identifier)
{
int soc;
char response;
uint16_t port = port_verifier;
soc = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
if(connect(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
printf("failed to connect: %s\n", strerror(errno));
}
printf("SEND_TOKEN_IDENTIFIER: %s\n", *token_identifier);
if(write(soc, *token_identifier, TOKEN_IDENTIFIER_SIZE) < 0) {
printf("Failed to write to socket\n");
}
if(read(soc, &response, 1) < 0) {
printf("Failed to read RESPONSE_LENGTH from socket\n");
}
cout << "RESPONSE : " << response <<endl;
close(soc);
return 0;
}
int mode2_get_token_identifier(const char *resource_name, EC_KEY **ec_key, char **token_identifier )
{
std::string map_key = std::to_string(port_verifier);
map_key.append(std::to_string(*resource_name));
if(map_table.find(map_key) == map_table.end())
{
int soc;
uint16_t port = port_issuer;
BIGNUM *x, *y;
x = BN_new();
y = BN_new();
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc == -1) {
printf("Socket Failed\n");
return 1;
}
struct sockaddr_in connectAddress;
memset(&connectAddress, 0, sizeof(connectAddress));
connectAddress.sin_family = AF_INET;
connectAddress.sin_addr.s_addr = MACHINE_IP;
connectAddress.sin_port = htons(port);
EC_GROUP* ec_group_new = EC_GROUP_new_by_curve_name(NID_X9_62_prime192v3);
const EC_GROUP *ec_group = ec_group_new;
const EC_POINT *ec_point = EC_KEY_get0_public_key(*ec_key);
BN_CTX *ctx;
ctx = BN_CTX_new();
EC_POINT_get_affine_coordinates_GFp(ec_group, ec_point, x, y, ctx);
char pub_key_b64[B64SIZE];
base64encode(pub_key_b64, x, y);
char *message;
message = (char *) malloc(B64SIZE + strlen(resource_name) + 2);
snprintf(message, B64SIZE, "%s", pub_key_b64);
strcat(message, "\n");
strcat(message,resource_name);
strcat(message, "\n");
strcat(message, std::to_string(port_verifier).c_str());
printf("MESSAGE: \n%s\n",message);
if(connect(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
printf("failed to connect: %s\n", strerror(errno));
}
if(write(soc, message, strlen(message)+1) < 0) {
printf("Failed to write to socket\n");
}
if(read(soc, *token_identifier, 17)<0) {
printf("Read from socket Failed\n");
}
cout<<"GOT_TOKEN_IDENTIFIER_FROM_ISSUER:"<< *token_identifier <<endl;
record r1 = make_pair(map_key, string(*token_identifier));
map_table.insert(r1);
close(soc);
}
else
{
strcpy(*token_identifier,(*(map_table.find(map_key))).second.c_str());
}
return 0;
}
int mode2_access_resource( const char *resource_name, EC_KEY **ec_key)
{
char *token_identifier;
token_identifier = (char *) malloc(TOKEN_IDENTIFIER_SIZE);
mode2_get_token_identifier(resource_name, ec_key, &token_identifier);
mode2_send_token_identifier(&token_identifier);
return 0;
}
void parse(string buffer, EC_KEY **ec_key)
{
std::vector<std::string> token_vector;
token_vector = split(buffer,' ');
std::vector<std::string>::iterator token_iterator = token_vector.begin();
// NOTE : No robustness checks in parser, assuming worlkload generation file will ALWAYS be correct.
while(token_iterator != token_vector.end()) {
if((*token_iterator).compare("#")==0)
{
//Ignore comment line (Note : comment line must have space "# ")
}
else if((*token_iterator).compare("creater")==0)
{
string resource_name = *(++token_iterator);
// Create Resource ?
}
else if((*token_iterator).compare("createc")==0)
{
string client_name = *(++token_iterator);
create_keypair(client_name.c_str(), ec_key);
}
else if((*token_iterator).compare("removec")==0)
{
string client_name = *(++token_iterator);
//Remove client key files
}
else if((*token_iterator).compare("remover")==0)
{
string resource_name = *(++token_iterator);
//Remove Resource ?
}
else if((*token_iterator).compare("access")==0)
{
string client_name = *(++token_iterator);
port_verifier = atoi(client_name.c_str());
string resource_name = *(++token_iterator);
printf("PORT : %d\n", port_verifier);
if(run_mode == 1)
mode1_access_resource(resource_name.c_str(), ec_key);
else if(run_mode == 2)
mode2_access_resource(resource_name.c_str(), ec_key);
}
token_iterator++;
}
}
int main(int argc, char *argv[])
{
EC_KEY *ec_key;
if(argc <= 3) {
printf("insufficient aguments\n");
return 1;
}
ifstream input_file(argv[1],std::ifstream::binary);
string buffer;
port_issuer = atoi(argv[2]);
run_mode = atoi(argv[3]);
while(!input_file.eof())
{
getline(input_file, buffer);
parse(buffer, &ec_key);
}
return 0;
}
| 26.619503 | 117 | 0.680147 | [
"vector"
] |
f34678795a7c428b15fbe951614e3250e95df0f5 | 6,396 | cpp | C++ | src/stats.cpp | davek44/Quake | f6e5381d2410bf3d19e6964fb3c345c81fa2f58a | [
"Artistic-2.0"
] | 1 | 2016-01-11T00:40:21.000Z | 2016-01-11T00:40:21.000Z | src/stats.cpp | davek44/Quake | f6e5381d2410bf3d19e6964fb3c345c81fa2f58a | [
"Artistic-2.0"
] | 2 | 2016-05-08T15:11:56.000Z | 2018-07-03T20:08:19.000Z | src/stats.cpp | davek44/Quake | f6e5381d2410bf3d19e6964fb3c345c81fa2f58a | [
"Artistic-2.0"
] | 2 | 2016-02-10T06:36:37.000Z | 2020-05-19T20:41:14.000Z | #include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <cstring>
#include <getopt.h>
#include <ext/hash_map>
namespace Sgi = ::__gnu_cxx; // GCC 4.0 and later
#define HASHMAP __gnu_cxx
using namespace::std;
////////////////////////////////////////////////////////////
// hash_map
////////////////////////////////////////////////////////////
struct eqstr {
bool operator()(const char* s1, const char* s2) const {
return strcmp(s1,s2) == 0;
}
};
namespace HASHMAP
{
template<> struct hash< std::string >
{
size_t operator()( const std::string& x ) const
{
return HASHMAP::hash< const char* >()( x.c_str() );
}
};
}
//typedef HASHMAP::hash_map<const char*, const char*, HASHMAP::hash<const char*>, eqstr> seq_hash;
//typedef HASHMAP::hash_map<const char*, const char*, HASHMAP::hash<const char*>, equal_to<string> > seq_hash;
typedef HASHMAP::hash_map<string, string> seq_hash;
////////////////////////////////////////////////////////////
// options
////////////////////////////////////////////////////////////
const static char* myopts = "r:c:IC";
// -r, fastq file of reads
static char* fastqf = NULL;
// -c, fastq file of corrected reads
static char* corf = NULL;
// -I
static bool illumina_qual = false;
// -C, Contrail output
static bool contrail_out = false;
////////////////////////////////////////////////////////////
// parse_command_line
////////////////////////////////////////////////////////////
static void parse_command_line(int argc, char **argv) {
bool errflg = false;
int ch;
optarg = NULL;
char* p;
// parse args
while(!errflg && ((ch = getopt(argc, argv, myopts)) != EOF)) {
switch(ch) {
case 'r':
fastqf = strdup(optarg);
break;
case 'c':
corf = strdup(optarg);
break;
case 'I':
illumina_qual = true;
break;
case 'C':
contrail_out = true;
break;
case '?' :
fprintf (stderr, "Unrecognized option -%c\n", optopt);
default:
errflg = true;
}
}
if(fastqf == NULL) {
cerr << "Must provide original read fastq file with -r" << endl;
exit(EXIT_FAILURE);
} else if(corf == NULL) {
// infer correction file
string fqf_str(fastqf);
unsigned int suffix_index = fqf_str.rfind(".");
corf = new char[fqf_str.size()+5];
strncpy(corf, fastqf, suffix_index);
strcat(corf, ".cor");
strncat(corf, &fastqf[suffix_index], fqf_str.size()-suffix_index);
cout << "Correction file assumed to be " << corf << endl;
}
// for some reason, optind is not advancing properly so this
// always returns an error
// return errors
/*
if(errflg || optind != argc-1) {
Usage(argv[0]);
exit(EXIT_FAILURE);
}
*/
}
////////////////////////////////////////////////////////////
// main
////////////////////////////////////////////////////////////
int main(int argc, char **argv) {
string header, seq, mid, qual;
const char * nts = "ACGT";
unsigned long oread_count = 0;
unsigned long cread_count = 0;
unsigned long correct_bp = 0;
unsigned long trim_bp = 0;
unsigned long ntnt_counts[4][4] = {0};
vector<unsigned long> pos_corrections;
vector<unsigned long> pos_trims; // to do this right, must hash on trim tag
parse_command_line(argc, argv);
////////////////////////////////////////
// hash corrections
////////////////////////////////////////
seq_hash corrected_reads;
ifstream correctionsf(corf);
unsigned int ci;
const char* crhead;
while(getline(correctionsf, header)) {
if(contrail_out) {
unsigned int line_tab = header.find('\t');
seq = header.substr(line_tab+1, header.size()-1-line_tab);
//qual = garbage...
header = header.substr(0, line_tab);
} else {
getline(correctionsf, seq);
getline(correctionsf, mid);
getline(correctionsf, qual);
}
cread_count++;
ci = header.find("correct");
//cout << header << " " << ci << endl;
if(ci != -1)
corrected_reads.insert(make_pair(header.substr(0,ci-1), seq));
}
correctionsf.close();
////////////////////////////////////////
// parse original file
////////////////////////////////////////
ifstream originalf(fastqf);
seq_hash::iterator fi;
string cseq;
while(getline(originalf, header)) {
getline(originalf, seq);
getline(originalf, mid);
getline(originalf, qual);
oread_count++;
// set up positional counts
if(pos_corrections.empty()) {
for(int p = 0; p < seq.size(); p++)
pos_corrections.push_back(0);
}
if(pos_trims.empty()) {
for(int p = 0; p < seq.size(); p++)
pos_trims.push_back(0);
}
// if corrected
fi = corrected_reads.find(header);
if(fi != corrected_reads.end()) {
cseq = fi->second;
int lastbp = correct_bp;
int i;
for(i = 0; i < cseq.size(); i++) {
// if correction
if(seq[i] != cseq[i]) {
correct_bp++;
// count nt->nt
if(seq[i] != 'N')
ntnt_counts[strchr(nts, cseq[i]) - nts][strchr(nts, seq[i]) - nts]++;
// count position - corrected and trimmed
pos_corrections[i]++;
}
}
// count trims
trim_bp += seq.size()-i;
for(; i < seq.size(); i++)
pos_trims[i]++;
if(correct_bp == lastbp)
cout << "No corrections for " << header << endl;
}
}
////////////////////////////////////////
// print stats
////////////////////////////////////////
cout << "Total reads: " << oread_count << endl << endl;
//cout << "Validated reads: " << (cread_count - ... hash trims to get this right
cout << "Tossed reads: " << (oread_count-cread_count) << endl;
cout << "Corrected reads: " << corrected_reads.size() << endl;
cout << "Corrected bp: " << correct_bp << endl;
cout << "Trimmed bp: " << trim_bp << " (incomplete)" << endl;
cout << "nt->nt error rate:" << endl;
cout << "\tA\tC\tG\tT" << endl;
for(int i = 0; i < 4; i++) {
cout << nts[i];
for(int j = 0; j < 4; j++)
cout << "\t" << ntnt_counts[i][j];
cout << endl;
}
cout << "errors by position:" << endl;
for(int i = 0; i < pos_corrections.size(); i++)
cout << (i+1) << " " << pos_corrections[i] << endl;
/* hash trims to get this right
cout << "trims by position:" << endl;
for(int i = 0; i < pos_trims.size(); i++)
cout << (i+1) << " " << pos_trims[i] << endl;
*/
return 0;
}
| 26.213115 | 111 | 0.527674 | [
"vector"
] |
f350b6e4a3634b36f924ebc4d1f31a9c142640e0 | 11,123 | cpp | C++ | tests/unit/samples.cpp | cppfw/svgren | 089832978aa25c174760de7fb5d46c803a06f11e | [
"MIT"
] | 48 | 2020-12-09T15:19:59.000Z | 2022-03-26T23:53:29.000Z | tests/unit/samples.cpp | cppfw/svgren | 089832978aa25c174760de7fb5d46c803a06f11e | [
"MIT"
] | 22 | 2020-12-01T16:21:56.000Z | 2022-01-13T15:09:12.000Z | tests/unit/samples.cpp | cppfw/svgren | 089832978aa25c174760de7fb5d46c803a06f11e | [
"MIT"
] | 8 | 2021-01-15T19:26:22.000Z | 2022-02-16T12:54:49.000Z | #include <tst/set.hpp>
#include <tst/check.hpp>
#include <regex>
#include <png.h>
#include <utki/config.hpp>
#include <utki/span.hpp>
#include <r4/vector.hpp>
#include <papki/fs_file.hpp>
#include <svgdom/dom.hpp>
#include "../../src/svgren/config.hxx"
#include "../../src/svgren/render.hpp"
namespace{
const unsigned tolerance = 10;
const std::string data_dir = "samples_data/";
const std::string render_backend_name =
#if SVGREN_BACKEND == SVGREN_BACKEND_CAIRO
"cairo"
#elif SVGREN_BACKEND == SVGREN_BACKEND_AGG
"agg"
#else
# error "Unknown rendering backend"
#endif
;
}
class Image final{
public:
/**
* @brief Image color depth.
*/
enum class ColorDepth_e{
UNKNOWN = 0,
GREY = 1, //1 channel. Only Grey channel
GREYA = 2, //2 channels. Grey with Alpha channel
RGB = 3, //3 channels. Red Green Blue channels
RGBA = 4 //4 channels. RGBA format (4 channels)
};
/**
* @brief Basic image exception.
*/
class Exc : public std::runtime_error{
public:
Exc(const std::string& msg = std::string()) :
std::runtime_error(msg.c_str())
{}
};
class IllegalArgumentExc : public Exc{
public:
IllegalArgumentExc(const std::string& msg = std::string()) :
Exc(msg)
{}
};
private:
ColorDepth_e colorDepth_v;
r4::vector2<unsigned> dim_v = 0;
std::vector<uint8_t> buf_v; // image pixels data
public:
/**
* @brief Default constructor.
* Creates uninitialized Image object.
*/
Image() :
colorDepth_v(ColorDepth_e::UNKNOWN)
{}
Image(const Image& im) = default;
/**
* @brief Get image dimensions.
* @return Image dimensions.
*/
const r4::vector2<unsigned>& dims()const noexcept{
return this->dim_v;
}
/**
* @brief Get color depth.
* @return Bits per pixel.
*/
unsigned bitsPerPixel()const{
return this->numChannels() * 8;
}
/**
* @brief Get color depth.
* @return Number of color channels.
*/
unsigned numChannels()const{
return unsigned(this->colorDepth_v);
}
/**
* @brief Get color depth.
* @return Color depth type.
*/
ColorDepth_e colorDepth()const{
return this->colorDepth_v;
}
/**
* @brief Get pixel data.
* @return Pixel data of the image.
*/
utki::span<uint8_t> buf(){
return utki::make_span(this->buf_v);
}
/**
* @brief Get pixel data.
* @return Pixel data of the image.
*/
utki::span<const uint8_t> buf()const{
return utki::make_span(this->buf_v);
}
public:
/**
* @brief Initialize this image object with given parameters.
* Pixel data remains uninitialized.
* @param dimensions - image dimensions.
* @param colorDepth - color depth.
*/
void init(r4::vector2<unsigned> dimensions, ColorDepth_e colorDepth){
this->dim_v = dimensions;
this->colorDepth_v = colorDepth;
this->buf_v.resize(this->dims().x() * this->dims().y() * this->numChannels());
}
/**
* @brief Flip image vertically.
*/
void flipVertical();
private:
static void PNG_CustomReadFunction(png_structp pngPtr, png_bytep data, png_size_t length){
papki::file* fi = reinterpret_cast<papki::file*>(png_get_io_ptr(pngPtr));
ASSERT_ALWAYS(fi)
// TRACE(<< "PNG_CustomReadFunction: fi = " << fi << " pngPtr = " << pngPtr << " data = " << std::hex << data << " length = " << length << std::endl)
try{
utki::span<png_byte> bufWrapper(data, size_t(length));
fi->read(bufWrapper);
// TRACE(<< "PNG_CustomReadFunction: fi->Read() finished" << std::endl)
}catch(...){
// do not let any exception get out of this function
// TRACE(<< "PNG_CustomReadFunction: fi->Read() failed" << std::endl)
}
}
public:
/**
* @brief Load image from PNG file.
* @param f - PNG file.
*/
void loadPNG(const papki::file& fi){
ASSERT_ALWAYS(!fi.is_open())
ASSERT_ALWAYS(this->buf_v.size() == 0)
papki::file::guard file_guard(fi); // this will guarantee that the file will be closed upon exit
// TRACE(<< "Image::LoadPNG(): file opened" << std::endl)
#define PNGSIGSIZE 8 // The size of PNG signature (max 8 bytes)
std::array<png_byte, PNGSIGSIZE> sig;
memset(&*sig.begin(), 0, sig.size() * sizeof(sig[0]));
{
auto ret = // TODO: we should not rely on that it will always read the requested number of bytes (or should we?)
fi.read(utki::make_span(sig));
ASSERT_ALWAYS(ret == sig.size() * sizeof(sig[0]))
}
if(png_sig_cmp(&*sig.begin(), 0, sig.size() * sizeof(sig[0])) != 0){ // if it is not a PNG-file
throw Image::Exc("Image::LoadPNG(): not a PNG file");
}
// Great!!! We have a PNG-file!
// TRACE(<< "Image::LoadPNG(): file is a PNG" << std::endl)
// Create internal PNG-structure to work with PNG file
// (no warning and error callbacks)
png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
png_infop infoPtr = png_create_info_struct(pngPtr);// Create structure with file info
png_set_sig_bytes(pngPtr, PNGSIGSIZE);// We've already read PNGSIGSIZE bytes
// Set custom "ReadFromFile" function
png_set_read_fn(pngPtr, const_cast<papki::file*>(&fi), PNG_CustomReadFunction);
png_read_info(pngPtr, infoPtr); // Read in all information about file
// Get information from infoPtr
png_uint_32 width = 0;
png_uint_32 height = 0;
int bitDepth = 0;
int colorType = 0;
png_get_IHDR(pngPtr, infoPtr, &width, &height, &bitDepth, &colorType, 0, 0, 0);
// Strip 16bit png to 8bit
if(bitDepth == 16){
png_set_strip_16(pngPtr);
}
// Convert paletted PNG to RGB image
if(colorType == PNG_COLOR_TYPE_PALETTE){
png_set_palette_to_rgb(pngPtr);
}
// Convert grayscale PNG to 8bit greyscale PNG
if(colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8){
png_set_expand_gray_1_2_4_to_8(pngPtr);
}
// if(png_get_valid(pngPtr, infoPtr,PNG_INFO_tRNS)) png_set_tRNS_to_alpha(pngPtr);
// set gamma information
double gamma = 0.0f;
// if there's gamma info in the file, set it to 2.2
if(png_get_gAMA(pngPtr, infoPtr, &gamma)){
png_set_gamma(pngPtr, 2.2, gamma);
}else{
png_set_gamma(pngPtr, 2.2, 0.45455); // set to 0.45455 otherwise (good guess for GIF images on PCs)
}
// update info after all transformations
png_read_update_info(pngPtr, infoPtr);
// get all dimensions and color info again
png_get_IHDR(pngPtr, infoPtr, &width, &height, &bitDepth, &colorType, 0, 0, 0);
ASSERT_ALWAYS(bitDepth == 8)
// Set image type
Image::ColorDepth_e imageType;
switch(colorType){
case PNG_COLOR_TYPE_GRAY:
imageType = Image::ColorDepth_e::GREY;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
imageType = Image::ColorDepth_e::GREYA;
break;
case PNG_COLOR_TYPE_RGB:
imageType = Image::ColorDepth_e::RGB;
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
imageType = Image::ColorDepth_e::RGBA;
break;
default:
throw Image::Exc("Image::LoadPNG(): unknown colorType");
break;
}
// Great! Number of channels and bits per pixel are initialized now!
// set image dimensions and set buffer size
this->init(r4::vector2<unsigned>(width, height), imageType);//Set buf array size (allocate memory)
// Great! height and width are initialized and buffer memory allocated
// TRACE(<< "Image::LoadPNG(): memory for image allocated" << std::endl)
// Read image data
png_size_t bytesPerRow = png_get_rowbytes(pngPtr, infoPtr);//get bytes per row
// check that our expectations are correct
if(bytesPerRow != this->dims().x() * this->numChannels()){
throw Image::Exc("Image::LoadPNG(): number of bytes per row does not match expected value");
}
ASSERT_ALWAYS((bytesPerRow * height) == this->buf_v.size())
// TRACE(<< "Image::LoadPNG(): going to read in the data" << std::endl)
{
ASSERT_ALWAYS(this->dims().y() && this->buf_v.size())
std::vector<png_bytep> rows(this->dims().y());
// initialize row pointers
// TRACE(<< "Image::LoadPNG(): this->buf.Buf() = " << std::hex << this->buf.Buf() << std::endl)
for(unsigned i = 0; i < this->dims().y(); ++i){
rows[i] = &*this->buf_v.begin() + i * bytesPerRow;
// TRACE(<< "Image::LoadPNG(): rows[i] = " << std::hex << rows[i] << std::endl)
}
// TRACE(<< "Image::LoadPNG(): row pointers are set" << std::endl)
// Read in image data!
png_read_image(pngPtr, &*rows.begin());
// TRACE(<< "Image::LoadPNG(): image data read" << std::endl)
}
png_destroy_read_struct(&pngPtr,0,0); // free libpng memory
}
};
namespace{
tst::set set("samples", [](tst::suite& suite){
std::vector<std::string> files;
{
const std::regex suffix_regex("^.*\\.svg$");
auto all_files = papki::fs_file(data_dir).list_dir();
std::copy_if(
all_files.begin(),
all_files.end(),
std::back_inserter(files),
[&suffix_regex](auto& f){
return std::regex_match(f, suffix_regex);
}
);
}
suite.add<std::string>(
"sample",
{
#if M_CPU_BITS != 64
tst::flag::disabled
#endif
},
std::move(files),
[](const auto& p){
papki::fs_file in_file(data_dir + p);
auto dom = svgdom::load(in_file);
auto res = svgren::render(*dom);
auto& img = res.pixels;
papki::fs_file png_file(data_dir + render_backend_name + "/" + papki::not_suffix(in_file.not_dir()) + ".png");
Image png;
png.loadPNG(png_file);
ASSERT_ALWAYS(png.buf().size() != 0)
tst::check(png.colorDepth() == Image::ColorDepth_e::RGBA, SL) << "Error: PNG color depth is not RGBA: " << unsigned(png.colorDepth());
tst::check(res.dims == png.dims(), SL) << "Error: svg dims " << res.dims << " did not match png dims " << png.dims();
tst::check(img.size() == png.buf().size() / png.numChannels(), SL) << "Error: svg pixel buffer size (" << img.size() << ") did not match png pixel buffer size(" << png.buf().size() / png.numChannels() << ")";
for(size_t i = 0; i != img.size(); ++i){
std::array<uint8_t, 4> rgba;
rgba[0] = img[i] & 0xff;
rgba[1] = (img[i] >> 8) & 0xff;
rgba[2] = (img[i] >> 16) & 0xff;
rgba[3] = (img[i] >> 24) & 0xff;
for(unsigned j = 0; j != rgba.size(); ++j){
auto c1 = rgba[j];
auto c2 = png.buf()[i * png.numChannels() + j];
if(c1 > c2){
std::swap(c1, c2);
}
if(unsigned(c2 - c1) > tolerance){
uint32_t pixel =
uint32_t(png.buf()[i * png.numChannels()]) |
(uint32_t(png.buf()[i * png.numChannels() + 1]) << 8) |
(uint32_t(png.buf()[i * png.numChannels() + 2]) << 16) |
(uint32_t(png.buf()[i * png.numChannels() + 3]) << 24)
;
tst::check(false, SL) << "Error: PNG pixel #" << std::dec << i << " [" << (i % res.dims.x()) << ", " << (i / res.dims.y()) << "]" << " (0x" << std::hex << pixel << ") did not match SVG pixel (0x" << img[i] << ")" << ", png_file = " << png_file.path();
}
}
}
}
);
});
}
| 29.661333 | 275 | 0.611885 | [
"render",
"object",
"vector"
] |
f3591879f7bb039c14f2bbe9bd7682d14ed884f6 | 476,196 | cpp | C++ | vm/external_libs/llvm/lib/Transforms/Scalar/InstructionCombining.cpp | deepakec/rubinius | 5ebbdf3d9a4e258204e0d21f00500de4f3fb6085 | [
"BSD-3-Clause"
] | 1 | 2016-05-08T21:05:11.000Z | 2016-05-08T21:05:11.000Z | vm/external_libs/llvm/lib/Transforms/Scalar/InstructionCombining.cpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | vm/external_libs/llvm/lib/Transforms/Scalar/InstructionCombining.cpp | taf2/rubinius | 493bfa2351fc509ca33d3bb03991c2e9c2b6dafa | [
"BSD-3-Clause"
] | null | null | null | //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// InstructionCombining - Combine instructions to form fewer, simple
// instructions. This pass does not modify the CFG This pass is where algebraic
// simplification happens.
//
// This pass combines things like:
// %Y = add i32 %X, 1
// %Z = add i32 %Y, 1
// into:
// %Z = add i32 %X, 2
//
// This is a simple worklist driven algorithm.
//
// This pass guarantees that the following canonicalizations are performed on
// the program:
// 1. If a binary operator has a constant operand, it is moved to the RHS
// 2. Bitwise operators with constant operands are always grouped so that
// shifts are performed first, then or's, then and's, then xor's.
// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
// 4. All cmp instructions on boolean values are replaced with logical ops
// 5. add X, X is represented as (X*2) => (X << 1)
// 6. Multiplies with a power-of-two constant argument are transformed into
// shifts.
// ... etc.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "instcombine"
#include "llvm/Transforms/Scalar.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Pass.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/ConstantRange.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/PatternMatch.h"
#include "llvm/Support/Compiler.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include <algorithm>
#include <climits>
#include <sstream>
using namespace llvm;
using namespace llvm::PatternMatch;
STATISTIC(NumCombined , "Number of insts combined");
STATISTIC(NumConstProp, "Number of constant folds");
STATISTIC(NumDeadInst , "Number of dead inst eliminated");
STATISTIC(NumDeadStore, "Number of dead stores eliminated");
STATISTIC(NumSunkInst , "Number of instructions sunk");
namespace {
class VISIBILITY_HIDDEN InstCombiner
: public FunctionPass,
public InstVisitor<InstCombiner, Instruction*> {
// Worklist of all of the instructions that need to be simplified.
std::vector<Instruction*> Worklist;
DenseMap<Instruction*, unsigned> WorklistMap;
TargetData *TD;
bool MustPreserveLCSSA;
public:
static char ID; // Pass identification, replacement for typeid
InstCombiner() : FunctionPass((intptr_t)&ID) {}
/// AddToWorkList - Add the specified instruction to the worklist if it
/// isn't already in it.
void AddToWorkList(Instruction *I) {
if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
Worklist.push_back(I);
}
// RemoveFromWorkList - remove I from the worklist if it exists.
void RemoveFromWorkList(Instruction *I) {
DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
if (It == WorklistMap.end()) return; // Not in worklist.
// Don't bother moving everything down, just null out the slot.
Worklist[It->second] = 0;
WorklistMap.erase(It);
}
Instruction *RemoveOneFromWorkList() {
Instruction *I = Worklist.back();
Worklist.pop_back();
WorklistMap.erase(I);
return I;
}
/// AddUsersToWorkList - When an instruction is simplified, add all users of
/// the instruction to the work lists because they might get more simplified
/// now.
///
void AddUsersToWorkList(Value &I) {
for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
UI != UE; ++UI)
AddToWorkList(cast<Instruction>(*UI));
}
/// AddUsesToWorkList - When an instruction is simplified, add operands to
/// the work lists because they might get more simplified now.
///
void AddUsesToWorkList(Instruction &I) {
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
AddToWorkList(Op);
}
/// AddSoonDeadInstToWorklist - The specified instruction is about to become
/// dead. Add all of its operands to the worklist, turning them into
/// undef's to reduce the number of uses of those instructions.
///
/// Return the specified operand before it is turned into an undef.
///
Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
Value *R = I.getOperand(op);
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
AddToWorkList(Op);
// Set the operand to undef to drop the use.
I.setOperand(i, UndefValue::get(Op->getType()));
}
return R;
}
public:
virtual bool runOnFunction(Function &F);
bool DoOneIteration(Function &F, unsigned ItNum);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetData>();
AU.addPreservedID(LCSSAID);
AU.setPreservesCFG();
}
TargetData &getTargetData() const { return *TD; }
// Visitation implementation - Implement instruction combining for different
// instruction types. The semantics are as follows:
// Return Value:
// null - No change was made
// I - Change was made, I is still valid, I may be dead though
// otherwise - Change was made, replace I with returned instruction
//
Instruction *visitAdd(BinaryOperator &I);
Instruction *visitSub(BinaryOperator &I);
Instruction *visitMul(BinaryOperator &I);
Instruction *visitURem(BinaryOperator &I);
Instruction *visitSRem(BinaryOperator &I);
Instruction *visitFRem(BinaryOperator &I);
Instruction *commonRemTransforms(BinaryOperator &I);
Instruction *commonIRemTransforms(BinaryOperator &I);
Instruction *commonDivTransforms(BinaryOperator &I);
Instruction *commonIDivTransforms(BinaryOperator &I);
Instruction *visitUDiv(BinaryOperator &I);
Instruction *visitSDiv(BinaryOperator &I);
Instruction *visitFDiv(BinaryOperator &I);
Instruction *visitAnd(BinaryOperator &I);
Instruction *visitOr (BinaryOperator &I);
Instruction *visitXor(BinaryOperator &I);
Instruction *visitShl(BinaryOperator &I);
Instruction *visitAShr(BinaryOperator &I);
Instruction *visitLShr(BinaryOperator &I);
Instruction *commonShiftTransforms(BinaryOperator &I);
Instruction *visitFCmpInst(FCmpInst &I);
Instruction *visitICmpInst(ICmpInst &I);
Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
Instruction *LHS,
ConstantInt *RHS);
Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
ConstantInt *DivRHS);
Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
ICmpInst::Predicate Cond, Instruction &I);
Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
BinaryOperator &I);
Instruction *commonCastTransforms(CastInst &CI);
Instruction *commonIntCastTransforms(CastInst &CI);
Instruction *commonPointerCastTransforms(CastInst &CI);
Instruction *visitTrunc(TruncInst &CI);
Instruction *visitZExt(ZExtInst &CI);
Instruction *visitSExt(SExtInst &CI);
Instruction *visitFPTrunc(FPTruncInst &CI);
Instruction *visitFPExt(CastInst &CI);
Instruction *visitFPToUI(CastInst &CI);
Instruction *visitFPToSI(CastInst &CI);
Instruction *visitUIToFP(CastInst &CI);
Instruction *visitSIToFP(CastInst &CI);
Instruction *visitPtrToInt(CastInst &CI);
Instruction *visitIntToPtr(IntToPtrInst &CI);
Instruction *visitBitCast(BitCastInst &CI);
Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
Instruction *FI);
Instruction *visitSelectInst(SelectInst &CI);
Instruction *visitCallInst(CallInst &CI);
Instruction *visitInvokeInst(InvokeInst &II);
Instruction *visitPHINode(PHINode &PN);
Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Instruction *visitAllocationInst(AllocationInst &AI);
Instruction *visitFreeInst(FreeInst &FI);
Instruction *visitLoadInst(LoadInst &LI);
Instruction *visitStoreInst(StoreInst &SI);
Instruction *visitBranchInst(BranchInst &BI);
Instruction *visitSwitchInst(SwitchInst &SI);
Instruction *visitInsertElementInst(InsertElementInst &IE);
Instruction *visitExtractElementInst(ExtractElementInst &EI);
Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
// visitInstruction - Specify what to return for unhandled instructions...
Instruction *visitInstruction(Instruction &I) { return 0; }
private:
Instruction *visitCallSite(CallSite CS);
bool transformConstExprCastCall(CallSite CS);
Instruction *transformCallThroughTrampoline(CallSite CS);
Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
bool DoXform = true);
public:
// InsertNewInstBefore - insert an instruction New before instruction Old
// in the program. Add the new instruction to the worklist.
//
Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
assert(New && New->getParent() == 0 &&
"New instruction already inserted into a basic block!");
BasicBlock *BB = Old.getParent();
BB->getInstList().insert(&Old, New); // Insert inst
AddToWorkList(New);
return New;
}
/// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
/// This also adds the cast to the worklist. Finally, this returns the
/// cast.
Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
Instruction &Pos) {
if (V->getType() == Ty) return V;
if (Constant *CV = dyn_cast<Constant>(V))
return ConstantExpr::getCast(opc, CV, Ty);
Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
AddToWorkList(C);
return C;
}
Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
}
// ReplaceInstUsesWith - This method is to be used when an instruction is
// found to be dead, replacable with another preexisting expression. Here
// we add all uses of I to the worklist, replace all uses of I with the new
// value, then return I, so that the inst combiner will know that I was
// modified.
//
Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
AddUsersToWorkList(I); // Add all modified instrs to worklist
if (&I != V) {
I.replaceAllUsesWith(V);
return &I;
} else {
// If we are replacing the instruction with itself, this must be in a
// segment of unreachable code, so just clobber the instruction.
I.replaceAllUsesWith(UndefValue::get(I.getType()));
return &I;
}
}
// UpdateValueUsesWith - This method is to be used when an value is
// found to be replacable with another preexisting expression or was
// updated. Here we add all uses of I to the worklist, replace all uses of
// I with the new value (unless the instruction was just updated), then
// return true, so that the inst combiner will know that I was modified.
//
bool UpdateValueUsesWith(Value *Old, Value *New) {
AddUsersToWorkList(*Old); // Add all modified instrs to worklist
if (Old != New)
Old->replaceAllUsesWith(New);
if (Instruction *I = dyn_cast<Instruction>(Old))
AddToWorkList(I);
if (Instruction *I = dyn_cast<Instruction>(New))
AddToWorkList(I);
return true;
}
// EraseInstFromFunction - When dealing with an instruction that has side
// effects or produces a void value, we can't rely on DCE to delete the
// instruction. Instead, visit methods should return the value returned by
// this function.
Instruction *EraseInstFromFunction(Instruction &I) {
assert(I.use_empty() && "Cannot erase instruction that is used!");
AddUsesToWorkList(I);
RemoveFromWorkList(&I);
I.eraseFromParent();
return 0; // Don't do anything with FI
}
private:
/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
/// InsertBefore instruction. This is specialized a bit to avoid inserting
/// casts that are known to not do anything...
///
Value *InsertOperandCastBefore(Instruction::CastOps opcode,
Value *V, const Type *DestTy,
Instruction *InsertBefore);
/// SimplifyCommutative - This performs a few simplifications for
/// commutative operators.
bool SimplifyCommutative(BinaryOperator &I);
/// SimplifyCompare - This reorders the operands of a CmpInst to get them in
/// most-complex to least-complex order.
bool SimplifyCompare(CmpInst &I);
/// SimplifyDemandedBits - Attempts to replace V with a simpler value based
/// on the demanded bits.
bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
APInt& KnownZero, APInt& KnownOne,
unsigned Depth = 0);
Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
uint64_t &UndefElts, unsigned Depth = 0);
// FoldOpIntoPhi - Given a binary operator or cast instruction which has a
// PHI node as operand #0, see if we can fold the instruction into the PHI
// (which is only possible if all operands to the PHI are constants).
Instruction *FoldOpIntoPhi(Instruction &I);
// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
// operator and they all are only used by the PHI, PHI together their
// inputs, and do the operation once, to the result of the PHI.
Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
ConstantInt *AndRHS, BinaryOperator &TheAnd);
Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
bool isSub, Instruction &I);
Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
bool isSigned, bool Inside, Instruction &IB);
Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Instruction *MatchBSwap(BinaryOperator &I);
bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Instruction *SimplifyMemSet(MemSetInst *MI);
Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
APInt& KnownOne, unsigned Depth = 0);
bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
unsigned CastOpc,
int &NumCastsRemoved);
unsigned GetOrEnforceKnownAlignment(Value *V,
unsigned PrefAlign = 0);
};
char InstCombiner::ID = 0;
RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
}
// getComplexity: Assign a complexity or rank value to LLVM Values...
// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
static unsigned getComplexity(Value *V) {
if (isa<Instruction>(V)) {
if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
return 3;
return 4;
}
if (isa<Argument>(V)) return 3;
return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
}
// isOnlyUse - Return true if this instruction will be deleted if we stop using
// it.
static bool isOnlyUse(Value *V) {
return V->hasOneUse() || isa<Constant>(V);
}
// getPromotedType - Return the specified type promoted as it would be to pass
// though a va_arg area...
static const Type *getPromotedType(const Type *Ty) {
if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
if (ITy->getBitWidth() < 32)
return Type::Int32Ty;
}
return Ty;
}
/// getBitCastOperand - If the specified operand is a CastInst or a constant
/// expression bitcast, return the operand value, otherwise return null.
static Value *getBitCastOperand(Value *V) {
if (BitCastInst *I = dyn_cast<BitCastInst>(V))
return I->getOperand(0);
else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == Instruction::BitCast)
return CE->getOperand(0);
return 0;
}
/// This function is a wrapper around CastInst::isEliminableCastPair. It
/// simply extracts arguments and returns what that function returns.
static Instruction::CastOps
isEliminableCastPair(
const CastInst *CI, ///< The first cast instruction
unsigned opcode, ///< The opcode of the second cast instruction
const Type *DstTy, ///< The target type for the second cast instruction
TargetData *TD ///< The target data for pointer size
) {
const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
const Type *MidTy = CI->getType(); // B from above
// Get the opcodes of the two Cast instructions
Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
Instruction::CastOps secondOp = Instruction::CastOps(opcode);
return Instruction::CastOps(
CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
DstTy, TD->getIntPtrType()));
}
/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
/// in any code being generated. It does not require codegen if V is simple
/// enough or if the cast can be folded into other casts.
static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
const Type *Ty, TargetData *TD) {
if (V->getType() == Ty || isa<Constant>(V)) return false;
// If this is another cast that can be eliminated, it isn't codegen either.
if (const CastInst *CI = dyn_cast<CastInst>(V))
if (isEliminableCastPair(CI, opcode, Ty, TD))
return false;
return true;
}
/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
/// InsertBefore instruction. This is specialized a bit to avoid inserting
/// casts that are known to not do anything...
///
Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
Value *V, const Type *DestTy,
Instruction *InsertBefore) {
if (V->getType() == DestTy) return V;
if (Constant *C = dyn_cast<Constant>(V))
return ConstantExpr::getCast(opcode, C, DestTy);
return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
}
// SimplifyCommutative - This performs a few simplifications for commutative
// operators:
//
// 1. Order operands such that they are listed from right (least complex) to
// left (most complex). This puts constants before unary operators before
// binary operators.
//
// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
//
bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
bool Changed = false;
if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Changed = !I.swapOperands();
if (!I.isAssociative()) return Changed;
Instruction::BinaryOps Opcode = I.getOpcode();
if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
if (isa<Constant>(I.getOperand(1))) {
Constant *Folded = ConstantExpr::get(I.getOpcode(),
cast<Constant>(I.getOperand(1)),
cast<Constant>(Op->getOperand(1)));
I.setOperand(0, Op->getOperand(0));
I.setOperand(1, Folded);
return true;
} else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
isOnlyUse(Op) && isOnlyUse(Op1)) {
Constant *C1 = cast<Constant>(Op->getOperand(1));
Constant *C2 = cast<Constant>(Op1->getOperand(1));
// Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
Op1->getOperand(0),
Op1->getName(), &I);
AddToWorkList(New);
I.setOperand(0, New);
I.setOperand(1, Folded);
return true;
}
}
return Changed;
}
/// SimplifyCompare - For a CmpInst this function just orders the operands
/// so that theyare listed from right (least complex) to left (most complex).
/// This puts constants before unary operators before binary operators.
bool InstCombiner::SimplifyCompare(CmpInst &I) {
if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
return false;
I.swapOperands();
// Compare instructions are not associative so there's nothing else we can do.
return true;
}
// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
// if the LHS is a constant zero (which is the 'negate' form).
//
static inline Value *dyn_castNegVal(Value *V) {
if (BinaryOperator::isNeg(V))
return BinaryOperator::getNegArgument(V);
// Constants can be considered to be negated values if they can be folded.
if (ConstantInt *C = dyn_cast<ConstantInt>(V))
return ConstantExpr::getNeg(C);
return 0;
}
static inline Value *dyn_castNotVal(Value *V) {
if (BinaryOperator::isNot(V))
return BinaryOperator::getNotArgument(V);
// Constants can be considered to be not'ed values...
if (ConstantInt *C = dyn_cast<ConstantInt>(V))
return ConstantInt::get(~C->getValue());
return 0;
}
// dyn_castFoldableMul - If this value is a multiply that can be folded into
// other computations (because it has a constant operand), return the
// non-constant operand of the multiply, and set CST to point to the multiplier.
// Otherwise, return null.
//
static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
if (V->hasOneUse() && V->getType()->isInteger())
if (Instruction *I = dyn_cast<Instruction>(V)) {
if (I->getOpcode() == Instruction::Mul)
if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
return I->getOperand(0);
if (I->getOpcode() == Instruction::Shl)
if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
// The multiplier is really 1 << CST.
uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
uint32_t CSTVal = CST->getLimitedValue(BitWidth);
CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
return I->getOperand(0);
}
}
return 0;
}
/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
/// expression, return it.
static User *dyn_castGetElementPtr(Value *V) {
if (isa<GetElementPtrInst>(V)) return cast<User>(V);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == Instruction::GetElementPtr)
return cast<User>(V);
return false;
}
/// getOpcode - If this is an Instruction or a ConstantExpr, return the
/// opcode value. Otherwise return UserOp1.
static unsigned getOpcode(User *U) {
if (Instruction *I = dyn_cast<Instruction>(U))
return I->getOpcode();
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
return CE->getOpcode();
// Use UserOp1 to mean there's no opcode.
return Instruction::UserOp1;
}
/// AddOne - Add one to a ConstantInt
static ConstantInt *AddOne(ConstantInt *C) {
APInt Val(C->getValue());
return ConstantInt::get(++Val);
}
/// SubOne - Subtract one from a ConstantInt
static ConstantInt *SubOne(ConstantInt *C) {
APInt Val(C->getValue());
return ConstantInt::get(--Val);
}
/// Add - Add two ConstantInts together
static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
return ConstantInt::get(C1->getValue() + C2->getValue());
}
/// And - Bitwise AND two ConstantInts together
static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
return ConstantInt::get(C1->getValue() & C2->getValue());
}
/// Subtract - Subtract one ConstantInt from another
static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
return ConstantInt::get(C1->getValue() - C2->getValue());
}
/// Multiply - Multiply two ConstantInts together
static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
return ConstantInt::get(C1->getValue() * C2->getValue());
}
/// MultiplyOverflows - True if the multiply can not be expressed in an int
/// this size.
static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
uint32_t W = C1->getBitWidth();
APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
if (sign) {
LHSExt.sext(W * 2);
RHSExt.sext(W * 2);
} else {
LHSExt.zext(W * 2);
RHSExt.zext(W * 2);
}
APInt MulExt = LHSExt * RHSExt;
if (sign) {
APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
return MulExt.slt(Min) || MulExt.sgt(Max);
} else
return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
}
/// ComputeMaskedBits - Determine which of the bits specified in Mask are
/// known to be either zero or one and return them in the KnownZero/KnownOne
/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
/// processing.
/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
/// we cannot optimize based on the assumption that it is zero without changing
/// it to be an explicit zero. If we don't change it to zero, other code could
/// optimized based on the contradictory assumption that it is non-zero.
/// Because instcombine aggressively folds operations with undef args anyway,
/// this won't lose us code quality.
void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
APInt& KnownZero, APInt& KnownOne,
unsigned Depth) {
assert(V && "No Value?");
assert(Depth <= 6 && "Limit Search Depth");
uint32_t BitWidth = Mask.getBitWidth();
assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
"Not integer or pointer type!");
assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
(!isa<IntegerType>(V->getType()) ||
V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
KnownZero.getBitWidth() == BitWidth &&
KnownOne.getBitWidth() == BitWidth &&
"V, Mask, KnownOne and KnownZero should have same BitWidth");
if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
// We know all of the bits for a constant!
KnownOne = CI->getValue() & Mask;
KnownZero = ~KnownOne & Mask;
return;
}
// Null is all-zeros.
if (isa<ConstantPointerNull>(V)) {
KnownOne.clear();
KnownZero = Mask;
return;
}
// The address of an aligned GlobalValue has trailing zeros.
if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
unsigned Align = GV->getAlignment();
if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
if (Align > 0)
KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
CountTrailingZeros_32(Align));
else
KnownZero.clear();
KnownOne.clear();
return;
}
KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
if (Depth == 6 || Mask == 0)
return; // Limit search depth.
User *I = dyn_cast<User>(V);
if (!I) return;
APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
switch (getOpcode(I)) {
default: break;
case Instruction::And: {
// If either the LHS or the RHS are Zero, the result is zero.
ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
APInt Mask2(Mask & ~KnownZero);
ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
// Output known-1 bits are only known if set in both the LHS & RHS.
KnownOne &= KnownOne2;
// Output known-0 are known to be clear if zero in either the LHS | RHS.
KnownZero |= KnownZero2;
return;
}
case Instruction::Or: {
ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
APInt Mask2(Mask & ~KnownOne);
ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
// Output known-0 bits are only known if clear in both the LHS & RHS.
KnownZero &= KnownZero2;
// Output known-1 are known to be set if set in either the LHS | RHS.
KnownOne |= KnownOne2;
return;
}
case Instruction::Xor: {
ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
// Output known-0 bits are known if clear or set in both the LHS & RHS.
APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
// Output known-1 are known to be set if set in only one of the LHS, RHS.
KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
KnownZero = KnownZeroOut;
return;
}
case Instruction::Mul: {
APInt Mask2 = APInt::getAllOnesValue(BitWidth);
ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
// If low bits are zero in either operand, output low known-0 bits.
// Also compute a conserative estimate for high known-0 bits.
// More trickiness is possible, but this is sufficient for the
// interesting case of alignment computation.
KnownOne.clear();
unsigned TrailZ = KnownZero.countTrailingOnes() +
KnownZero2.countTrailingOnes();
unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
KnownZero2.countLeadingOnes(),
BitWidth) - BitWidth;
TrailZ = std::min(TrailZ, BitWidth);
LeadZ = std::min(LeadZ, BitWidth);
KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
APInt::getHighBitsSet(BitWidth, LeadZ);
KnownZero &= Mask;
return;
}
case Instruction::UDiv: {
// For the purposes of computing leading zeros we can conservatively
// treat a udiv as a logical right shift by the power of 2 known to
// be less than the denominator.
APInt AllOnes = APInt::getAllOnesValue(BitWidth);
ComputeMaskedBits(I->getOperand(0),
AllOnes, KnownZero2, KnownOne2, Depth+1);
unsigned LeadZ = KnownZero2.countLeadingOnes();
KnownOne2.clear();
KnownZero2.clear();
ComputeMaskedBits(I->getOperand(1),
AllOnes, KnownZero2, KnownOne2, Depth+1);
unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
if (RHSUnknownLeadingOnes != BitWidth)
LeadZ = std::min(BitWidth,
LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
return;
}
case Instruction::Select:
ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
// Only known if known in both the LHS and RHS.
KnownOne &= KnownOne2;
KnownZero &= KnownZero2;
return;
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::SIToFP:
case Instruction::UIToFP:
return; // Can't work with floating point.
case Instruction::PtrToInt:
case Instruction::IntToPtr:
// We can't handle these if we don't know the pointer size.
if (!TD) return;
// Fall through and handle them the same as zext/trunc.
case Instruction::ZExt:
case Instruction::Trunc: {
// All these have integer operands
const Type *SrcTy = I->getOperand(0)->getType();
uint32_t SrcBitWidth = TD ?
TD->getTypeSizeInBits(SrcTy) :
SrcTy->getPrimitiveSizeInBits();
APInt MaskIn(Mask);
MaskIn.zextOrTrunc(SrcBitWidth);
KnownZero.zextOrTrunc(SrcBitWidth);
KnownOne.zextOrTrunc(SrcBitWidth);
ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
KnownZero.zextOrTrunc(BitWidth);
KnownOne.zextOrTrunc(BitWidth);
// Any top bits are known to be zero.
if (BitWidth > SrcBitWidth)
KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
return;
}
case Instruction::BitCast: {
const Type *SrcTy = I->getOperand(0)->getType();
if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
return;
}
break;
}
case Instruction::SExt: {
// Compute the bits in the result that are not present in the input.
const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
uint32_t SrcBitWidth = SrcTy->getBitWidth();
APInt MaskIn(Mask);
MaskIn.trunc(SrcBitWidth);
KnownZero.trunc(SrcBitWidth);
KnownOne.trunc(SrcBitWidth);
ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
KnownZero.zext(BitWidth);
KnownOne.zext(BitWidth);
// If the sign bit of the input is known set or clear, then we know the
// top bits of the result.
if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
return;
}
case Instruction::Shl:
// (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
APInt Mask2(Mask.lshr(ShiftAmt));
ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
KnownZero <<= ShiftAmt;
KnownOne <<= ShiftAmt;
KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
return;
}
break;
case Instruction::LShr:
// (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
// Compute the new bits that are at the top now.
uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
// Unsigned shift right.
APInt Mask2(Mask.shl(ShiftAmt));
ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
// high bits known zero.
KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
return;
}
break;
case Instruction::AShr:
// (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
// Compute the new bits that are at the top now.
uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
// Signed shift right.
APInt Mask2(Mask.shl(ShiftAmt));
ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
KnownZero |= HighBits;
else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
KnownOne |= HighBits;
return;
}
break;
case Instruction::Sub: {
if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
// We know that the top bits of C-X are clear if X contains less bits
// than C (i.e. no wrap-around can happen). For example, 20-X is
// positive if we can prove that X is >= 0 and < 16.
if (!CLHS->getValue().isNegative()) {
unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
// NLZ can't be BitWidth with no sign bit
APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
Depth+1);
// If all of the MaskV bits are known to be zero, then we know the
// output top bits are zero, because we now know that the output is
// from [0-C].
if ((KnownZero2 & MaskV) == MaskV) {
unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
// Top bits known zero.
KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
}
}
}
}
// fall through
case Instruction::Add: {
// Output known-0 bits are known if clear or set in both the low clear bits
// common to both LHS & RHS. For example, 8+(X<<3) is known to have the
// low 3 bits clear.
APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
KnownZeroOut = std::min(KnownZeroOut,
KnownZero2.countTrailingOnes());
KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
return;
}
case Instruction::SRem:
if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
APInt RA = Rem->getValue();
if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
// The sign of a remainder is equal to the sign of the first
// operand (zero being positive).
if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
KnownZero2 |= ~LowBits;
else if (KnownOne2[BitWidth-1])
KnownOne2 |= ~LowBits;
KnownZero |= KnownZero2 & Mask;
KnownOne |= KnownOne2 & Mask;
assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
}
}
break;
case Instruction::URem: {
if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
APInt RA = Rem->getValue();
if (RA.isPowerOf2()) {
APInt LowBits = (RA - 1);
APInt Mask2 = LowBits & Mask;
KnownZero |= ~LowBits & Mask;
ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
break;
}
}
// Since the result is less than or equal to either operand, any leading
// zero bits in either operand must also exist in the result.
APInt AllOnes = APInt::getAllOnesValue(BitWidth);
ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
Depth+1);
ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
Depth+1);
uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
KnownZero2.countLeadingOnes());
KnownOne.clear();
KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
break;
}
case Instruction::Alloca:
case Instruction::Malloc: {
AllocationInst *AI = cast<AllocationInst>(V);
unsigned Align = AI->getAlignment();
if (Align == 0 && TD) {
if (isa<AllocaInst>(AI))
Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
else if (isa<MallocInst>(AI)) {
// Malloc returns maximally aligned memory.
Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Align =
std::max(Align,
(unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Align =
std::max(Align,
(unsigned)TD->getABITypeAlignment(Type::Int64Ty));
}
}
if (Align > 0)
KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
CountTrailingZeros_32(Align));
break;
}
case Instruction::GetElementPtr: {
// Analyze all of the subscripts of this getelementptr instruction
// to determine if we can prove known low zero bits.
APInt LocalMask = APInt::getAllOnesValue(BitWidth);
APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
ComputeMaskedBits(I->getOperand(0), LocalMask,
LocalKnownZero, LocalKnownOne, Depth+1);
unsigned TrailZ = LocalKnownZero.countTrailingOnes();
gep_type_iterator GTI = gep_type_begin(I);
for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
Value *Index = I->getOperand(i);
if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
// Handle struct member offset arithmetic.
if (!TD) return;
const StructLayout *SL = TD->getStructLayout(STy);
unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
uint64_t Offset = SL->getElementOffset(Idx);
TrailZ = std::min(TrailZ,
CountTrailingZeros_64(Offset));
} else {
// Handle array index arithmetic.
const Type *IndexedTy = GTI.getIndexedType();
if (!IndexedTy->isSized()) return;
unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
LocalMask = APInt::getAllOnesValue(GEPOpiBits);
LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
ComputeMaskedBits(Index, LocalMask,
LocalKnownZero, LocalKnownOne, Depth+1);
TrailZ = std::min(TrailZ,
CountTrailingZeros_64(TypeSize) +
LocalKnownZero.countTrailingOnes());
}
}
KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
break;
}
case Instruction::PHI: {
PHINode *P = cast<PHINode>(I);
// Handle the case of a simple two-predecessor recurrence PHI.
// There's a lot more that could theoretically be done here, but
// this is sufficient to catch some interesting cases.
if (P->getNumIncomingValues() == 2) {
for (unsigned i = 0; i != 2; ++i) {
Value *L = P->getIncomingValue(i);
Value *R = P->getIncomingValue(!i);
User *LU = dyn_cast<User>(L);
unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
// Check for operations that have the property that if
// both their operands have low zero bits, the result
// will have low zero bits.
if (Opcode == Instruction::Add ||
Opcode == Instruction::Sub ||
Opcode == Instruction::And ||
Opcode == Instruction::Or ||
Opcode == Instruction::Mul) {
Value *LL = LU->getOperand(0);
Value *LR = LU->getOperand(1);
// Find a recurrence.
if (LL == I)
L = LR;
else if (LR == I)
L = LL;
else
break;
// Ok, we have a PHI of the form L op= R. Check for low
// zero bits.
APInt Mask2 = APInt::getAllOnesValue(BitWidth);
ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
Mask2 = APInt::getLowBitsSet(BitWidth,
KnownZero2.countTrailingOnes());
KnownOne2.clear();
KnownZero2.clear();
ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
KnownZero = Mask &
APInt::getLowBitsSet(BitWidth,
KnownZero2.countTrailingOnes());
break;
}
}
}
break;
}
case Instruction::Call:
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
switch (II->getIntrinsicID()) {
default: break;
case Intrinsic::ctpop:
case Intrinsic::ctlz:
case Intrinsic::cttz: {
unsigned LowBits = Log2_32(BitWidth)+1;
KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
break;
}
}
}
break;
}
}
/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
/// this predicate to simplify operations downstream. Mask is known to be zero
/// for bits that V cannot have.
bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
unsigned Depth) {
APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
return (KnownZero & Mask) == Mask;
}
/// ShrinkDemandedConstant - Check to see if the specified operand of the
/// specified instruction is a constant integer. If so, check to see if there
/// are any bits set in the constant that are not demanded. If so, shrink the
/// constant and return true.
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
APInt Demanded) {
assert(I && "No instruction?");
assert(OpNo < I->getNumOperands() && "Operand index too large");
// If the operand is not a constant integer, nothing to do.
ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
if (!OpC) return false;
// If there are no bits set that aren't demanded, nothing to do.
Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
if ((~Demanded & OpC->getValue()) == 0)
return false;
// This instruction is producing bits that are not demanded. Shrink the RHS.
Demanded &= OpC->getValue();
I->setOperand(OpNo, ConstantInt::get(Demanded));
return true;
}
// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
// set of known zero and one bits, compute the maximum and minimum values that
// could have the specified known zero and known one bits, returning them in
// min/max.
static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
const APInt& KnownZero,
const APInt& KnownOne,
APInt& Min, APInt& Max) {
uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
assert(KnownZero.getBitWidth() == BitWidth &&
KnownOne.getBitWidth() == BitWidth &&
Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
"Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
APInt UnknownBits = ~(KnownZero|KnownOne);
// The minimum value is when all unknown bits are zeros, EXCEPT for the sign
// bit if it is unknown.
Min = KnownOne;
Max = KnownOne|UnknownBits;
if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Min.set(BitWidth-1);
Max.clear(BitWidth-1);
}
}
// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
// a set of known zero and one bits, compute the maximum and minimum values that
// could have the specified known zero and known one bits, returning them in
// min/max.
static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
const APInt &KnownZero,
const APInt &KnownOne,
APInt &Min, APInt &Max) {
uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
assert(KnownZero.getBitWidth() == BitWidth &&
KnownOne.getBitWidth() == BitWidth &&
Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
"Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
APInt UnknownBits = ~(KnownZero|KnownOne);
// The minimum value is when the unknown bits are all zeros.
Min = KnownOne;
// The maximum value is when the unknown bits are all ones.
Max = KnownOne|UnknownBits;
}
/// SimplifyDemandedBits - This function attempts to replace V with a simpler
/// value based on the demanded bits. When this function is called, it is known
/// that only the bits set in DemandedMask of the result of V are ever used
/// downstream. Consequently, depending on the mask and V, it may be possible
/// to replace V with a constant or one of its operands. In such cases, this
/// function does the replacement and returns true. In all other cases, it
/// returns false after analyzing the expression and setting KnownOne and known
/// to be one in the expression. KnownZero contains all the bits that are known
/// to be zero in the expression. These are provided to potentially allow the
/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
/// the expression. KnownOne and KnownZero always follow the invariant that
/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
/// the bits in KnownOne and KnownZero may only be accurate for those bits set
/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
/// and KnownOne must all be the same.
bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
APInt& KnownZero, APInt& KnownOne,
unsigned Depth) {
assert(V != 0 && "Null pointer of Value???");
assert(Depth <= 6 && "Limit Search Depth");
uint32_t BitWidth = DemandedMask.getBitWidth();
const IntegerType *VTy = cast<IntegerType>(V->getType());
assert(VTy->getBitWidth() == BitWidth &&
KnownZero.getBitWidth() == BitWidth &&
KnownOne.getBitWidth() == BitWidth &&
"Value *V, DemandedMask, KnownZero and KnownOne \
must have same BitWidth");
if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
// We know all of the bits for a constant!
KnownOne = CI->getValue() & DemandedMask;
KnownZero = ~KnownOne & DemandedMask;
return false;
}
KnownZero.clear();
KnownOne.clear();
if (!V->hasOneUse()) { // Other users may use these bits.
if (Depth != 0) { // Not at the root.
// Just compute the KnownZero/KnownOne bits to simplify things downstream.
ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
return false;
}
// If this is the root being simplified, allow it to have multiple uses,
// just set the DemandedMask to all bits.
DemandedMask = APInt::getAllOnesValue(BitWidth);
} else if (DemandedMask == 0) { // Not demanding any bits from V.
if (V != UndefValue::get(VTy))
return UpdateValueUsesWith(V, UndefValue::get(VTy));
return false;
} else if (Depth == 6) { // Limit search depth.
return false;
}
Instruction *I = dyn_cast<Instruction>(V);
if (!I) return false; // Only analyze instructions.
APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
switch (I->getOpcode()) {
default:
ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
break;
case Instruction::And:
// If either the LHS or the RHS are Zero, the result is zero.
if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// If something is known zero on the RHS, the bits aren't demanded on the
// LHS.
if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
assert((LHSKnownZero & LHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// If all of the demanded bits are known 1 on one side, return the other.
// These bits cannot contribute to the result of the 'and'.
if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
(DemandedMask & ~LHSKnownZero))
return UpdateValueUsesWith(I, I->getOperand(0));
if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
(DemandedMask & ~RHSKnownZero))
return UpdateValueUsesWith(I, I->getOperand(1));
// If all of the demanded bits in the inputs are known zeros, return zero.
if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
// If the RHS is a constant, see if we can simplify it.
if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
return UpdateValueUsesWith(I, I);
// Output known-1 bits are only known if set in both the LHS & RHS.
RHSKnownOne &= LHSKnownOne;
// Output known-0 are known to be clear if zero in either the LHS | RHS.
RHSKnownZero |= LHSKnownZero;
break;
case Instruction::Or:
// If either the LHS or the RHS are One, the result is One.
if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// If something is known one on the RHS, the bits aren't demanded on the
// LHS.
if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
assert((LHSKnownZero & LHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// If all of the demanded bits are known zero on one side, return the other.
// These bits cannot contribute to the result of the 'or'.
if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
(DemandedMask & ~LHSKnownOne))
return UpdateValueUsesWith(I, I->getOperand(0));
if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
(DemandedMask & ~RHSKnownOne))
return UpdateValueUsesWith(I, I->getOperand(1));
// If all of the potentially set bits on one side are known to be set on
// the other side, just use the 'other' side.
if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
(DemandedMask & (~RHSKnownZero)))
return UpdateValueUsesWith(I, I->getOperand(0));
if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
(DemandedMask & (~LHSKnownZero)))
return UpdateValueUsesWith(I, I->getOperand(1));
// If the RHS is a constant, see if we can simplify it.
if (ShrinkDemandedConstant(I, 1, DemandedMask))
return UpdateValueUsesWith(I, I);
// Output known-0 bits are only known if clear in both the LHS & RHS.
RHSKnownZero &= LHSKnownZero;
// Output known-1 are known to be set if set in either the LHS | RHS.
RHSKnownOne |= LHSKnownOne;
break;
case Instruction::Xor: {
if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
assert((LHSKnownZero & LHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// If all of the demanded bits are known zero on one side, return the other.
// These bits cannot contribute to the result of the 'xor'.
if ((DemandedMask & RHSKnownZero) == DemandedMask)
return UpdateValueUsesWith(I, I->getOperand(0));
if ((DemandedMask & LHSKnownZero) == DemandedMask)
return UpdateValueUsesWith(I, I->getOperand(1));
// Output known-0 bits are known if clear or set in both the LHS & RHS.
APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
(RHSKnownOne & LHSKnownOne);
// Output known-1 are known to be set if set in only one of the LHS, RHS.
APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
(RHSKnownOne & LHSKnownZero);
// If all of the demanded bits are known to be zero on one side or the
// other, turn this into an *inclusive* or.
// e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
Instruction *Or =
BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
I->getName());
InsertNewInstBefore(Or, *I);
return UpdateValueUsesWith(I, Or);
}
// If all of the demanded bits on one side are known, and all of the set
// bits on that side are also known to be set on the other side, turn this
// into an AND, as we know the bits will be cleared.
// e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
// all known
if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
Instruction *And =
BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
InsertNewInstBefore(And, *I);
return UpdateValueUsesWith(I, And);
}
}
// If the RHS is a constant, see if we can simplify it.
// FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
if (ShrinkDemandedConstant(I, 1, DemandedMask))
return UpdateValueUsesWith(I, I);
RHSKnownZero = KnownZeroOut;
RHSKnownOne = KnownOneOut;
break;
}
case Instruction::Select:
if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
assert((LHSKnownZero & LHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// If the operands are constants, see if we can simplify them.
if (ShrinkDemandedConstant(I, 1, DemandedMask))
return UpdateValueUsesWith(I, I);
if (ShrinkDemandedConstant(I, 2, DemandedMask))
return UpdateValueUsesWith(I, I);
// Only known if known in both the LHS and RHS.
RHSKnownOne &= LHSKnownOne;
RHSKnownZero &= LHSKnownZero;
break;
case Instruction::Trunc: {
uint32_t truncBf =
cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
DemandedMask.zext(truncBf);
RHSKnownZero.zext(truncBf);
RHSKnownOne.zext(truncBf);
if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
DemandedMask.trunc(BitWidth);
RHSKnownZero.trunc(BitWidth);
RHSKnownOne.trunc(BitWidth);
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
break;
}
case Instruction::BitCast:
if (!I->getOperand(0)->getType()->isInteger())
return false;
if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
break;
case Instruction::ZExt: {
// Compute the bits in the result that are not present in the input.
const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
uint32_t SrcBitWidth = SrcTy->getBitWidth();
DemandedMask.trunc(SrcBitWidth);
RHSKnownZero.trunc(SrcBitWidth);
RHSKnownOne.trunc(SrcBitWidth);
if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
DemandedMask.zext(BitWidth);
RHSKnownZero.zext(BitWidth);
RHSKnownOne.zext(BitWidth);
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// The top bits are known to be zero.
RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
break;
}
case Instruction::SExt: {
// Compute the bits in the result that are not present in the input.
const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
uint32_t SrcBitWidth = SrcTy->getBitWidth();
APInt InputDemandedBits = DemandedMask &
APInt::getLowBitsSet(BitWidth, SrcBitWidth);
APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
// If any of the sign extended bits are demanded, we know that the sign
// bit is demanded.
if ((NewBits & DemandedMask) != 0)
InputDemandedBits.set(SrcBitWidth-1);
InputDemandedBits.trunc(SrcBitWidth);
RHSKnownZero.trunc(SrcBitWidth);
RHSKnownOne.trunc(SrcBitWidth);
if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
InputDemandedBits.zext(BitWidth);
RHSKnownZero.zext(BitWidth);
RHSKnownOne.zext(BitWidth);
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// If the sign bit of the input is known set or clear, then we know the
// top bits of the result.
// If the input sign bit is known zero, or if the NewBits are not demanded
// convert this into a zero extension.
if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
{
// Convert to ZExt cast
CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
return UpdateValueUsesWith(I, NewCast);
} else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
RHSKnownOne |= NewBits;
}
break;
}
case Instruction::Add: {
// Figure out what the input bits are. If the top bits of the and result
// are not demanded, then the add doesn't demand them from its input
// either.
uint32_t NLZ = DemandedMask.countLeadingZeros();
// If there is a constant on the RHS, there are a variety of xformations
// we can do.
if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
// If null, this should be simplified elsewhere. Some of the xforms here
// won't work if the RHS is zero.
if (RHS->isZero())
break;
// If the top bit of the output is demanded, demand everything from the
// input. Otherwise, we demand all the input bits except NLZ top bits.
APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
// Find information about known zero/one bits in the input.
if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
// If the RHS of the add has bits set that can't affect the input, reduce
// the constant.
if (ShrinkDemandedConstant(I, 1, InDemandedBits))
return UpdateValueUsesWith(I, I);
// Avoid excess work.
if (LHSKnownZero == 0 && LHSKnownOne == 0)
break;
// Turn it into OR if input bits are zero.
if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
Instruction *Or =
BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
I->getName());
InsertNewInstBefore(Or, *I);
return UpdateValueUsesWith(I, Or);
}
// We can say something about the output known-zero and known-one bits,
// depending on potential carries from the input constant and the
// unknowns. For example if the LHS is known to have at most the 0x0F0F0
// bits set and the RHS constant is 0x01001, then we know we have a known
// one mask of 0x00001 and a known zero mask of 0xE0F0E.
// To compute this, we first compute the potential carry bits. These are
// the bits which may be modified. I'm not aware of a better way to do
// this scan.
const APInt& RHSVal = RHS->getValue();
APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
// Now that we know which bits have carries, compute the known-1/0 sets.
// Bits are known one if they are known zero in one operand and one in the
// other, and there is no input carry.
RHSKnownOne = ((LHSKnownZero & RHSVal) |
(LHSKnownOne & ~RHSVal)) & ~CarryBits;
// Bits are known zero if they are known zero in both operands and there
// is no input carry.
RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
} else {
// If the high-bits of this ADD are not demanded, then it does not demand
// the high bits of its LHS or RHS.
if (DemandedMask[BitWidth-1] == 0) {
// Right fill the mask of bits for this ADD to demand the most
// significant bit and all those below it.
APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
}
}
break;
}
case Instruction::Sub:
// If the high-bits of this SUB are not demanded, then it does not demand
// the high bits of its LHS or RHS.
if (DemandedMask[BitWidth-1] == 0) {
// Right fill the mask of bits for this SUB to demand the most
// significant bit and all those below it.
uint32_t NLZ = DemandedMask.countLeadingZeros();
APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
}
// Otherwise just hand the sub off to ComputeMaskedBits to fill in
// the known zeros and ones.
ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
break;
case Instruction::Shl:
if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
RHSKnownZero <<= ShiftAmt;
RHSKnownOne <<= ShiftAmt;
// low bits known zero.
if (ShiftAmt)
RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
}
break;
case Instruction::LShr:
// For a logical shift right
if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
// Unsigned shift right.
APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
if (ShiftAmt) {
// Compute the new bits that are at the top now.
APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
RHSKnownZero |= HighBits; // high bits known zero.
}
}
break;
case Instruction::AShr:
// If this is an arithmetic shift right and only the low-bit is set, we can
// always convert this into a logical shr, even if the shift amount is
// variable. The low bit of the shift cannot be an input sign bit unless
// the shift amount is >= the size of the datatype, which is undefined.
if (DemandedMask == 1) {
// Perform the logical shift right.
Value *NewVal = BinaryOperator::createLShr(
I->getOperand(0), I->getOperand(1), I->getName());
InsertNewInstBefore(cast<Instruction>(NewVal), *I);
return UpdateValueUsesWith(I, NewVal);
}
// If the sign bit is the only bit demanded by this ashr, then there is no
// need to do it, the shift doesn't change the high bit.
if (DemandedMask.isSignBit())
return UpdateValueUsesWith(I, I->getOperand(0));
if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
// Signed shift right.
APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
// If any of the "high bits" are demanded, we should set the sign bit as
// demanded.
if (DemandedMask.countLeadingZeros() <= ShiftAmt)
DemandedMaskIn.set(BitWidth-1);
if (SimplifyDemandedBits(I->getOperand(0),
DemandedMaskIn,
RHSKnownZero, RHSKnownOne, Depth+1))
return true;
assert((RHSKnownZero & RHSKnownOne) == 0 &&
"Bits known to be one AND zero?");
// Compute the new bits that are at the top now.
APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
// Handle the sign bits.
APInt SignBit(APInt::getSignBit(BitWidth));
// Adjust to where it is now in the mask.
SignBit = APIntOps::lshr(SignBit, ShiftAmt);
// If the input sign bit is known to be zero, or if none of the top bits
// are demanded, turn this into an unsigned shift right.
if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
(HighBits & ~DemandedMask) == HighBits) {
// Perform the logical shift right.
Value *NewVal = BinaryOperator::createLShr(
I->getOperand(0), SA, I->getName());
InsertNewInstBefore(cast<Instruction>(NewVal), *I);
return UpdateValueUsesWith(I, NewVal);
} else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
RHSKnownOne |= HighBits;
}
}
break;
case Instruction::SRem:
if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
APInt RA = Rem->getValue();
if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
if (SimplifyDemandedBits(I->getOperand(0), Mask2,
LHSKnownZero, LHSKnownOne, Depth+1))
return true;
if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
LHSKnownZero |= ~LowBits;
else if (LHSKnownOne[BitWidth-1])
LHSKnownOne |= ~LowBits;
KnownZero |= LHSKnownZero & DemandedMask;
KnownOne |= LHSKnownOne & DemandedMask;
assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
}
}
break;
case Instruction::URem: {
if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
APInt RA = Rem->getValue();
if (RA.isPowerOf2()) {
APInt LowBits = (RA - 1);
APInt Mask2 = LowBits & DemandedMask;
KnownZero |= ~LowBits & DemandedMask;
if (SimplifyDemandedBits(I->getOperand(0), Mask2,
KnownZero, KnownOne, Depth+1))
return true;
assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
break;
}
}
APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
APInt AllOnes = APInt::getAllOnesValue(BitWidth);
if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
KnownZero2, KnownOne2, Depth+1))
return true;
uint32_t Leaders = KnownZero2.countLeadingOnes();
if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
KnownZero2, KnownOne2, Depth+1))
return true;
Leaders = std::max(Leaders,
KnownZero2.countLeadingOnes());
KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
break;
}
}
// If the client is only demanding bits that we know, return the known
// constant.
if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
return false;
}
/// SimplifyDemandedVectorElts - The specified value producecs a vector with
/// 64 or fewer elements. DemandedElts contains the set of elements that are
/// actually used by the caller. This method analyzes which elements of the
/// operand are undef and returns that information in UndefElts.
///
/// If the information about demanded elements can be used to simplify the
/// operation, the operation is simplified, then the resultant value is
/// returned. This returns null if no change was made.
Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
uint64_t &UndefElts,
unsigned Depth) {
unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
assert(VWidth <= 64 && "Vector too wide to analyze!");
uint64_t EltMask = ~0ULL >> (64-VWidth);
assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
"Invalid DemandedElts!");
if (isa<UndefValue>(V)) {
// If the entire vector is undefined, just return this info.
UndefElts = EltMask;
return 0;
} else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
UndefElts = EltMask;
return UndefValue::get(V->getType());
}
UndefElts = 0;
if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Constant *Undef = UndefValue::get(EltTy);
std::vector<Constant*> Elts;
for (unsigned i = 0; i != VWidth; ++i)
if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
Elts.push_back(Undef);
UndefElts |= (1ULL << i);
} else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
Elts.push_back(Undef);
UndefElts |= (1ULL << i);
} else { // Otherwise, defined.
Elts.push_back(CP->getOperand(i));
}
// If we changed the constant, return it.
Constant *NewCP = ConstantVector::get(Elts);
return NewCP != CP ? NewCP : 0;
} else if (isa<ConstantAggregateZero>(V)) {
// Simplify the CAZ to a ConstantVector where the non-demanded elements are
// set to undef.
const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Constant *Zero = Constant::getNullValue(EltTy);
Constant *Undef = UndefValue::get(EltTy);
std::vector<Constant*> Elts;
for (unsigned i = 0; i != VWidth; ++i)
Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
UndefElts = DemandedElts ^ EltMask;
return ConstantVector::get(Elts);
}
if (!V->hasOneUse()) { // Other users may use these bits.
if (Depth != 0) { // Not at the root.
// TODO: Just compute the UndefElts information recursively.
return false;
}
return false;
} else if (Depth == 10) { // Limit search depth.
return false;
}
Instruction *I = dyn_cast<Instruction>(V);
if (!I) return false; // Only analyze instructions.
bool MadeChange = false;
uint64_t UndefElts2;
Value *TmpV;
switch (I->getOpcode()) {
default: break;
case Instruction::InsertElement: {
// If this is a variable index, we don't know which element it overwrites.
// demand exactly the same input as we produce.
ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
if (Idx == 0) {
// Note that we can't propagate undef elt info, because we don't know
// which elt is getting updated.
TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
UndefElts2, Depth+1);
if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
break;
}
// If this is inserting an element that isn't demanded, remove this
// insertelement.
unsigned IdxNo = Idx->getZExtValue();
if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
return AddSoonDeadInstToWorklist(*I, 0);
// Otherwise, the element inserted overwrites whatever was there, so the
// input demanded set is simpler than the output set.
TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
DemandedElts & ~(1ULL << IdxNo),
UndefElts, Depth+1);
if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
// The inserted element is defined.
UndefElts |= 1ULL << IdxNo;
break;
}
case Instruction::BitCast: {
// Vector->vector casts only.
const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
if (!VTy) break;
unsigned InVWidth = VTy->getNumElements();
uint64_t InputDemandedElts = 0;
unsigned Ratio;
if (VWidth == InVWidth) {
// If we are converting from <4 x i32> -> <4 x f32>, we demand the same
// elements as are demanded of us.
Ratio = 1;
InputDemandedElts = DemandedElts;
} else if (VWidth > InVWidth) {
// Untested so far.
break;
// If there are more elements in the result than there are in the source,
// then an input element is live if any of the corresponding output
// elements are live.
Ratio = VWidth/InVWidth;
for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
if (DemandedElts & (1ULL << OutIdx))
InputDemandedElts |= 1ULL << (OutIdx/Ratio);
}
} else {
// Untested so far.
break;
// If there are more elements in the source than there are in the result,
// then an input element is live if the corresponding output element is
// live.
Ratio = InVWidth/VWidth;
for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
if (DemandedElts & (1ULL << InIdx/Ratio))
InputDemandedElts |= 1ULL << InIdx;
}
// div/rem demand all inputs, because they don't want divide by zero.
TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
UndefElts2, Depth+1);
if (TmpV) {
I->setOperand(0, TmpV);
MadeChange = true;
}
UndefElts = UndefElts2;
if (VWidth > InVWidth) {
assert(0 && "Unimp");
// If there are more elements in the result than there are in the source,
// then an output element is undef if the corresponding input element is
// undef.
for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
UndefElts |= 1ULL << OutIdx;
} else if (VWidth < InVWidth) {
assert(0 && "Unimp");
// If there are more elements in the source than there are in the result,
// then a result element is undef if all of the corresponding input
// elements are undef.
UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
}
break;
}
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
// div/rem demand all inputs, because they don't want divide by zero.
TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
UndefElts, Depth+1);
if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
UndefElts2, Depth+1);
if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
// Output elements are undefined if both are undefined. Consider things
// like undef&0. The result is known zero, not undef.
UndefElts &= UndefElts2;
break;
case Instruction::Call: {
IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
if (!II) break;
switch (II->getIntrinsicID()) {
default: break;
// Binary vector operations that work column-wise. A dest element is a
// function of the corresponding input elements from the two inputs.
case Intrinsic::x86_sse_sub_ss:
case Intrinsic::x86_sse_mul_ss:
case Intrinsic::x86_sse_min_ss:
case Intrinsic::x86_sse_max_ss:
case Intrinsic::x86_sse2_sub_sd:
case Intrinsic::x86_sse2_mul_sd:
case Intrinsic::x86_sse2_min_sd:
case Intrinsic::x86_sse2_max_sd:
TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
UndefElts, Depth+1);
if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
UndefElts2, Depth+1);
if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
// If only the low elt is demanded and this is a scalarizable intrinsic,
// scalarize it now.
if (DemandedElts == 1) {
switch (II->getIntrinsicID()) {
default: break;
case Intrinsic::x86_sse_sub_ss:
case Intrinsic::x86_sse_mul_ss:
case Intrinsic::x86_sse2_sub_sd:
case Intrinsic::x86_sse2_mul_sd:
// TODO: Lower MIN/MAX/ABS/etc
Value *LHS = II->getOperand(1);
Value *RHS = II->getOperand(2);
// Extract the element as scalars.
LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
switch (II->getIntrinsicID()) {
default: assert(0 && "Case stmts out of sync!");
case Intrinsic::x86_sse_sub_ss:
case Intrinsic::x86_sse2_sub_sd:
TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
II->getName()), *II);
break;
case Intrinsic::x86_sse_mul_ss:
case Intrinsic::x86_sse2_mul_sd:
TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
II->getName()), *II);
break;
}
Instruction *New =
InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
II->getName());
InsertNewInstBefore(New, *II);
AddSoonDeadInstToWorklist(*II, 0);
return New;
}
}
// Output elements are undefined if both are undefined. Consider things
// like undef&0. The result is known zero, not undef.
UndefElts &= UndefElts2;
break;
}
break;
}
}
return MadeChange ? I : 0;
}
/// @returns true if the specified compare predicate is
/// true when both operands are equal...
/// @brief Determine if the icmp Predicate is true when both operands are equal
static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
pred == ICmpInst::ICMP_SLE;
}
/// @returns true if the specified compare instruction is
/// true when both operands are equal...
/// @brief Determine if the ICmpInst returns true when both operands are equal
static bool isTrueWhenEqual(ICmpInst &ICI) {
return isTrueWhenEqual(ICI.getPredicate());
}
/// AssociativeOpt - Perform an optimization on an associative operator. This
/// function is designed to check a chain of associative operators for a
/// potential to apply a certain optimization. Since the optimization may be
/// applicable if the expression was reassociated, this checks the chain, then
/// reassociates the expression as necessary to expose the optimization
/// opportunity. This makes use of a special Functor, which must define
/// 'shouldApply' and 'apply' methods.
///
template<typename Functor>
Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
unsigned Opcode = Root.getOpcode();
Value *LHS = Root.getOperand(0);
// Quick check, see if the immediate LHS matches...
if (F.shouldApply(LHS))
return F.apply(Root);
// Otherwise, if the LHS is not of the same opcode as the root, return.
Instruction *LHSI = dyn_cast<Instruction>(LHS);
while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
// Should we apply this transform to the RHS?
bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
// If not to the RHS, check to see if we should apply to the LHS...
if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
ShouldApply = true;
}
// If the functor wants to apply the optimization to the RHS of LHSI,
// reassociate the expression from ((? op A) op B) to (? op (A op B))
if (ShouldApply) {
BasicBlock *BB = Root.getParent();
// Now all of the instructions are in the current basic block, go ahead
// and perform the reassociation.
Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
// First move the selected RHS to the LHS of the root...
Root.setOperand(0, LHSI->getOperand(1));
// Make what used to be the LHS of the root be the user of the root...
Value *ExtraOperand = TmpLHSI->getOperand(1);
if (&Root == TmpLHSI) {
Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
return 0;
}
Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
BasicBlock::iterator ARI = &Root; ++ARI;
BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
ARI = Root;
// Now propagate the ExtraOperand down the chain of instructions until we
// get to LHSI.
while (TmpLHSI != LHSI) {
Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
// Move the instruction to immediately before the chain we are
// constructing to avoid breaking dominance properties.
NextLHSI->getParent()->getInstList().remove(NextLHSI);
BB->getInstList().insert(ARI, NextLHSI);
ARI = NextLHSI;
Value *NextOp = NextLHSI->getOperand(1);
NextLHSI->setOperand(1, ExtraOperand);
TmpLHSI = NextLHSI;
ExtraOperand = NextOp;
}
// Now that the instructions are reassociated, have the functor perform
// the transformation...
return F.apply(Root);
}
LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
}
return 0;
}
// AddRHS - Implements: X + X --> X << 1
struct AddRHS {
Value *RHS;
AddRHS(Value *rhs) : RHS(rhs) {}
bool shouldApply(Value *LHS) const { return LHS == RHS; }
Instruction *apply(BinaryOperator &Add) const {
return BinaryOperator::createShl(Add.getOperand(0),
ConstantInt::get(Add.getType(), 1));
}
};
// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
// iff C1&C2 == 0
struct AddMaskingAnd {
Constant *C2;
AddMaskingAnd(Constant *c) : C2(c) {}
bool shouldApply(Value *LHS) const {
ConstantInt *C1;
return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
ConstantExpr::getAnd(C1, C2)->isNullValue();
}
Instruction *apply(BinaryOperator &Add) const {
return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
}
};
static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
InstCombiner *IC) {
if (CastInst *CI = dyn_cast<CastInst>(&I)) {
if (Constant *SOC = dyn_cast<Constant>(SO))
return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
return IC->InsertNewInstBefore(CastInst::create(
CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
}
// Figure out if the constant is the left or the right argument.
bool ConstIsRHS = isa<Constant>(I.getOperand(1));
Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
if (Constant *SOC = dyn_cast<Constant>(SO)) {
if (ConstIsRHS)
return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
}
Value *Op0 = SO, *Op1 = ConstOperand;
if (!ConstIsRHS)
std::swap(Op0, Op1);
Instruction *New;
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
SO->getName()+".cmp");
else {
assert(0 && "Unknown binary instruction type!");
abort();
}
return IC->InsertNewInstBefore(New, I);
}
// FoldOpIntoSelect - Given an instruction with a select as one operand and a
// constant as the other operand, try to fold the binary operator into the
// select arguments. This also works for Cast instructions, which obviously do
// not have a second operand.
static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
InstCombiner *IC) {
// Don't modify shared select instructions
if (!SI->hasOneUse()) return 0;
Value *TV = SI->getOperand(1);
Value *FV = SI->getOperand(2);
if (isa<Constant>(TV) || isa<Constant>(FV)) {
// Bool selects with constant operands can be folded to logical ops.
if (SI->getType() == Type::Int1Ty) return 0;
Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
return SelectInst::Create(SI->getCondition(), SelectTrueVal,
SelectFalseVal);
}
return 0;
}
/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
/// node as operand #0, see if we can fold the instruction into the PHI (which
/// is only possible if all operands to the PHI are constants).
Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
PHINode *PN = cast<PHINode>(I.getOperand(0));
unsigned NumPHIValues = PN->getNumIncomingValues();
if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
// Check to see if all of the operands of the PHI are constants. If there is
// one non-constant value, remember the BB it is. If there is more than one
// or if *it* is a PHI, bail out.
BasicBlock *NonConstBB = 0;
for (unsigned i = 0; i != NumPHIValues; ++i)
if (!isa<Constant>(PN->getIncomingValue(i))) {
if (NonConstBB) return 0; // More than one non-const value.
if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
NonConstBB = PN->getIncomingBlock(i);
// If the incoming non-constant value is in I's block, we have an infinite
// loop.
if (NonConstBB == I.getParent())
return 0;
}
// If there is exactly one non-constant value, we can insert a copy of the
// operation in that block. However, if this is a critical edge, we would be
// inserting the computation one some other paths (e.g. inside a loop). Only
// do this if the pred block is unconditionally branching into the phi block.
if (NonConstBB) {
BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
if (!BI || !BI->isUnconditional()) return 0;
}
// Okay, we can do the transformation: create the new PHI node.
PHINode *NewPN = PHINode::Create(I.getType(), "");
NewPN->reserveOperandSpace(PN->getNumOperands()/2);
InsertNewInstBefore(NewPN, *PN);
NewPN->takeName(PN);
// Next, add all of the operands to the PHI.
if (I.getNumOperands() == 2) {
Constant *C = cast<Constant>(I.getOperand(1));
for (unsigned i = 0; i != NumPHIValues; ++i) {
Value *InV = 0;
if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
if (CmpInst *CI = dyn_cast<CmpInst>(&I))
InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
else
InV = ConstantExpr::get(I.getOpcode(), InC, C);
} else {
assert(PN->getIncomingBlock(i) == NonConstBB);
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
InV = BinaryOperator::create(BO->getOpcode(),
PN->getIncomingValue(i), C, "phitmp",
NonConstBB->getTerminator());
else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
InV = CmpInst::create(CI->getOpcode(),
CI->getPredicate(),
PN->getIncomingValue(i), C, "phitmp",
NonConstBB->getTerminator());
else
assert(0 && "Unknown binop!");
AddToWorkList(cast<Instruction>(InV));
}
NewPN->addIncoming(InV, PN->getIncomingBlock(i));
}
} else {
CastInst *CI = cast<CastInst>(&I);
const Type *RetTy = CI->getType();
for (unsigned i = 0; i != NumPHIValues; ++i) {
Value *InV;
if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
} else {
assert(PN->getIncomingBlock(i) == NonConstBB);
InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
I.getType(), "phitmp",
NonConstBB->getTerminator());
AddToWorkList(cast<Instruction>(InV));
}
NewPN->addIncoming(InV, PN->getIncomingBlock(i));
}
}
return ReplaceInstUsesWith(I, NewPN);
}
/// CannotBeNegativeZero - Return true if we can prove that the specified FP
/// value is never equal to -0.0.
///
/// Note that this function will need to be revisited when we support nondefault
/// rounding modes!
///
static bool CannotBeNegativeZero(const Value *V) {
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
return !CFP->getValueAPF().isNegZero();
// (add x, 0.0) is guaranteed to return +0.0, not -0.0.
if (const Instruction *I = dyn_cast<Instruction>(V)) {
if (I->getOpcode() == Instruction::Add &&
isa<ConstantFP>(I->getOperand(1)) &&
cast<ConstantFP>(I->getOperand(1))->isNullValue())
return true;
if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
if (II->getIntrinsicID() == Intrinsic::sqrt)
return CannotBeNegativeZero(II->getOperand(1));
if (const CallInst *CI = dyn_cast<CallInst>(I))
if (const Function *F = CI->getCalledFunction()) {
if (F->isDeclaration()) {
switch (F->getNameLen()) {
case 3: // abs(x) != -0.0
if (!strcmp(F->getNameStart(), "abs")) return true;
break;
case 4: // abs[lf](x) != -0.0
if (!strcmp(F->getNameStart(), "absf")) return true;
if (!strcmp(F->getNameStart(), "absl")) return true;
break;
}
}
}
}
return false;
}
Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
bool Changed = SimplifyCommutative(I);
Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
// X + undef -> undef
if (isa<UndefValue>(RHS))
return ReplaceInstUsesWith(I, RHS);
// X + 0 --> X
if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
if (RHSC->isNullValue())
return ReplaceInstUsesWith(I, LHS);
} else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
if (CFP->isExactlyValue(ConstantFP::getNegativeZero
(I.getType())->getValueAPF()))
return ReplaceInstUsesWith(I, LHS);
}
if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
// X + (signbit) --> X ^ signbit
const APInt& Val = CI->getValue();
uint32_t BitWidth = Val.getBitWidth();
if (Val == APInt::getSignBit(BitWidth))
return BinaryOperator::createXor(LHS, RHS);
// See if SimplifyDemandedBits can simplify this. This handles stuff like
// (X & 254)+1 -> (X&254)|1
if (!isa<VectorType>(I.getType())) {
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
KnownZero, KnownOne))
return &I;
}
}
if (isa<PHINode>(LHS))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
ConstantInt *XorRHS = 0;
Value *XorLHS = 0;
if (isa<ConstantInt>(RHSC) &&
match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
uint32_t Size = TySizeBits / 2;
APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
APInt CFF80Val(-C0080Val);
do {
if (TySizeBits > Size) {
// If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
// If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
(RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
// This is a sign extend if the top bits are known zero.
if (!MaskedValueIsZero(XorLHS,
APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Size = 0; // Not a sign ext, but can't be any others either.
break;
}
}
Size >>= 1;
C0080Val = APIntOps::lshr(C0080Val, Size);
CFF80Val = APIntOps::ashr(CFF80Val, Size);
} while (Size >= 1);
// FIXME: This shouldn't be necessary. When the backends can handle types
// with funny bit widths then this whole cascade of if statements should
// be removed. It is just here to get the size of the "middle" type back
// up to something that the back ends can handle.
const Type *MiddleType = 0;
switch (Size) {
default: break;
case 32: MiddleType = Type::Int32Ty; break;
case 16: MiddleType = Type::Int16Ty; break;
case 8: MiddleType = Type::Int8Ty; break;
}
if (MiddleType) {
Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
InsertNewInstBefore(NewTrunc, I);
return new SExtInst(NewTrunc, I.getType(), I.getName());
}
}
}
// X + X --> X << 1
if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
if (RHSI->getOpcode() == Instruction::Sub)
if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
return ReplaceInstUsesWith(I, RHSI->getOperand(0));
}
if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
if (LHSI->getOpcode() == Instruction::Sub)
if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
return ReplaceInstUsesWith(I, LHSI->getOperand(0));
}
}
// -A + B --> B - A
// -A + -B --> -(A + B)
if (Value *LHSV = dyn_castNegVal(LHS)) {
if (LHS->getType()->isIntOrIntVector()) {
if (Value *RHSV = dyn_castNegVal(RHS)) {
Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
InsertNewInstBefore(NewAdd, I);
return BinaryOperator::createNeg(NewAdd);
}
}
return BinaryOperator::createSub(RHS, LHSV);
}
// A + -B --> A - B
if (!isa<Constant>(RHS))
if (Value *V = dyn_castNegVal(RHS))
return BinaryOperator::createSub(LHS, V);
ConstantInt *C2;
if (Value *X = dyn_castFoldableMul(LHS, C2)) {
if (X == RHS) // X*C + X --> X * (C+1)
return BinaryOperator::createMul(RHS, AddOne(C2));
// X*C1 + X*C2 --> X * (C1+C2)
ConstantInt *C1;
if (X == dyn_castFoldableMul(RHS, C1))
return BinaryOperator::createMul(X, Add(C1, C2));
}
// X + X*C --> X * (C+1)
if (dyn_castFoldableMul(RHS, C2) == LHS)
return BinaryOperator::createMul(LHS, AddOne(C2));
// X + ~X --> -1 since ~X = -X-1
if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
// (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
return R;
// W*X + Y*Z --> W * (X+Z) iff W == Y
if (I.getType()->isIntOrIntVector()) {
Value *W, *X, *Y, *Z;
if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
if (W != Y) {
if (W == Z) {
std::swap(Y, Z);
} else if (Y == X) {
std::swap(W, X);
} else if (X == Z) {
std::swap(Y, Z);
std::swap(W, X);
}
}
if (W == Y) {
Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
LHS->getName()), I);
return BinaryOperator::createMul(W, NewAdd);
}
}
}
if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Value *X = 0;
if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
return BinaryOperator::createSub(SubOne(CRHS), X);
// (X & FF00) + xx00 -> (X+xx00) & FF00
if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Constant *Anded = And(CRHS, C2);
if (Anded == CRHS) {
// See if all bits from the first bit set in the Add RHS up are included
// in the mask. First, get the rightmost bit.
const APInt& AddRHSV = CRHS->getValue();
// Form a mask of all bits from the lowest bit added through the top.
APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
// See if the and mask includes all of these bits.
APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
if (AddRHSHighBits == AddRHSHighBitsAnd) {
// Okay, the xform is safe. Insert the new add pronto.
Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
LHS->getName()), I);
return BinaryOperator::createAnd(NewAdd, C2);
}
}
}
// Try to fold constant add into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
}
// add (cast *A to intptrtype) B ->
// cast (GEP (cast *A to sbyte*) B) --> intptrtype
{
CastInst *CI = dyn_cast<CastInst>(LHS);
Value *Other = RHS;
if (!CI) {
CI = dyn_cast<CastInst>(RHS);
Other = LHS;
}
if (CI && CI->getType()->isSized() &&
(CI->getType()->getPrimitiveSizeInBits() ==
TD->getIntPtrType()->getPrimitiveSizeInBits())
&& isa<PointerType>(CI->getOperand(0)->getType())) {
unsigned AS =
cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Value *I2 = InsertBitCastBefore(CI->getOperand(0),
PointerType::get(Type::Int8Ty, AS), I);
I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
return new PtrToIntInst(I2, CI->getType());
}
}
// add (select X 0 (sub n A)) A --> select X A n
{
SelectInst *SI = dyn_cast<SelectInst>(LHS);
Value *Other = RHS;
if (!SI) {
SI = dyn_cast<SelectInst>(RHS);
Other = LHS;
}
if (SI && SI->hasOneUse()) {
Value *TV = SI->getTrueValue();
Value *FV = SI->getFalseValue();
Value *A, *N;
// Can we fold the add into the argument of the select?
// We check both true and false select arguments for a matching subtract.
if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
A == Other) // Fold the add into the true select value.
return SelectInst::Create(SI->getCondition(), N, A);
if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
A == Other) // Fold the add into the false select value.
return SelectInst::Create(SI->getCondition(), A, N);
}
}
// Check for X+0.0. Simplify it to X if we know X is not -0.0.
if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
return ReplaceInstUsesWith(I, LHS);
return Changed ? &I : 0;
}
// isSignBit - Return true if the value represented by the constant only has the
// highest order bit set.
static bool isSignBit(ConstantInt *CI) {
uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
return CI->getValue() == APInt::getSignBit(NumBits);
}
Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Op0 == Op1) // sub X, X -> 0
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
// If this is a 'B = x-(-A)', change to B = x+A...
if (Value *V = dyn_castNegVal(Op1))
return BinaryOperator::createAdd(Op0, V);
if (isa<UndefValue>(Op0))
return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
if (isa<UndefValue>(Op1))
return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
// Replace (-1 - A) with (~A)...
if (C->isAllOnesValue())
return BinaryOperator::createNot(Op1);
// C - ~X == X + (1+C)
Value *X = 0;
if (match(Op1, m_Not(m_Value(X))))
return BinaryOperator::createAdd(X, AddOne(C));
// -(X >>u 31) -> (X >>s 31)
// -(X >>s 31) -> (X >>u 31)
if (C->isZero()) {
if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
if (SI->getOpcode() == Instruction::LShr) {
if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
// Check to see if we are shifting out everything but the sign bit.
if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
SI->getType()->getPrimitiveSizeInBits()-1) {
// Ok, the transformation is safe. Insert AShr.
return BinaryOperator::create(Instruction::AShr,
SI->getOperand(0), CU, SI->getName());
}
}
}
else if (SI->getOpcode() == Instruction::AShr) {
if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
// Check to see if we are shifting out everything but the sign bit.
if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
SI->getType()->getPrimitiveSizeInBits()-1) {
// Ok, the transformation is safe. Insert LShr.
return BinaryOperator::createLShr(
SI->getOperand(0), CU, SI->getName());
}
}
}
}
}
// Try to fold constant sub into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
if (Op1I->getOpcode() == Instruction::Add &&
!Op0->getType()->isFPOrFPVector()) {
if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
// C1-(X+C2) --> (C1-C2)-X
return BinaryOperator::createSub(Subtract(CI1, CI2),
Op1I->getOperand(0));
}
}
if (Op1I->hasOneUse()) {
// Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
// is not used by anyone else...
//
if (Op1I->getOpcode() == Instruction::Sub &&
!Op1I->getType()->isFPOrFPVector()) {
// Swap the two operands of the subexpr...
Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
Op1I->setOperand(0, IIOp1);
Op1I->setOperand(1, IIOp0);
// Create the new top level add instruction...
return BinaryOperator::createAdd(Op0, Op1);
}
// Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
//
if (Op1I->getOpcode() == Instruction::And &&
(Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
Value *NewNot =
InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
return BinaryOperator::createAnd(Op0, NewNot);
}
// 0 - (X sdiv C) -> (X sdiv -C)
if (Op1I->getOpcode() == Instruction::SDiv)
if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
if (CSI->isZero())
if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
return BinaryOperator::createSDiv(Op1I->getOperand(0),
ConstantExpr::getNeg(DivRHS));
// X - X*C --> X * (1-C)
ConstantInt *C2 = 0;
if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
return BinaryOperator::createMul(Op0, CP1);
}
// X - ((X / Y) * Y) --> X % Y
if (Op1I->getOpcode() == Instruction::Mul)
if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
if (Op0 == I->getOperand(0) &&
Op1I->getOperand(1) == I->getOperand(1)) {
if (I->getOpcode() == Instruction::SDiv)
return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
if (I->getOpcode() == Instruction::UDiv)
return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
}
}
}
if (!Op0->getType()->isFPOrFPVector())
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
if (Op0I->getOpcode() == Instruction::Add) {
if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
return ReplaceInstUsesWith(I, Op0I->getOperand(1));
else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
return ReplaceInstUsesWith(I, Op0I->getOperand(0));
} else if (Op0I->getOpcode() == Instruction::Sub) {
if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
}
}
ConstantInt *C1;
if (Value *X = dyn_castFoldableMul(Op0, C1)) {
if (X == Op1) // X*C - X --> X * (C-1)
return BinaryOperator::createMul(Op1, SubOne(C1));
ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
if (X == dyn_castFoldableMul(Op1, C2))
return BinaryOperator::createMul(X, Subtract(C1, C2));
}
return 0;
}
/// isSignBitCheck - Given an exploded icmp instruction, return true if the
/// comparison only checks the sign bit. If it only checks the sign bit, set
/// TrueIfSigned if the result of the comparison is true when the input value is
/// signed.
static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
bool &TrueIfSigned) {
switch (pred) {
case ICmpInst::ICMP_SLT: // True if LHS s< 0
TrueIfSigned = true;
return RHS->isZero();
case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
TrueIfSigned = true;
return RHS->isAllOnesValue();
case ICmpInst::ICMP_SGT: // True if LHS s> -1
TrueIfSigned = false;
return RHS->isAllOnesValue();
case ICmpInst::ICMP_UGT:
// True if LHS u> RHS and RHS == high-bit-mask - 1
TrueIfSigned = true;
return RHS->getValue() ==
APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
case ICmpInst::ICMP_UGE:
// True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
TrueIfSigned = true;
return RHS->getValue() ==
APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
default:
return false;
}
}
Instruction *InstCombiner::visitMul(BinaryOperator &I) {
bool Changed = SimplifyCommutative(I);
Value *Op0 = I.getOperand(0);
if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
// Simplify mul instructions with a constant RHS...
if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
// ((X << C1)*C2) == (X * (C2 << C1))
if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
if (SI->getOpcode() == Instruction::Shl)
if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
return BinaryOperator::createMul(SI->getOperand(0),
ConstantExpr::getShl(CI, ShOp));
if (CI->isZero())
return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
if (CI->equalsInt(1)) // X * 1 == X
return ReplaceInstUsesWith(I, Op0);
if (CI->isAllOnesValue()) // X * -1 == 0 - X
return BinaryOperator::createNeg(Op0, I.getName());
const APInt& Val = cast<ConstantInt>(CI)->getValue();
if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
return BinaryOperator::createShl(Op0,
ConstantInt::get(Op0->getType(), Val.logBase2()));
}
} else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
if (Op1F->isNullValue())
return ReplaceInstUsesWith(I, Op1);
// "In IEEE floating point, x*1 is not equivalent to x for nans. However,
// ANSI says we can drop signals, so we can do this anyway." (from GCC)
// We need a better interface for long double here.
if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
if (Op1F->isExactlyValue(1.0))
return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
}
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
isa<ConstantInt>(Op0I->getOperand(1))) {
// Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
Op1, "tmp");
InsertNewInstBefore(Add, I);
Value *C1C2 = ConstantExpr::getMul(Op1,
cast<Constant>(Op0I->getOperand(1)));
return BinaryOperator::createAdd(Add, C1C2);
}
// Try to fold constant mul into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
return BinaryOperator::createMul(Op0v, Op1v);
// If one of the operands of the multiply is a cast from a boolean value, then
// we know the bool is either zero or one, so this is a 'masking' multiply.
// See if we can simplify things based on how the boolean was originally
// formed.
CastInst *BoolCast = 0;
if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
if (CI->getOperand(0)->getType() == Type::Int1Ty)
BoolCast = CI;
if (!BoolCast)
if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
if (CI->getOperand(0)->getType() == Type::Int1Ty)
BoolCast = CI;
if (BoolCast) {
if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
const Type *SCOpTy = SCIOp0->getType();
bool TIS = false;
// If the icmp is true iff the sign bit of X is set, then convert this
// multiply into a shift/and combination.
if (isa<ConstantInt>(SCIOp1) &&
isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
TIS) {
// Shift the X value right to turn it into "all signbits".
Constant *Amt = ConstantInt::get(SCIOp0->getType(),
SCOpTy->getPrimitiveSizeInBits()-1);
Value *V =
InsertNewInstBefore(
BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
BoolCast->getOperand(0)->getName()+
".mask"), I);
// If the multiply type is not the same as the source type, sign extend
// or truncate to the multiply type.
if (I.getType() != V->getType()) {
uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
V = InsertCastBefore(opcode, V, I.getType(), I);
}
Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
return BinaryOperator::createAnd(V, OtherOp);
}
}
}
return Changed ? &I : 0;
}
/// This function implements the transforms on div instructions that work
/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
/// used by the visitors to those instructions.
/// @brief Transforms common to all three div instructions
Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
// undef / X -> 0 for integer.
// undef / X -> undef for FP (the undef could be a snan).
if (isa<UndefValue>(Op0)) {
if (Op0->getType()->isFPOrFPVector())
return ReplaceInstUsesWith(I, Op0);
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
}
// X / undef -> undef
if (isa<UndefValue>(Op1))
return ReplaceInstUsesWith(I, Op1);
// Handle cases involving: [su]div X, (select Cond, Y, Z)
// This does not apply for fdiv.
if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
// [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
// the same basic block, then we replace the select with Y, and the
// condition of the select with false (if the cond value is in the same BB).
// If the select has uses other than the div, this allows them to be
// simplified also. Note that div X, Y is just as good as div X, 0 (undef)
if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
if (ST->isNullValue()) {
Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
if (CondI && CondI->getParent() == I.getParent())
UpdateValueUsesWith(CondI, ConstantInt::getFalse());
else if (I.getParent() != SI->getParent() || SI->hasOneUse())
I.setOperand(1, SI->getOperand(2));
else
UpdateValueUsesWith(SI, SI->getOperand(2));
return &I;
}
// Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
if (ST->isNullValue()) {
Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
if (CondI && CondI->getParent() == I.getParent())
UpdateValueUsesWith(CondI, ConstantInt::getTrue());
else if (I.getParent() != SI->getParent() || SI->hasOneUse())
I.setOperand(1, SI->getOperand(1));
else
UpdateValueUsesWith(SI, SI->getOperand(1));
return &I;
}
}
return 0;
}
/// This function implements the transforms common to both integer division
/// instructions (udiv and sdiv). It is called by the visitors to those integer
/// division instructions.
/// @brief Common integer divide transforms
Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Instruction *Common = commonDivTransforms(I))
return Common;
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
// div X, 1 == X
if (RHS->equalsInt(1))
return ReplaceInstUsesWith(I, Op0);
// (X / C1) / C2 -> X / (C1*C2)
if (Instruction *LHS = dyn_cast<Instruction>(Op0))
if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
else
return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Multiply(RHS, LHSRHS));
}
if (!RHS->isZero()) { // avoid X udiv 0
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
}
// 0 / X == 0, we don't need to preserve faults!
if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
if (LHS->equalsInt(0))
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
return 0;
}
Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
// Handle the integer div common cases
if (Instruction *Common = commonIDivTransforms(I))
return Common;
// X udiv C^2 -> X >> C
// Check to see if this is an unsigned division with an exact power of 2,
// if so, convert to a right shift.
if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
return BinaryOperator::createLShr(Op0,
ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
}
// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
if (RHSI->getOpcode() == Instruction::Shl &&
isa<ConstantInt>(RHSI->getOperand(0))) {
const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
if (C1.isPowerOf2()) {
Value *N = RHSI->getOperand(1);
const Type *NTy = N->getType();
if (uint32_t C2 = C1.logBase2()) {
Constant *C2V = ConstantInt::get(NTy, C2);
N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
}
return BinaryOperator::createLShr(Op0, N);
}
}
}
// udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
// where C1&C2 are powers of two.
if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
// Compute the shift amounts
uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
// Construct the "on true" case of the select
Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Instruction *TSI = BinaryOperator::createLShr(
Op0, TC, SI->getName()+".t");
TSI = InsertNewInstBefore(TSI, I);
// Construct the "on false" case of the select
Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Instruction *FSI = BinaryOperator::createLShr(
Op0, FC, SI->getName()+".f");
FSI = InsertNewInstBefore(FSI, I);
// construct the select instruction and return it.
return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
}
}
return 0;
}
Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
// Handle the integer div common cases
if (Instruction *Common = commonIDivTransforms(I))
return Common;
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
// sdiv X, -1 == -X
if (RHS->isAllOnesValue())
return BinaryOperator::createNeg(Op0);
// -X/C -> X/-C
if (Value *LHSNeg = dyn_castNegVal(Op0))
return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
}
// If the sign bits of both operands are zero (i.e. we can prove they are
// unsigned inputs), turn this into a udiv.
if (I.getType()->isInteger()) {
APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
// X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
return BinaryOperator::createUDiv(Op0, Op1, I.getName());
}
}
return 0;
}
Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
return commonDivTransforms(I);
}
/// This function implements the transforms on rem instructions that work
/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
/// is used by the visitors to those instructions.
/// @brief Transforms common to all three rem instructions
Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
// 0 % X == 0 for integer, we don't need to preserve faults!
if (Constant *LHS = dyn_cast<Constant>(Op0))
if (LHS->isNullValue())
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
if (isa<UndefValue>(Op0)) { // undef % X -> 0
if (I.getType()->isFPOrFPVector())
return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
}
if (isa<UndefValue>(Op1))
return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
// Handle cases involving: rem X, (select Cond, Y, Z)
if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
// rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
// the same basic block, then we replace the select with Y, and the
// condition of the select with false (if the cond value is in the same
// BB). If the select has uses other than the div, this allows them to be
// simplified also.
if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
if (ST->isNullValue()) {
Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
if (CondI && CondI->getParent() == I.getParent())
UpdateValueUsesWith(CondI, ConstantInt::getFalse());
else if (I.getParent() != SI->getParent() || SI->hasOneUse())
I.setOperand(1, SI->getOperand(2));
else
UpdateValueUsesWith(SI, SI->getOperand(2));
return &I;
}
// Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
if (ST->isNullValue()) {
Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
if (CondI && CondI->getParent() == I.getParent())
UpdateValueUsesWith(CondI, ConstantInt::getTrue());
else if (I.getParent() != SI->getParent() || SI->hasOneUse())
I.setOperand(1, SI->getOperand(1));
else
UpdateValueUsesWith(SI, SI->getOperand(1));
return &I;
}
}
return 0;
}
/// This function implements the transforms common to both integer remainder
/// instructions (urem and srem). It is called by the visitors to those integer
/// remainder instructions.
/// @brief Common integer remainder transforms
Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Instruction *common = commonRemTransforms(I))
return common;
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
// X % 0 == undef, we don't need to preserve faults!
if (RHS->equalsInt(0))
return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
if (RHS->equalsInt(1)) // X % 1 == 0
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
} else if (isa<PHINode>(Op0I)) {
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
// See if we can fold away this rem instruction.
uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
KnownZero, KnownOne))
return &I;
}
}
return 0;
}
Instruction *InstCombiner::visitURem(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (Instruction *common = commonIRemTransforms(I))
return common;
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
// X urem C^2 -> X and C
// Check to see if this is an unsigned remainder with an exact power of 2,
// if so, convert to a bitwise and.
if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
if (C->getValue().isPowerOf2())
return BinaryOperator::createAnd(Op0, SubOne(C));
}
if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
// Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
if (RHSI->getOpcode() == Instruction::Shl &&
isa<ConstantInt>(RHSI->getOperand(0))) {
if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
"tmp"), I);
return BinaryOperator::createAnd(Op0, Add);
}
}
}
// urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
// where C1&C2 are powers of two.
if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
// STO == 0 and SFO == 0 handled above.
if ((STO->getValue().isPowerOf2()) &&
(SFO->getValue().isPowerOf2())) {
Value *TrueAnd = InsertNewInstBefore(
BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Value *FalseAnd = InsertNewInstBefore(
BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
}
}
}
return 0;
}
Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
// Handle the integer rem common cases
if (Instruction *common = commonIRemTransforms(I))
return common;
if (Value *RHSNeg = dyn_castNegVal(Op1))
if (!isa<ConstantInt>(RHSNeg) ||
cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
// X % -Y -> X % Y
AddUsesToWorkList(I);
I.setOperand(1, RHSNeg);
return &I;
}
// If the sign bits of both operands are zero (i.e. we can prove they are
// unsigned inputs), turn this into a urem.
if (I.getType()->isInteger()) {
APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
// X srem Y -> X urem Y, iff X and Y don't have sign bit set
return BinaryOperator::createURem(Op0, Op1, I.getName());
}
}
return 0;
}
Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
return commonRemTransforms(I);
}
// isMaxValueMinusOne - return true if this is Max-1
static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
if (!isSigned)
return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
}
// isMinValuePlusOne - return true if this is Min+1
static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
if (!isSigned)
return C->getValue() == 1; // unsigned
// Calculate 1111111111000000000000
uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
}
// isOneBitSet - Return true if there is exactly one bit set in the specified
// constant.
static bool isOneBitSet(const ConstantInt *CI) {
return CI->getValue().isPowerOf2();
}
// isHighOnes - Return true if the constant is of the form 1+0+.
// This is the same as lowones(~X).
static bool isHighOnes(const ConstantInt *CI) {
return (~CI->getValue() + 1).isPowerOf2();
}
/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
/// are carefully arranged to allow folding of expressions such as:
///
/// (A < B) | (A > B) --> (A != B)
///
/// Note that this is only valid if the first and second predicates have the
/// same sign. Is illegal to do: (A u< B) | (A s> B)
///
/// Three bits are used to represent the condition, as follows:
/// 0 A > B
/// 1 A == B
/// 2 A < B
///
/// <=> Value Definition
/// 000 0 Always false
/// 001 1 A > B
/// 010 2 A == B
/// 011 3 A >= B
/// 100 4 A < B
/// 101 5 A != B
/// 110 6 A <= B
/// 111 7 Always true
///
static unsigned getICmpCode(const ICmpInst *ICI) {
switch (ICI->getPredicate()) {
// False -> 0
case ICmpInst::ICMP_UGT: return 1; // 001
case ICmpInst::ICMP_SGT: return 1; // 001
case ICmpInst::ICMP_EQ: return 2; // 010
case ICmpInst::ICMP_UGE: return 3; // 011
case ICmpInst::ICMP_SGE: return 3; // 011
case ICmpInst::ICMP_ULT: return 4; // 100
case ICmpInst::ICMP_SLT: return 4; // 100
case ICmpInst::ICMP_NE: return 5; // 101
case ICmpInst::ICMP_ULE: return 6; // 110
case ICmpInst::ICMP_SLE: return 6; // 110
// True -> 7
default:
assert(0 && "Invalid ICmp predicate!");
return 0;
}
}
/// getICmpValue - This is the complement of getICmpCode, which turns an
/// opcode and two operands into either a constant true or false, or a brand
/// new ICmp instruction. The sign is passed in to determine which kind
/// of predicate to use in new icmp instructions.
static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
switch (code) {
default: assert(0 && "Illegal ICmp code!");
case 0: return ConstantInt::getFalse();
case 1:
if (sign)
return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
else
return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
case 3:
if (sign)
return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
else
return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
case 4:
if (sign)
return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
else
return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
case 6:
if (sign)
return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
else
return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
case 7: return ConstantInt::getTrue();
}
}
static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
(ICmpInst::isSignedPredicate(p1) &&
(p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
(ICmpInst::isSignedPredicate(p2) &&
(p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
}
namespace {
// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
struct FoldICmpLogical {
InstCombiner &IC;
Value *LHS, *RHS;
ICmpInst::Predicate pred;
FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
: IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
pred(ICI->getPredicate()) {}
bool shouldApply(Value *V) const {
if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
if (PredicatesFoldable(pred, ICI->getPredicate()))
return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
(ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
return false;
}
Instruction *apply(Instruction &Log) const {
ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
if (ICI->getOperand(0) != LHS) {
assert(ICI->getOperand(1) == LHS);
ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
}
ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
unsigned LHSCode = getICmpCode(ICI);
unsigned RHSCode = getICmpCode(RHSICI);
unsigned Code;
switch (Log.getOpcode()) {
case Instruction::And: Code = LHSCode & RHSCode; break;
case Instruction::Or: Code = LHSCode | RHSCode; break;
case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
default: assert(0 && "Illegal logical opcode!"); return 0;
}
bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
ICmpInst::isSignedPredicate(ICI->getPredicate());
Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
if (Instruction *I = dyn_cast<Instruction>(RV))
return I;
// Otherwise, it's a constant boolean value...
return IC.ReplaceInstUsesWith(Log, RV);
}
};
} // end anonymous namespace
// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
// guaranteed to be a binary operator.
Instruction *InstCombiner::OptAndOp(Instruction *Op,
ConstantInt *OpRHS,
ConstantInt *AndRHS,
BinaryOperator &TheAnd) {
Value *X = Op->getOperand(0);
Constant *Together = 0;
if (!Op->isShift())
Together = And(AndRHS, OpRHS);
switch (Op->getOpcode()) {
case Instruction::Xor:
if (Op->hasOneUse()) {
// (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Instruction *And = BinaryOperator::createAnd(X, AndRHS);
InsertNewInstBefore(And, TheAnd);
And->takeName(Op);
return BinaryOperator::createXor(And, Together);
}
break;
case Instruction::Or:
if (Together == AndRHS) // (X | C) & C --> C
return ReplaceInstUsesWith(TheAnd, AndRHS);
if (Op->hasOneUse() && Together != OpRHS) {
// (X | C1) & C2 --> (X | (C1&C2)) & C2
Instruction *Or = BinaryOperator::createOr(X, Together);
InsertNewInstBefore(Or, TheAnd);
Or->takeName(Op);
return BinaryOperator::createAnd(Or, AndRHS);
}
break;
case Instruction::Add:
if (Op->hasOneUse()) {
// Adding a one to a single bit bit-field should be turned into an XOR
// of the bit. First thing to check is to see if this AND is with a
// single bit constant.
const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
// If there is only one bit set...
if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
// Ok, at this point, we know that we are masking the result of the
// ADD down to exactly one bit. If the constant we are adding has
// no bits set below this bit, then we can eliminate the ADD.
const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
// Check to see if any bits below the one bit set in AndRHSV are set.
if ((AddRHS & (AndRHSV-1)) == 0) {
// If not, the only thing that can effect the output of the AND is
// the bit specified by AndRHSV. If that bit is set, the effect of
// the XOR is to toggle the bit. If it is clear, then the ADD has
// no effect.
if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
TheAnd.setOperand(0, X);
return &TheAnd;
} else {
// Pull the XOR out of the AND.
Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
InsertNewInstBefore(NewAnd, TheAnd);
NewAnd->takeName(Op);
return BinaryOperator::createXor(NewAnd, AndRHS);
}
}
}
}
break;
case Instruction::Shl: {
// We know that the AND will not produce any of the bits shifted in, so if
// the anded constant includes them, clear them now!
//
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
if (CI->getValue() == ShlMask) {
// Masking out bits that the shift already masks
return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
} else if (CI != AndRHS) { // Reducing bits set in and.
TheAnd.setOperand(1, CI);
return &TheAnd;
}
break;
}
case Instruction::LShr:
{
// We know that the AND will not produce any of the bits shifted in, so if
// the anded constant includes them, clear them now! This only applies to
// unsigned shifts, because a signed shr may bring in set bits!
//
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
if (CI->getValue() == ShrMask) {
// Masking out bits that the shift already masks.
return ReplaceInstUsesWith(TheAnd, Op);
} else if (CI != AndRHS) {
TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
return &TheAnd;
}
break;
}
case Instruction::AShr:
// Signed shr.
// See if this is shifting in some sign extension, then masking it out
// with an and.
if (Op->hasOneUse()) {
uint32_t BitWidth = AndRHS->getType()->getBitWidth();
uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
if (C == AndRHS) { // Masking out bits shifted in.
// (Val ashr C1) & C2 -> (Val lshr C1) & C2
// Make the argument unsigned.
Value *ShVal = Op->getOperand(0);
ShVal = InsertNewInstBefore(
BinaryOperator::createLShr(ShVal, OpRHS,
Op->getName()), TheAnd);
return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
}
}
break;
}
return 0;
}
/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
/// whether to treat the V, Lo and HI as signed or not. IB is the location to
/// insert new instructions.
Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
bool isSigned, bool Inside,
Instruction &IB) {
assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
"Lo is not <= Hi in range emission code!");
if (Inside) {
if (Lo == Hi) // Trivially false.
return new ICmpInst(ICmpInst::ICMP_NE, V, V);
// V >= Min && V < Hi --> V < Hi
if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
ICmpInst::Predicate pred = (isSigned ?
ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
return new ICmpInst(pred, V, Hi);
}
// Emit V-Lo <u Hi-Lo
Constant *NegLo = ConstantExpr::getNeg(Lo);
Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
InsertNewInstBefore(Add, IB);
Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
}
if (Lo == Hi) // Trivially true.
return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
// V < Min || V >= Hi -> V > Hi-1
Hi = SubOne(cast<ConstantInt>(Hi));
if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
ICmpInst::Predicate pred = (isSigned ?
ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
return new ICmpInst(pred, V, Hi);
}
// Emit V-Lo >u Hi-1-Lo
// Note that Hi has already had one subtracted from it, above.
ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
InsertNewInstBefore(Add, IB);
Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
}
// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
// any number of 0s on either side. The 1s are allowed to wrap from LSB to
// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
// not, since all 1s are not contiguous.
static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
const APInt& V = Val->getValue();
uint32_t BitWidth = Val->getType()->getBitWidth();
if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
// look for the first zero bit after the run of ones
MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
// look for the first non-zero bit
ME = V.getActiveBits();
return true;
}
/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
/// where isSub determines whether the operator is a sub. If we can fold one of
/// the following xforms:
///
/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
///
/// return (A +/- B).
///
Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
ConstantInt *Mask, bool isSub,
Instruction &I) {
Instruction *LHSI = dyn_cast<Instruction>(LHS);
if (!LHSI || LHSI->getNumOperands() != 2 ||
!isa<ConstantInt>(LHSI->getOperand(1))) return 0;
ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
switch (LHSI->getOpcode()) {
default: return 0;
case Instruction::And:
if (And(N, Mask) == Mask) {
// If the AndRHS is a power of two minus one (0+1+), this is simple.
if ((Mask->getValue().countLeadingZeros() +
Mask->getValue().countPopulation()) ==
Mask->getValue().getBitWidth())
break;
// Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
// part, we don't need any explicit masks to take them out of A. If that
// is all N is, ignore it.
uint32_t MB = 0, ME = 0;
if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
if (MaskedValueIsZero(RHS, Mask))
break;
}
}
return 0;
case Instruction::Or:
case Instruction::Xor:
// If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
if ((Mask->getValue().countLeadingZeros() +
Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
&& And(N, Mask)->isZero())
break;
return 0;
}
Instruction *New;
if (isSub)
New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
else
New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
return InsertNewInstBefore(New, I);
}
Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
bool Changed = SimplifyCommutative(I);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (isa<UndefValue>(Op1)) // X & undef -> 0
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
// and X, X = X
if (Op0 == Op1)
return ReplaceInstUsesWith(I, Op1);
// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
if (!isa<VectorType>(I.getType())) {
uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
KnownZero, KnownOne))
return &I;
} else {
if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
if (CP->isAllOnesValue()) // X & <-1,-1> -> X
return ReplaceInstUsesWith(I, I.getOperand(0));
} else if (isa<ConstantAggregateZero>(Op1)) {
return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
}
}
if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
const APInt& AndRHSMask = AndRHS->getValue();
APInt NotAndRHS(~AndRHSMask);
// Optimize a variety of ((val OP C1) & C2) combinations...
if (isa<BinaryOperator>(Op0)) {
Instruction *Op0I = cast<Instruction>(Op0);
Value *Op0LHS = Op0I->getOperand(0);
Value *Op0RHS = Op0I->getOperand(1);
switch (Op0I->getOpcode()) {
case Instruction::Xor:
case Instruction::Or:
// If the mask is only needed on one incoming arm, push it up.
if (Op0I->hasOneUse()) {
if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
// Not masking anything out for the LHS, move to RHS.
Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
Op0RHS->getName()+".masked");
InsertNewInstBefore(NewRHS, I);
return BinaryOperator::create(
cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
}
if (!isa<Constant>(Op0RHS) &&
MaskedValueIsZero(Op0RHS, NotAndRHS)) {
// Not masking anything out for the RHS, move to LHS.
Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
Op0LHS->getName()+".masked");
InsertNewInstBefore(NewLHS, I);
return BinaryOperator::create(
cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
}
}
break;
case Instruction::Add:
// ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
// ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
// ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
return BinaryOperator::createAnd(V, AndRHS);
if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
return BinaryOperator::createAnd(V, AndRHS); // Add commutes
break;
case Instruction::Sub:
// ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
// ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
// ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
return BinaryOperator::createAnd(V, AndRHS);
break;
}
if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
return Res;
} else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
// If this is an integer truncation or change from signed-to-unsigned, and
// if the source is an and/or with immediate, transform it. This
// frequently occurs for bitfield accesses.
if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
CastOp->getNumOperands() == 2)
if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
if (CastOp->getOpcode() == Instruction::And) {
// Change: and (cast (and X, C1) to T), C2
// into : and (cast X to T), trunc_or_bitcast(C1)&C2
// This will fold the two constants together, which may allow
// other simplifications.
Instruction *NewCast = CastInst::createTruncOrBitCast(
CastOp->getOperand(0), I.getType(),
CastOp->getName()+".shrunk");
NewCast = InsertNewInstBefore(NewCast, I);
// trunc_or_bitcast(C1)&C2
Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
C3 = ConstantExpr::getAnd(C3, AndRHS);
return BinaryOperator::createAnd(NewCast, C3);
} else if (CastOp->getOpcode() == Instruction::Or) {
// Change: and (cast (or X, C1) to T), C2
// into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
return ReplaceInstUsesWith(I, AndRHS);
}
}
}
}
// Try to fold constant and into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
Value *Op0NotVal = dyn_castNotVal(Op0);
Value *Op1NotVal = dyn_castNotVal(Op1);
if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
// (~A & ~B) == (~(A | B)) - De Morgan's Law
if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
I.getName()+".demorgan");
InsertNewInstBefore(Or, I);
return BinaryOperator::createNot(Or);
}
{
Value *A = 0, *B = 0, *C = 0, *D = 0;
if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
if (A == Op1 || B == Op1) // (A | ?) & A --> A
return ReplaceInstUsesWith(I, Op1);
// (A|B) & ~(A&B) -> A^B
if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
if ((A == C && B == D) || (A == D && B == C))
return BinaryOperator::createXor(A, B);
}
}
if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
if (A == Op0 || B == Op0) // A & (A | ?) --> A
return ReplaceInstUsesWith(I, Op0);
// ~(A&B) & (A|B) -> A^B
if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
if ((A == C && B == D) || (A == D && B == C))
return BinaryOperator::createXor(A, B);
}
}
if (Op0->hasOneUse() &&
match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
if (A == Op1) { // (A^B)&A -> A&(A^B)
I.swapOperands(); // Simplify below
std::swap(Op0, Op1);
} else if (B == Op1) { // (A^B)&B -> B&(B^A)
cast<BinaryOperator>(Op0)->swapOperands();
I.swapOperands(); // Simplify below
std::swap(Op0, Op1);
}
}
if (Op1->hasOneUse() &&
match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
if (B == Op0) { // B&(A^B) -> B&(B^A)
cast<BinaryOperator>(Op1)->swapOperands();
std::swap(A, B);
}
if (A == Op0) { // A&(A^B) -> A & ~B
Instruction *NotB = BinaryOperator::createNot(B, "tmp");
InsertNewInstBefore(NotB, I);
return BinaryOperator::createAnd(A, NotB);
}
}
}
if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
// (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
return R;
Value *LHSVal, *RHSVal;
ConstantInt *LHSCst, *RHSCst;
ICmpInst::Predicate LHSCC, RHSCC;
if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
// ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
// Don't try to fold ICMP_SLT + ICMP_ULT.
(ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
ICmpInst::isSignedPredicate(LHSCC) ==
ICmpInst::isSignedPredicate(RHSCC))) {
// Ensure that the larger constant is on the RHS.
ICmpInst::Predicate GT;
if (ICmpInst::isSignedPredicate(LHSCC) ||
(ICmpInst::isEquality(LHSCC) &&
ICmpInst::isSignedPredicate(RHSCC)))
GT = ICmpInst::ICMP_SGT;
else
GT = ICmpInst::ICMP_UGT;
Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
ICmpInst *LHS = cast<ICmpInst>(Op0);
if (cast<ConstantInt>(Cmp)->getZExtValue()) {
std::swap(LHS, RHS);
std::swap(LHSCst, RHSCst);
std::swap(LHSCC, RHSCC);
}
// At this point, we know we have have two icmp instructions
// comparing a value against two constants and and'ing the result
// together. Because of the above check, we know that we only have
// icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
// (from the FoldICmpLogical check above), that the two constants
// are not equal and that the larger constant is on the RHS
assert(LHSCst != RHSCst && "Compares not folded above?");
switch (LHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
return ReplaceInstUsesWith(I, LHS);
}
case ICmpInst::ICMP_NE:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_ULT:
if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
break; // (X != 13 & X u< 15) -> no change
case ICmpInst::ICMP_SLT:
if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
break; // (X != 13 & X s< 15) -> no change
case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
return ReplaceInstUsesWith(I, RHS);
case ICmpInst::ICMP_NE:
if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
LHSVal->getName()+".off");
InsertNewInstBefore(Add, I);
return new ICmpInst(ICmpInst::ICMP_UGT, Add,
ConstantInt::get(Add->getType(), 1));
}
break; // (X != 13 & X != 15) -> no change
}
break;
case ICmpInst::ICMP_ULT:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
return ReplaceInstUsesWith(I, LHS);
case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_SLT:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
return ReplaceInstUsesWith(I, LHS);
case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_UGT:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
return ReplaceInstUsesWith(I, LHS);
case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
return ReplaceInstUsesWith(I, RHS);
case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
break;
case ICmpInst::ICMP_NE:
if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
return new ICmpInst(LHSCC, LHSVal, RHSCst);
break; // (X u> 13 & X != 15) -> no change
case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
true, I);
case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_SGT:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
return ReplaceInstUsesWith(I, RHS);
case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
break;
case ICmpInst::ICMP_NE:
if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
return new ICmpInst(LHSCC, LHSVal, RHSCst);
break; // (X s> 13 & X != 15) -> no change
case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
true, I);
case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
break;
}
break;
}
}
}
// fold (and (cast A), (cast B)) -> (cast (and A, B))
if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
const Type *SrcTy = Op0C->getOperand(0)->getType();
if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
// Only do this if the casts both really cause code to be generated.
ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
I.getType(), TD) &&
ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
I.getType(), TD)) {
Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
Op1C->getOperand(0),
I.getName());
InsertNewInstBefore(NewOp, I);
return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
}
}
// (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
SI0->getOperand(1) == SI1->getOperand(1) &&
(SI0->hasOneUse() || SI1->hasOneUse())) {
Instruction *NewOp =
InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
SI1->getOperand(0),
SI0->getName()), I);
return BinaryOperator::create(SI1->getOpcode(), NewOp,
SI1->getOperand(1));
}
}
// (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
RHS->getPredicate() == FCmpInst::FCMP_ORD)
if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
// If either of the constants are nans, then the whole thing returns
// false.
if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
RHS->getOperand(0));
}
}
}
return Changed ? &I : 0;
}
/// CollectBSwapParts - Look to see if the specified value defines a single byte
/// in the result. If it does, and if the specified byte hasn't been filled in
/// yet, fill it in and return false.
static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Instruction *I = dyn_cast<Instruction>(V);
if (I == 0) return true;
// If this is an or instruction, it is an inner node of the bswap.
if (I->getOpcode() == Instruction::Or)
return CollectBSwapParts(I->getOperand(0), ByteValues) ||
CollectBSwapParts(I->getOperand(1), ByteValues);
uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
// If this is a shift by a constant int, and it is "24", then its operand
// defines a byte. We only handle unsigned types here.
if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
// Not shifting the entire input by N-1 bytes?
if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
8*(ByteValues.size()-1))
return true;
unsigned DestNo;
if (I->getOpcode() == Instruction::Shl) {
// X << 24 defines the top byte with the lowest of the input bytes.
DestNo = ByteValues.size()-1;
} else {
// X >>u 24 defines the low byte with the highest of the input bytes.
DestNo = 0;
}
// If the destination byte value is already defined, the values are or'd
// together, which isn't a bswap (unless it's an or of the same bits).
if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
return true;
ByteValues[DestNo] = I->getOperand(0);
return false;
}
// Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
// don't have this.
Value *Shift = 0, *ShiftLHS = 0;
ConstantInt *AndAmt = 0, *ShiftAmt = 0;
if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
!match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
return true;
Instruction *SI = cast<Instruction>(Shift);
// Make sure that the shift amount is by a multiple of 8 and isn't too big.
if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
return true;
// Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
unsigned DestByte;
if (AndAmt->getValue().getActiveBits() > 64)
return true;
uint64_t AndAmtVal = AndAmt->getZExtValue();
for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
break;
// Unknown mask for bswap.
if (DestByte == ByteValues.size()) return true;
unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
unsigned SrcByte;
if (SI->getOpcode() == Instruction::Shl)
SrcByte = DestByte - ShiftBytes;
else
SrcByte = DestByte + ShiftBytes;
// If the SrcByte isn't a bswapped value from the DestByte, reject it.
if (SrcByte != ByteValues.size()-DestByte-1)
return true;
// If the destination byte value is already defined, the values are or'd
// together, which isn't a bswap (unless it's an or of the same bits).
if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
return true;
ByteValues[DestByte] = SI->getOperand(0);
return false;
}
/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
/// If so, insert the new bswap intrinsic and return it.
Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
if (!ITy || ITy->getBitWidth() % 16)
return 0; // Can only bswap pairs of bytes. Can't do vectors.
/// ByteValues - For each byte of the result, we keep track of which value
/// defines each byte.
SmallVector<Value*, 8> ByteValues;
ByteValues.resize(ITy->getBitWidth()/8);
// Try to find all the pieces corresponding to the bswap.
if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
CollectBSwapParts(I.getOperand(1), ByteValues))
return 0;
// Check to see if all of the bytes come from the same value.
Value *V = ByteValues[0];
if (V == 0) return 0; // Didn't find a byte? Must be zero.
// Check to make sure that all of the bytes come from the same value.
for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
if (ByteValues[i] != V)
return 0;
const Type *Tys[] = { ITy };
Module *M = I.getParent()->getParent()->getParent();
Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
return CallInst::Create(F, V);
}
Instruction *InstCombiner::visitOr(BinaryOperator &I) {
bool Changed = SimplifyCommutative(I);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (isa<UndefValue>(Op1)) // X | undef -> -1
return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
// or X, X = X
if (Op0 == Op1)
return ReplaceInstUsesWith(I, Op0);
// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
if (!isa<VectorType>(I.getType())) {
uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
KnownZero, KnownOne))
return &I;
} else if (isa<ConstantAggregateZero>(Op1)) {
return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
} else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
return ReplaceInstUsesWith(I, I.getOperand(1));
}
// or X, -1 == -1
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
ConstantInt *C1 = 0; Value *X = 0;
// (X & C1) | C2 --> (X | C2) & (C1|C2)
if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Instruction *Or = BinaryOperator::createOr(X, RHS);
InsertNewInstBefore(Or, I);
Or->takeName(Op0);
return BinaryOperator::createAnd(Or,
ConstantInt::get(RHS->getValue() | C1->getValue()));
}
// (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Instruction *Or = BinaryOperator::createOr(X, RHS);
InsertNewInstBefore(Or, I);
Or->takeName(Op0);
return BinaryOperator::createXor(Or,
ConstantInt::get(C1->getValue() & ~RHS->getValue()));
}
// Try to fold constant and into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
Value *A = 0, *B = 0;
ConstantInt *C1 = 0, *C2 = 0;
if (match(Op0, m_And(m_Value(A), m_Value(B))))
if (A == Op1 || B == Op1) // (A & ?) | A --> A
return ReplaceInstUsesWith(I, Op1);
if (match(Op1, m_And(m_Value(A), m_Value(B))))
if (A == Op0 || B == Op0) // A | (A & ?) --> A
return ReplaceInstUsesWith(I, Op0);
// (A | B) | C and A | (B | C) -> bswap if possible.
// (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
if (match(Op0, m_Or(m_Value(), m_Value())) ||
match(Op1, m_Or(m_Value(), m_Value())) ||
(match(Op0, m_Shift(m_Value(), m_Value())) &&
match(Op1, m_Shift(m_Value(), m_Value())))) {
if (Instruction *BSwap = MatchBSwap(I))
return BSwap;
}
// (X^C)|Y -> (X|Y)^C iff Y&C == 0
if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
MaskedValueIsZero(Op1, C1->getValue())) {
Instruction *NOr = BinaryOperator::createOr(A, Op1);
InsertNewInstBefore(NOr, I);
NOr->takeName(Op0);
return BinaryOperator::createXor(NOr, C1);
}
// Y|(X^C) -> (X|Y)^C iff Y&C == 0
if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
MaskedValueIsZero(Op0, C1->getValue())) {
Instruction *NOr = BinaryOperator::createOr(A, Op0);
InsertNewInstBefore(NOr, I);
NOr->takeName(Op0);
return BinaryOperator::createXor(NOr, C1);
}
// (A & C)|(B & D)
Value *C = 0, *D = 0;
if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
match(Op1, m_And(m_Value(B), m_Value(D)))) {
Value *V1 = 0, *V2 = 0, *V3 = 0;
C1 = dyn_cast<ConstantInt>(C);
C2 = dyn_cast<ConstantInt>(D);
if (C1 && C2) { // (A & C1)|(B & C2)
// If we have: ((V + N) & C1) | (V & C2)
// .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
// replace with V+N.
if (C1->getValue() == ~C2->getValue()) {
if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
match(A, m_Add(m_Value(V1), m_Value(V2)))) {
// Add commutes, try both ways.
if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
return ReplaceInstUsesWith(I, A);
if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
return ReplaceInstUsesWith(I, A);
}
// Or commutes, try both ways.
if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
match(B, m_Add(m_Value(V1), m_Value(V2)))) {
// Add commutes, try both ways.
if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
return ReplaceInstUsesWith(I, B);
if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
return ReplaceInstUsesWith(I, B);
}
}
V1 = 0; V2 = 0; V3 = 0;
}
// Check to see if we have any common things being and'ed. If so, find the
// terms for V1 & (V2|V3).
if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
if (A == B) // (A & C)|(A & D) == A & (C|D)
V1 = A, V2 = C, V3 = D;
else if (A == D) // (A & C)|(B & A) == A & (B|C)
V1 = A, V2 = B, V3 = C;
else if (C == B) // (A & C)|(C & D) == C & (A|D)
V1 = C, V2 = A, V3 = D;
else if (C == D) // (A & C)|(B & C) == C & (A|B)
V1 = C, V2 = A, V3 = B;
if (V1) {
Value *Or =
InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
return BinaryOperator::createAnd(V1, Or);
}
}
}
// (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
SI0->getOperand(1) == SI1->getOperand(1) &&
(SI0->hasOneUse() || SI1->hasOneUse())) {
Instruction *NewOp =
InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
SI1->getOperand(0),
SI0->getName()), I);
return BinaryOperator::create(SI1->getOpcode(), NewOp,
SI1->getOperand(1));
}
}
if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
if (A == Op1) // ~A | A == -1
return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
} else {
A = 0;
}
// Note, A is still live here!
if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
if (Op0 == B)
return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
// (~A | ~B) == (~(A & B)) - De Morgan's Law
if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
I.getName()+".demorgan"), I);
return BinaryOperator::createNot(And);
}
}
// (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
return R;
Value *LHSVal, *RHSVal;
ConstantInt *LHSCst, *RHSCst;
ICmpInst::Predicate LHSCC, RHSCC;
if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
// icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
// We can't fold (ugt x, C) | (sgt x, C2).
PredicatesFoldable(LHSCC, RHSCC)) {
// Ensure that the larger constant is on the RHS.
ICmpInst *LHS = cast<ICmpInst>(Op0);
bool NeedsSwap;
if (ICmpInst::isSignedPredicate(LHSCC))
NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
else
NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
if (NeedsSwap) {
std::swap(LHS, RHS);
std::swap(LHSCst, RHSCst);
std::swap(LHSCC, RHSCC);
}
// At this point, we know we have have two icmp instructions
// comparing a value against two constants and or'ing the result
// together. Because of the above check, we know that we only have
// ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
// FoldICmpLogical check above), that the two constants are not
// equal.
assert(LHSCst != RHSCst && "Compares not folded above?");
switch (LHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ:
if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
LHSVal->getName()+".off");
InsertNewInstBefore(Add, I);
AddCST = Subtract(AddOne(RHSCst), LHSCst);
return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
}
break; // (X == 13 | X == 15) -> no change
case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
break;
case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
return ReplaceInstUsesWith(I, RHS);
}
break;
case ICmpInst::ICMP_NE:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
return ReplaceInstUsesWith(I, LHS);
case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
}
break;
case ICmpInst::ICMP_ULT:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
break;
case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
// If RHSCst is [us]MAXINT, it is always false. Not handling
// this can cause overflow.
if (RHSCst->isMaxValue(false))
return ReplaceInstUsesWith(I, LHS);
return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
false, I);
case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
return ReplaceInstUsesWith(I, RHS);
case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_SLT:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
break;
case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
// If RHSCst is [us]MAXINT, it is always false. Not handling
// this can cause overflow.
if (RHSCst->isMaxValue(true))
return ReplaceInstUsesWith(I, LHS);
return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
false, I);
case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
return ReplaceInstUsesWith(I, RHS);
case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_UGT:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
return ReplaceInstUsesWith(I, LHS);
case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
break;
}
break;
case ICmpInst::ICMP_SGT:
switch (RHSCC) {
default: assert(0 && "Unknown integer condition code!");
case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
return ReplaceInstUsesWith(I, LHS);
case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
break;
case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
break;
}
break;
}
}
}
// fold (or (cast A), (cast B)) -> (cast (or A, B))
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
!isa<ICmpInst>(Op1C->getOperand(0))) {
const Type *SrcTy = Op0C->getOperand(0)->getType();
if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
// Only do this if the casts both really cause code to be
// generated.
ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
I.getType(), TD) &&
ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
I.getType(), TD)) {
Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
Op1C->getOperand(0),
I.getName());
InsertNewInstBefore(NewOp, I);
return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
}
}
}
}
// (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
RHS->getPredicate() == FCmpInst::FCMP_UNO &&
LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
// If either of the constants are nans, then the whole thing returns
// true.
if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
// Otherwise, no need to compare the two constants, compare the
// rest.
return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
RHS->getOperand(0));
}
}
}
return Changed ? &I : 0;
}
// XorSelf - Implements: X ^ X --> 0
struct XorSelf {
Value *RHS;
XorSelf(Value *rhs) : RHS(rhs) {}
bool shouldApply(Value *LHS) const { return LHS == RHS; }
Instruction *apply(BinaryOperator &Xor) const {
return &Xor;
}
};
Instruction *InstCombiner::visitXor(BinaryOperator &I) {
bool Changed = SimplifyCommutative(I);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
if (isa<UndefValue>(Op1)) {
if (isa<UndefValue>(Op0))
// Handle undef ^ undef -> 0 special case. This is a common
// idiom (misuse).
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
}
// xor X, X = 0, even if X is nested in a sequence of Xor's.
if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
}
// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
if (!isa<VectorType>(I.getType())) {
uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
KnownZero, KnownOne))
return &I;
} else if (isa<ConstantAggregateZero>(Op1)) {
return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
}
// Is this a ~ operation?
if (Value *NotOp = dyn_castNotVal(&I)) {
// ~(~X & Y) --> (X | ~Y) - De Morgan's Law
// ~(~X | Y) === (X & ~Y) - De Morgan's Law
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
if (Op0I->getOpcode() == Instruction::And ||
Op0I->getOpcode() == Instruction::Or) {
if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Instruction *NotY =
BinaryOperator::createNot(Op0I->getOperand(1),
Op0I->getOperand(1)->getName()+".not");
InsertNewInstBefore(NotY, I);
if (Op0I->getOpcode() == Instruction::And)
return BinaryOperator::createOr(Op0NotVal, NotY);
else
return BinaryOperator::createAnd(Op0NotVal, NotY);
}
}
}
}
if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
// xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
return new ICmpInst(ICI->getInversePredicate(),
ICI->getOperand(0), ICI->getOperand(1));
if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
return new FCmpInst(FCI->getInversePredicate(),
FCI->getOperand(0), FCI->getOperand(1));
}
if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
// ~(c-X) == X-c-1 == X+(-c-1)
if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
ConstantInt::get(I.getType(), 1));
return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
}
if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
if (Op0I->getOpcode() == Instruction::Add) {
// ~(X-c) --> (-c-1)-X
if (RHS->isAllOnesValue()) {
Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
return BinaryOperator::createSub(
ConstantExpr::getSub(NegOp0CI,
ConstantInt::get(I.getType(), 1)),
Op0I->getOperand(0));
} else if (RHS->getValue().isSignBit()) {
// (X + C) ^ signbit -> (X + C + signbit)
Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
return BinaryOperator::createAdd(Op0I->getOperand(0), C);
}
} else if (Op0I->getOpcode() == Instruction::Or) {
// (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
// Anything in both C1 and C2 is known to be zero, remove it from
// NewRHS.
Constant *CommonBits = And(Op0CI, RHS);
NewRHS = ConstantExpr::getAnd(NewRHS,
ConstantExpr::getNot(CommonBits));
AddToWorkList(Op0I);
I.setOperand(0, Op0I->getOperand(0));
I.setOperand(1, NewRHS);
return &I;
}
}
}
}
// Try to fold constant and into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
}
if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
if (X == Op1)
return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
if (X == Op0)
return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
if (Op1I) {
Value *A, *B;
if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
if (A == Op0) { // B^(B|A) == (A|B)^B
Op1I->swapOperands();
I.swapOperands();
std::swap(Op0, Op1);
} else if (B == Op0) { // B^(A|B) == (A|B)^B
I.swapOperands(); // Simplified below.
std::swap(Op0, Op1);
}
} else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
if (Op0 == A) // A^(A^B) == B
return ReplaceInstUsesWith(I, B);
else if (Op0 == B) // A^(B^A) == B
return ReplaceInstUsesWith(I, A);
} else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
if (A == Op0) { // A^(A&B) -> A^(B&A)
Op1I->swapOperands();
std::swap(A, B);
}
if (B == Op0) { // A^(B&A) -> (B&A)^A
I.swapOperands(); // Simplified below.
std::swap(Op0, Op1);
}
}
}
BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
if (Op0I) {
Value *A, *B;
if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
if (A == Op1) // (B|A)^B == (A|B)^B
std::swap(A, B);
if (B == Op1) { // (A|B)^B == A & ~B
Instruction *NotB =
InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
return BinaryOperator::createAnd(A, NotB);
}
} else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
if (Op1 == A) // (A^B)^A == B
return ReplaceInstUsesWith(I, B);
else if (Op1 == B) // (B^A)^A == B
return ReplaceInstUsesWith(I, A);
} else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
if (A == Op1) // (A&B)^A -> (B&A)^A
std::swap(A, B);
if (B == Op1 && // (B&A)^A == ~B & A
!isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Instruction *N =
InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
return BinaryOperator::createAnd(N, Op1);
}
}
}
// (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
if (Op0I && Op1I && Op0I->isShift() &&
Op0I->getOpcode() == Op1I->getOpcode() &&
Op0I->getOperand(1) == Op1I->getOperand(1) &&
(Op1I->hasOneUse() || Op1I->hasOneUse())) {
Instruction *NewOp =
InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
Op1I->getOperand(0),
Op0I->getName()), I);
return BinaryOperator::create(Op1I->getOpcode(), NewOp,
Op1I->getOperand(1));
}
if (Op0I && Op1I) {
Value *A, *B, *C, *D;
// (A & B)^(A | B) -> A ^ B
if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
if ((A == C && B == D) || (A == D && B == C))
return BinaryOperator::createXor(A, B);
}
// (A | B)^(A & B) -> A ^ B
if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
match(Op1I, m_And(m_Value(C), m_Value(D)))) {
if ((A == C && B == D) || (A == D && B == C))
return BinaryOperator::createXor(A, B);
}
// (A & B)^(C & D)
if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
match(Op0I, m_And(m_Value(A), m_Value(B))) &&
match(Op1I, m_And(m_Value(C), m_Value(D)))) {
// (X & Y)^(X & Y) -> (Y^Z) & X
Value *X = 0, *Y = 0, *Z = 0;
if (A == C)
X = A, Y = B, Z = D;
else if (A == D)
X = A, Y = B, Z = C;
else if (B == C)
X = B, Y = A, Z = D;
else if (B == D)
X = B, Y = A, Z = C;
if (X) {
Instruction *NewOp =
InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
return BinaryOperator::createAnd(NewOp, X);
}
}
}
// (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
return R;
// fold (xor (cast A), (cast B)) -> (cast (xor A, B))
if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
const Type *SrcTy = Op0C->getOperand(0)->getType();
if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
// Only do this if the casts both really cause code to be generated.
ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
I.getType(), TD) &&
ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
I.getType(), TD)) {
Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
Op1C->getOperand(0),
I.getName());
InsertNewInstBefore(NewOp, I);
return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
}
}
}
return Changed ? &I : 0;
}
/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
/// overflowed for this type.
static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
ConstantInt *In2, bool IsSigned = false) {
Result = cast<ConstantInt>(Add(In1, In2));
if (IsSigned)
if (In2->getValue().isNegative())
return Result->getValue().sgt(In1->getValue());
else
return Result->getValue().slt(In1->getValue());
else
return Result->getValue().ult(In1->getValue());
}
/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
/// code necessary to compute the offset from the base pointer (without adding
/// in the base pointer). Return the result as a signed integer of intptr size.
static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
TargetData &TD = IC.getTargetData();
gep_type_iterator GTI = gep_type_begin(GEP);
const Type *IntPtrTy = TD.getIntPtrType();
Value *Result = Constant::getNullValue(IntPtrTy);
// Build a mask for high order bits.
unsigned IntPtrWidth = TD.getPointerSizeInBits();
uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Value *Op = GEP->getOperand(i);
uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
if (OpC->isZero()) continue;
// Handle a struct index, which adds its field offset to the pointer.
if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
else
Result = IC.InsertNewInstBefore(
BinaryOperator::createAdd(Result,
ConstantInt::get(IntPtrTy, Size),
GEP->getName()+".offs"), I);
continue;
}
Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Scale = ConstantExpr::getMul(OC, Scale);
if (Constant *RC = dyn_cast<Constant>(Result))
Result = ConstantExpr::getAdd(RC, Scale);
else {
// Emit an add instruction.
Result = IC.InsertNewInstBefore(
BinaryOperator::createAdd(Result, Scale,
GEP->getName()+".offs"), I);
}
continue;
}
// Convert to correct type.
if (Op->getType() != IntPtrTy) {
if (Constant *OpC = dyn_cast<Constant>(Op))
Op = ConstantExpr::getSExt(OpC, IntPtrTy);
else
Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
Op->getName()+".c"), I);
}
if (Size != 1) {
Constant *Scale = ConstantInt::get(IntPtrTy, Size);
if (Constant *OpC = dyn_cast<Constant>(Op))
Op = ConstantExpr::getMul(OpC, Scale);
else // We'll let instcombine(mul) convert this to a shl if possible.
Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
GEP->getName()+".idx"), I);
}
// Emit an add instruction.
if (isa<Constant>(Op) && isa<Constant>(Result))
Result = ConstantExpr::getAdd(cast<Constant>(Op),
cast<Constant>(Result));
else
Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
GEP->getName()+".offs"), I);
}
return Result;
}
/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
/// complex, and scales are involved. The above expression would also be legal
/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
/// later form is less amenable to optimization though, and we are allowed to
/// generate the first by knowing that pointer arithmetic doesn't overflow.
///
/// If we can't emit an optimized form for this expression, this returns null.
///
static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
InstCombiner &IC) {
TargetData &TD = IC.getTargetData();
gep_type_iterator GTI = gep_type_begin(GEP);
// Check to see if this gep only has a single variable index. If so, and if
// any constant indices are a multiple of its scale, then we can compute this
// in terms of the scale of the variable index. For example, if the GEP
// implies an offset of "12 + i*4", then we can codegen this as "3 + i",
// because the expression will cross zero at the same point.
unsigned i, e = GEP->getNumOperands();
int64_t Offset = 0;
for (i = 1; i != e; ++i, ++GTI) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
// Compute the aggregate offset of constant indices.
if (CI->isZero()) continue;
// Handle a struct index, which adds its field offset to the pointer.
if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
} else {
uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
Offset += Size*CI->getSExtValue();
}
} else {
// Found our variable index.
break;
}
}
// If there are no variable indices, we must have a constant offset, just
// evaluate it the general way.
if (i == e) return 0;
Value *VariableIdx = GEP->getOperand(i);
// Determine the scale factor of the variable element. For example, this is
// 4 if the variable index is into an array of i32.
uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
// Verify that there are no other variable indices. If so, emit the hard way.
for (++i, ++GTI; i != e; ++i, ++GTI) {
ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
if (!CI) return 0;
// Compute the aggregate offset of constant indices.
if (CI->isZero()) continue;
// Handle a struct index, which adds its field offset to the pointer.
if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
} else {
uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
Offset += Size*CI->getSExtValue();
}
}
// Okay, we know we have a single variable index, which must be a
// pointer/array/vector index. If there is no offset, life is simple, return
// the index.
unsigned IntPtrWidth = TD.getPointerSizeInBits();
if (Offset == 0) {
// Cast to intptrty in case a truncation occurs. If an extension is needed,
// we don't need to bother extending: the extension won't affect where the
// computation crosses zero.
if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
VariableIdx->getNameStart(), &I);
return VariableIdx;
}
// Otherwise, there is an index. The computation we will do will be modulo
// the pointer size, so get it.
uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Offset &= PtrSizeMask;
VariableScale &= PtrSizeMask;
// To do this transformation, any constant index must be a multiple of the
// variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
// but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
// multiple of the variable scale.
int64_t NewOffs = Offset / (int64_t)VariableScale;
if (Offset != NewOffs*(int64_t)VariableScale)
return 0;
// Okay, we can do this evaluation. Start by converting the index to intptr.
const Type *IntPtrTy = TD.getIntPtrType();
if (VariableIdx->getType() != IntPtrTy)
VariableIdx = CastInst::createIntegerCast(VariableIdx, IntPtrTy,
true /*SExt*/,
VariableIdx->getNameStart(), &I);
Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
return BinaryOperator::createAdd(VariableIdx, OffsetVal, "offset", &I);
}
/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
/// else. At this point we know that the GEP is on the LHS of the comparison.
Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
ICmpInst::Predicate Cond,
Instruction &I) {
assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
// Look through bitcasts.
if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
RHS = BCI->getOperand(0);
Value *PtrBase = GEPLHS->getOperand(0);
if (PtrBase == RHS) {
// ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
// This transformation (ignoring the base and scales) is valid because we
// know pointers can't overflow. See if we can output an optimized form.
Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
// If not, synthesize the offset the hard way.
if (Offset == 0)
Offset = EmitGEPOffset(GEPLHS, I, *this);
return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Constant::getNullValue(Offset->getType()));
} else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
// If the base pointers are different, but the indices are the same, just
// compare the base pointer.
if (PtrBase != GEPRHS->getOperand(0)) {
bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
GEPRHS->getOperand(0)->getType();
if (IndicesTheSame)
for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
IndicesTheSame = false;
break;
}
// If all indices are the same, just compare the base pointers.
if (IndicesTheSame)
return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
GEPLHS->getOperand(0), GEPRHS->getOperand(0));
// Otherwise, the base pointers are different and the indices are
// different, bail out.
return 0;
}
// If one of the GEPs has all zero indices, recurse.
bool AllZeros = true;
for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
if (!isa<Constant>(GEPLHS->getOperand(i)) ||
!cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
AllZeros = false;
break;
}
if (AllZeros)
return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
ICmpInst::getSwappedPredicate(Cond), I);
// If the other GEP has all zero indices, recurse.
AllZeros = true;
for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
if (!isa<Constant>(GEPRHS->getOperand(i)) ||
!cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
AllZeros = false;
break;
}
if (AllZeros)
return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
// If the GEPs only differ by one index, compare it.
unsigned NumDifferences = 0; // Keep track of # differences.
unsigned DiffOperand = 0; // The operand that differs.
for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
// Irreconcilable differences.
NumDifferences = 2;
break;
} else {
if (NumDifferences++) break;
DiffOperand = i;
}
}
if (NumDifferences == 0) // SAME GEP?
return ReplaceInstUsesWith(I, // No comparison is needed here.
ConstantInt::get(Type::Int1Ty,
isTrueWhenEqual(Cond)));
else if (NumDifferences == 1) {
Value *LHSV = GEPLHS->getOperand(DiffOperand);
Value *RHSV = GEPRHS->getOperand(DiffOperand);
// Make sure we do a signed comparison here.
return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
}
}
// Only lower this if the icmp is the only user of the GEP or if we expect
// the result to fold to a constant!
if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
(isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
// ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Value *L = EmitGEPOffset(GEPLHS, I, *this);
Value *R = EmitGEPOffset(GEPRHS, I, *this);
return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
}
}
return 0;
}
Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
bool Changed = SimplifyCompare(I);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
// Fold trivial predicates.
if (I.getPredicate() == FCmpInst::FCMP_FALSE)
return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
if (I.getPredicate() == FCmpInst::FCMP_TRUE)
return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
// Simplify 'fcmp pred X, X'
if (Op0 == Op1) {
switch (I.getPredicate()) {
default: assert(0 && "Unknown predicate!");
case FCmpInst::FCMP_UEQ: // True if unordered or equal
case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
case FCmpInst::FCMP_OGT: // True if ordered and greater than
case FCmpInst::FCMP_OLT: // True if ordered and less than
case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
case FCmpInst::FCMP_ULT: // True if unordered or less than
case FCmpInst::FCMP_UGT: // True if unordered or greater than
case FCmpInst::FCMP_UNE: // True if unordered or not equal
// Canonicalize these to be 'fcmp uno %X, 0.0'.
I.setPredicate(FCmpInst::FCMP_UNO);
I.setOperand(1, Constant::getNullValue(Op0->getType()));
return &I;
case FCmpInst::FCMP_ORD: // True if ordered (no nans)
case FCmpInst::FCMP_OEQ: // True if ordered and equal
case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
// Canonicalize these to be 'fcmp ord %X, 0.0'.
I.setPredicate(FCmpInst::FCMP_ORD);
I.setOperand(1, Constant::getNullValue(Op0->getType()));
return &I;
}
}
if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
// Handle fcmp with constant RHS
if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
switch (LHSI->getOpcode()) {
case Instruction::PHI:
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
break;
case Instruction::Select:
// If either operand of the select is a constant, we can fold the
// comparison into the select arms, which will cause one to be
// constant folded and the select turned into a bitwise or.
Value *Op1 = 0, *Op2 = 0;
if (LHSI->hasOneUse()) {
if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
// Fold the known value into the constant operand.
Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
// Insert a new FCmp of the other select operand.
Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
LHSI->getOperand(2), RHSC,
I.getName()), I);
} else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
// Fold the known value into the constant operand.
Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
// Insert a new FCmp of the other select operand.
Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
LHSI->getOperand(1), RHSC,
I.getName()), I);
}
}
if (Op1)
return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
break;
}
}
return Changed ? &I : 0;
}
Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
bool Changed = SimplifyCompare(I);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
const Type *Ty = Op0->getType();
// icmp X, X
if (Op0 == Op1)
return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
isTrueWhenEqual(I)));
if (isa<UndefValue>(Op1)) // X icmp undef -> undef
return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
// icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
// addresses never equal each other! We already know that Op0 != Op1.
if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
isa<ConstantPointerNull>(Op0)) &&
(isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
isa<ConstantPointerNull>(Op1)))
return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
!isTrueWhenEqual(I)));
// icmp's with boolean values can always be turned into bitwise operations
if (Ty == Type::Int1Ty) {
switch (I.getPredicate()) {
default: assert(0 && "Invalid icmp instruction!");
case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
InsertNewInstBefore(Xor, I);
return BinaryOperator::createNot(Xor);
}
case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
return BinaryOperator::createXor(Op0, Op1);
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_SGT:
std::swap(Op0, Op1); // Change icmp gt -> icmp lt
// FALL THROUGH
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
InsertNewInstBefore(Not, I);
return BinaryOperator::createAnd(Not, Op1);
}
case ICmpInst::ICMP_UGE:
case ICmpInst::ICMP_SGE:
std::swap(Op0, Op1); // Change icmp ge -> icmp le
// FALL THROUGH
case ICmpInst::ICMP_ULE:
case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
InsertNewInstBefore(Not, I);
return BinaryOperator::createOr(Not, Op1);
}
}
}
// See if we are doing a comparison between a constant and an instruction that
// can be folded into the comparison.
if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Value *A, *B;
// (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
if (I.isEquality() && CI->isNullValue() &&
match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
// (icmp cond A B) if cond is equality
return new ICmpInst(I.getPredicate(), A, B);
}
switch (I.getPredicate()) {
default: break;
case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
if (CI->isMinValue(false))
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
// (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
if (CI->isMinValue(true))
return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
ConstantInt::getAllOnesValue(Op0->getType()));
break;
case ICmpInst::ICMP_SLT:
if (CI->isMinValue(true)) // A <s MIN -> FALSE
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
break;
case ICmpInst::ICMP_UGT:
if (CI->isMaxValue(false)) // A >u MAX -> FALSE
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
if (CI->isMinValue(false)) // A >u MIN -> A != MIN
return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
// (x >u 2147483647) -> (x <s 0) -> true if sign bit set
if (CI->isMaxValue(true))
return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
ConstantInt::getNullValue(Op0->getType()));
break;
case ICmpInst::ICMP_SGT:
if (CI->isMaxValue(true)) // A >s MAX -> FALSE
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
if (CI->isMinValue(true)) // A >s MIN -> A != MIN
return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
break;
case ICmpInst::ICMP_ULE:
if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
break;
case ICmpInst::ICMP_SLE:
if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
break;
case ICmpInst::ICMP_UGE:
if (CI->isMinValue(false)) // A >=u MIN -> TRUE
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
break;
case ICmpInst::ICMP_SGE:
if (CI->isMinValue(true)) // A >=s MIN -> TRUE
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
break;
}
// If we still have a icmp le or icmp ge instruction, turn it into the
// appropriate icmp lt or icmp gt instruction. Since the border cases have
// already been handled above, this requires little checking.
//
switch (I.getPredicate()) {
default: break;
case ICmpInst::ICMP_ULE:
return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
case ICmpInst::ICMP_SLE:
return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
case ICmpInst::ICMP_UGE:
return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
case ICmpInst::ICMP_SGE:
return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
}
// See if we can fold the comparison based on bits known to be zero or one
// in the input. If this comparison is a normal comparison, it demands all
// bits, if it is a sign bit comparison, it only demands the sign bit.
bool UnusedBit;
bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
if (SimplifyDemandedBits(Op0,
isSignBit ? APInt::getSignBit(BitWidth)
: APInt::getAllOnesValue(BitWidth),
KnownZero, KnownOne, 0))
return &I;
// Given the known and unknown bits, compute a range that the LHS could be
// in.
if ((KnownOne | KnownZero) != 0) {
// Compute the Min, Max and RHS values based on the known bits. For the
// EQ and NE we use unsigned values.
APInt Min(BitWidth, 0), Max(BitWidth, 0);
const APInt& RHSVal = CI->getValue();
if (ICmpInst::isSignedPredicate(I.getPredicate())) {
ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
Max);
} else {
ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
Max);
}
switch (I.getPredicate()) { // LE/GE have been folded already.
default: assert(0 && "Unknown icmp opcode!");
case ICmpInst::ICMP_EQ:
if (Max.ult(RHSVal) || Min.ugt(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
break;
case ICmpInst::ICMP_NE:
if (Max.ult(RHSVal) || Min.ugt(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
break;
case ICmpInst::ICMP_ULT:
if (Max.ult(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
if (Min.uge(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
break;
case ICmpInst::ICMP_UGT:
if (Min.ugt(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
if (Max.ule(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
break;
case ICmpInst::ICMP_SLT:
if (Max.slt(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
if (Min.sgt(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
break;
case ICmpInst::ICMP_SGT:
if (Min.sgt(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getTrue());
if (Max.sle(RHSVal))
return ReplaceInstUsesWith(I, ConstantInt::getFalse());
break;
}
}
// Since the RHS is a ConstantInt (CI), if the left hand side is an
// instruction, see if that instruction also has constants so that the
// instruction can be folded into the icmp
if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
return Res;
}
// Handle icmp with constant (but not simple integer constant) RHS
if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
switch (LHSI->getOpcode()) {
case Instruction::GetElementPtr:
if (RHSC->isNullValue()) {
// icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
bool isAllZeros = true;
for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
if (!isa<Constant>(LHSI->getOperand(i)) ||
!cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
isAllZeros = false;
break;
}
if (isAllZeros)
return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Constant::getNullValue(LHSI->getOperand(0)->getType()));
}
break;
case Instruction::PHI:
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
break;
case Instruction::Select: {
// If either operand of the select is a constant, we can fold the
// comparison into the select arms, which will cause one to be
// constant folded and the select turned into a bitwise or.
Value *Op1 = 0, *Op2 = 0;
if (LHSI->hasOneUse()) {
if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
// Fold the known value into the constant operand.
Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
// Insert a new ICmp of the other select operand.
Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
LHSI->getOperand(2), RHSC,
I.getName()), I);
} else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
// Fold the known value into the constant operand.
Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
// Insert a new ICmp of the other select operand.
Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
LHSI->getOperand(1), RHSC,
I.getName()), I);
}
}
if (Op1)
return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
break;
}
case Instruction::Malloc:
// If we have (malloc != null), and if the malloc has a single use, we
// can assume it is successful and remove the malloc.
if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
AddToWorkList(LHSI);
return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
!isTrueWhenEqual(I)));
}
break;
}
}
// If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
if (User *GEP = dyn_castGetElementPtr(Op0))
if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
return NI;
if (User *GEP = dyn_castGetElementPtr(Op1))
if (Instruction *NI = FoldGEPICmp(GEP, Op0,
ICmpInst::getSwappedPredicate(I.getPredicate()), I))
return NI;
// Test to see if the operands of the icmp are casted versions of other
// values. If the ptr->ptr cast can be stripped off both arguments, we do so
// now.
if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
if (isa<PointerType>(Op0->getType()) &&
(isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
// We keep moving the cast from the left operand over to the right
// operand, where it can often be eliminated completely.
Op0 = CI->getOperand(0);
// If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
// so eliminate it as well.
if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
Op1 = CI2->getOperand(0);
// If Op1 is a constant, we can fold the cast into the constant.
if (Op0->getType() != Op1->getType()) {
if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
} else {
// Otherwise, cast the RHS right before the icmp
Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
}
}
return new ICmpInst(I.getPredicate(), Op0, Op1);
}
}
if (isa<CastInst>(Op0)) {
// Handle the special case of: icmp (cast bool to X), <cst>
// This comes up when you have code like
// int X = A < B;
// if (X) ...
// For generality, we handle any zero-extension of any operand comparison
// with a constant or another cast from the same type.
if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
if (Instruction *R = visitICmpInstWithCastAndCast(I))
return R;
}
// ~x < ~y --> y < x
{ Value *A, *B;
if (match(Op0, m_Not(m_Value(A))) &&
match(Op1, m_Not(m_Value(B))))
return new ICmpInst(I.getPredicate(), B, A);
}
if (I.isEquality()) {
Value *A, *B, *C, *D;
// -x == -y --> x == y
if (match(Op0, m_Neg(m_Value(A))) &&
match(Op1, m_Neg(m_Value(B))))
return new ICmpInst(I.getPredicate(), A, B);
if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
Value *OtherVal = A == Op1 ? B : A;
return new ICmpInst(I.getPredicate(), OtherVal,
Constant::getNullValue(A->getType()));
}
if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
// A^c1 == C^c2 --> A == C^(c1^c2)
if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
if (Op1->hasOneUse()) {
Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
return new ICmpInst(I.getPredicate(), A,
InsertNewInstBefore(Xor, I));
}
// A^B == A^D -> B == D
if (A == C) return new ICmpInst(I.getPredicate(), B, D);
if (A == D) return new ICmpInst(I.getPredicate(), B, C);
if (B == C) return new ICmpInst(I.getPredicate(), A, D);
if (B == D) return new ICmpInst(I.getPredicate(), A, C);
}
}
if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
(A == Op0 || B == Op0)) {
// A == (A^B) -> B == 0
Value *OtherVal = A == Op0 ? B : A;
return new ICmpInst(I.getPredicate(), OtherVal,
Constant::getNullValue(A->getType()));
}
if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
// (A-B) == A -> B == 0
return new ICmpInst(I.getPredicate(), B,
Constant::getNullValue(B->getType()));
}
if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
// A == (A-B) -> B == 0
return new ICmpInst(I.getPredicate(), B,
Constant::getNullValue(B->getType()));
}
// (X&Z) == (Y&Z) -> (X^Y) & Z == 0
if (Op0->hasOneUse() && Op1->hasOneUse() &&
match(Op0, m_And(m_Value(A), m_Value(B))) &&
match(Op1, m_And(m_Value(C), m_Value(D)))) {
Value *X = 0, *Y = 0, *Z = 0;
if (A == C) {
X = B; Y = D; Z = A;
} else if (A == D) {
X = B; Y = C; Z = A;
} else if (B == C) {
X = A; Y = D; Z = B;
} else if (B == D) {
X = A; Y = C; Z = B;
}
if (X) { // Build (X^Y) & Z
Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
I.setOperand(0, Op1);
I.setOperand(1, Constant::getNullValue(Op1->getType()));
return &I;
}
}
}
return Changed ? &I : 0;
}
/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
/// and CmpRHS are both known to be integer constants.
Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
ConstantInt *DivRHS) {
ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
const APInt &CmpRHSV = CmpRHS->getValue();
// FIXME: If the operand types don't match the type of the divide
// then don't attempt this transform. The code below doesn't have the
// logic to deal with a signed divide and an unsigned compare (and
// vice versa). This is because (x /s C1) <s C2 produces different
// results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
// (x /u C1) <u C2. Simply casting the operands and result won't
// work. :( The if statement below tests that condition and bails
// if it finds it.
bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
return 0;
if (DivRHS->isZero())
return 0; // The ProdOV computation fails on divide by zero.
// Compute Prod = CI * DivRHS. We are essentially solving an equation
// of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
// C2 (CI). By solving for X we can turn this into a range check
// instead of computing a divide.
ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
// Determine if the product overflows by seeing if the product is
// not equal to the divide. Make sure we do the same kind of divide
// as in the LHS instruction that we're folding.
bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
// Get the ICmp opcode
ICmpInst::Predicate Pred = ICI.getPredicate();
// Figure out the interval that is being checked. For example, a comparison
// like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
// Compute this interval based on the constants involved and the signedness of
// the compare/divide. This computes a half-open interval, keeping track of
// whether either value in the interval overflows. After analysis each
// overflow variable is set to 0 if it's corresponding bound variable is valid
// -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
int LoOverflow = 0, HiOverflow = 0;
ConstantInt *LoBound = 0, *HiBound = 0;
if (!DivIsSigned) { // udiv
// e.g. X/5 op 3 --> [15, 20)
LoBound = Prod;
HiOverflow = LoOverflow = ProdOV;
if (!HiOverflow)
HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
} else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
if (CmpRHSV == 0) { // (X / pos) op 0
// Can't overflow. e.g. X/2 op 0 --> [-1, 2)
LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
HiBound = DivRHS;
} else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
HiOverflow = LoOverflow = ProdOV;
if (!HiOverflow)
HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
} else { // (X / pos) op neg
// e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
LoOverflow = AddWithOverflow(LoBound, Prod,
cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
HiBound = AddOne(Prod);
HiOverflow = ProdOV ? -1 : 0;
}
} else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
if (CmpRHSV == 0) { // (X / neg) op 0
// e.g. X/-5 op 0 --> [-4, 5)
LoBound = AddOne(DivRHS);
HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
if (HiBound == DivRHS) { // -INTMIN = INTMIN
HiOverflow = 1; // [INTMIN+1, overflow)
HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
}
} else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
// e.g. X/-5 op 3 --> [-19, -14)
HiOverflow = LoOverflow = ProdOV ? -1 : 0;
if (!LoOverflow)
LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
HiBound = AddOne(Prod);
} else { // (X / neg) op neg
// e.g. X/-5 op -3 --> [15, 20)
LoBound = Prod;
LoOverflow = HiOverflow = ProdOV ? 1 : 0;
HiBound = Subtract(Prod, DivRHS);
}
// Dividing by a negative swaps the condition. LT <-> GT
Pred = ICmpInst::getSwappedPredicate(Pred);
}
Value *X = DivI->getOperand(0);
switch (Pred) {
default: assert(0 && "Unhandled icmp opcode!");
case ICmpInst::ICMP_EQ:
if (LoOverflow && HiOverflow)
return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
else if (HiOverflow)
return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
ICmpInst::ICMP_UGE, X, LoBound);
else if (LoOverflow)
return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
ICmpInst::ICMP_ULT, X, HiBound);
else
return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
case ICmpInst::ICMP_NE:
if (LoOverflow && HiOverflow)
return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
else if (HiOverflow)
return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
ICmpInst::ICMP_ULT, X, LoBound);
else if (LoOverflow)
return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
ICmpInst::ICMP_UGE, X, HiBound);
else
return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_SLT:
if (LoOverflow == +1) // Low bound is greater than input range.
return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
if (LoOverflow == -1) // Low bound is less than input range.
return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
return new ICmpInst(Pred, X, LoBound);
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_SGT:
if (HiOverflow == +1) // High bound greater than input range.
return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
else if (HiOverflow == -1) // High bound less than input range.
return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
if (Pred == ICmpInst::ICMP_UGT)
return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
else
return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
}
}
/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
///
Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
Instruction *LHSI,
ConstantInt *RHS) {
const APInt &RHSV = RHS->getValue();
switch (LHSI->getOpcode()) {
case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
// If this is a comparison that tests the signbit (X < 0) or (x > -1),
// fold the xor.
if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
(ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Value *CompareVal = LHSI->getOperand(0);
// If the sign bit of the XorCST is not set, there is no change to
// the operation, just stop using the Xor.
if (!XorCST->getValue().isNegative()) {
ICI.setOperand(0, CompareVal);
AddToWorkList(LHSI);
return &ICI;
}
// Was the old condition true if the operand is positive?
bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
// If so, the new one isn't.
isTrueIfPositive ^= true;
if (isTrueIfPositive)
return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
else
return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
}
}
break;
case Instruction::And: // (icmp pred (and X, AndCST), RHS)
if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
LHSI->getOperand(0)->hasOneUse()) {
ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
// If the LHS is an AND of a truncating cast, we can widen the
// and/compare to be the input width without changing the value
// produced, eliminating a cast.
if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
// We can do this transformation if either the AND constant does not
// have its sign bit set or if it is an equality comparison.
// Extending a relational comparison when we're checking the sign
// bit would not work.
if (Cast->hasOneUse() &&
(ICI.isEquality() ||
(AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
uint32_t BitWidth =
cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
APInt NewCST = AndCST->getValue();
NewCST.zext(BitWidth);
APInt NewCI = RHSV;
NewCI.zext(BitWidth);
Instruction *NewAnd =
BinaryOperator::createAnd(Cast->getOperand(0),
ConstantInt::get(NewCST),LHSI->getName());
InsertNewInstBefore(NewAnd, ICI);
return new ICmpInst(ICI.getPredicate(), NewAnd,
ConstantInt::get(NewCI));
}
}
// If this is: (X >> C1) & C2 != C3 (where any shift and any compare
// could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
// happens a LOT in code produced by the C front-end, for bitfield
// access.
BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
if (Shift && !Shift->isShift())
Shift = 0;
ConstantInt *ShAmt;
ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
const Type *AndTy = AndCST->getType(); // Type of the and.
// We can fold this as long as we can't shift unknown bits
// into the mask. This can only happen with signed shift
// rights, as they sign-extend.
if (ShAmt) {
bool CanFold = Shift->isLogicalShift();
if (!CanFold) {
// To test for the bad case of the signed shr, see if any
// of the bits shifted in could be tested after the mask.
uint32_t TyBits = Ty->getPrimitiveSizeInBits();
int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
AndCST->getValue()) == 0)
CanFold = true;
}
if (CanFold) {
Constant *NewCst;
if (Shift->getOpcode() == Instruction::Shl)
NewCst = ConstantExpr::getLShr(RHS, ShAmt);
else
NewCst = ConstantExpr::getShl(RHS, ShAmt);
// Check to see if we are shifting out any of the bits being
// compared.
if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
// If we shifted bits out, the fold is not going to work out.
// As a special case, check to see if this means that the
// result is always true or false now.
if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
if (ICI.getPredicate() == ICmpInst::ICMP_NE)
return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
} else {
ICI.setOperand(1, NewCst);
Constant *NewAndCST;
if (Shift->getOpcode() == Instruction::Shl)
NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
else
NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
LHSI->setOperand(1, NewAndCST);
LHSI->setOperand(0, Shift->getOperand(0));
AddToWorkList(Shift); // Shift is dead.
AddUsesToWorkList(ICI);
return &ICI;
}
}
}
// Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
// preferable because it allows the C<<Y expression to be hoisted out
// of a loop if Y is invariant and X is not.
if (Shift && Shift->hasOneUse() && RHSV == 0 &&
ICI.isEquality() && !Shift->isArithmeticShift() &&
isa<Instruction>(Shift->getOperand(0))) {
// Compute C << Y.
Value *NS;
if (Shift->getOpcode() == Instruction::LShr) {
NS = BinaryOperator::createShl(AndCST,
Shift->getOperand(1), "tmp");
} else {
// Insert a logical shift.
NS = BinaryOperator::createLShr(AndCST,
Shift->getOperand(1), "tmp");
}
InsertNewInstBefore(cast<Instruction>(NS), ICI);
// Compute X & (C << Y).
Instruction *NewAnd =
BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
InsertNewInstBefore(NewAnd, ICI);
ICI.setOperand(0, NewAnd);
return &ICI;
}
}
break;
case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
if (!ShAmt) break;
uint32_t TypeBits = RHSV.getBitWidth();
// Check that the shift amount is in range. If not, don't perform
// undefined shifts. When the shift is visited it will be
// simplified.
if (ShAmt->uge(TypeBits))
break;
if (ICI.isEquality()) {
// If we are comparing against bits always shifted out, the
// comparison cannot succeed.
Constant *Comp =
ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
if (Comp != RHS) {// Comparing against a bit that we know is zero.
bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
return ReplaceInstUsesWith(ICI, Cst);
}
if (LHSI->hasOneUse()) {
// Otherwise strength reduce the shift into an and.
uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Constant *Mask =
ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Instruction *AndI =
BinaryOperator::createAnd(LHSI->getOperand(0),
Mask, LHSI->getName()+".mask");
Value *And = InsertNewInstBefore(AndI, ICI);
return new ICmpInst(ICI.getPredicate(), And,
ConstantInt::get(RHSV.lshr(ShAmtVal)));
}
}
// Otherwise, if this is a comparison of the sign bit, simplify to and/test.
bool TrueIfSigned = false;
if (LHSI->hasOneUse() &&
isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
// (X << 31) <s 0 --> (X&1) != 0
Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
(TypeBits-ShAmt->getZExtValue()-1));
Instruction *AndI =
BinaryOperator::createAnd(LHSI->getOperand(0),
Mask, LHSI->getName()+".mask");
Value *And = InsertNewInstBefore(AndI, ICI);
return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
And, Constant::getNullValue(And->getType()));
}
break;
}
case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
case Instruction::AShr: {
// Only handle equality comparisons of shift-by-constant.
ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
if (!ShAmt || !ICI.isEquality()) break;
// Check that the shift amount is in range. If not, don't perform
// undefined shifts. When the shift is visited it will be
// simplified.
uint32_t TypeBits = RHSV.getBitWidth();
if (ShAmt->uge(TypeBits))
break;
uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
// If we are comparing against bits always shifted out, the
// comparison cannot succeed.
APInt Comp = RHSV << ShAmtVal;
if (LHSI->getOpcode() == Instruction::LShr)
Comp = Comp.lshr(ShAmtVal);
else
Comp = Comp.ashr(ShAmtVal);
if (Comp != RHSV) { // Comparing against a bit that we know is zero.
bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
return ReplaceInstUsesWith(ICI, Cst);
}
// Otherwise, check to see if the bits shifted out are known to be zero.
// If so, we can compare against the unshifted value:
// (X & 4) >> 1 == 2 --> (X & 4) == 4.
if (LHSI->hasOneUse() &&
MaskedValueIsZero(LHSI->getOperand(0),
APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
ConstantExpr::getShl(RHS, ShAmt));
}
if (LHSI->hasOneUse()) {
// Otherwise strength reduce the shift into an and.
APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Constant *Mask = ConstantInt::get(Val);
Instruction *AndI =
BinaryOperator::createAnd(LHSI->getOperand(0),
Mask, LHSI->getName()+".mask");
Value *And = InsertNewInstBefore(AndI, ICI);
return new ICmpInst(ICI.getPredicate(), And,
ConstantExpr::getShl(RHS, ShAmt));
}
break;
}
case Instruction::SDiv:
case Instruction::UDiv:
// Fold: icmp pred ([us]div X, C1), C2 -> range test
// Fold this div into the comparison, producing a range check.
// Determine, based on the divide type, what the range is being
// checked. If there is an overflow on the low or high side, remember
// it, otherwise compute the range [low, hi) bounding the new value.
// See: InsertRangeTest above for the kinds of replacements possible.
if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
DivRHS))
return R;
break;
case Instruction::Add:
// Fold: icmp pred (add, X, C1), C2
if (!ICI.isEquality()) {
ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
if (!LHSC) break;
const APInt &LHSV = LHSC->getValue();
ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
.subtract(LHSV);
if (ICI.isSignedPredicate()) {
if (CR.getLower().isSignBit()) {
return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
ConstantInt::get(CR.getUpper()));
} else if (CR.getUpper().isSignBit()) {
return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
ConstantInt::get(CR.getLower()));
}
} else {
if (CR.getLower().isMinValue()) {
return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
ConstantInt::get(CR.getUpper()));
} else if (CR.getUpper().isMinValue()) {
return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
ConstantInt::get(CR.getLower()));
}
}
}
break;
}
// Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
if (ICI.isEquality()) {
bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
// If the first operand is (add|sub|and|or|xor|rem) with a constant, and
// the second operand is a constant, simplify a bit.
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
switch (BO->getOpcode()) {
case Instruction::SRem:
// If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Instruction *NewRem =
BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
BO->getName());
InsertNewInstBefore(NewRem, ICI);
return new ICmpInst(ICI.getPredicate(), NewRem,
Constant::getNullValue(BO->getType()));
}
}
break;
case Instruction::Add:
// Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
if (BO->hasOneUse())
return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Subtract(RHS, BOp1C));
} else if (RHSV == 0) {
// Replace ((add A, B) != 0) with (A != -B) if A or B is
// efficiently invertible, or if the add has just this one use.
Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
if (Value *NegVal = dyn_castNegVal(BOp1))
return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
else if (Value *NegVal = dyn_castNegVal(BOp0))
return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
else if (BO->hasOneUse()) {
Instruction *Neg = BinaryOperator::createNeg(BOp1);
InsertNewInstBefore(Neg, ICI);
Neg->takeName(BO);
return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
}
}
break;
case Instruction::Xor:
// For the xor case, we can xor two constants together, eliminating
// the explicit xor.
if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
ConstantExpr::getXor(RHS, BOC));
// FALLTHROUGH
case Instruction::Sub:
// Replace (([sub|xor] A, B) != 0) with (A != B)
if (RHSV == 0)
return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
BO->getOperand(1));
break;
case Instruction::Or:
// If bits are being or'd in that are not present in the constant we
// are comparing against, then the comparison could never succeed!
if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Constant *NotCI = ConstantExpr::getNot(RHS);
if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
isICMP_NE));
}
break;
case Instruction::And:
if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
// If bits are being compared against that are and'd out, then the
// comparison can never succeed!
if ((RHSV & ~BOC->getValue()) != 0)
return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
isICMP_NE));
// If we have ((X & C) == C), turn it into ((X & C) != 0).
if (RHS == BOC && RHSV.isPowerOf2())
return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
ICmpInst::ICMP_NE, LHSI,
Constant::getNullValue(RHS->getType()));
// Replace (and X, (1 << size(X)-1) != 0) with x s< 0
if (isSignBit(BOC)) {
Value *X = BO->getOperand(0);
Constant *Zero = Constant::getNullValue(X->getType());
ICmpInst::Predicate pred = isICMP_NE ?
ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
return new ICmpInst(pred, X, Zero);
}
// ((X & ~7) == 0) --> X < 8
if (RHSV == 0 && isHighOnes(BOC)) {
Value *X = BO->getOperand(0);
Constant *NegX = ConstantExpr::getNeg(BOC);
ICmpInst::Predicate pred = isICMP_NE ?
ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
return new ICmpInst(pred, X, NegX);
}
}
default: break;
}
} else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
// Handle icmp {eq|ne} <intrinsic>, intcst.
if (II->getIntrinsicID() == Intrinsic::bswap) {
AddToWorkList(II);
ICI.setOperand(0, II->getOperand(1));
ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
return &ICI;
}
}
} else { // Not a ICMP_EQ/ICMP_NE
// If the LHS is a cast from an integral value of the same size,
// then since we know the RHS is a constant, try to simlify.
if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
Value *CastOp = Cast->getOperand(0);
const Type *SrcTy = CastOp->getType();
uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
if (SrcTy->isInteger() &&
SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
// If this is an unsigned comparison, try to make the comparison use
// smaller constant values.
if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
// X u< 128 => X s> -1
return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
} else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
RHSV == APInt::getSignedMaxValue(SrcTySize)) {
// X u> 127 => X s< 0
return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
Constant::getNullValue(SrcTy));
}
}
}
}
return 0;
}
/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
/// We only handle extending casts so far.
///
Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Value *LHSCIOp = LHSCI->getOperand(0);
const Type *SrcTy = LHSCIOp->getType();
const Type *DestTy = LHSCI->getType();
Value *RHSCIOp;
// Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
// integer type is the same size as the pointer type.
if (LHSCI->getOpcode() == Instruction::PtrToInt &&
getTargetData().getPointerSizeInBits() ==
cast<IntegerType>(DestTy)->getBitWidth()) {
Value *RHSOp = 0;
if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
} else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
RHSOp = RHSC->getOperand(0);
// If the pointer types don't match, insert a bitcast.
if (LHSCIOp->getType() != RHSOp->getType())
RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
}
if (RHSOp)
return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
}
// The code below only handles extension cast instructions, so far.
// Enforce this.
if (LHSCI->getOpcode() != Instruction::ZExt &&
LHSCI->getOpcode() != Instruction::SExt)
return 0;
bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
bool isSignedCmp = ICI.isSignedPredicate();
if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
// Not an extension from the same type?
RHSCIOp = CI->getOperand(0);
if (RHSCIOp->getType() != LHSCIOp->getType())
return 0;
// If the signedness of the two casts doesn't agree (i.e. one is a sext
// and the other is a zext), then we can't handle this.
if (CI->getOpcode() != LHSCI->getOpcode())
return 0;
// Deal with equality cases early.
if (ICI.isEquality())
return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
// A signed comparison of sign extended values simplifies into a
// signed comparison.
if (isSignedCmp && isSignedExt)
return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
// The other three cases all fold into an unsigned comparison.
return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
}
// If we aren't dealing with a constant on the RHS, exit early
ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
if (!CI)
return 0;
// Compute the constant that would happen if we truncated to SrcTy then
// reextended to DestTy.
Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
// If the re-extended constant didn't change...
if (Res2 == CI) {
// Make sure that sign of the Cmp and the sign of the Cast are the same.
// For example, we might have:
// %A = sext short %X to uint
// %B = icmp ugt uint %A, 1330
// It is incorrect to transform this into
// %B = icmp ugt short %X, 1330
// because %A may have negative value.
//
// However, it is OK if SrcTy is bool (See cast-set.ll testcase)
// OR operation is EQ/NE.
if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
else
return 0;
}
// The re-extended constant changed so the constant cannot be represented
// in the shorter type. Consequently, we cannot emit a simple comparison.
// First, handle some easy cases. We know the result cannot be equal at this
// point so handle the ICI.isEquality() cases
if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
if (ICI.getPredicate() == ICmpInst::ICMP_NE)
return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
// Evaluate the comparison for LT (we invert for GT below). LE and GE cases
// should have been folded away previously and not enter in here.
Value *Result;
if (isSignedCmp) {
// We're performing a signed comparison.
if (cast<ConstantInt>(CI)->getValue().isNegative())
Result = ConstantInt::getFalse(); // X < (small) --> false
else
Result = ConstantInt::getTrue(); // X < (large) --> true
} else {
// We're performing an unsigned comparison.
if (isSignedExt) {
// We're performing an unsigned comp with a sign extended value.
// This is true if the input is >= 0. [aka >s -1]
Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
NegOne, ICI.getName()), ICI);
} else {
// Unsigned extend & unsigned compare -> always true.
Result = ConstantInt::getTrue();
}
}
// Finally, return the value computed.
if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
ICI.getPredicate() == ICmpInst::ICMP_SLT) {
return ReplaceInstUsesWith(ICI, Result);
} else {
assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
"ICmp should be folded!");
if (Constant *CI = dyn_cast<Constant>(Result))
return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
else
return BinaryOperator::createNot(Result);
}
}
Instruction *InstCombiner::visitShl(BinaryOperator &I) {
return commonShiftTransforms(I);
}
Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
return commonShiftTransforms(I);
}
Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
if (Instruction *R = commonShiftTransforms(I))
return R;
Value *Op0 = I.getOperand(0);
// ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
if (CSI->isAllOnesValue())
return ReplaceInstUsesWith(I, CSI);
// See if we can turn a signed shr into an unsigned shr.
if (MaskedValueIsZero(Op0,
APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
return BinaryOperator::createLShr(Op0, I.getOperand(1));
return 0;
}
Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
// shl X, 0 == X and shr X, 0 == X
// shl 0, X == 0 and shr 0, X == 0
if (Op1 == Constant::getNullValue(Op1->getType()) ||
Op0 == Constant::getNullValue(Op0->getType()))
return ReplaceInstUsesWith(I, Op0);
if (isa<UndefValue>(Op0)) {
if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
return ReplaceInstUsesWith(I, Op0);
else // undef << X -> 0, undef >>u X -> 0
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
}
if (isa<UndefValue>(Op1)) {
if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
return ReplaceInstUsesWith(I, Op0);
else // X << undef, X >>u undef -> 0
return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
}
// Try to fold constant and into select arguments.
if (isa<Constant>(Op0))
if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
return Res;
return 0;
}
Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
BinaryOperator &I) {
bool isLeftShift = I.getOpcode() == Instruction::Shl;
// See if we can simplify any instructions used by the instruction whose sole
// purpose is to compute bits we don't care about.
uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
KnownZero, KnownOne))
return &I;
// shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
// of a signed value.
//
if (Op1->uge(TypeBits)) {
if (I.getOpcode() != Instruction::AShr)
return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
else {
I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
return &I;
}
}
// ((X*C1) << C2) == (X * (C1 << C2))
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
if (BO->getOpcode() == Instruction::Mul && isLeftShift)
if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
return BinaryOperator::createMul(BO->getOperand(0),
ConstantExpr::getShl(BOOp, Op1));
// Try to fold constant and into select arguments.
if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
if (Instruction *R = FoldOpIntoSelect(I, SI, this))
return R;
if (isa<PHINode>(Op0))
if (Instruction *NV = FoldOpIntoPhi(I))
return NV;
// Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
// If 'shift2' is an ashr, we would have to get the sign bit into a funny
// place. Don't try to do this transformation in this case. Also, we
// require that the input operand is a shift-by-constant so that we have
// confidence that the shifts will get folded together. We could do this
// xform in more cases, but it is unlikely to be profitable.
if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
isa<ConstantInt>(TrOp->getOperand(1))) {
// Okay, we'll do this xform. Make the shift of shift.
Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
I.getName());
InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
// For logical shifts, the truncation has the effect of making the high
// part of the register be zeros. Emulate this by inserting an AND to
// clear the top bits as needed. This 'and' will usually be zapped by
// other xforms later if dead.
unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
// The mask we constructed says what the trunc would do if occurring
// between the shifts. We want to know the effect *after* the second
// shift. We know that it is a logical shift by a constant, so adjust the
// mask as appropriate.
if (I.getOpcode() == Instruction::Shl)
MaskV <<= Op1->getZExtValue();
else {
assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
MaskV = MaskV.lshr(Op1->getZExtValue());
}
Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
TI->getName());
InsertNewInstBefore(And, I); // shift1 & 0x00FF
// Return the value truncated to the interesting size.
return new TruncInst(And, I.getType());
}
}
if (Op0->hasOneUse()) {
if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
// Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Value *V1, *V2;
ConstantInt *CC;
switch (Op0BO->getOpcode()) {
default: break;
case Instruction::Add:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor: {
// These operators commute.
// Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
match(Op0BO->getOperand(1),
m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Instruction *YS = BinaryOperator::createShl(
Op0BO->getOperand(0), Op1,
Op0BO->getName());
InsertNewInstBefore(YS, I); // (Y << C)
Instruction *X =
BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
Op0BO->getOperand(1)->getName());
InsertNewInstBefore(X, I); // (X + (Y << C))
uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
return BinaryOperator::createAnd(X, ConstantInt::get(
APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
}
// Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Value *Op0BOOp1 = Op0BO->getOperand(1);
if (isLeftShift && Op0BOOp1->hasOneUse() &&
match(Op0BOOp1,
m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
V2 == Op1) {
Instruction *YS = BinaryOperator::createShl(
Op0BO->getOperand(0), Op1,
Op0BO->getName());
InsertNewInstBefore(YS, I); // (Y << C)
Instruction *XM =
BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
V1->getName()+".mask");
InsertNewInstBefore(XM, I); // X & (CC << C)
return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
}
}
// FALL THROUGH.
case Instruction::Sub: {
// Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
match(Op0BO->getOperand(0),
m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Instruction *YS = BinaryOperator::createShl(
Op0BO->getOperand(1), Op1,
Op0BO->getName());
InsertNewInstBefore(YS, I); // (Y << C)
Instruction *X =
BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Op0BO->getOperand(0)->getName());
InsertNewInstBefore(X, I); // (X + (Y << C))
uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
return BinaryOperator::createAnd(X, ConstantInt::get(
APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
}
// Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
match(Op0BO->getOperand(0),
m_And(m_Shr(m_Value(V1), m_Value(V2)),
m_ConstantInt(CC))) && V2 == Op1 &&
cast<BinaryOperator>(Op0BO->getOperand(0))
->getOperand(0)->hasOneUse()) {
Instruction *YS = BinaryOperator::createShl(
Op0BO->getOperand(1), Op1,
Op0BO->getName());
InsertNewInstBefore(YS, I); // (Y << C)
Instruction *XM =
BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
V1->getName()+".mask");
InsertNewInstBefore(XM, I); // X & (CC << C)
return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
}
break;
}
}
// If the operand is an bitwise operator with a constant RHS, and the
// shift is the only use, we can pull it out of the shift.
if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
bool isValid = true; // Valid only for And, Or, Xor
bool highBitSet = false; // Transform if high bit of constant set?
switch (Op0BO->getOpcode()) {
default: isValid = false; break; // Do not perform transform!
case Instruction::Add:
isValid = isLeftShift;
break;
case Instruction::Or:
case Instruction::Xor:
highBitSet = false;
break;
case Instruction::And:
highBitSet = true;
break;
}
// If this is a signed shift right, and the high bit is modified
// by the logical operation, do not perform the transformation.
// The highBitSet boolean indicates the value of the high bit of
// the constant which would cause it to be modified for this
// operation.
//
if (isValid && I.getOpcode() == Instruction::AShr)
isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
if (isValid) {
Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Instruction *NewShift =
BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
InsertNewInstBefore(NewShift, I);
NewShift->takeName(Op0BO);
return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
NewRHS);
}
}
}
}
// Find out if this is a shift of a shift by a constant.
BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
if (ShiftOp && !ShiftOp->isShift())
ShiftOp = 0;
if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
Value *X = ShiftOp->getOperand(0);
uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
if (AmtSum > TypeBits)
AmtSum = TypeBits;
const IntegerType *Ty = cast<IntegerType>(I.getType());
// Check for (X << c1) << c2 and (X >> c1) >> c2
if (I.getOpcode() == ShiftOp->getOpcode()) {
return BinaryOperator::create(I.getOpcode(), X,
ConstantInt::get(Ty, AmtSum));
} else if (ShiftOp->getOpcode() == Instruction::LShr &&
I.getOpcode() == Instruction::AShr) {
// ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
} else if (ShiftOp->getOpcode() == Instruction::AShr &&
I.getOpcode() == Instruction::LShr) {
// ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Instruction *Shift =
BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
InsertNewInstBefore(Shift, I);
APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
}
// Okay, if we get here, one shift must be left, and the other shift must be
// right. See if the amounts are equal.
if (ShiftAmt1 == ShiftAmt2) {
// If we have ((X >>? C) << C), turn this into X & (-1 << C).
if (I.getOpcode() == Instruction::Shl) {
APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
}
// If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
if (I.getOpcode() == Instruction::LShr) {
APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
}
// We can simplify ((X << C) >>s C) into a trunc + sext.
// NOTE: we could do this for any C, but that would make 'unusual' integer
// types. For now, just stick to ones well-supported by the code
// generators.
const Type *SExtType = 0;
switch (Ty->getBitWidth() - ShiftAmt1) {
case 1 :
case 8 :
case 16 :
case 32 :
case 64 :
case 128:
SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
break;
default: break;
}
if (SExtType) {
Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
InsertNewInstBefore(NewTrunc, I);
return new SExtInst(NewTrunc, Ty);
}
// Otherwise, we can't handle it yet.
} else if (ShiftAmt1 < ShiftAmt2) {
uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
// (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
if (I.getOpcode() == Instruction::Shl) {
assert(ShiftOp->getOpcode() == Instruction::LShr ||
ShiftOp->getOpcode() == Instruction::AShr);
Instruction *Shift =
BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
InsertNewInstBefore(Shift, I);
APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
}
// (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
if (I.getOpcode() == Instruction::LShr) {
assert(ShiftOp->getOpcode() == Instruction::Shl);
Instruction *Shift =
BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
InsertNewInstBefore(Shift, I);
APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
}
// We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
} else {
assert(ShiftAmt2 < ShiftAmt1);
uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
// (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
if (I.getOpcode() == Instruction::Shl) {
assert(ShiftOp->getOpcode() == Instruction::LShr ||
ShiftOp->getOpcode() == Instruction::AShr);
Instruction *Shift =
BinaryOperator::create(ShiftOp->getOpcode(), X,
ConstantInt::get(Ty, ShiftDiff));
InsertNewInstBefore(Shift, I);
APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
}
// (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
if (I.getOpcode() == Instruction::LShr) {
assert(ShiftOp->getOpcode() == Instruction::Shl);
Instruction *Shift =
BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
InsertNewInstBefore(Shift, I);
APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
}
// We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
}
}
return 0;
}
/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
/// expression. If so, decompose it, returning some value X, such that Val is
/// X*Scale+Offset.
///
static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
int &Offset) {
assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Offset = CI->getZExtValue();
Scale = 0;
return ConstantInt::get(Type::Int32Ty, 0);
} else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
if (I->getOpcode() == Instruction::Shl) {
// This is a value scaled by '1 << the shift amt'.
Scale = 1U << RHS->getZExtValue();
Offset = 0;
return I->getOperand(0);
} else if (I->getOpcode() == Instruction::Mul) {
// This value is scaled by 'RHS'.
Scale = RHS->getZExtValue();
Offset = 0;
return I->getOperand(0);
} else if (I->getOpcode() == Instruction::Add) {
// We have X+C. Check to see if we really have (X*C2)+C1,
// where C1 is divisible by C2.
unsigned SubScale;
Value *SubVal =
DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Offset += RHS->getZExtValue();
Scale = SubScale;
return SubVal;
}
}
}
// Otherwise, we can't look past this.
Scale = 1;
Offset = 0;
return Val;
}
/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
/// try to eliminate the cast by moving the type information into the alloc.
Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
AllocationInst &AI) {
const PointerType *PTy = cast<PointerType>(CI.getType());
// Remove any uses of AI that are dead.
assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
Instruction *User = cast<Instruction>(*UI++);
if (isInstructionTriviallyDead(User)) {
while (UI != E && *UI == User)
++UI; // If this instruction uses AI more than once, don't break UI.
++NumDeadInst;
DOUT << "IC: DCE: " << *User;
EraseInstFromFunction(*User);
}
}
// Get the type really allocated and the type casted to.
const Type *AllocElTy = AI.getAllocatedType();
const Type *CastElTy = PTy->getElementType();
if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
if (CastElTyAlign < AllocElTyAlign) return 0;
// If the allocation has multiple uses, only promote it if we are strictly
// increasing the alignment of the resultant allocation. If we keep it the
// same, we open the door to infinite loops of various kinds.
if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
if (CastElTySize == 0 || AllocElTySize == 0) return 0;
// See if we can satisfy the modulus by pulling a scale out of the array
// size argument.
unsigned ArraySizeScale;
int ArrayOffset;
Value *NumElements = // See if the array size is a decomposable linear expr.
DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
// If we can now satisfy the modulus, by using a non-1 scale, we really can
// do the xform.
if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
(AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
Value *Amt = 0;
if (Scale == 1) {
Amt = NumElements;
} else {
// If the allocation size is constant, form a constant mul expression
Amt = ConstantInt::get(Type::Int32Ty, Scale);
if (isa<ConstantInt>(NumElements))
Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
// otherwise multiply the amount and the number of elements
else if (Scale != 1) {
Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
Amt = InsertNewInstBefore(Tmp, AI);
}
}
if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
Amt = InsertNewInstBefore(Tmp, AI);
}
AllocationInst *New;
if (isa<MallocInst>(AI))
New = new MallocInst(CastElTy, Amt, AI.getAlignment());
else
New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
InsertNewInstBefore(New, AI);
New->takeName(&AI);
// If the allocation has multiple uses, insert a cast and change all things
// that used it to use the new cast. This will also hack on CI, but it will
// die soon.
if (!AI.hasOneUse()) {
AddUsesToWorkList(AI);
// New is the allocation instruction, pointer typed. AI is the original
// allocation instruction, also pointer typed. Thus, cast to use is BitCast.
CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
InsertNewInstBefore(NewCast, AI);
AI.replaceAllUsesWith(NewCast);
}
return ReplaceInstUsesWith(CI, New);
}
/// CanEvaluateInDifferentType - Return true if we can take the specified value
/// and return it as type Ty without inserting any new casts and without
/// changing the computed value. This is used by code that tries to decide
/// whether promoting or shrinking integer operations to wider or smaller types
/// will allow us to eliminate a truncate or extend.
///
/// This is a truncation operation if Ty is smaller than V->getType(), or an
/// extension operation if Ty is larger.
bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
unsigned CastOpc,
int &NumCastsRemoved) {
// We can always evaluate constants in another type.
if (isa<ConstantInt>(V))
return true;
Instruction *I = dyn_cast<Instruction>(V);
if (!I) return false;
const IntegerType *OrigTy = cast<IntegerType>(V->getType());
// If this is an extension or truncate, we can often eliminate it.
if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
// If this is a cast from the destination type, we can trivially eliminate
// it, and this will remove a cast overall.
if (I->getOperand(0)->getType() == Ty) {
// If the first operand is itself a cast, and is eliminable, do not count
// this as an eliminable cast. We would prefer to eliminate those two
// casts first.
if (!isa<CastInst>(I->getOperand(0)))
++NumCastsRemoved;
return true;
}
}
// We can't extend or shrink something that has multiple uses: doing so would
// require duplicating the instruction in general, which isn't profitable.
if (!I->hasOneUse()) return false;
switch (I->getOpcode()) {
case Instruction::Add:
case Instruction::Sub:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
// These operators can all arbitrarily be extended or truncated.
return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
NumCastsRemoved) &&
CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
NumCastsRemoved);
case Instruction::Mul:
// A multiply can be truncated by truncating its operands.
return Ty->getBitWidth() < OrigTy->getBitWidth() &&
CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
NumCastsRemoved) &&
CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
NumCastsRemoved);
case Instruction::Shl:
// If we are truncating the result of this SHL, and if it's a shift of a
// constant amount, we can always perform a SHL in a smaller type.
if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
uint32_t BitWidth = Ty->getBitWidth();
if (BitWidth < OrigTy->getBitWidth() &&
CI->getLimitedValue(BitWidth) < BitWidth)
return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
NumCastsRemoved);
}
break;
case Instruction::LShr:
// If this is a truncate of a logical shr, we can truncate it to a smaller
// lshr iff we know that the bits we would otherwise be shifting in are
// already zeros.
if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
uint32_t OrigBitWidth = OrigTy->getBitWidth();
uint32_t BitWidth = Ty->getBitWidth();
if (BitWidth < OrigBitWidth &&
MaskedValueIsZero(I->getOperand(0),
APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
CI->getLimitedValue(BitWidth) < BitWidth) {
return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
NumCastsRemoved);
}
}
break;
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::Trunc:
// If this is the same kind of case as our original (e.g. zext+zext), we
// can safely replace it. Note that replacing it does not reduce the number
// of casts in the input.
if (I->getOpcode() == CastOpc)
return true;
break;
default:
// TODO: Can handle more cases here.
break;
}
return false;
}
/// EvaluateInDifferentType - Given an expression that
/// CanEvaluateInDifferentType returns true for, actually insert the code to
/// evaluate the expression.
Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
bool isSigned) {
if (Constant *C = dyn_cast<Constant>(V))
return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
// Otherwise, it must be an instruction.
Instruction *I = cast<Instruction>(V);
Instruction *Res = 0;
switch (I->getOpcode()) {
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::AShr:
case Instruction::LShr:
case Instruction::Shl: {
Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
LHS, RHS, I->getName());
break;
}
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
// If the source type of the cast is the type we're trying for then we can
// just return the source. There's no need to insert it because it is not
// new.
if (I->getOperand(0)->getType() == Ty)
return I->getOperand(0);
// Otherwise, must be the same type of case, so just reinsert a new one.
Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Ty, I->getName());
break;
default:
// TODO: Can handle more cases here.
assert(0 && "Unreachable!");
break;
}
return InsertNewInstBefore(Res, *I);
}
/// @brief Implement the transforms common to all CastInst visitors.
Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Value *Src = CI.getOperand(0);
// Many cases of "cast of a cast" are eliminable. If it's eliminable we just
// eliminate it now.
if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
if (Instruction::CastOps opc =
isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
// The first cast (CSrc) is eliminable so we need to fix up or replace
// the second cast (CI). CSrc will then have a good chance of being dead.
return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
}
}
// If we are casting a select then fold the cast into the select
if (SelectInst *SI = dyn_cast<SelectInst>(Src))
if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
return NV;
// If we are casting a PHI then fold the cast into the PHI
if (isa<PHINode>(Src))
if (Instruction *NV = FoldOpIntoPhi(CI))
return NV;
return 0;
}
/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
Value *Src = CI.getOperand(0);
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
// If casting the result of a getelementptr instruction with no offset, turn
// this into a cast of the original pointer!
if (GEP->hasAllZeroIndices()) {
// Changing the cast operand is usually not a good idea but it is safe
// here because the pointer operand is being replaced with another
// pointer operand so the opcode doesn't need to change.
AddToWorkList(GEP);
CI.setOperand(0, GEP->getOperand(0));
return &CI;
}
// If the GEP has a single use, and the base pointer is a bitcast, and the
// GEP computes a constant offset, see if we can convert these three
// instructions into fewer. This typically happens with unions and other
// non-type-safe code.
if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
if (GEP->hasAllConstantIndices()) {
// We are guaranteed to get a constant from EmitGEPOffset.
ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
int64_t Offset = OffsetV->getSExtValue();
// Get the base pointer input of the bitcast, and the type it points to.
Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
const Type *GEPIdxTy =
cast<PointerType>(OrigBase->getType())->getElementType();
if (GEPIdxTy->isSized()) {
SmallVector<Value*, 8> NewIndices;
// Start with the index over the outer type. Note that the type size
// might be zero (even if the offset isn't zero) if the indexed type
// is something like [0 x {int, int}]
const Type *IntPtrTy = TD->getIntPtrType();
int64_t FirstIdx = 0;
if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
FirstIdx = Offset/TySize;
Offset %= TySize;
// Handle silly modulus not returning values values [0..TySize).
if (Offset < 0) {
--FirstIdx;
Offset += TySize;
assert(Offset >= 0);
}
assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
}
NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
// Index into the types. If we fail, set OrigBase to null.
while (Offset) {
if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
const StructLayout *SL = TD->getStructLayout(STy);
if (Offset < (int64_t)SL->getSizeInBytes()) {
unsigned Elt = SL->getElementContainingOffset(Offset);
NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Offset -= SL->getElementOffset(Elt);
GEPIdxTy = STy->getElementType(Elt);
} else {
// Otherwise, we can't index into this, bail out.
Offset = 0;
OrigBase = 0;
}
} else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Offset %= EltSize;
} else {
NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
}
GEPIdxTy = STy->getElementType();
} else {
// Otherwise, we can't index into this, bail out.
Offset = 0;
OrigBase = 0;
}
}
if (OrigBase) {
// If we were able to index down into an element, create the GEP
// and bitcast the result. This eliminates one bitcast, potentially
// two.
Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
NewIndices.begin(),
NewIndices.end(), "");
InsertNewInstBefore(NGEP, CI);
NGEP->takeName(GEP);
if (isa<BitCastInst>(CI))
return new BitCastInst(NGEP, CI.getType());
assert(isa<PtrToIntInst>(CI));
return new PtrToIntInst(NGEP, CI.getType());
}
}
}
}
}
return commonCastTransforms(CI);
}
/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
/// integer types. This function implements the common transforms for all those
/// cases.
/// @brief Implement the transforms common to CastInst with integer operands
Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
if (Instruction *Result = commonCastTransforms(CI))
return Result;
Value *Src = CI.getOperand(0);
const Type *SrcTy = Src->getType();
const Type *DestTy = CI.getType();
uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
// See if we can simplify any instructions used by the LHS whose sole
// purpose is to compute bits we don't care about.
APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
KnownZero, KnownOne))
return &CI;
// If the source isn't an instruction or has more than one use then we
// can't do anything more.
Instruction *SrcI = dyn_cast<Instruction>(Src);
if (!SrcI || !Src->hasOneUse())
return 0;
// Attempt to propagate the cast into the instruction for int->int casts.
int NumCastsRemoved = 0;
if (!isa<BitCastInst>(CI) &&
CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
CI.getOpcode(), NumCastsRemoved)) {
// If this cast is a truncate, evaluting in a different type always
// eliminates the cast, so it is always a win. If this is a zero-extension,
// we need to do an AND to maintain the clear top-part of the computation,
// so we require that the input have eliminated at least one cast. If this
// is a sign extension, we insert two new casts (to do the extension) so we
// require that two casts have been eliminated.
bool DoXForm;
switch (CI.getOpcode()) {
default:
// All the others use floating point so we shouldn't actually
// get here because of the check above.
assert(0 && "Unknown cast type");
case Instruction::Trunc:
DoXForm = true;
break;
case Instruction::ZExt:
DoXForm = NumCastsRemoved >= 1;
break;
case Instruction::SExt:
DoXForm = NumCastsRemoved >= 2;
break;
}
if (DoXForm) {
Value *Res = EvaluateInDifferentType(SrcI, DestTy,
CI.getOpcode() == Instruction::SExt);
assert(Res->getType() == DestTy);
switch (CI.getOpcode()) {
default: assert(0 && "Unknown cast type!");
case Instruction::Trunc:
case Instruction::BitCast:
// Just replace this cast with the result.
return ReplaceInstUsesWith(CI, Res);
case Instruction::ZExt: {
// We need to emit an AND to clear the high bits.
assert(SrcBitSize < DestBitSize && "Not a zext?");
Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
SrcBitSize));
return BinaryOperator::createAnd(Res, C);
}
case Instruction::SExt:
// We need to emit a cast to truncate, then a cast to sext.
return CastInst::create(Instruction::SExt,
InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
CI), DestTy);
}
}
}
Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
switch (SrcI->getOpcode()) {
case Instruction::Add:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
// If we are discarding information, rewrite.
if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
// Don't insert two casts if they cannot be eliminated. We allow
// two casts to be inserted if the sizes are the same. This could
// only be converting signedness, which is a noop.
if (DestBitSize == SrcBitSize ||
!ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
!ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Instruction::CastOps opcode = CI.getOpcode();
Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
return BinaryOperator::create(
cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
}
}
// cast (xor bool X, true) to int --> xor (cast bool X to int), 1
if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
SrcI->getOpcode() == Instruction::Xor &&
Op1 == ConstantInt::getTrue() &&
(!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
}
break;
case Instruction::SDiv:
case Instruction::UDiv:
case Instruction::SRem:
case Instruction::URem:
// If we are just changing the sign, rewrite.
if (DestBitSize == SrcBitSize) {
// Don't insert two casts if they cannot be eliminated. We allow
// two casts to be inserted if the sizes are the same. This could
// only be converting signedness, which is a noop.
if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
!ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
Op0, DestTy, SrcI);
Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
Op1, DestTy, SrcI);
return BinaryOperator::create(
cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
}
}
break;
case Instruction::Shl:
// Allow changing the sign of the source operand. Do not allow
// changing the size of the shift, UNLESS the shift amount is a
// constant. We must not change variable sized shifts to a smaller
// size, because it is undefined to shift more bits out than exist
// in the value.
if (DestBitSize == SrcBitSize ||
(DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
Instruction::BitCast : Instruction::Trunc);
Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
return BinaryOperator::createShl(Op0c, Op1c);
}
break;
case Instruction::AShr:
// If this is a signed shr, and if all bits shifted in are about to be
// truncated off, turn it into an unsigned shr to allow greater
// simplifications.
if (DestBitSize < SrcBitSize &&
isa<ConstantInt>(Op1)) {
uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
// Insert the new logical shift right.
return BinaryOperator::createLShr(Op0, Op1);
}
}
break;
}
return 0;
}
Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
if (Instruction *Result = commonIntCastTransforms(CI))
return Result;
Value *Src = CI.getOperand(0);
const Type *Ty = CI.getType();
uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
switch (SrcI->getOpcode()) {
default: break;
case Instruction::LShr:
// We can shrink lshr to something smaller if we know the bits shifted in
// are already zeros.
if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
// Get a mask for the bits shifting in.
APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Value* SrcIOp0 = SrcI->getOperand(0);
if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
if (ShAmt >= DestBitWidth) // All zeros.
return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
// Okay, we can shrink this. Truncate the input, then return a new
// shift.
Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
Ty, CI);
return BinaryOperator::createLShr(V1, V2);
}
} else { // This is a variable shr.
// Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
// more LLVM instructions, but allows '1 << Y' to be hoisted if
// loop-invariant and CSE'd.
if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Value *One = ConstantInt::get(SrcI->getType(), 1);
Value *V = InsertNewInstBefore(
BinaryOperator::createShl(One, SrcI->getOperand(1),
"tmp"), CI);
V = InsertNewInstBefore(BinaryOperator::createAnd(V,
SrcI->getOperand(0),
"tmp"), CI);
Value *Zero = Constant::getNullValue(V->getType());
return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
}
}
break;
}
}
return 0;
}
/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
/// in order to eliminate the icmp.
Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
bool DoXform) {
// If we are just checking for a icmp eq of a single bit and zext'ing it
// to an integer, then shift the bit to the appropriate place and then
// cast to integer to avoid the comparison.
if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
const APInt &Op1CV = Op1C->getValue();
// zext (x <s 0) to i32 --> x>>u31 true if signbit set.
// zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
(ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
if (!DoXform) return ICI;
Value *In = ICI->getOperand(0);
Value *Sh = ConstantInt::get(In->getType(),
In->getType()->getPrimitiveSizeInBits()-1);
In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
In->getName()+".lobit"),
CI);
if (In->getType() != CI.getType())
In = CastInst::createIntegerCast(In, CI.getType(),
false/*ZExt*/, "tmp", &CI);
if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Constant *One = ConstantInt::get(In->getType(), 1);
In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
In->getName()+".not"),
CI);
}
return ReplaceInstUsesWith(CI, In);
}
// zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
// zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
// zext (X == 1) to i32 --> X iff X has only the low bit set.
// zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
// zext (X != 0) to i32 --> X iff X has only the low bit set.
// zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
// zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
// zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
// This only works for EQ and NE
ICI->isEquality()) {
// If Op1C some other power of two, convert:
uint32_t BitWidth = Op1C->getType()->getBitWidth();
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
APInt TypeMask(APInt::getAllOnesValue(BitWidth));
ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
APInt KnownZeroMask(~KnownZero);
if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
if (!DoXform) return ICI;
bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
// (X&4) == 2 --> false
// (X&4) != 2 --> true
Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Res = ConstantExpr::getZExt(Res, CI.getType());
return ReplaceInstUsesWith(CI, Res);
}
uint32_t ShiftAmt = KnownZeroMask.logBase2();
Value *In = ICI->getOperand(0);
if (ShiftAmt) {
// Perform a logical shr by shiftamt.
// Insert the shift to put the result in the low bit.
In = InsertNewInstBefore(BinaryOperator::createLShr(In,
ConstantInt::get(In->getType(), ShiftAmt),
In->getName()+".lobit"), CI);
}
if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Constant *One = ConstantInt::get(In->getType(), 1);
In = BinaryOperator::createXor(In, One, "tmp");
InsertNewInstBefore(cast<Instruction>(In), CI);
}
if (CI.getType() == In->getType())
return ReplaceInstUsesWith(CI, In);
else
return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
}
}
}
return 0;
}
Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
// If one of the common conversion will work ..
if (Instruction *Result = commonIntCastTransforms(CI))
return Result;
Value *Src = CI.getOperand(0);
// If this is a cast of a cast
if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
// If this is a TRUNC followed by a ZEXT then we are dealing with integral
// types and if the sizes are just right we can convert this into a logical
// 'and' which will be much cheaper than the pair of casts.
if (isa<TruncInst>(CSrc)) {
// Get the sizes of the types involved
Value *A = CSrc->getOperand(0);
uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
// If we're actually extending zero bits and the trunc is a no-op
if (MidSize < DstSize && SrcSize == DstSize) {
// Replace both of the casts with an And of the type mask.
APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Constant *AndConst = ConstantInt::get(AndValue);
Instruction *And =
BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
// Unfortunately, if the type changed, we need to cast it back.
if (And->getType() != CI.getType()) {
And->setName(CSrc->getName()+".mask");
InsertNewInstBefore(And, CI);
And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
}
return And;
}
}
}
if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
return transformZExtICmp(ICI, CI);
BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
if (SrcI && SrcI->getOpcode() == Instruction::Or) {
// zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
// of the (zext icmp) will be transformed.
ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
(transformZExtICmp(LHS, CI, false) ||
transformZExtICmp(RHS, CI, false))) {
Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
return BinaryOperator::create(Instruction::Or, LCast, RCast);
}
}
return 0;
}
Instruction *InstCombiner::visitSExt(SExtInst &CI) {
if (Instruction *I = commonIntCastTransforms(CI))
return I;
Value *Src = CI.getOperand(0);
// sext (x <s 0) -> ashr x, 31 -> all ones if signed
// sext (x >s -1) -> ashr x, 31 -> all ones if not signed
if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
// If we are just checking for a icmp eq of a single bit and zext'ing it
// to an integer, then shift the bit to the appropriate place and then
// cast to integer to avoid the comparison.
if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
const APInt &Op1CV = Op1C->getValue();
// sext (x <s 0) to i32 --> x>>s31 true if signbit set.
// sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
(ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
Value *In = ICI->getOperand(0);
Value *Sh = ConstantInt::get(In->getType(),
In->getType()->getPrimitiveSizeInBits()-1);
In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
In->getName()+".lobit"),
CI);
if (In->getType() != CI.getType())
In = CastInst::createIntegerCast(In, CI.getType(),
true/*SExt*/, "tmp", &CI);
if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
In = InsertNewInstBefore(BinaryOperator::createNot(In,
In->getName()+".not"), CI);
return ReplaceInstUsesWith(CI, In);
}
}
}
return 0;
}
/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
/// in the specified FP type without changing its value.
static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
APFloat F = CFP->getValueAPF();
if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
return ConstantFP::get(F);
return 0;
}
/// LookThroughFPExtensions - If this is an fp extension instruction, look
/// through it until we get the source value.
static Value *LookThroughFPExtensions(Value *V) {
if (Instruction *I = dyn_cast<Instruction>(V))
if (I->getOpcode() == Instruction::FPExt)
return LookThroughFPExtensions(I->getOperand(0));
// If this value is a constant, return the constant in the smallest FP type
// that can accurately represent it. This allows us to turn
// (float)((double)X+2.0) into x+2.0f.
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
if (CFP->getType() == Type::PPC_FP128Ty)
return V; // No constant folding of this.
// See if the value can be truncated to float and then reextended.
if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
return V;
if (CFP->getType() == Type::DoubleTy)
return V; // Won't shrink.
if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
return V;
// Don't try to shrink to various long double types.
}
return V;
}
Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
if (Instruction *I = commonCastTransforms(CI))
return I;
// If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
// smaller than the destination type, we can eliminate the truncate by doing
// the add as the smaller type. This applies to add/sub/mul/div as well as
// many builtins (sqrt, etc).
BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
if (OpI && OpI->hasOneUse()) {
switch (OpI->getOpcode()) {
default: break;
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
case Instruction::FDiv:
case Instruction::FRem:
const Type *SrcTy = OpI->getType();
Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
if (LHSTrunc->getType() != SrcTy &&
RHSTrunc->getType() != SrcTy) {
unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
// If the source types were both smaller than the destination type of
// the cast, do this xform.
if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
CI.getType(), CI);
RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
CI.getType(), CI);
return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
}
}
break;
}
}
return 0;
}
Instruction *InstCombiner::visitFPExt(CastInst &CI) {
return commonCastTransforms(CI);
}
Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
return commonCastTransforms(CI);
}
Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
return commonCastTransforms(CI);
}
Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
return commonCastTransforms(CI);
}
Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
return commonCastTransforms(CI);
}
Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
return commonPointerCastTransforms(CI);
}
Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
if (Instruction *I = commonCastTransforms(CI))
return I;
const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
if (!DestPointee->isSized()) return 0;
// If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
ConstantInt *Cst;
Value *X;
if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
m_ConstantInt(Cst)))) {
// If the source and destination operands have the same type, see if this
// is a single-index GEP.
if (X->getType() == CI.getType()) {
// Get the size of the pointee type.
uint64_t Size = TD->getABITypeSize(DestPointee);
// Convert the constant to intptr type.
APInt Offset = Cst->getValue();
Offset.sextOrTrunc(TD->getPointerSizeInBits());
// If Offset is evenly divisible by Size, we can do this xform.
if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
}
}
// TODO: Could handle other cases, e.g. where add is indexing into field of
// struct etc.
} else if (CI.getOperand(0)->hasOneUse() &&
match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
// Otherwise, if this is inttoptr(add x, cst), try to turn this into an
// "inttoptr+GEP" instead of "add+intptr".
// Get the size of the pointee type.
uint64_t Size = TD->getABITypeSize(DestPointee);
// Convert the constant to intptr type.
APInt Offset = Cst->getValue();
Offset.sextOrTrunc(TD->getPointerSizeInBits());
// If Offset is evenly divisible by Size, we can do this xform.
if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
"tmp"), CI);
return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
}
}
return 0;
}
Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
// If the operands are integer typed then apply the integer transforms,
// otherwise just apply the common ones.
Value *Src = CI.getOperand(0);
const Type *SrcTy = Src->getType();
const Type *DestTy = CI.getType();
if (SrcTy->isInteger() && DestTy->isInteger()) {
if (Instruction *Result = commonIntCastTransforms(CI))
return Result;
} else if (isa<PointerType>(SrcTy)) {
if (Instruction *I = commonPointerCastTransforms(CI))
return I;
} else {
if (Instruction *Result = commonCastTransforms(CI))
return Result;
}
// Get rid of casts from one type to the same type. These are useless and can
// be replaced by the operand.
if (DestTy == Src->getType())
return ReplaceInstUsesWith(CI, Src);
if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
const PointerType *SrcPTy = cast<PointerType>(SrcTy);
const Type *DstElTy = DstPTy->getElementType();
const Type *SrcElTy = SrcPTy->getElementType();
// If the address spaces don't match, don't eliminate the bitcast, which is
// required for changing types.
if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
return 0;
// If we are casting a malloc or alloca to a pointer to a type of the same
// size, rewrite the allocation instruction to allocate the "right" type.
if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
return V;
// If the source and destination are pointers, and this cast is equivalent
// to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
// This can enhance SROA and other transforms that want type-safe pointers.
Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
unsigned NumZeros = 0;
while (SrcElTy != DstElTy &&
isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
SrcElTy->getNumContainedTypes() /* not "{}" */) {
SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
++NumZeros;
}
// If we found a path from the src to dest, create the getelementptr now.
if (SrcElTy == DstElTy) {
SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
((Instruction*) NULL));
}
}
if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
if (SVI->hasOneUse()) {
// Okay, we have (bitconvert (shuffle ..)). Check to see if this is
// a bitconvert to a vector with the same # elts.
if (isa<VectorType>(DestTy) &&
cast<VectorType>(DestTy)->getNumElements() ==
SVI->getType()->getNumElements()) {
CastInst *Tmp;
// If either of the operands is a cast from CI.getType(), then
// evaluating the shuffle in the casted destination's type will allow
// us to eliminate at least one cast.
if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
Tmp->getOperand(0)->getType() == DestTy) ||
((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Tmp->getOperand(0)->getType() == DestTy)) {
Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
SVI->getOperand(0), DestTy, &CI);
Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
SVI->getOperand(1), DestTy, &CI);
// Return a new shuffle vector. Use the same element ID's, as we
// know the vector types match #elts.
return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
}
}
}
}
return 0;
}
/// GetSelectFoldableOperands - We want to turn code that looks like this:
/// %C = or %A, %B
/// %D = select %cond, %C, %A
/// into:
/// %C = select %cond, %B, 0
/// %D = or %A, %C
///
/// Assuming that the specified instruction is an operand to the select, return
/// a bitmask indicating which operands of this instruction are foldable if they
/// equal the other incoming value of the select.
///
static unsigned GetSelectFoldableOperands(Instruction *I) {
switch (I->getOpcode()) {
case Instruction::Add:
case Instruction::Mul:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
return 3; // Can fold through either operand.
case Instruction::Sub: // Can only fold on the amount subtracted.
case Instruction::Shl: // Can only fold on the shift amount.
case Instruction::LShr:
case Instruction::AShr:
return 1;
default:
return 0; // Cannot fold
}
}
/// GetSelectFoldableConstant - For the same transformation as the previous
/// function, return the identity constant that goes into the select.
static Constant *GetSelectFoldableConstant(Instruction *I) {
switch (I->getOpcode()) {
default: assert(0 && "This cannot happen!"); abort();
case Instruction::Add:
case Instruction::Sub:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
return Constant::getNullValue(I->getType());
case Instruction::And:
return Constant::getAllOnesValue(I->getType());
case Instruction::Mul:
return ConstantInt::get(I->getType(), 1);
}
}
/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
/// have the same opcode and only one use each. Try to simplify this.
Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
Instruction *FI) {
if (TI->getNumOperands() == 1) {
// If this is a non-volatile load or a cast from the same type,
// merge.
if (TI->isCast()) {
if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
return 0;
} else {
return 0; // unknown unary op.
}
// Fold this by inserting a select from the input values.
SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
FI->getOperand(0), SI.getName()+".v");
InsertNewInstBefore(NewSI, SI);
return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
TI->getType());
}
// Only handle binary operators here.
if (!isa<BinaryOperator>(TI))
return 0;
// Figure out if the operations have any operands in common.
Value *MatchOp, *OtherOpT, *OtherOpF;
bool MatchIsOpZero;
if (TI->getOperand(0) == FI->getOperand(0)) {
MatchOp = TI->getOperand(0);
OtherOpT = TI->getOperand(1);
OtherOpF = FI->getOperand(1);
MatchIsOpZero = true;
} else if (TI->getOperand(1) == FI->getOperand(1)) {
MatchOp = TI->getOperand(1);
OtherOpT = TI->getOperand(0);
OtherOpF = FI->getOperand(0);
MatchIsOpZero = false;
} else if (!TI->isCommutative()) {
return 0;
} else if (TI->getOperand(0) == FI->getOperand(1)) {
MatchOp = TI->getOperand(0);
OtherOpT = TI->getOperand(1);
OtherOpF = FI->getOperand(0);
MatchIsOpZero = true;
} else if (TI->getOperand(1) == FI->getOperand(0)) {
MatchOp = TI->getOperand(1);
OtherOpT = TI->getOperand(0);
OtherOpF = FI->getOperand(1);
MatchIsOpZero = true;
} else {
return 0;
}
// If we reach here, they do have operations in common.
SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
OtherOpF, SI.getName()+".v");
InsertNewInstBefore(NewSI, SI);
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
if (MatchIsOpZero)
return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
else
return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
}
assert(0 && "Shouldn't get here");
return 0;
}
Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Value *CondVal = SI.getCondition();
Value *TrueVal = SI.getTrueValue();
Value *FalseVal = SI.getFalseValue();
// select true, X, Y -> X
// select false, X, Y -> Y
if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
// select C, X, X -> X
if (TrueVal == FalseVal)
return ReplaceInstUsesWith(SI, TrueVal);
if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
return ReplaceInstUsesWith(SI, FalseVal);
if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
return ReplaceInstUsesWith(SI, TrueVal);
if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
if (isa<Constant>(TrueVal))
return ReplaceInstUsesWith(SI, TrueVal);
else
return ReplaceInstUsesWith(SI, FalseVal);
}
if (SI.getType() == Type::Int1Ty) {
if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
if (C->getZExtValue()) {
// Change: A = select B, true, C --> A = or B, C
return BinaryOperator::createOr(CondVal, FalseVal);
} else {
// Change: A = select B, false, C --> A = and !B, C
Value *NotCond =
InsertNewInstBefore(BinaryOperator::createNot(CondVal,
"not."+CondVal->getName()), SI);
return BinaryOperator::createAnd(NotCond, FalseVal);
}
} else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
if (C->getZExtValue() == false) {
// Change: A = select B, C, false --> A = and B, C
return BinaryOperator::createAnd(CondVal, TrueVal);
} else {
// Change: A = select B, C, true --> A = or !B, C
Value *NotCond =
InsertNewInstBefore(BinaryOperator::createNot(CondVal,
"not."+CondVal->getName()), SI);
return BinaryOperator::createOr(NotCond, TrueVal);
}
}
// select a, b, a -> a&b
// select a, a, b -> a|b
if (CondVal == TrueVal)
return BinaryOperator::createOr(CondVal, FalseVal);
else if (CondVal == FalseVal)
return BinaryOperator::createAnd(CondVal, TrueVal);
}
// Selecting between two integer constants?
if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
// select C, 1, 0 -> zext C to int
if (FalseValC->isZero() && TrueValC->getValue() == 1) {
return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
} else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
// select C, 0, 1 -> zext !C to int
Value *NotCond =
InsertNewInstBefore(BinaryOperator::createNot(CondVal,
"not."+CondVal->getName()), SI);
return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
}
// FIXME: Turn select 0/-1 and -1/0 into sext from condition!
if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
// (x <s 0) ? -1 : 0 -> ashr x, 31
if (TrueValC->isAllOnesValue() && FalseValC->isZero())
if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
// The comparison constant and the result are not neccessarily the
// same width. Make an all-ones value by inserting a AShr.
Value *X = IC->getOperand(0);
uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
ShAmt, "ones");
InsertNewInstBefore(SRA, SI);
// Finally, convert to the type of the select RHS. We figure out
// if this requires a SExt, Trunc or BitCast based on the sizes.
Instruction::CastOps opc = Instruction::BitCast;
uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
if (SRASize < SISize)
opc = Instruction::SExt;
else if (SRASize > SISize)
opc = Instruction::Trunc;
return CastInst::create(opc, SRA, SI.getType());
}
}
// If one of the constants is zero (we know they can't both be) and we
// have an icmp instruction with zero, and we have an 'and' with the
// non-constant value, eliminate this whole mess. This corresponds to
// cases like this: ((X & 27) ? 27 : 0)
if (TrueValC->isZero() || FalseValC->isZero())
if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
cast<Constant>(IC->getOperand(1))->isNullValue())
if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
if (ICA->getOpcode() == Instruction::And &&
isa<ConstantInt>(ICA->getOperand(1)) &&
(ICA->getOperand(1) == TrueValC ||
ICA->getOperand(1) == FalseValC) &&
isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
// Okay, now we know that everything is set up, we just don't
// know whether we have a icmp_ne or icmp_eq and whether the
// true or false val is the zero.
bool ShouldNotVal = !TrueValC->isZero();
ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Value *V = ICA;
if (ShouldNotVal)
V = InsertNewInstBefore(BinaryOperator::create(
Instruction::Xor, V, ICA->getOperand(1)), SI);
return ReplaceInstUsesWith(SI, V);
}
}
}
// See if we are selecting two values based on a comparison of the two values.
if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
// Transform (X == Y) ? X : Y -> Y
if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
// This is not safe in general for floating point:
// consider X== -0, Y== +0.
// It becomes safe if either operand is a nonzero constant.
ConstantFP *CFPt, *CFPf;
if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
!CFPt->getValueAPF().isZero()) ||
((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
!CFPf->getValueAPF().isZero()))
return ReplaceInstUsesWith(SI, FalseVal);
}
// Transform (X != Y) ? X : Y -> X
if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
return ReplaceInstUsesWith(SI, TrueVal);
// NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
} else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
// Transform (X == Y) ? Y : X -> X
if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
// This is not safe in general for floating point:
// consider X== -0, Y== +0.
// It becomes safe if either operand is a nonzero constant.
ConstantFP *CFPt, *CFPf;
if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
!CFPt->getValueAPF().isZero()) ||
((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
!CFPf->getValueAPF().isZero()))
return ReplaceInstUsesWith(SI, FalseVal);
}
// Transform (X != Y) ? Y : X -> Y
if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
return ReplaceInstUsesWith(SI, TrueVal);
// NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
}
}
// See if we are selecting two values based on a comparison of the two values.
if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
// Transform (X == Y) ? X : Y -> Y
if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
return ReplaceInstUsesWith(SI, FalseVal);
// Transform (X != Y) ? X : Y -> X
if (ICI->getPredicate() == ICmpInst::ICMP_NE)
return ReplaceInstUsesWith(SI, TrueVal);
// NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
} else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
// Transform (X == Y) ? Y : X -> X
if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
return ReplaceInstUsesWith(SI, FalseVal);
// Transform (X != Y) ? Y : X -> Y
if (ICI->getPredicate() == ICmpInst::ICMP_NE)
return ReplaceInstUsesWith(SI, TrueVal);
// NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
}
}
if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
if (TI->hasOneUse() && FI->hasOneUse()) {
Instruction *AddOp = 0, *SubOp = 0;
// Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
if (TI->getOpcode() == FI->getOpcode())
if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
return IV;
// Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
// even legal for FP.
if (TI->getOpcode() == Instruction::Sub &&
FI->getOpcode() == Instruction::Add) {
AddOp = FI; SubOp = TI;
} else if (FI->getOpcode() == Instruction::Sub &&
TI->getOpcode() == Instruction::Add) {
AddOp = TI; SubOp = FI;
}
if (AddOp) {
Value *OtherAddOp = 0;
if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
OtherAddOp = AddOp->getOperand(1);
} else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
OtherAddOp = AddOp->getOperand(0);
}
if (OtherAddOp) {
// So at this point we know we have (Y -> OtherAddOp):
// select C, (add X, Y), (sub X, Z)
Value *NegVal; // Compute -Z
if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
NegVal = ConstantExpr::getNeg(C);
} else {
NegVal = InsertNewInstBefore(
BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
}
Value *NewTrueOp = OtherAddOp;
Value *NewFalseOp = NegVal;
if (AddOp != TI)
std::swap(NewTrueOp, NewFalseOp);
Instruction *NewSel =
SelectInst::Create(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
NewSel = InsertNewInstBefore(NewSel, SI);
return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
}
}
}
// See if we can fold the select into one of our operands.
if (SI.getType()->isInteger()) {
// See the comment above GetSelectFoldableOperands for a description of the
// transformation we are doing here.
if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
!isa<Constant>(FalseVal))
if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
unsigned OpToFold = 0;
if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
OpToFold = 1;
} else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
OpToFold = 2;
}
if (OpToFold) {
Constant *C = GetSelectFoldableConstant(TVI);
Instruction *NewSel =
SelectInst::Create(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
InsertNewInstBefore(NewSel, SI);
NewSel->takeName(TVI);
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
else {
assert(0 && "Unknown instruction!!");
}
}
}
if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
!isa<Constant>(TrueVal))
if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
unsigned OpToFold = 0;
if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
OpToFold = 1;
} else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
OpToFold = 2;
}
if (OpToFold) {
Constant *C = GetSelectFoldableConstant(FVI);
Instruction *NewSel =
SelectInst::Create(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
InsertNewInstBefore(NewSel, SI);
NewSel->takeName(FVI);
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
else
assert(0 && "Unknown instruction!!");
}
}
}
if (BinaryOperator::isNot(CondVal)) {
SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
SI.setOperand(1, FalseVal);
SI.setOperand(2, TrueVal);
return &SI;
}
return 0;
}
/// EnforceKnownAlignment - If the specified pointer points to an object that
/// we control, modify the object's alignment to PrefAlign. This isn't
/// often possible though. If alignment is important, a more reliable approach
/// is to simply align all global variables and allocation instructions to
/// their preferred alignment from the beginning.
///
static unsigned EnforceKnownAlignment(Value *V,
unsigned Align, unsigned PrefAlign) {
User *U = dyn_cast<User>(V);
if (!U) return Align;
switch (getOpcode(U)) {
default: break;
case Instruction::BitCast:
return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
case Instruction::GetElementPtr: {
// If all indexes are zero, it is just the alignment of the base pointer.
bool AllZeroOperands = true;
for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
if (!isa<Constant>(U->getOperand(i)) ||
!cast<Constant>(U->getOperand(i))->isNullValue()) {
AllZeroOperands = false;
break;
}
if (AllZeroOperands) {
// Treat this like a bitcast.
return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
}
break;
}
}
if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
// If there is a large requested alignment and we can, bump up the alignment
// of the global.
if (!GV->isDeclaration()) {
GV->setAlignment(PrefAlign);
Align = PrefAlign;
}
} else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
// If there is a requested alignment and if this is an alloca, round up. We
// don't do this for malloc, because some systems can't respect the request.
if (isa<AllocaInst>(AI)) {
AI->setAlignment(PrefAlign);
Align = PrefAlign;
}
}
return Align;
}
/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
/// and it is more than the alignment of the ultimate object, see if we can
/// increase the alignment of the ultimate object, making this check succeed.
unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
unsigned PrefAlign) {
unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
sizeof(PrefAlign) * CHAR_BIT;
APInt Mask = APInt::getAllOnesValue(BitWidth);
APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
unsigned TrailZ = KnownZero.countTrailingOnes();
unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
if (PrefAlign > Align)
Align = EnforceKnownAlignment(V, Align, PrefAlign);
// We don't need to make any adjustment.
return Align;
}
Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
unsigned MinAlign = std::min(DstAlign, SrcAlign);
unsigned CopyAlign = MI->getAlignment()->getZExtValue();
if (CopyAlign < MinAlign) {
MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
return MI;
}
// If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
// load/store.
ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
if (MemOpLength == 0) return 0;
// Source and destination pointer types are always "i8*" for intrinsic. See
// if the size is something we can handle with a single primitive load/store.
// A single load+store correctly handles overlapping memory in the memmove
// case.
unsigned Size = MemOpLength->getZExtValue();
if (Size == 0) return MI; // Delete this mem transfer.
if (Size > 8 || (Size&(Size-1)))
return 0; // If not 1/2/4/8 bytes, exit.
// Use an integer load+store unless we can find something better.
Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
// Memcpy forces the use of i8* for the source and destination. That means
// that if you're using memcpy to move one double around, you'll get a cast
// from double* to i8*. We'd much rather use a double load+store rather than
// an i64 load+store, here because this improves the odds that the source or
// dest address will be promotable. See if we can find a better type than the
// integer datatype.
if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
// The SrcETy might be something like {{{double}}} or [1 x double]. Rip
// down through these levels if so.
while (!SrcETy->isFirstClassType()) {
if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
if (STy->getNumElements() == 1)
SrcETy = STy->getElementType(0);
else
break;
} else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
if (ATy->getNumElements() == 1)
SrcETy = ATy->getElementType();
else
break;
} else
break;
}
if (SrcETy->isFirstClassType())
NewPtrTy = PointerType::getUnqual(SrcETy);
}
}
// If the memcpy/memmove provides better alignment info than we can
// infer, use it.
SrcAlign = std::max(SrcAlign, CopyAlign);
DstAlign = std::max(DstAlign, CopyAlign);
Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
InsertNewInstBefore(L, *MI);
InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
// Set the size of the copy to 0, it will be deleted on the next iteration.
MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
return MI;
}
Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
if (MI->getAlignment()->getZExtValue() < Alignment) {
MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
return MI;
}
// Extract the length and alignment and fill if they are constant.
ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
return 0;
uint64_t Len = LenC->getZExtValue();
Alignment = MI->getAlignment()->getZExtValue();
// If the length is zero, this is a no-op
if (Len == 0) return MI; // memset(d,c,0,a) -> noop
// memset(s,c,n) -> store s, c (for n=1,2,4,8)
if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
Value *Dest = MI->getDest();
Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
// Alignment 0 is identity for alignment 1 for memset, but not store.
if (Alignment == 0) Alignment = 1;
// Extract the fill value and store.
uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
Alignment), *MI);
// Set the size of the copy to 0, it will be deleted on the next iteration.
MI->setLength(Constant::getNullValue(LenC->getType()));
return MI;
}
return 0;
}
/// visitCallInst - CallInst simplification. This mostly only handles folding
/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
/// the heavy lifting.
///
Instruction *InstCombiner::visitCallInst(CallInst &CI) {
IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
if (!II) return visitCallSite(&CI);
// Intrinsics cannot occur in an invoke, so handle them here instead of in
// visitCallSite.
if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
bool Changed = false;
// memmove/cpy/set of zero bytes is a noop.
if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
if (CI->getZExtValue() == 1) {
// Replace the instruction with just byte operations. We would
// transform other cases to loads/stores, but we don't know if
// alignment is sufficient.
}
}
// If we have a memmove and the source operation is a constant global,
// then the source and dest pointers can't alias, so we can change this
// into a call to memcpy.
if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
if (GVSrc->isConstant()) {
Module *M = CI.getParent()->getParent()->getParent();
Intrinsic::ID MemCpyID;
if (CI.getOperand(3)->getType() == Type::Int32Ty)
MemCpyID = Intrinsic::memcpy_i32;
else
MemCpyID = Intrinsic::memcpy_i64;
CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Changed = true;
}
}
// If we can determine a pointer alignment that is bigger than currently
// set, update the alignment.
if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
if (Instruction *I = SimplifyMemTransfer(MI))
return I;
} else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
if (Instruction *I = SimplifyMemSet(MSI))
return I;
}
if (Changed) return II;
} else {
switch (II->getIntrinsicID()) {
default: break;
case Intrinsic::ppc_altivec_lvx:
case Intrinsic::ppc_altivec_lvxl:
case Intrinsic::x86_sse_loadu_ps:
case Intrinsic::x86_sse2_loadu_pd:
case Intrinsic::x86_sse2_loadu_dq:
// Turn PPC lvx -> load if the pointer is known aligned.
// Turn X86 loadups -> load if the pointer is known aligned.
if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Value *Ptr = InsertBitCastBefore(II->getOperand(1),
PointerType::getUnqual(II->getType()),
CI);
return new LoadInst(Ptr);
}
break;
case Intrinsic::ppc_altivec_stvx:
case Intrinsic::ppc_altivec_stvxl:
// Turn stvx -> store if the pointer is known aligned.
if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
const Type *OpPtrTy =
PointerType::getUnqual(II->getOperand(1)->getType());
Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
return new StoreInst(II->getOperand(1), Ptr);
}
break;
case Intrinsic::x86_sse_storeu_ps:
case Intrinsic::x86_sse2_storeu_pd:
case Intrinsic::x86_sse2_storeu_dq:
case Intrinsic::x86_sse2_storel_dq:
// Turn X86 storeu -> store if the pointer is known aligned.
if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
const Type *OpPtrTy =
PointerType::getUnqual(II->getOperand(2)->getType());
Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
return new StoreInst(II->getOperand(2), Ptr);
}
break;
case Intrinsic::x86_sse_cvttss2si: {
// These intrinsics only demands the 0th element of its input vector. If
// we can simplify the input based on that, do so now.
uint64_t UndefElts;
if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
UndefElts)) {
II->setOperand(1, V);
return II;
}
break;
}
case Intrinsic::ppc_altivec_vperm:
// Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
// Check that all of the elements are integer constants or undefs.
bool AllEltsOk = true;
for (unsigned i = 0; i != 16; ++i) {
if (!isa<ConstantInt>(Mask->getOperand(i)) &&
!isa<UndefValue>(Mask->getOperand(i))) {
AllEltsOk = false;
break;
}
}
if (AllEltsOk) {
// Cast the input vectors to byte vectors.
Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Value *Result = UndefValue::get(Op0->getType());
// Only extract each element once.
Value *ExtractedElts[32];
memset(ExtractedElts, 0, sizeof(ExtractedElts));
for (unsigned i = 0; i != 16; ++i) {
if (isa<UndefValue>(Mask->getOperand(i)))
continue;
unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Idx &= 31; // Match the hardware behavior.
if (ExtractedElts[Idx] == 0) {
Instruction *Elt =
new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
InsertNewInstBefore(Elt, CI);
ExtractedElts[Idx] = Elt;
}
// Insert this value into the result vector.
Result = InsertElementInst::Create(Result, ExtractedElts[Idx], i, "tmp");
InsertNewInstBefore(cast<Instruction>(Result), CI);
}
return CastInst::create(Instruction::BitCast, Result, CI.getType());
}
}
break;
case Intrinsic::stackrestore: {
// If the save is right next to the restore, remove the restore. This can
// happen when variable allocas are DCE'd.
if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
if (SS->getIntrinsicID() == Intrinsic::stacksave) {
BasicBlock::iterator BI = SS;
if (&*++BI == II)
return EraseInstFromFunction(CI);
}
}
// Scan down this block to see if there is another stack restore in the
// same block without an intervening call/alloca.
BasicBlock::iterator BI = II;
TerminatorInst *TI = II->getParent()->getTerminator();
bool CannotRemove = false;
for (++BI; &*BI != TI; ++BI) {
if (isa<AllocaInst>(BI)) {
CannotRemove = true;
break;
}
if (isa<CallInst>(BI)) {
if (!isa<IntrinsicInst>(BI)) {
CannotRemove = true;
break;
}
// If there is a stackrestore below this one, remove this one.
return EraseInstFromFunction(CI);
}
}
// If the stack restore is in a return/unwind block and if there are no
// allocas or calls between the restore and the return, nuke the restore.
if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
return EraseInstFromFunction(CI);
break;
}
}
}
return visitCallSite(II);
}
// InvokeInst simplification
//
Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
return visitCallSite(&II);
}
/// isSafeToEliminateVarargsCast - If this cast does not affect the value
/// passed through the varargs area, we can eliminate the use of the cast.
static bool isSafeToEliminateVarargsCast(const CallSite CS,
const CastInst * const CI,
const TargetData * const TD,
const int ix) {
if (!CI->isLosslessCast())
return false;
// The size of ByVal arguments is derived from the type, so we
// can't change to a type with a different size. If the size were
// passed explicitly we could avoid this check.
if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
return true;
const Type* SrcTy =
cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
if (!SrcTy->isSized() || !DstTy->isSized())
return false;
if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
return false;
return true;
}
// visitCallSite - Improvements for call and invoke instructions.
//
Instruction *InstCombiner::visitCallSite(CallSite CS) {
bool Changed = false;
// If the callee is a constexpr cast of a function, attempt to move the cast
// to the arguments of the call/invoke.
if (transformConstExprCastCall(CS)) return 0;
Value *Callee = CS.getCalledValue();
if (Function *CalleeF = dyn_cast<Function>(Callee))
if (CalleeF->getCallingConv() != CS.getCallingConv()) {
Instruction *OldCall = CS.getInstruction();
// If the call and callee calling conventions don't match, this call must
// be unreachable, as the call is undefined.
new StoreInst(ConstantInt::getTrue(),
UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
OldCall);
if (!OldCall->use_empty())
OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
return EraseInstFromFunction(*OldCall);
return 0;
}
if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
// This instruction is not reachable, just remove it. We insert a store to
// undef so that we know that this code is not reachable, despite the fact
// that we can't modify the CFG here.
new StoreInst(ConstantInt::getTrue(),
UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
CS.getInstruction());
if (!CS.getInstruction()->use_empty())
CS.getInstruction()->
replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
// Don't break the CFG, insert a dummy cond branch.
BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
ConstantInt::getTrue(), II);
}
return EraseInstFromFunction(*CS.getInstruction());
}
if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
if (In->getIntrinsicID() == Intrinsic::init_trampoline)
return transformCallThroughTrampoline(CS);
const PointerType *PTy = cast<PointerType>(Callee->getType());
const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
if (FTy->isVarArg()) {
int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
// See if we can optimize any arguments passed through the varargs area of
// the call.
for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
E = CS.arg_end(); I != E; ++I, ++ix) {
CastInst *CI = dyn_cast<CastInst>(*I);
if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
*I = CI->getOperand(0);
Changed = true;
}
}
}
if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
// Inline asm calls cannot throw - mark them 'nounwind'.
CS.setDoesNotThrow();
Changed = true;
}
return Changed ? CS.getInstruction() : 0;
}
// transformConstExprCastCall - If the callee is a constexpr cast of a function,
// attempt to move the cast to the arguments of the call/invoke.
//
bool InstCombiner::transformConstExprCastCall(CallSite CS) {
if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
if (CE->getOpcode() != Instruction::BitCast ||
!isa<Function>(CE->getOperand(0)))
return false;
Function *Callee = cast<Function>(CE->getOperand(0));
Instruction *Caller = CS.getInstruction();
const PAListPtr &CallerPAL = CS.getParamAttrs();
// Okay, this is a cast from a function to a different type. Unless doing so
// would cause a type conversion of one of our arguments, change this call to
// be a direct call with arguments casted to the appropriate types.
//
const FunctionType *FT = Callee->getFunctionType();
const Type *OldRetTy = Caller->getType();
if (isa<StructType>(FT->getReturnType()))
return false; // TODO: Handle multiple return values.
// Check to see if we are changing the return type...
if (OldRetTy != FT->getReturnType()) {
if (Callee->isDeclaration() && !Caller->use_empty() &&
// Conversion is ok if changing from pointer to int of same size.
!(isa<PointerType>(FT->getReturnType()) &&
TD->getIntPtrType() == OldRetTy))
return false; // Cannot transform this return value.
if (!Caller->use_empty() &&
// void -> non-void is handled specially
FT->getReturnType() != Type::VoidTy &&
!CastInst::isCastable(FT->getReturnType(), OldRetTy))
return false; // Cannot transform this return value.
if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
return false; // Attribute not compatible with transformed value.
}
// If the callsite is an invoke instruction, and the return value is used by
// a PHI node in a successor, we cannot change the return type of the call
// because there is no place to put the cast instruction (without breaking
// the critical edge). Bail out in this case.
if (!Caller->use_empty())
if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
UI != E; ++UI)
if (PHINode *PN = dyn_cast<PHINode>(*UI))
if (PN->getParent() == II->getNormalDest() ||
PN->getParent() == II->getUnwindDest())
return false;
}
unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
CallSite::arg_iterator AI = CS.arg_begin();
for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
const Type *ParamTy = FT->getParamType(i);
const Type *ActTy = (*AI)->getType();
if (!CastInst::isCastable(ActTy, ParamTy))
return false; // Cannot transform this parameter value.
if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
return false; // Attribute not compatible with transformed value.
ConstantInt *c = dyn_cast<ConstantInt>(*AI);
// Some conversions are safe even if we do not have a body.
// Either we can cast directly, or we can upconvert the argument
bool isConvertible = ActTy == ParamTy ||
(isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
(ParamTy->isInteger() && ActTy->isInteger() &&
ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
(c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
&& c->getValue().isStrictlyPositive());
if (Callee->isDeclaration() && !isConvertible) return false;
}
if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Callee->isDeclaration())
return false; // Do not delete arguments unless we have a function body.
if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
!CallerPAL.isEmpty())
// In this case we have more arguments than the new function type, but we
// won't be dropping them. Check that these extra arguments have attributes
// that are compatible with being a vararg call argument.
for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
break;
ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
if (PAttrs & ParamAttr::VarArgsIncompatible)
return false;
}
// Okay, we decided that this is a safe thing to do: go ahead and start
// inserting cast instructions as necessary...
std::vector<Value*> Args;
Args.reserve(NumActualArgs);
SmallVector<ParamAttrsWithIndex, 8> attrVec;
attrVec.reserve(NumCommonArgs);
// Get any return attributes.
ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
// If the return value is not being used, the type may not be compatible
// with the existing attributes. Wipe out any problematic attributes.
RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
// Add the new return attributes.
if (RAttrs)
attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
AI = CS.arg_begin();
for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
const Type *ParamTy = FT->getParamType(i);
if ((*AI)->getType() == ParamTy) {
Args.push_back(*AI);
} else {
Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
false, ParamTy, false);
CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Args.push_back(InsertNewInstBefore(NewCast, *Caller));
}
// Add any parameter attributes.
if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
}
// If the function takes more arguments than the call was taking, add them
// now...
for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Args.push_back(Constant::getNullValue(FT->getParamType(i)));
// If we are removing arguments to the function, emit an obnoxious warning...
if (FT->getNumParams() < NumActualArgs) {
if (!FT->isVarArg()) {
cerr << "WARNING: While resolving call to function '"
<< Callee->getName() << "' arguments were dropped!\n";
} else {
// Add all of the arguments in their promoted form to the arg list...
for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
const Type *PTy = getPromotedType((*AI)->getType());
if (PTy != (*AI)->getType()) {
// Must promote to pass through va_arg area!
Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
PTy, false);
Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
InsertNewInstBefore(Cast, *Caller);
Args.push_back(Cast);
} else {
Args.push_back(*AI);
}
// Add any parameter attributes.
if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
}
}
}
if (FT->getReturnType() == Type::VoidTy)
Caller->setName(""); // Void type should not have a name.
const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Instruction *NC;
if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Args.begin(), Args.end(), Caller->getName(), Caller);
cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
} else {
NC = CallInst::Create(Callee, Args.begin(), Args.end(),
Caller->getName(), Caller);
CallInst *CI = cast<CallInst>(Caller);
if (CI->isTailCall())
cast<CallInst>(NC)->setTailCall();
cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
}
// Insert a cast of the return type as necessary.
Value *NV = NC;
if (OldRetTy != NV->getType() && !Caller->use_empty()) {
if (NV->getType() != Type::VoidTy) {
Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
OldRetTy, false);
NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
// If this is an invoke instruction, we should insert it after the first
// non-phi, instruction in the normal successor block.
if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
BasicBlock::iterator I = II->getNormalDest()->begin();
while (isa<PHINode>(I)) ++I;
InsertNewInstBefore(NC, *I);
} else {
// Otherwise, it's a call, just insert cast right after the call instr
InsertNewInstBefore(NC, *Caller);
}
AddUsersToWorkList(*Caller);
} else {
NV = UndefValue::get(Caller->getType());
}
}
if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
Caller->replaceAllUsesWith(NV);
Caller->eraseFromParent();
RemoveFromWorkList(Caller);
return true;
}
// transformCallThroughTrampoline - Turn a call to a function created by the
// init_trampoline intrinsic into a direct call to the underlying function.
//
Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
Value *Callee = CS.getCalledValue();
const PointerType *PTy = cast<PointerType>(Callee->getType());
const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
const PAListPtr &Attrs = CS.getParamAttrs();
// If the call already has the 'nest' attribute somewhere then give up -
// otherwise 'nest' would occur twice after splicing in the chain.
if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
return 0;
IntrinsicInst *Tramp =
cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
const PAListPtr &NestAttrs = NestF->getParamAttrs();
if (!NestAttrs.isEmpty()) {
unsigned NestIdx = 1;
const Type *NestTy = 0;
ParameterAttributes NestAttr = ParamAttr::None;
// Look for a parameter marked with the 'nest' attribute.
for (FunctionType::param_iterator I = NestFTy->param_begin(),
E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
// Record the parameter type and any other attributes.
NestTy = *I;
NestAttr = NestAttrs.getParamAttrs(NestIdx);
break;
}
if (NestTy) {
Instruction *Caller = CS.getInstruction();
std::vector<Value*> NewArgs;
NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
NewAttrs.reserve(Attrs.getNumSlots() + 1);
// Insert the nest argument into the call argument list, which may
// mean appending it. Likewise for attributes.
// Add any function result attributes.
if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
{
unsigned Idx = 1;
CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
do {
if (Idx == NestIdx) {
// Add the chain argument and attributes.
Value *NestVal = Tramp->getOperand(3);
if (NestVal->getType() != NestTy)
NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
NewArgs.push_back(NestVal);
NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
}
if (I == E)
break;
// Add the original argument and attributes.
NewArgs.push_back(*I);
if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
NewAttrs.push_back
(ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
++Idx, ++I;
} while (1);
}
// The trampoline may have been bitcast to a bogus type (FTy).
// Handle this by synthesizing a new function type, equal to FTy
// with the chain parameter inserted.
std::vector<const Type*> NewTypes;
NewTypes.reserve(FTy->getNumParams()+1);
// Insert the chain's type into the list of parameter types, which may
// mean appending it.
{
unsigned Idx = 1;
FunctionType::param_iterator I = FTy->param_begin(),
E = FTy->param_end();
do {
if (Idx == NestIdx)
// Add the chain's type.
NewTypes.push_back(NestTy);
if (I == E)
break;
// Add the original type.
NewTypes.push_back(*I);
++Idx, ++I;
} while (1);
}
// Replace the trampoline call with a direct call. Let the generic
// code sort out any function type mismatches.
FunctionType *NewFTy =
FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Instruction *NewCaller;
if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
NewCaller = InvokeInst::Create(NewCallee,
II->getNormalDest(), II->getUnwindDest(),
NewArgs.begin(), NewArgs.end(),
Caller->getName(), Caller);
cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
} else {
NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
Caller->getName(), Caller);
if (cast<CallInst>(Caller)->isTailCall())
cast<CallInst>(NewCaller)->setTailCall();
cast<CallInst>(NewCaller)->
setCallingConv(cast<CallInst>(Caller)->getCallingConv());
cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
}
if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
Caller->replaceAllUsesWith(NewCaller);
Caller->eraseFromParent();
RemoveFromWorkList(Caller);
return 0;
}
}
// Replace the trampoline call with a direct call. Since there is no 'nest'
// parameter, there is no need to adjust the argument list. Let the generic
// code sort out any function type mismatches.
Constant *NewCallee =
NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
CS.setCalledFunction(NewCallee);
return CS.getInstruction();
}
/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
/// and a single binop.
Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
isa<CmpInst>(FirstInst));
unsigned Opc = FirstInst->getOpcode();
Value *LHSVal = FirstInst->getOperand(0);
Value *RHSVal = FirstInst->getOperand(1);
const Type *LHSType = LHSVal->getType();
const Type *RHSType = RHSVal->getType();
// Scan to see if all operands are the same opcode, all have one use, and all
// kill their operands (i.e. the operands have one use).
for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
// Verify type of the LHS matches so we don't fold cmp's of different
// types or GEP's with different index types.
I->getOperand(0)->getType() != LHSType ||
I->getOperand(1)->getType() != RHSType)
return 0;
// If they are CmpInst instructions, check their predicates
if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
if (cast<CmpInst>(I)->getPredicate() !=
cast<CmpInst>(FirstInst)->getPredicate())
return 0;
// Keep track of which operand needs a phi node.
if (I->getOperand(0) != LHSVal) LHSVal = 0;
if (I->getOperand(1) != RHSVal) RHSVal = 0;
}
// Otherwise, this is safe to transform, determine if it is profitable.
// If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
// Indexes are often folded into load/store instructions, so we don't want to
// hide them behind a phi.
if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
return 0;
Value *InLHS = FirstInst->getOperand(0);
Value *InRHS = FirstInst->getOperand(1);
PHINode *NewLHS = 0, *NewRHS = 0;
if (LHSVal == 0) {
NewLHS = PHINode::Create(LHSType, FirstInst->getOperand(0)->getName()+".pn");
NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
InsertNewInstBefore(NewLHS, PN);
LHSVal = NewLHS;
}
if (RHSVal == 0) {
NewRHS = PHINode::Create(RHSType, FirstInst->getOperand(1)->getName()+".pn");
NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
InsertNewInstBefore(NewRHS, PN);
RHSVal = NewRHS;
}
// Add all operands to the new PHIs.
for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
if (NewLHS) {
Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
}
if (NewRHS) {
Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
}
}
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
RHSVal);
else {
assert(isa<GetElementPtrInst>(FirstInst));
return GetElementPtrInst::Create(LHSVal, RHSVal);
}
}
/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
/// of the block that defines it. This means that it must be obvious the value
/// of the load is not changed from the point of the load to the end of the
/// block it is in.
///
/// Finally, it is safe, but not profitable, to sink a load targetting a
/// non-address-taken alloca. Doing so will cause us to not promote the alloca
/// to a register.
static bool isSafeToSinkLoad(LoadInst *L) {
BasicBlock::iterator BBI = L, E = L->getParent()->end();
for (++BBI; BBI != E; ++BBI)
if (BBI->mayWriteToMemory())
return false;
// Check for non-address taken alloca. If not address-taken already, it isn't
// profitable to do this xform.
if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
bool isAddressTaken = false;
for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
UI != E; ++UI) {
if (isa<LoadInst>(UI)) continue;
if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
// If storing TO the alloca, then the address isn't taken.
if (SI->getOperand(1) == AI) continue;
}
isAddressTaken = true;
break;
}
if (!isAddressTaken)
return false;
}
return true;
}
// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
// operator and they all are only used by the PHI, PHI together their
// inputs, and do the operation once, to the result of the PHI.
Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
// Scan the instruction, looking for input operations that can be folded away.
// If all input operands to the phi are the same instruction (e.g. a cast from
// the same type or "+42") we can pull the operation through the PHI, reducing
// code size and simplifying code.
Constant *ConstantOp = 0;
const Type *CastSrcTy = 0;
bool isVolatile = false;
if (isa<CastInst>(FirstInst)) {
CastSrcTy = FirstInst->getOperand(0)->getType();
} else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
// Can fold binop, compare or shift here if the RHS is a constant,
// otherwise call FoldPHIArgBinOpIntoPHI.
ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
if (ConstantOp == 0)
return FoldPHIArgBinOpIntoPHI(PN);
} else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
isVolatile = LI->isVolatile();
// We can't sink the load if the loaded value could be modified between the
// load and the PHI.
if (LI->getParent() != PN.getIncomingBlock(0) ||
!isSafeToSinkLoad(LI))
return 0;
} else if (isa<GetElementPtrInst>(FirstInst)) {
if (FirstInst->getNumOperands() == 2)
return FoldPHIArgBinOpIntoPHI(PN);
// Can't handle general GEPs yet.
return 0;
} else {
return 0; // Cannot fold this operation.
}
// Check to see if all arguments are the same operation.
for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
return 0;
if (CastSrcTy) {
if (I->getOperand(0)->getType() != CastSrcTy)
return 0; // Cast operation must match.
} else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
// We can't sink the load if the loaded value could be modified between
// the load and the PHI.
if (LI->isVolatile() != isVolatile ||
LI->getParent() != PN.getIncomingBlock(i) ||
!isSafeToSinkLoad(LI))
return 0;
// If the PHI is volatile and its block has multiple successors, sinking
// it would remove a load of the volatile value from the path through the
// other successor.
if (isVolatile &&
LI->getParent()->getTerminator()->getNumSuccessors() != 1)
return 0;
} else if (I->getOperand(1) != ConstantOp) {
return 0;
}
}
// Okay, they are all the same operation. Create a new PHI node of the
// correct type, and PHI together all of the LHS's of the instructions.
PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
PN.getName()+".in");
NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Value *InVal = FirstInst->getOperand(0);
NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
// Add all operands to the new PHI.
for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
if (NewInVal != InVal)
InVal = 0;
NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
}
Value *PhiVal;
if (InVal) {
// The new PHI unions all of the same values together. This is really
// common, so we handle it intelligently here for compile-time speed.
PhiVal = InVal;
delete NewPN;
} else {
InsertNewInstBefore(NewPN, PN);
PhiVal = NewPN;
}
// Insert and return the new operation.
if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
PhiVal, ConstantOp);
assert(isa<LoadInst>(FirstInst) && "Unknown operation");
// If this was a volatile load that we are merging, make sure to loop through
// and mark all the input loads as non-volatile. If we don't do this, we will
// insert a new volatile load and the old ones will not be deletable.
if (isVolatile)
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
return new LoadInst(PhiVal, "", isVolatile);
}
/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
/// that is dead.
static bool DeadPHICycle(PHINode *PN,
SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
if (PN->use_empty()) return true;
if (!PN->hasOneUse()) return false;
// Remember this node, and if we find the cycle, return.
if (!PotentiallyDeadPHIs.insert(PN))
return true;
// Don't scan crazily complex things.
if (PotentiallyDeadPHIs.size() == 16)
return false;
if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
return DeadPHICycle(PU, PotentiallyDeadPHIs);
return false;
}
/// PHIsEqualValue - Return true if this phi node is always equal to
/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
/// z = some value; x = phi (y, z); y = phi (x, z)
static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
// See if we already saw this PHI node.
if (!ValueEqualPHIs.insert(PN))
return true;
// Don't scan crazily complex things.
if (ValueEqualPHIs.size() == 16)
return false;
// Scan the operands to see if they are either phi nodes or are equal to
// the value.
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Op = PN->getIncomingValue(i);
if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
return false;
} else if (Op != NonPhiInVal)
return false;
}
return true;
}
// PHINode simplification
//
Instruction *InstCombiner::visitPHINode(PHINode &PN) {
// If LCSSA is around, don't mess with Phi nodes
if (MustPreserveLCSSA) return 0;
if (Value *V = PN.hasConstantValue())
return ReplaceInstUsesWith(PN, V);
// If all PHI operands are the same operation, pull them through the PHI,
// reducing code size.
if (isa<Instruction>(PN.getIncomingValue(0)) &&
PN.getIncomingValue(0)->hasOneUse())
if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
return Result;
// If this is a trivial cycle in the PHI node graph, remove it. Basically, if
// this PHI only has a single use (a PHI), and if that PHI only has one use (a
// PHI)... break the cycle.
if (PN.hasOneUse()) {
Instruction *PHIUser = cast<Instruction>(PN.use_back());
if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
PotentiallyDeadPHIs.insert(&PN);
if (DeadPHICycle(PU, PotentiallyDeadPHIs))
return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
}
// If this phi has a single use, and if that use just computes a value for
// the next iteration of a loop, delete the phi. This occurs with unused
// induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
// common case here is good because the only other things that catch this
// are induction variable analysis (sometimes) and ADCE, which is only run
// late.
if (PHIUser->hasOneUse() &&
(isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
PHIUser->use_back() == &PN) {
return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
}
}
// We sometimes end up with phi cycles that non-obviously end up being the
// same value, for example:
// z = some value; x = phi (y, z); y = phi (x, z)
// where the phi nodes don't necessarily need to be in the same block. Do a
// quick check to see if the PHI node only contains a single non-phi value, if
// so, scan to see if the phi cycle is actually equal to that value.
{
unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
// Scan for the first non-phi operand.
while (InValNo != NumOperandVals &&
isa<PHINode>(PN.getIncomingValue(InValNo)))
++InValNo;
if (InValNo != NumOperandVals) {
Value *NonPhiInVal = PN.getOperand(InValNo);
// Scan the rest of the operands to see if there are any conflicts, if so
// there is no need to recursively scan other phis.
for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
Value *OpVal = PN.getIncomingValue(InValNo);
if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
break;
}
// If we scanned over all operands, then we have one unique value plus
// phi values. Scan PHI nodes to see if they all merge in each other or
// the value.
if (InValNo == NumOperandVals) {
SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
return ReplaceInstUsesWith(PN, NonPhiInVal);
}
}
}
return 0;
}
static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
Instruction *InsertPoint,
InstCombiner *IC) {
unsigned PtrSize = DTy->getPrimitiveSizeInBits();
unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
// We must cast correctly to the pointer type. Ensure that we
// sign extend the integer value if it is smaller as this is
// used for address computation.
Instruction::CastOps opcode =
(VTySize < PtrSize ? Instruction::SExt :
(VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
}
Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Value *PtrOp = GEP.getOperand(0);
// Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
// If so, eliminate the noop.
if (GEP.getNumOperands() == 1)
return ReplaceInstUsesWith(GEP, PtrOp);
if (isa<UndefValue>(GEP.getOperand(0)))
return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
bool HasZeroPointerIndex = false;
if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
HasZeroPointerIndex = C->isNullValue();
if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
return ReplaceInstUsesWith(GEP, PtrOp);
// Eliminate unneeded casts for indices.
bool MadeChange = false;
gep_type_iterator GTI = gep_type_begin(GEP);
for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
if (isa<SequentialType>(*GTI)) {
if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
if (CI->getOpcode() == Instruction::ZExt ||
CI->getOpcode() == Instruction::SExt) {
const Type *SrcTy = CI->getOperand(0)->getType();
// We can eliminate a cast from i32 to i64 iff the target
// is a 32-bit pointer target.
if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
MadeChange = true;
GEP.setOperand(i, CI->getOperand(0));
}
}
}
// If we are using a wider index than needed for this platform, shrink it
// to what we need. If the incoming value needs a cast instruction,
// insert it. This explicit cast can make subsequent optimizations more
// obvious.
Value *Op = GEP.getOperand(i);
if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
if (Constant *C = dyn_cast<Constant>(Op)) {
GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
MadeChange = true;
} else {
Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
GEP);
GEP.setOperand(i, Op);
MadeChange = true;
}
}
}
}
if (MadeChange) return &GEP;
// If this GEP instruction doesn't move the pointer, and if the input operand
// is a bitcast of another pointer, just replace the GEP with a bitcast of the
// real input to the dest type.
if (GEP.hasAllZeroIndices()) {
if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
// If the bitcast is of an allocation, and the allocation will be
// converted to match the type of the cast, don't touch this.
if (isa<AllocationInst>(BCI->getOperand(0))) {
// See if the bitcast simplifies, if so, don't nuke this GEP yet.
if (Instruction *I = visitBitCast(*BCI)) {
if (I != BCI) {
I->takeName(BCI);
BCI->getParent()->getInstList().insert(BCI, I);
ReplaceInstUsesWith(*BCI, I);
}
return &GEP;
}
}
return new BitCastInst(BCI->getOperand(0), GEP.getType());
}
}
// Combine Indices - If the source pointer to this getelementptr instruction
// is a getelementptr instruction, combine the indices of the two
// getelementptr instructions into a single instruction.
//
SmallVector<Value*, 8> SrcGEPOperands;
if (User *Src = dyn_castGetElementPtr(PtrOp))
SrcGEPOperands.append(Src->op_begin(), Src->op_end());
if (!SrcGEPOperands.empty()) {
// Note that if our source is a gep chain itself that we wait for that
// chain to be resolved before we perform this transformation. This
// avoids us creating a TON of code in some cases.
//
if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
return 0; // Wait until our source is folded to completion.
SmallVector<Value*, 8> Indices;
// Find out whether the last index in the source GEP is a sequential idx.
bool EndsWithSequential = false;
for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
EndsWithSequential = !isa<StructType>(*I);
// Can we combine the two pointer arithmetics offsets?
if (EndsWithSequential) {
// Replace: gep (gep %P, long B), long A, ...
// With: T = long A+B; gep %P, T, ...
//
Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
if (SO1 == Constant::getNullValue(SO1->getType())) {
Sum = GO1;
} else if (GO1 == Constant::getNullValue(GO1->getType())) {
Sum = SO1;
} else {
// If they aren't the same type, convert both to an integer of the
// target's pointer size.
if (SO1->getType() != GO1->getType()) {
if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
} else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
} else {
unsigned PS = TD->getPointerSizeInBits();
if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
// Convert GO1 to SO1's type.
GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
} else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
// Convert SO1 to GO1's type.
SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
} else {
const Type *PT = TD->getIntPtrType();
SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
}
}
}
if (isa<Constant>(SO1) && isa<Constant>(GO1))
Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
else {
Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
InsertNewInstBefore(cast<Instruction>(Sum), GEP);
}
}
// Recycle the GEP we already have if possible.
if (SrcGEPOperands.size() == 2) {
GEP.setOperand(0, SrcGEPOperands[0]);
GEP.setOperand(1, Sum);
return &GEP;
} else {
Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
SrcGEPOperands.end()-1);
Indices.push_back(Sum);
Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
}
} else if (isa<Constant>(*GEP.idx_begin()) &&
cast<Constant>(*GEP.idx_begin())->isNullValue() &&
SrcGEPOperands.size() != 1) {
// Otherwise we can do the fold if the first index of the GEP is a zero
Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
SrcGEPOperands.end());
Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
}
if (!Indices.empty())
return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
Indices.end(), GEP.getName());
} else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
// GEP of global variable. If all of the indices for this GEP are
// constants, we can promote this to a constexpr instead of an instruction.
// Scan for nonconstants...
SmallVector<Constant*, 8> Indices;
User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
for (; I != E && isa<Constant>(*I); ++I)
Indices.push_back(cast<Constant>(*I));
if (I == E) { // If they are all constants...
Constant *CE = ConstantExpr::getGetElementPtr(GV,
&Indices[0],Indices.size());
// Replace all uses of the GEP with the new constexpr...
return ReplaceInstUsesWith(GEP, CE);
}
} else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
if (!isa<PointerType>(X->getType())) {
// Not interesting. Source pointer must be a cast from pointer.
} else if (HasZeroPointerIndex) {
// transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
// into : GEP [10 x i8]* X, i32 0, ...
//
// This occurs when the program declares an array extern like "int X[];"
//
const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
const PointerType *XTy = cast<PointerType>(X->getType());
if (const ArrayType *XATy =
dyn_cast<ArrayType>(XTy->getElementType()))
if (const ArrayType *CATy =
dyn_cast<ArrayType>(CPTy->getElementType()))
if (CATy->getElementType() == XATy->getElementType()) {
// At this point, we know that the cast source type is a pointer
// to an array of the same type as the destination pointer
// array. Because the array type is never stepped over (there
// is a leading zero) we can fold the cast into this GEP.
GEP.setOperand(0, X);
return &GEP;
}
} else if (GEP.getNumOperands() == 2) {
// Transform things like:
// %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
// into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
if (isa<ArrayType>(SrcElTy) &&
TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
TD->getABITypeSize(ResElTy)) {
Value *Idx[2];
Idx[0] = Constant::getNullValue(Type::Int32Ty);
Idx[1] = GEP.getOperand(1);
Value *V = InsertNewInstBefore(
GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
// V and GEP are both pointer types --> BitCast
return new BitCastInst(V, GEP.getType());
}
// Transform things like:
// getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
// (where tmp = 8*tmp2) into:
// getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
uint64_t ArrayEltSize =
TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
// Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
// allow either a mul, shift, or constant here.
Value *NewIdx = 0;
ConstantInt *Scale = 0;
if (ArrayEltSize == 1) {
NewIdx = GEP.getOperand(1);
Scale = ConstantInt::get(NewIdx->getType(), 1);
} else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
NewIdx = ConstantInt::get(CI->getType(), 1);
Scale = CI;
} else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
if (Inst->getOpcode() == Instruction::Shl &&
isa<ConstantInt>(Inst->getOperand(1))) {
ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
NewIdx = Inst->getOperand(0);
} else if (Inst->getOpcode() == Instruction::Mul &&
isa<ConstantInt>(Inst->getOperand(1))) {
Scale = cast<ConstantInt>(Inst->getOperand(1));
NewIdx = Inst->getOperand(0);
}
}
// If the index will be to exactly the right offset with the scale taken
// out, perform the transformation. Note, we don't know whether Scale is
// signed or not. We'll use unsigned version of division/modulo
// operation after making sure Scale doesn't have the sign bit set.
if (Scale && Scale->getSExtValue() >= 0LL &&
Scale->getZExtValue() % ArrayEltSize == 0) {
Scale = ConstantInt::get(Scale->getType(),
Scale->getZExtValue() / ArrayEltSize);
if (Scale->getZExtValue() != 1) {
Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
false /*ZExt*/);
Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
NewIdx = InsertNewInstBefore(Sc, GEP);
}
// Insert the new GEP instruction.
Value *Idx[2];
Idx[0] = Constant::getNullValue(Type::Int32Ty);
Idx[1] = NewIdx;
Instruction *NewGEP =
GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
NewGEP = InsertNewInstBefore(NewGEP, GEP);
// The NewGEP must be pointer typed, so must the old one -> BitCast
return new BitCastInst(NewGEP, GEP.getType());
}
}
}
}
return 0;
}
Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
// Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
if (AI.isArrayAllocation()) { // Check C != 1
if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
const Type *NewTy =
ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
AllocationInst *New = 0;
// Create and insert the replacement instruction...
if (isa<MallocInst>(AI))
New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
else {
assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
}
InsertNewInstBefore(New, AI);
// Scan to the end of the allocation instructions, to skip over a block of
// allocas if possible...
//
BasicBlock::iterator It = New;
while (isa<AllocationInst>(*It)) ++It;
// Now that I is pointing to the first non-allocation-inst in the block,
// insert our getelementptr instruction...
//
Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Value *Idx[2];
Idx[0] = NullIdx;
Idx[1] = NullIdx;
Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
New->getName()+".sub", It);
// Now make everything use the getelementptr instead of the original
// allocation.
return ReplaceInstUsesWith(AI, V);
} else if (isa<UndefValue>(AI.getArraySize())) {
return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
}
}
// If alloca'ing a zero byte object, replace the alloca with a null pointer.
// Note that we only do this for alloca's, because malloc should allocate and
// return a unique pointer, even for a zero byte allocation.
if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
TD->getABITypeSize(AI.getAllocatedType()) == 0)
return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
return 0;
}
Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
Value *Op = FI.getOperand(0);
// free undef -> unreachable.
if (isa<UndefValue>(Op)) {
// Insert a new store to null because we cannot modify the CFG here.
new StoreInst(ConstantInt::getTrue(),
UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
return EraseInstFromFunction(FI);
}
// If we have 'free null' delete the instruction. This can happen in stl code
// when lots of inlining happens.
if (isa<ConstantPointerNull>(Op))
return EraseInstFromFunction(FI);
// Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
FI.setOperand(0, CI->getOperand(0));
return &FI;
}
// Change free (gep X, 0,0,0,0) into free(X)
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
if (GEPI->hasAllZeroIndices()) {
AddToWorkList(GEPI);
FI.setOperand(0, GEPI->getOperand(0));
return &FI;
}
}
// Change free(malloc) into nothing, if the malloc has a single use.
if (MallocInst *MI = dyn_cast<MallocInst>(Op))
if (MI->hasOneUse()) {
EraseInstFromFunction(FI);
return EraseInstFromFunction(*MI);
}
return 0;
}
/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
const TargetData *TD) {
User *CI = cast<User>(LI.getOperand(0));
Value *CastOp = CI->getOperand(0);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
// Instead of loading constant c string, use corresponding integer value
// directly if string length is small enough.
const std::string &Str = CE->getOperand(0)->getStringValue();
if (!Str.empty()) {
unsigned len = Str.length();
const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
unsigned numBits = Ty->getPrimitiveSizeInBits();
// Replace LI with immediate integer store.
if ((numBits >> 3) == len + 1) {
APInt StrVal(numBits, 0);
APInt SingleChar(numBits, 0);
if (TD->isLittleEndian()) {
for (signed i = len-1; i >= 0; i--) {
SingleChar = (uint64_t) Str[i];
StrVal = (StrVal << 8) | SingleChar;
}
} else {
for (unsigned i = 0; i < len; i++) {
SingleChar = (uint64_t) Str[i];
StrVal = (StrVal << 8) | SingleChar;
}
// Append NULL at the end.
SingleChar = 0;
StrVal = (StrVal << 8) | SingleChar;
}
Value *NL = ConstantInt::get(StrVal);
return IC.ReplaceInstUsesWith(LI, NL);
}
}
}
const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
const Type *SrcPTy = SrcTy->getElementType();
if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
isa<VectorType>(DestPTy)) {
// If the source is an array, the code below will not succeed. Check to
// see if a trivial 'gep P, 0, 0' will help matters. Only do this for
// constants.
if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
if (Constant *CSrc = dyn_cast<Constant>(CastOp))
if (ASrcTy->getNumElements() != 0) {
Value *Idxs[2];
Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
SrcTy = cast<PointerType>(CastOp->getType());
SrcPTy = SrcTy->getElementType();
}
if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
isa<VectorType>(SrcPTy)) &&
// Do not allow turning this into a load of an integer, which is then
// casted to a pointer, this pessimizes pointer analysis a lot.
(isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
IC.getTargetData().getTypeSizeInBits(DestPTy)) {
// Okay, we are casting from one integer or pointer type to another of
// the same size. Instead of casting the pointer before the load, cast
// the result of the loaded value.
Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
CI->getName(),
LI.isVolatile()),LI);
// Now cast the result of the load.
return new BitCastInst(NewLoad, LI.getType());
}
}
}
return 0;
}
/// isSafeToLoadUnconditionally - Return true if we know that executing a load
/// from this value cannot trap. If it is not obviously safe to load from the
/// specified pointer, we do a quick local scan of the basic block containing
/// ScanFrom, to determine if the address is already accessed.
static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
// If it is an alloca it is always safe to load from.
if (isa<AllocaInst>(V)) return true;
// If it is a global variable it is mostly safe to load from.
if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
// Don't try to evaluate aliases. External weak GV can be null.
return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
// Otherwise, be a little bit agressive by scanning the local block where we
// want to check to see if the pointer is already being loaded or stored
// from/to. If so, the previous load or store would have already trapped,
// so there is no harm doing an extra load (also, CSE will later eliminate
// the load entirely).
BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
while (BBI != E) {
--BBI;
if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
if (LI->getOperand(0) == V) return true;
} else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
if (SI->getOperand(1) == V) return true;
}
return false;
}
/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
/// until we find the underlying object a pointer is referring to or something
/// we don't understand. Note that the returned pointer may be offset from the
/// input, because we ignore GEP indices.
static Value *GetUnderlyingObject(Value *Ptr) {
while (1) {
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
if (CE->getOpcode() == Instruction::BitCast ||
CE->getOpcode() == Instruction::GetElementPtr)
Ptr = CE->getOperand(0);
else
return Ptr;
} else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
Ptr = BCI->getOperand(0);
} else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
Ptr = GEP->getOperand(0);
} else {
return Ptr;
}
}
}
Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
Value *Op = LI.getOperand(0);
// Attempt to improve the alignment.
unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
if (KnownAlign >
(LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
LI.getAlignment()))
LI.setAlignment(KnownAlign);
// load (cast X) --> cast (load X) iff safe
if (isa<CastInst>(Op))
if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
return Res;
// None of the following transforms are legal for volatile loads.
if (LI.isVolatile()) return 0;
if (&LI.getParent()->front() != &LI) {
BasicBlock::iterator BBI = &LI; --BBI;
// If the instruction immediately before this is a store to the same
// address, do a simple form of store->load forwarding.
if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
if (SI->getOperand(1) == LI.getOperand(0))
return ReplaceInstUsesWith(LI, SI->getOperand(0));
if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
if (LIB->getOperand(0) == LI.getOperand(0))
return ReplaceInstUsesWith(LI, LIB);
}
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
const Value *GEPI0 = GEPI->getOperand(0);
// TODO: Consider a target hook for valid address spaces for this xform.
if (isa<ConstantPointerNull>(GEPI0) &&
cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
// Insert a new store to null instruction before the load to indicate
// that this code is not reachable. We do this instead of inserting
// an unreachable instruction directly because we cannot modify the
// CFG.
new StoreInst(UndefValue::get(LI.getType()),
Constant::getNullValue(Op->getType()), &LI);
return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
}
}
if (Constant *C = dyn_cast<Constant>(Op)) {
// load null/undef -> undef
// TODO: Consider a target hook for valid address spaces for this xform.
if (isa<UndefValue>(C) || (C->isNullValue() &&
cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
// Insert a new store to null instruction before the load to indicate that
// this code is not reachable. We do this instead of inserting an
// unreachable instruction directly because we cannot modify the CFG.
new StoreInst(UndefValue::get(LI.getType()),
Constant::getNullValue(Op->getType()), &LI);
return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
}
// Instcombine load (constant global) into the value loaded.
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
if (GV->isConstant() && !GV->isDeclaration())
return ReplaceInstUsesWith(LI, GV->getInitializer());
// Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
if (CE->getOpcode() == Instruction::GetElementPtr) {
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
if (GV->isConstant() && !GV->isDeclaration())
if (Constant *V =
ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
return ReplaceInstUsesWith(LI, V);
if (CE->getOperand(0)->isNullValue()) {
// Insert a new store to null instruction before the load to indicate
// that this code is not reachable. We do this instead of inserting
// an unreachable instruction directly because we cannot modify the
// CFG.
new StoreInst(UndefValue::get(LI.getType()),
Constant::getNullValue(Op->getType()), &LI);
return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
}
} else if (CE->isCast()) {
if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
return Res;
}
}
}
// If this load comes from anywhere in a constant global, and if the global
// is all undef or zero, we know what it loads.
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
if (GV->isConstant() && GV->hasInitializer()) {
if (GV->getInitializer()->isNullValue())
return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
else if (isa<UndefValue>(GV->getInitializer()))
return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
}
}
if (Op->hasOneUse()) {
// Change select and PHI nodes to select values instead of addresses: this
// helps alias analysis out a lot, allows many others simplifications, and
// exposes redundancy in the code.
//
// Note that we cannot do the transformation unless we know that the
// introduced loads cannot trap! Something like this is valid as long as
// the condition is always false: load (select bool %C, int* null, int* %G),
// but it would not be valid if we transformed it to load from null
// unconditionally.
//
if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
// load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
SI->getOperand(1)->getName()+".val"), LI);
Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
SI->getOperand(2)->getName()+".val"), LI);
return SelectInst::Create(SI->getCondition(), V1, V2);
}
// load (select (cond, null, P)) -> load P
if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
if (C->isNullValue()) {
LI.setOperand(0, SI->getOperand(2));
return &LI;
}
// load (select (cond, P, null)) -> load P
if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
if (C->isNullValue()) {
LI.setOperand(0, SI->getOperand(1));
return &LI;
}
}
}
return 0;
}
/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
/// when possible.
static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
User *CI = cast<User>(SI.getOperand(1));
Value *CastOp = CI->getOperand(0);
const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
const Type *SrcPTy = SrcTy->getElementType();
if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
// If the source is an array, the code below will not succeed. Check to
// see if a trivial 'gep P, 0, 0' will help matters. Only do this for
// constants.
if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
if (Constant *CSrc = dyn_cast<Constant>(CastOp))
if (ASrcTy->getNumElements() != 0) {
Value* Idxs[2];
Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
SrcTy = cast<PointerType>(CastOp->getType());
SrcPTy = SrcTy->getElementType();
}
if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
IC.getTargetData().getTypeSizeInBits(DestPTy)) {
// Okay, we are casting from one integer or pointer type to another of
// the same size. Instead of casting the pointer before
// the store, cast the value to be stored.
Value *NewCast;
Value *SIOp0 = SI.getOperand(0);
Instruction::CastOps opcode = Instruction::BitCast;
const Type* CastSrcTy = SIOp0->getType();
const Type* CastDstTy = SrcPTy;
if (isa<PointerType>(CastDstTy)) {
if (CastSrcTy->isInteger())
opcode = Instruction::IntToPtr;
} else if (isa<IntegerType>(CastDstTy)) {
if (isa<PointerType>(SIOp0->getType()))
opcode = Instruction::PtrToInt;
}
if (Constant *C = dyn_cast<Constant>(SIOp0))
NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
else
NewCast = IC.InsertNewInstBefore(
CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
SI);
return new StoreInst(NewCast, CastOp);
}
}
}
return 0;
}
Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
Value *Val = SI.getOperand(0);
Value *Ptr = SI.getOperand(1);
if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
EraseInstFromFunction(SI);
++NumCombined;
return 0;
}
// If the RHS is an alloca with a single use, zapify the store, making the
// alloca dead.
if (Ptr->hasOneUse() && !SI.isVolatile()) {
if (isa<AllocaInst>(Ptr)) {
EraseInstFromFunction(SI);
++NumCombined;
return 0;
}
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
if (isa<AllocaInst>(GEP->getOperand(0)) &&
GEP->getOperand(0)->hasOneUse()) {
EraseInstFromFunction(SI);
++NumCombined;
return 0;
}
}
// Attempt to improve the alignment.
unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
if (KnownAlign >
(SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
SI.getAlignment()))
SI.setAlignment(KnownAlign);
// Do really simple DSE, to catch cases where there are several consequtive
// stores to the same location, separated by a few arithmetic operations. This
// situation often occurs with bitfield accesses.
BasicBlock::iterator BBI = &SI;
for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
--ScanInsts) {
--BBI;
if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
// Prev store isn't volatile, and stores to the same location?
if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
++NumDeadStore;
++BBI;
EraseInstFromFunction(*PrevSI);
continue;
}
break;
}
// If this is a load, we have to stop. However, if the loaded value is from
// the pointer we're loading and is producing the pointer we're storing,
// then *this* store is dead (X = load P; store X -> P).
if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
EraseInstFromFunction(SI);
++NumCombined;
return 0;
}
// Otherwise, this is a load from some other location. Stores before it
// may not be dead.
break;
}
// Don't skip over loads or things that can modify memory.
if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
break;
}
if (SI.isVolatile()) return 0; // Don't hack volatile stores.
// store X, null -> turns into 'unreachable' in SimplifyCFG
if (isa<ConstantPointerNull>(Ptr)) {
if (!isa<UndefValue>(Val)) {
SI.setOperand(0, UndefValue::get(Val->getType()));
if (Instruction *U = dyn_cast<Instruction>(Val))
AddToWorkList(U); // Dropped a use.
++NumCombined;
}
return 0; // Do not modify these!
}
// store undef, Ptr -> noop
if (isa<UndefValue>(Val)) {
EraseInstFromFunction(SI);
++NumCombined;
return 0;
}
// If the pointer destination is a cast, see if we can fold the cast into the
// source instead.
if (isa<CastInst>(Ptr))
if (Instruction *Res = InstCombineStoreToCast(*this, SI))
return Res;
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
if (CE->isCast())
if (Instruction *Res = InstCombineStoreToCast(*this, SI))
return Res;
// If this store is the last instruction in the basic block, and if the block
// ends with an unconditional branch, try to move it to the successor block.
BBI = &SI; ++BBI;
if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
if (BI->isUnconditional())
if (SimplifyStoreAtEndOfBlock(SI))
return 0; // xform done!
return 0;
}
/// SimplifyStoreAtEndOfBlock - Turn things like:
/// if () { *P = v1; } else { *P = v2 }
/// into a phi node with a store in the successor.
///
/// Simplify things like:
/// *P = v1; if () { *P = v2; }
/// into a phi node with a store in the successor.
///
bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
BasicBlock *StoreBB = SI.getParent();
// Check to see if the successor block has exactly two incoming edges. If
// so, see if the other predecessor contains a store to the same location.
// if so, insert a PHI node (if needed) and move the stores down.
BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
// Determine whether Dest has exactly two predecessors and, if so, compute
// the other predecessor.
pred_iterator PI = pred_begin(DestBB);
BasicBlock *OtherBB = 0;
if (*PI != StoreBB)
OtherBB = *PI;
++PI;
if (PI == pred_end(DestBB))
return false;
if (*PI != StoreBB) {
if (OtherBB)
return false;
OtherBB = *PI;
}
if (++PI != pred_end(DestBB))
return false;
// Verify that the other block ends in a branch and is not otherwise empty.
BasicBlock::iterator BBI = OtherBB->getTerminator();
BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
if (!OtherBr || BBI == OtherBB->begin())
return false;
// If the other block ends in an unconditional branch, check for the 'if then
// else' case. there is an instruction before the branch.
StoreInst *OtherStore = 0;
if (OtherBr->isUnconditional()) {
// If this isn't a store, or isn't a store to the same location, bail out.
--BBI;
OtherStore = dyn_cast<StoreInst>(BBI);
if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
return false;
} else {
// Otherwise, the other block ended with a conditional branch. If one of the
// destinations is StoreBB, then we have the if/then case.
if (OtherBr->getSuccessor(0) != StoreBB &&
OtherBr->getSuccessor(1) != StoreBB)
return false;
// Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
// if/then triangle. See if there is a store to the same ptr as SI that
// lives in OtherBB.
for (;; --BBI) {
// Check to see if we find the matching store.
if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
if (OtherStore->getOperand(1) != SI.getOperand(1))
return false;
break;
}
// If we find something that may be using the stored value, or if we run
// out of instructions, we can't do the xform.
if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
BBI == OtherBB->begin())
return false;
}
// In order to eliminate the store in OtherBr, we have to
// make sure nothing reads the stored value in StoreBB.
for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
// FIXME: This should really be AA driven.
if (isa<LoadInst>(I) || I->mayWriteToMemory())
return false;
}
}
// Insert a PHI node now if we need it.
Value *MergedVal = OtherStore->getOperand(0);
if (MergedVal != SI.getOperand(0)) {
PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
PN->reserveOperandSpace(2);
PN->addIncoming(SI.getOperand(0), SI.getParent());
PN->addIncoming(OtherStore->getOperand(0), OtherBB);
MergedVal = InsertNewInstBefore(PN, DestBB->front());
}
// Advance to a place where it is safe to insert the new store and
// insert it.
BBI = DestBB->begin();
while (isa<PHINode>(BBI)) ++BBI;
InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
OtherStore->isVolatile()), *BBI);
// Nuke the old stores.
EraseInstFromFunction(SI);
EraseInstFromFunction(*OtherStore);
++NumCombined;
return true;
}
Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
// Change br (not X), label True, label False to: br X, label False, True
Value *X = 0;
BasicBlock *TrueDest;
BasicBlock *FalseDest;
if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
!isa<Constant>(X)) {
// Swap Destinations and condition...
BI.setCondition(X);
BI.setSuccessor(0, FalseDest);
BI.setSuccessor(1, TrueDest);
return &BI;
}
// Cannonicalize fcmp_one -> fcmp_oeq
FCmpInst::Predicate FPred; Value *Y;
if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
TrueDest, FalseDest)))
if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
FCmpInst *I = cast<FCmpInst>(BI.getCondition());
FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
NewSCC->takeName(I);
// Swap Destinations and condition...
BI.setCondition(NewSCC);
BI.setSuccessor(0, FalseDest);
BI.setSuccessor(1, TrueDest);
RemoveFromWorkList(I);
I->eraseFromParent();
AddToWorkList(NewSCC);
return &BI;
}
// Cannonicalize icmp_ne -> icmp_eq
ICmpInst::Predicate IPred;
if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
TrueDest, FalseDest)))
if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
ICmpInst *I = cast<ICmpInst>(BI.getCondition());
ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
NewSCC->takeName(I);
// Swap Destinations and condition...
BI.setCondition(NewSCC);
BI.setSuccessor(0, FalseDest);
BI.setSuccessor(1, TrueDest);
RemoveFromWorkList(I);
I->eraseFromParent();;
AddToWorkList(NewSCC);
return &BI;
}
return 0;
}
Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
Value *Cond = SI.getCondition();
if (Instruction *I = dyn_cast<Instruction>(Cond)) {
if (I->getOpcode() == Instruction::Add)
if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
// change 'switch (X+4) case 1:' into 'switch (X) case -3'
for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
AddRHS));
SI.setOperand(0, I->getOperand(0));
AddToWorkList(I);
return &SI;
}
}
return 0;
}
/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
/// is to leave as a vector operation.
static bool CheapToScalarize(Value *V, bool isConstant) {
if (isa<ConstantAggregateZero>(V))
return true;
if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
if (isConstant) return true;
// If all elts are the same, we can extract.
Constant *Op0 = C->getOperand(0);
for (unsigned i = 1; i < C->getNumOperands(); ++i)
if (C->getOperand(i) != Op0)
return false;
return true;
}
Instruction *I = dyn_cast<Instruction>(V);
if (!I) return false;
// Insert element gets simplified to the inserted element or is deleted if
// this is constant idx extract element and its a constant idx insertelt.
if (I->getOpcode() == Instruction::InsertElement && isConstant &&
isa<ConstantInt>(I->getOperand(2)))
return true;
if (I->getOpcode() == Instruction::Load && I->hasOneUse())
return true;
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
if (BO->hasOneUse() &&
(CheapToScalarize(BO->getOperand(0), isConstant) ||
CheapToScalarize(BO->getOperand(1), isConstant)))
return true;
if (CmpInst *CI = dyn_cast<CmpInst>(I))
if (CI->hasOneUse() &&
(CheapToScalarize(CI->getOperand(0), isConstant) ||
CheapToScalarize(CI->getOperand(1), isConstant)))
return true;
return false;
}
/// Read and decode a shufflevector mask.
///
/// It turns undef elements into values that are larger than the number of
/// elements in the input.
static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
unsigned NElts = SVI->getType()->getNumElements();
if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
return std::vector<unsigned>(NElts, 0);
if (isa<UndefValue>(SVI->getOperand(2)))
return std::vector<unsigned>(NElts, 2*NElts);
std::vector<unsigned> Result;
const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
if (isa<UndefValue>(CP->getOperand(i)))
Result.push_back(NElts*2); // undef -> 8
else
Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
return Result;
}
/// FindScalarElement - Given a vector and an element number, see if the scalar
/// value is already around as a register, for example if it were inserted then
/// extracted from the vector.
static Value *FindScalarElement(Value *V, unsigned EltNo) {
assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
const VectorType *PTy = cast<VectorType>(V->getType());
unsigned Width = PTy->getNumElements();
if (EltNo >= Width) // Out of range access.
return UndefValue::get(PTy->getElementType());
if (isa<UndefValue>(V))
return UndefValue::get(PTy->getElementType());
else if (isa<ConstantAggregateZero>(V))
return Constant::getNullValue(PTy->getElementType());
else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
return CP->getOperand(EltNo);
else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
// If this is an insert to a variable element, we don't know what it is.
if (!isa<ConstantInt>(III->getOperand(2)))
return 0;
unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
// If this is an insert to the element we are looking for, return the
// inserted value.
if (EltNo == IIElt)
return III->getOperand(1);
// Otherwise, the insertelement doesn't modify the value, recurse on its
// vector input.
return FindScalarElement(III->getOperand(0), EltNo);
} else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
unsigned InEl = getShuffleMask(SVI)[EltNo];
if (InEl < Width)
return FindScalarElement(SVI->getOperand(0), InEl);
else if (InEl < Width*2)
return FindScalarElement(SVI->getOperand(1), InEl - Width);
else
return UndefValue::get(PTy->getElementType());
}
// Otherwise, we don't know.
return 0;
}
Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
// If vector val is undef, replace extract with scalar undef.
if (isa<UndefValue>(EI.getOperand(0)))
return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
// If vector val is constant 0, replace extract with scalar 0.
if (isa<ConstantAggregateZero>(EI.getOperand(0)))
return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
// If vector val is constant with uniform operands, replace EI
// with that operand
Constant *op0 = C->getOperand(0);
for (unsigned i = 1; i < C->getNumOperands(); ++i)
if (C->getOperand(i) != op0) {
op0 = 0;
break;
}
if (op0)
return ReplaceInstUsesWith(EI, op0);
}
// If extracting a specified index from the vector, see if we can recursively
// find a previously computed scalar that was inserted into the vector.
if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
unsigned IndexVal = IdxC->getZExtValue();
unsigned VectorWidth =
cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
// If this is extracting an invalid index, turn this into undef, to avoid
// crashing the code below.
if (IndexVal >= VectorWidth)
return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
// This instruction only demands the single element from the input vector.
// If the input vector has a single use, simplify it based on this use
// property.
if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
uint64_t UndefElts;
if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
1 << IndexVal,
UndefElts)) {
EI.setOperand(0, V);
return &EI;
}
}
if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
return ReplaceInstUsesWith(EI, Elt);
// If the this extractelement is directly using a bitcast from a vector of
// the same number of elements, see if we can find the source element from
// it. In this case, we will end up needing to bitcast the scalars.
if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
if (const VectorType *VT =
dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
if (VT->getNumElements() == VectorWidth)
if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
return new BitCastInst(Elt, EI.getType());
}
}
if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
if (I->hasOneUse()) {
// Push extractelement into predecessor operation if legal and
// profitable to do so
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
if (CheapToScalarize(BO, isConstantElt)) {
ExtractElementInst *newEI0 =
new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
EI.getName()+".lhs");
ExtractElementInst *newEI1 =
new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
EI.getName()+".rhs");
InsertNewInstBefore(newEI0, EI);
InsertNewInstBefore(newEI1, EI);
return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
}
} else if (isa<LoadInst>(I)) {
unsigned AS =
cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Value *Ptr = InsertBitCastBefore(I->getOperand(0),
PointerType::get(EI.getType(), AS),EI);
GetElementPtrInst *GEP =
GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName() + ".gep");
InsertNewInstBefore(GEP, EI);
return new LoadInst(GEP);
}
}
if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
// Extracting the inserted element?
if (IE->getOperand(2) == EI.getOperand(1))
return ReplaceInstUsesWith(EI, IE->getOperand(1));
// If the inserted and extracted elements are constants, they must not
// be the same value, extract from the pre-inserted value instead.
if (isa<Constant>(IE->getOperand(2)) &&
isa<Constant>(EI.getOperand(1))) {
AddUsesToWorkList(EI);
EI.setOperand(0, IE->getOperand(0));
return &EI;
}
} else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
// If this is extracting an element from a shufflevector, figure out where
// it came from and extract from the appropriate input element instead.
if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Value *Src;
if (SrcIdx < SVI->getType()->getNumElements())
Src = SVI->getOperand(0);
else if (SrcIdx < SVI->getType()->getNumElements()*2) {
SrcIdx -= SVI->getType()->getNumElements();
Src = SVI->getOperand(1);
} else {
return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
}
return new ExtractElementInst(Src, SrcIdx);
}
}
}
return 0;
}
/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
/// elements from either LHS or RHS, return the shuffle mask and true.
/// Otherwise, return false.
static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
std::vector<Constant*> &Mask) {
assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
"Invalid CollectSingleShuffleElements");
unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
if (isa<UndefValue>(V)) {
Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
return true;
} else if (V == LHS) {
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
return true;
} else if (V == RHS) {
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
return true;
} else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
// If this is an insert of an extract from some other vector, include it.
Value *VecOp = IEI->getOperand(0);
Value *ScalarOp = IEI->getOperand(1);
Value *IdxOp = IEI->getOperand(2);
if (!isa<ConstantInt>(IdxOp))
return false;
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
// Okay, we can handle this if the vector we are insertinting into is
// transitively ok.
if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
// If so, update the mask to reflect the inserted undef.
Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
return true;
}
} else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
if (isa<ConstantInt>(EI->getOperand(1)) &&
EI->getOperand(0)->getType() == V->getType()) {
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
// This must be extracting from either LHS or RHS.
if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
// Okay, we can handle this if the vector we are insertinting into is
// transitively ok.
if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
// If so, update the mask to reflect the inserted value.
if (EI->getOperand(0) == LHS) {
Mask[InsertedIdx & (NumElts-1)] =
ConstantInt::get(Type::Int32Ty, ExtractedIdx);
} else {
assert(EI->getOperand(0) == RHS);
Mask[InsertedIdx & (NumElts-1)] =
ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
}
return true;
}
}
}
}
}
// TODO: Handle shufflevector here!
return false;
}
/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
/// that computes V and the LHS value of the shuffle.
static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Value *&RHS) {
assert(isa<VectorType>(V->getType()) &&
(RHS == 0 || V->getType() == RHS->getType()) &&
"Invalid shuffle!");
unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
if (isa<UndefValue>(V)) {
Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
return V;
} else if (isa<ConstantAggregateZero>(V)) {
Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
return V;
} else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
// If this is an insert of an extract from some other vector, include it.
Value *VecOp = IEI->getOperand(0);
Value *ScalarOp = IEI->getOperand(1);
Value *IdxOp = IEI->getOperand(2);
if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
EI->getOperand(0)->getType() == V->getType()) {
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
// Either the extracted from or inserted into vector must be RHSVec,
// otherwise we'd end up with a shuffle of three inputs.
if (EI->getOperand(0) == RHS || RHS == 0) {
RHS = EI->getOperand(0);
Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mask[InsertedIdx & (NumElts-1)] =
ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
return V;
}
if (VecOp == RHS) {
Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
// Everything but the extracted element is replaced with the RHS.
for (unsigned i = 0; i != NumElts; ++i) {
if (i != InsertedIdx)
Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
}
return V;
}
// If this insertelement is a chain that comes from exactly these two
// vectors, return the vector and the effective shuffle.
if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
return EI->getOperand(0);
}
}
}
// TODO: Handle shufflevector here!
// Otherwise, can't do anything fancy. Return an identity vector.
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
return V;
}
Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
Value *VecOp = IE.getOperand(0);
Value *ScalarOp = IE.getOperand(1);
Value *IdxOp = IE.getOperand(2);
// Inserting an undef or into an undefined place, remove this.
if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
ReplaceInstUsesWith(IE, VecOp);
// If the inserted element was extracted from some other vector, and if the
// indexes are constant, try to turn this into a shufflevector operation.
if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
EI->getOperand(0)->getType() == IE.getType()) {
unsigned NumVectorElts = IE.getType()->getNumElements();
unsigned ExtractedIdx =
cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
if (ExtractedIdx >= NumVectorElts) // Out of range extract.
return ReplaceInstUsesWith(IE, VecOp);
if (InsertedIdx >= NumVectorElts) // Out of range insert.
return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
// If we are extracting a value from a vector, then inserting it right
// back into the same place, just use the input vector.
if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
return ReplaceInstUsesWith(IE, VecOp);
// We could theoretically do this for ANY input. However, doing so could
// turn chains of insertelement instructions into a chain of shufflevector
// instructions, and right now we do not merge shufflevectors. As such,
// only do this in a situation where it is clear that there is benefit.
if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
// Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
// the values of VecOp, except then one read from EIOp0.
// Build a new shuffle mask.
std::vector<Constant*> Mask;
if (isa<UndefValue>(VecOp))
Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
else {
assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
NumVectorElts));
}
Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
return new ShuffleVectorInst(EI->getOperand(0), VecOp,
ConstantVector::get(Mask));
}
// If this insertelement isn't used by some other insertelement, turn it
// (and any insertelements it points to), into one big shuffle.
if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
std::vector<Constant*> Mask;
Value *RHS = 0;
Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
if (RHS == 0) RHS = UndefValue::get(LHS->getType());
// We now have a shuffle of LHS, RHS, Mask.
return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
}
}
}
return 0;
}
Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
Value *LHS = SVI.getOperand(0);
Value *RHS = SVI.getOperand(1);
std::vector<unsigned> Mask = getShuffleMask(&SVI);
bool MadeChange = false;
// Undefined shuffle mask -> undefined value.
if (isa<UndefValue>(SVI.getOperand(2)))
return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
// If we have shuffle(x, undef, mask) and any elements of mask refer to
// the undef, change them to undefs.
if (isa<UndefValue>(SVI.getOperand(1))) {
// Scan to see if there are any references to the RHS. If so, replace them
// with undef element refs and set MadeChange to true.
for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
if (Mask[i] >= e && Mask[i] != 2*e) {
Mask[i] = 2*e;
MadeChange = true;
}
}
if (MadeChange) {
// Remap any references to RHS to use LHS.
std::vector<Constant*> Elts;
for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
if (Mask[i] == 2*e)
Elts.push_back(UndefValue::get(Type::Int32Ty));
else
Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
}
SVI.setOperand(2, ConstantVector::get(Elts));
}
}
// Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
// Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
if (LHS == RHS || isa<UndefValue>(LHS)) {
if (isa<UndefValue>(LHS) && LHS == RHS) {
// shuffle(undef,undef,mask) -> undef.
return ReplaceInstUsesWith(SVI, LHS);
}
// Remap any references to RHS to use LHS.
std::vector<Constant*> Elts;
for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
if (Mask[i] >= 2*e)
Elts.push_back(UndefValue::get(Type::Int32Ty));
else {
if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
(Mask[i] < e && isa<UndefValue>(LHS)))
Mask[i] = 2*e; // Turn into undef.
else
Mask[i] &= (e-1); // Force to LHS.
Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
}
}
SVI.setOperand(0, SVI.getOperand(1));
SVI.setOperand(1, UndefValue::get(RHS->getType()));
SVI.setOperand(2, ConstantVector::get(Elts));
LHS = SVI.getOperand(0);
RHS = SVI.getOperand(1);
MadeChange = true;
}
// Analyze the shuffle, are the LHS or RHS and identity shuffles?
bool isLHSID = true, isRHSID = true;
for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
if (Mask[i] >= e*2) continue; // Ignore undef values.
// Is this an identity shuffle of the LHS value?
isLHSID &= (Mask[i] == i);
// Is this an identity shuffle of the RHS value?
isRHSID &= (Mask[i]-e == i);
}
// Eliminate identity shuffles.
if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
// If the LHS is a shufflevector itself, see if we can combine it with this
// one without producing an unusual shuffle. Here we are really conservative:
// we are absolutely afraid of producing a shuffle mask not in the input
// program, because the code gen may not be smart enough to turn a merged
// shuffle into two specific shuffles: it may produce worse code. As such,
// we only merge two shuffles if the result is one of the two input shuffle
// masks. In this case, merging the shuffles just removes one instruction,
// which we know is safe. This is good for things like turning:
// (splat(splat)) -> splat.
if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
if (isa<UndefValue>(RHS)) {
std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
std::vector<unsigned> NewMask;
for (unsigned i = 0, e = Mask.size(); i != e; ++i)
if (Mask[i] >= 2*e)
NewMask.push_back(2*e);
else
NewMask.push_back(LHSMask[Mask[i]]);
// If the result mask is equal to the src shuffle or this shuffle mask, do
// the replacement.
if (NewMask == LHSMask || NewMask == Mask) {
std::vector<Constant*> Elts;
for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
if (NewMask[i] >= e*2) {
Elts.push_back(UndefValue::get(Type::Int32Ty));
} else {
Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
}
}
return new ShuffleVectorInst(LHSSVI->getOperand(0),
LHSSVI->getOperand(1),
ConstantVector::get(Elts));
}
}
}
return MadeChange ? &SVI : 0;
}
/// TryToSinkInstruction - Try to move the specified instruction from its
/// current block into the beginning of DestBlock, which can only happen if it's
/// safe to move the instruction past all of the instructions between it and the
/// end of its block.
static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
assert(I->hasOneUse() && "Invariants didn't hold!");
// Cannot move control-flow-involving, volatile loads, vaarg, etc.
if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
return false;
// Do not sink alloca instructions out of the entry block.
if (isa<AllocaInst>(I) && I->getParent() ==
&DestBlock->getParent()->getEntryBlock())
return false;
// We can only sink load instructions if there is nothing between the load and
// the end of block that could change the value.
if (I->mayReadFromMemory()) {
for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Scan != E; ++Scan)
if (Scan->mayWriteToMemory())
return false;
}
BasicBlock::iterator InsertPos = DestBlock->begin();
while (isa<PHINode>(InsertPos)) ++InsertPos;
I->moveBefore(InsertPos);
++NumSunkInst;
return true;
}
/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
/// all reachable code to the worklist.
///
/// This has a couple of tricks to make the code faster and more powerful. In
/// particular, we constant fold and DCE instructions as we go, to avoid adding
/// them to the worklist (this significantly speeds up instcombine on code where
/// many instructions are dead or constant). Additionally, if we find a branch
/// whose condition is a known constant, we only visit the reachable successors.
///
static void AddReachableCodeToWorklist(BasicBlock *BB,
SmallPtrSet<BasicBlock*, 64> &Visited,
InstCombiner &IC,
const TargetData *TD) {
std::vector<BasicBlock*> Worklist;
Worklist.push_back(BB);
while (!Worklist.empty()) {
BB = Worklist.back();
Worklist.pop_back();
// We have now visited this block! If we've already been here, ignore it.
if (!Visited.insert(BB)) continue;
for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Instruction *Inst = BBI++;
// DCE instruction if trivially dead.
if (isInstructionTriviallyDead(Inst)) {
++NumDeadInst;
DOUT << "IC: DCE: " << *Inst;
Inst->eraseFromParent();
continue;
}
// ConstantProp instruction if trivially constant.
if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Inst->replaceAllUsesWith(C);
++NumConstProp;
Inst->eraseFromParent();
continue;
}
IC.AddToWorkList(Inst);
}
// Recursively visit successors. If this is a branch or switch on a
// constant, only visit the reachable successor.
TerminatorInst *TI = BB->getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Worklist.push_back(ReachableBB);
continue;
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
// See if this is an explicit destination.
for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
if (SI->getCaseValue(i) == Cond) {
BasicBlock *ReachableBB = SI->getSuccessor(i);
Worklist.push_back(ReachableBB);
continue;
}
// Otherwise it is the default destination.
Worklist.push_back(SI->getSuccessor(0));
continue;
}
}
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Worklist.push_back(TI->getSuccessor(i));
}
}
bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
bool Changed = false;
TD = &getAnalysis<TargetData>();
DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
<< F.getNameStr() << "\n");
{
// Do a depth-first traversal of the function, populate the worklist with
// the reachable instructions. Ignore blocks that are not reachable. Keep
// track of which blocks we visit.
SmallPtrSet<BasicBlock*, 64> Visited;
AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
// Do a quick scan over the function. If we find any blocks that are
// unreachable, remove any instructions inside of them. This prevents
// the instcombine code from having to deal with some bad special cases.
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
if (!Visited.count(BB)) {
Instruction *Term = BB->getTerminator();
while (Term != BB->begin()) { // Remove instrs bottom-up
BasicBlock::iterator I = Term; --I;
DOUT << "IC: DCE: " << *I;
++NumDeadInst;
if (!I->use_empty())
I->replaceAllUsesWith(UndefValue::get(I->getType()));
I->eraseFromParent();
}
}
}
while (!Worklist.empty()) {
Instruction *I = RemoveOneFromWorkList();
if (I == 0) continue; // skip null values.
// Check to see if we can DCE the instruction.
if (isInstructionTriviallyDead(I)) {
// Add operands to the worklist.
if (I->getNumOperands() < 4)
AddUsesToWorkList(*I);
++NumDeadInst;
DOUT << "IC: DCE: " << *I;
I->eraseFromParent();
RemoveFromWorkList(I);
continue;
}
// Instruction isn't dead, see if we can constant propagate it.
if (Constant *C = ConstantFoldInstruction(I, TD)) {
DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
// Add operands to the worklist.
AddUsesToWorkList(*I);
ReplaceInstUsesWith(*I, C);
++NumConstProp;
I->eraseFromParent();
RemoveFromWorkList(I);
continue;
}
// See if we can trivially sink this instruction to a successor basic block.
// FIXME: Remove GetResultInst test when first class support for aggregates
// is implemented.
if (I->hasOneUse() && !isa<GetResultInst>(I)) {
BasicBlock *BB = I->getParent();
BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
if (UserParent != BB) {
bool UserIsSuccessor = false;
// See if the user is one of our successors.
for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
if (*SI == UserParent) {
UserIsSuccessor = true;
break;
}
// If the user is one of our immediate successors, and if that successor
// only has us as a predecessors (we'd have to split the critical edge
// otherwise), we can keep going.
if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
next(pred_begin(UserParent)) == pred_end(UserParent))
// Okay, the CFG is simple enough, try to sink this instruction.
Changed |= TryToSinkInstruction(I, UserParent);
}
}
// Now that we have an instruction, try combining it to simplify it...
#ifndef NDEBUG
std::string OrigI;
#endif
DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
if (Instruction *Result = visit(*I)) {
++NumCombined;
// Should we replace the old instruction with a new one?
if (Result != I) {
DOUT << "IC: Old = " << *I
<< " New = " << *Result;
// Everything uses the new instruction now.
I->replaceAllUsesWith(Result);
// Push the new instruction and any users onto the worklist.
AddToWorkList(Result);
AddUsersToWorkList(*Result);
// Move the name to the new instruction first.
Result->takeName(I);
// Insert the new instruction into the basic block...
BasicBlock *InstParent = I->getParent();
BasicBlock::iterator InsertPos = I;
if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
++InsertPos;
InstParent->getInstList().insert(InsertPos, Result);
// Make sure that we reprocess all operands now that we reduced their
// use counts.
AddUsesToWorkList(*I);
// Instructions can end up on the worklist more than once. Make sure
// we do not process an instruction that has been deleted.
RemoveFromWorkList(I);
// Erase the old instruction.
InstParent->getInstList().erase(I);
} else {
#ifndef NDEBUG
DOUT << "IC: Mod = " << OrigI
<< " New = " << *I;
#endif
// If the instruction was modified, it's possible that it is now dead.
// if so, remove it.
if (isInstructionTriviallyDead(I)) {
// Make sure we process all operands now that we are reducing their
// use counts.
AddUsesToWorkList(*I);
// Instructions may end up in the worklist more than once. Erase all
// occurrences of this instruction.
RemoveFromWorkList(I);
I->eraseFromParent();
} else {
AddToWorkList(I);
AddUsersToWorkList(*I);
}
}
Changed = true;
}
}
assert(WorklistMap.empty() && "Worklist empty, but map not?");
// Do an explicit clear, this shrinks the map if needed.
WorklistMap.clear();
return Changed;
}
bool InstCombiner::runOnFunction(Function &F) {
MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
bool EverMadeChange = false;
// Iterate while there is work to do.
unsigned Iteration = 0;
while (DoOneIteration(F, Iteration++))
EverMadeChange = true;
return EverMadeChange;
}
FunctionPass *llvm::createInstructionCombiningPass() {
return new InstCombiner();
}
| 41.33287 | 85 | 0.597668 | [
"object",
"vector",
"transform"
] |
f35c1a369061c37b81770337d9eb81b252398997 | 6,785 | cpp | C++ | MyNetPhoneClient/decoder/Idct.cpp | Vladimir-Novick/MyNetPhone | 3994085b46ac059e0523ddaf0f5b6effc388106a | [
"MIT"
] | 2 | 2019-06-03T07:29:08.000Z | 2022-01-08T17:41:28.000Z | MyNetPhoneClient/decoder/Idct.cpp | Vladimir-Novick/MyNetPhone | 3994085b46ac059e0523ddaf0f5b6effc388106a | [
"MIT"
] | 1 | 2020-08-28T07:37:25.000Z | 2020-08-28T07:37:25.000Z | MyNetPhoneClient/decoder/Idct.cpp | Vladimir-Novick/MyNetPhone | 3994085b46ac059e0523ddaf0f5b6effc388106a | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////
//
//
// Project : VideoNet Ver. 1.0.
// Description : Video Conferencing over the LAN.
// Author : Vladiimir Novick ( v_novick@yahoo.com )
// Date : 17/12/2005
//
// This is the modified version of tmndecode (H.263 decoder)
// written by Karl & Robert.It was in ANSI C. I have converted into C++
// so that it can be integrated into any windows application. I have
// removed some of the files which had display and file storing
// functions.I have removed the unnecessary code and also added some
// new files..
// Original library dealt with files. Input & Output , both were files.
// I have done some major changes so that it can be used for real time
// decoding process. Now one can use this library for decoding H263 frames.
//
//
// File description :
// Name : Idct.cpp
//
/////////////////////////////////////////////////////////////////////////////
/************************************************************************
*
* idct.c, inverse fast DCT for tmndecode (H.263 decoder)
* Copyright (C) 1996 Telenor R&D, Norway
* Karl Olav Lillevold <Karl.Lillevold@nta.no>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Karl Olav Lillevold <Karl.Lillevold@nta.no>
* Telenor Research and Development
* P.O.Box 83 tel.: +47 63 84 84 00
* N-2007 Kjeller, Norway fax.: +47 63 81 00 76
*
* Robert Danielsen e-mail: Robert.Danielsen@nta.no
* Telenor Research and Development www: http://www.nta.no/brukere/DVC/
* P.O.Box 83 tel.: +47 63 84 84 00
* N-2007 Kjeller, Norway fax.: +47 63 81 00 76
*
************************************************************************/
/*
* based on mpeg2decode, (C) 1994, MPEG Software Simulation Group
* and mpeg2play, (C) 1994 Stefan Eckart
* <stefan@lis.e-technik.tu-muenchen.de>
*
*/
/**********************************************************/
/* inverse two dimensional DCT, Chen-Wang algorithm */
/* (cf. IEEE ASSP-32, pp. 803-816, Aug. 1984) */
/* 32-bit integer arithmetic (8 bit coefficients) */
/* 11 mults, 29 adds per DCT */
/* sE, 18.8.91 */
/**********************************************************/
/* coefficients extended to 12 bit for IEEE1180-1990 */
/* compliance sE, 2.1.94 */
/**********************************************************/
/* this code assumes >> to be a two's-complement arithmetic */
/* right shift: (-2)>>1 == -1 , (-3)>>1 == -2 */
#include "Idct.h"
/* row (horizontal) IDCT
*
* 7 pi 1
* dst[k] = sum c[l] * src[l] * cos( -- * ( k + - ) * l )
* l=0 8 2
*
* where: c[0] = 128
* c[1..7] = 128*sqrt(2)
*/
static void idctrow(short *blk)
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8;
/* shortcut */
if (!((x1 = blk[4]<<11) | (x2 = blk[6]) | (x3 = blk[2]) |
(x4 = blk[1]) | (x5 = blk[7]) | (x6 = blk[5]) | (x7 = blk[3])))
{
blk[0]=blk[1]=blk[2]=blk[3]=blk[4]=blk[5]=blk[6]=blk[7]=blk[0]<<3;
return;
}
x0 = (blk[0]<<11) + 128; /* for proper rounding in the fourth stage */
/* first stage */
x8 = W7*(x4+x5);
x4 = x8 + (W1-W7)*x4;
x5 = x8 - (W1+W7)*x5;
x8 = W3*(x6+x7);
x6 = x8 - (W3-W5)*x6;
x7 = x8 - (W3+W5)*x7;
/* second stage */
x8 = x0 + x1;
x0 -= x1;
x1 = W6*(x3+x2);
x2 = x1 - (W2+W6)*x2;
x3 = x1 + (W2-W6)*x3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
/* third stage */
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181*(x4+x5)+128)>>8;
x4 = (181*(x4-x5)+128)>>8;
/* fourth stage */
blk[0] = (x7+x1)>>8;
blk[1] = (x3+x2)>>8;
blk[2] = (x0+x4)>>8;
blk[3] = (x8+x6)>>8;
blk[4] = (x8-x6)>>8;
blk[5] = (x0-x4)>>8;
blk[6] = (x3-x2)>>8;
blk[7] = (x7-x1)>>8;
}
/* column (vertical) IDCT
*
* 7 pi 1
* dst[8*k] = sum c[l] * src[8*l] * cos( -- * ( k + - ) * l )
* l=0 8 2
*
* where: c[0] = 1/1024
* c[1..7] = (1/1024)*sqrt(2)
*/
static void idctcol(short *blk)
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8;
/* shortcut */
if (!((x1 = (blk[8*4]<<8)) | (x2 = blk[8*6]) | (x3 = blk[8*2]) |
(x4 = blk[8*1]) | (x5 = blk[8*7]) | (x6 = blk[8*5]) | (x7 = blk[8*3])))
{
blk[8*0]=blk[8*1]=blk[8*2]=blk[8*3]=blk[8*4]=blk[8*5]=blk[8*6]=blk[8*7]=
iclp[(blk[8*0]+32)>>6];
return;
}
x0 = (blk[8*0]<<8) + 8192;
/* first stage */
x8 = W7*(x4+x5) + 4;
x4 = (x8+(W1-W7)*x4)>>3;
x5 = (x8-(W1+W7)*x5)>>3;
x8 = W3*(x6+x7) + 4;
x6 = (x8-(W3-W5)*x6)>>3;
x7 = (x8-(W3+W5)*x7)>>3;
/* second stage */
x8 = x0 + x1;
x0 -= x1;
x1 = W6*(x3+x2) + 4;
x2 = (x1-(W2+W6)*x2)>>3;
x3 = (x1+(W2-W6)*x3)>>3;
x1 = x4 + x6;
x4 -= x6;
x6 = x5 + x7;
x5 -= x7;
/* third stage */
x7 = x8 + x3;
x8 -= x3;
x3 = x0 + x2;
x0 -= x2;
x2 = (181*(x4+x5)+128)>>8;
x4 = (181*(x4-x5)+128)>>8;
/* fourth stage */
blk[8*0] = iclp[(x7+x1)>>14];
blk[8*1] = iclp[(x3+x2)>>14];
blk[8*2] = iclp[(x0+x4)>>14];
blk[8*3] = iclp[(x8+x6)>>14];
blk[8*4] = iclp[(x8-x6)>>14];
blk[8*5] = iclp[(x0-x4)>>14];
blk[8*6] = iclp[(x3-x2)>>14];
blk[8*7] = iclp[(x7-x1)>>14];
}
/* two dimensional inverse discrete cosine transform */
void idct(short *block)
{
int i;
for (i=0; i<8; i++)
idctrow(block+8*i);
for (i=0; i<8; i++)
idctcol(block+i);
}
void init_idct()
{
int i;
iclp = iclip+512;
for (i= -512; i<512; i++)
iclp[i] = (i<-256) ? -256 : ((i>255) ? 255 : i);
}
| 30.022124 | 80 | 0.456153 | [
"transform"
] |
f35d6482c8b1b078e3e9b76e438400896cb4d17c | 3,482 | cpp | C++ | src/main_minimum_tracking_example.cpp.cpp | ibogun/DeepAntrack | 0b13d363a30c8ad63c0e2c8cbc16aebff90de69a | [
"MIT"
] | 1 | 2016-09-13T18:20:17.000Z | 2016-09-13T18:20:17.000Z | src/main_minimum_tracking_example.cpp.cpp | ibogun/DeepAntrack | 0b13d363a30c8ad63c0e2c8cbc16aebff90de69a | [
"MIT"
] | null | null | null | src/main_minimum_tracking_example.cpp.cpp | ibogun/DeepAntrack | 0b13d363a30c8ad63c0e2c8cbc16aebff90de69a | [
"MIT"
] | null | null | null | //
// main.cpp
// Robust Struck
//
// Created by Ivan Bogun on 10/5/14.
// Copyright (c) 2014 Ivan Bogun. All rights reserved.
//
#include <opencv2/opencv.hpp>
#include <glog/logging.h>
#include <gflags/gflags.h>
#include "Tracker/Struck.h"
#include "Tracker/ObjDetectorStruck.h"
DEFINE_int32(budget, 100, "Budget");
DEFINE_int32(display, 1, "Display settings.");
DEFINE_double(lambda_s, 0.3, "Straddling lambda in ObjDetectorTracker().");
DEFINE_double(lambda_e, 0.3, "Edge density lambda in ObjDetectorTracker().");
DEFINE_double(inner, 0.9, "Inner bounding box for objectness.");
DEFINE_double(straddeling_threshold, 1.5,
"Straddeling threshold.");
DEFINE_int32(frame_from, 0, "Frame from");
DEFINE_int32(frame_to, 5000, "Frame to");
DEFINE_int32(tracker_type, 1,
"Type of the tracker (RobStruck - 0, ObjDet - 1, FilterBad - 2)");
DEFINE_double(topK, 50, "Top K objectness boxes in FilterBadStruck tracker.");
int main(int argc, char *argv[]) {
google::InitGoogleLogging(argv[0]);
gflags::ParseCommandLineFlags(&argc, &argv, true);
std::string feature = "hogANDhist";
std::string kernel = "int";
bool pretraining = false;
bool filter = true;
bool straddling = false;
bool edgeness = false;
bool spatialPrior = false;
std::string note = " Object Struck tracker";
int frames = 10;
int tracker_type = FLAGS_tracker_type;
pair<string, vector<string>> gt_images = video_gt_images[vidIndex];
vector<cv::Rect> groundTruth = dataset->readGroundTruth(gt_images.first);
int useFilter = filter;
bool useStraddling = straddling;
bool useEdgeDensity = edgeness;
bool scalePrior = spatialPrior;
Struck* tracker = new
ObjDetectorStruck(pretraining, useFilter,
useEdgeDensity, useStraddling,
scalePrior,
kernel,
feature, note);
//ObjDetectorStruck tracker(pretraining, filter, edgeness,
// straddling,
// spatialPrior, kernel, feature, note);
std::unordered_map<std::string, double> map;
map.insert(std::make_pair("lambda_straddling", FLAGS_lambda_s));
map.insert(std::make_pair("lambda_edgeness", FLAGS_lambda_e));
map.insert(std::make_pair("inner", FLAGS_inner));
map.insert(std::make_pair("straddling_threshold",
FLAGS_straddeling_threshold));
map.insert(std::make_pair("topK", FLAGS_topK));
tracker->setParams(map);
tracker->display = FLAGS_display;
double b = 10;
cv::Mat image = cv::imread(gt_images.second[startingFrame]);
tracker->initialize(image, rect);
for (int i = startingFrame; i < endingFrame; i++) {
tracker->track(gt_images.second[i]);
std::cout << "Frame #" << i - startingFrame << " out of "
<< endingFrame - startingFrame
<< tracker->getBoundingBoxes()[i - startingFrame] << std::endl;
cv::Mat tracking_image = tracker->getObjectnessCanvas();
std::string savefilename= saveTrackingImage+prefix + std::to_string(1000+i) + ".png";
std::cout<< "saving to file: " << savefilename << std::endl;
cv::imwrite(savefilename, tracking_image);
}
std::string tracker_save_file = dirName + "/" + dataset->videos[vidIndex];
tracker->saveResults(tracker_save_file);
delete vot2014;
delete vot2015;
delete wu2013;
return 0;
}
| 33.161905 | 94 | 0.649627 | [
"object",
"vector"
] |
f365696e0a011fb6cdc747aaf752b3de04a3c27f | 9,527 | cpp | C++ | compiler/optimizers/QubitTapering.cpp | zpparks314/xacc-vqe | 37aaadb12d856324532c42ca9f7e56147edbd2e7 | [
"BSD-3-Clause"
] | 14 | 2017-09-15T19:05:11.000Z | 2021-11-04T05:24:51.000Z | compiler/optimizers/QubitTapering.cpp | zpparks314/xacc-vqe | 37aaadb12d856324532c42ca9f7e56147edbd2e7 | [
"BSD-3-Clause"
] | 25 | 2017-08-08T16:03:55.000Z | 2019-12-22T12:18:27.000Z | compiler/optimizers/QubitTapering.cpp | zpparks314/xacc-vqe | 37aaadb12d856324532c42ca9f7e56147edbd2e7 | [
"BSD-3-Clause"
] | 17 | 2018-06-25T20:20:16.000Z | 2021-04-03T18:31:44.000Z | #include "QubitTapering.hpp"
#include "PauliOperator.hpp"
#include "MPIProvider.hpp"
#include "DiagonalizeTask.hpp"
#include <algorithm>
#include <iomanip>
namespace xacc {
namespace vqe {
Eigen::MatrixXi QubitTapering::computeTableaux(PauliOperator &H, const int n) {
int nRows = 0;
Eigen::MatrixXi tableaux;
for (auto &term : H) {
Eigen::VectorXi x(n), z(n), row(2 * n);
auto p = term.second.toBinaryVector(n);
int c = 0;
for (auto &i : p.first) {
z(c) = i;
c++;
}
c = 0;
for (auto &i : p.second) {
x(c) = i;
c++;
}
row << x, z;
if (row != Eigen::VectorXi::Zero(2 * n)) {
nRows++;
tableaux.conservativeResize(nRows, 2 * n);
tableaux.row(nRows - 1) = row;
}
}
return tableaux;
}
std::vector<std::vector<int>> QubitTapering::generateCombinations(
const int n, std::function<void(std::vector<int> &)> &&f) {
std::vector<std::vector<int>> combinations;
for (int nOnes = 0; nOnes <= n; nOnes++) {
std::vector<int> test(n);
for (int k = 0; k < nOnes; k++)
test[n - k - 1] = 1;
do {
// Perform custom mapping on the vector before adding
// By default this does nothing
f(test);
combinations.push_back(test);
} while (std::next_permutation(test.begin(), test.end()));
}
return combinations;
}
int QubitTapering::binaryVectorInnerProduct(std::vector<int> &bv1,
std::vector<int> &bv2) {
std::vector<int> ax(bv1.begin(), bv1.begin() + bv1.size() / 2);
std::vector<int> az(bv1.begin() + bv1.size() / 2, bv1.begin() + bv1.size());
std::vector<int> bx(bv2.begin(), bv2.begin() + bv2.size() / 2);
std::vector<int> bz(bv2.begin() + bv2.size() / 2, bv2.begin() + bv2.size());
Eigen::VectorXi axv = Eigen::Map<Eigen::VectorXi>(ax.data(), ax.size());
Eigen::VectorXi azv = Eigen::Map<Eigen::VectorXi>(az.data(), az.size());
Eigen::VectorXi bxv = Eigen::Map<Eigen::VectorXi>(bx.data(), bx.size());
Eigen::VectorXi bzv = Eigen::Map<Eigen::VectorXi>(bz.data(), bz.size());
return (axv.dot(bzv) + azv.dot(bxv)) % 2;
}
std::shared_ptr<IR> QubitTapering::transform(std::shared_ptr<IR> ir) {
// Convert the IR into a Hamiltonian
PauliOperator H;
H.fromXACCIR(ir);
auto n = H.nQubits();
int counter = 0;
// Compute Tableaux of the hamiltonian,
// This is the E matrix from arxiv:1701.08213
Eigen::MatrixXi tableaux = computeTableaux(H, n);
std::vector<int> pivotCols;
// Convert tableaux to rref
Eigen::MatrixXi b = gauss(tableaux, pivotCols);
// Get linear independent vectors from rref
int ker_dim = 2 * n - pivotCols.size();
Eigen::MatrixXi linIndVecs(pivotCols.size(), 2 * n);
linIndVecs.setZero();
std::vector<std::vector<int>> linIndVecsVector;
for (int i = 0; i < pivotCols.size(); i++) {
linIndVecs.row(i) = b.row(i);
}
// Build up the symmetry group generators
std::vector<int> zero(2 * n);
std::set<std::vector<int>> generators, generated;
generated.insert(zero);
// Get all g_z (combinations of nqubit 1s and 0s)
auto combinations = generateCombinations(n);
// Lambda to compute the union of 2 sets
auto getUnion = [](const std::set<std::vector<int>> &a,
const std::set<std::vector<int>> &b) {
std::set<std::vector<int>> result = a;
result.insert(b.begin(), b.end());
return result;
};
// Loop over the g_z 0s and 1s combinations
for (auto &gz : combinations) {
std::vector<int> tau(n);
tau.insert(tau.end(), gz.begin(), gz.end());
if (generated.find(tau) != generated.end()) {
continue;
} else {
int sum = 0;
for (int i = 0; i < linIndVecs.rows(); i++) {
Eigen::VectorXi row = linIndVecs.row(i);
std::vector<int> h(2 * n);
Eigen::VectorXi::Map(&h[0], 2 * n) = row;
sum += binaryVectorInnerProduct(tau, h);
}
if (sum == 0) {
generators.insert(tau);
counter++;
if (counter == ker_dim)
break;
for (auto &g : generators) {
std::vector<int> s(2 * n);
for (int i = 0; i < 2 * n; i++) {
s[i] = (tau[i] + g[i]) % 2;
}
std::set<std::vector<int>> unionSet = getUnion(generators, generated);
if (unionSet.find(s) == unionSet.end()) {
generated.insert(s);
}
}
}
}
}
// Create the tau generators
std::vector<PauliOperator> taus;
for (auto &g : generators) {
std::map<int, std::string> terms;
for (int i = 0; i < 2 * n; i++) {
if (g[i] == 1) {
if (i < n) {
terms.insert({i, "X"});
} else {
terms.insert({i - n, "Z"});
}
}
}
taus.emplace_back(terms);
}
// for (auto t : taus) std::cout << "GEN: " << t.toString() << "\n";
// Lambda to compute hermitian conjugate of PauliOperator
auto hc = [](PauliOperator &op) {
PauliOperator newOp = op;
for (auto &kv : newOp) {
kv.second.coeff() = std::conj(kv.second.coeff());
}
return newOp;
};
// Compute U = U1 U2 U3 ...
double invSqrt2 = 1.0 / std::sqrt(2.0);
PauliOperator U(1.0);
for (auto &t : taus) {
int i = t.getTerms().begin()->second.ops().begin()->first;
U *= (t + PauliOperator({{i, "X"}})) * invSqrt2;
U *= (PauliOperator({{i, "X"}}) + PauliOperator({{i, "Z"}})) *
(1.0 / std::sqrt(2));
}
// Use U to compute HPrime
PauliOperator HPrime = hc(U) * H * U;
// Compute rref of HPrime
Eigen::MatrixXi hPrimeTableaux = computeTableaux(HPrime, n);
std::vector<int> hPrimePivotCols;
Eigen::MatrixXi b2 = gauss(hPrimeTableaux, hPrimePivotCols);
// Convert to hPrimePivotCols vector to a set
std::set<int> hPrimePivotColsSet(hPrimePivotCols.begin(),
hPrimePivotCols.end()),
doubleNSet, nSet;
// Generate range(2*n)
for (int i = 0; i < 2 * n; i++)
doubleNSet.insert(i);
// Generate range(n)
for (int i = 0; i < n; i++)
nSet.insert(i);
// Create the phase_sites set which is the difference between
// range(2*nQ) and the hPrimePivotSet
std::set<int> phase_sites, keep_sites;
std::set_difference(doubleNSet.begin(), doubleNSet.end(),
hPrimePivotColsSet.begin(), hPrimePivotColsSet.end(),
std::inserter(phase_sites, phase_sites.end()));
// Create the keep_sites set, i.e. the qubit sites we
// are keeping in the reduction
std::set_difference(nSet.begin(), nSet.end(), phase_sites.begin(),
phase_sites.end(),
std::inserter(keep_sites, keep_sites.end()));
// Generate all 1s and 0s of list size phase_sites.size(), map
// all 0s to -1s.
std::vector<std::vector<int>> phase_configs =
generateCombinations(phase_sites.size(), [&](std::vector<int> &tmp) {
for (int i = 0; i < phase_sites.size(); i++) {
if (tmp[i] == 0)
tmp[i] = -1;
}
return;
});
// Create the reduced hamiltonian
// by mapping operators on unused qubits to
// +-1 subspace
PauliOperator actualReduced;
double energy = 0.0;
for (auto &phases : phase_configs) {
counter = 0;
std::map<int, int> Z2_dict;
for (auto &z : phase_sites) {
Z2_dict.insert({z, phases[counter]});
counter++;
}
PauliOperator reduced;
for (auto &kv : HPrime) {
auto term = kv.second;
if (term.ops().empty()) {
reduced += PauliOperator(term.coeff());
} else {
std::map<int, std::string> newTerm;
double phase = 1.0;
for (auto &termKv : term.ops()) {
if (keep_sites.find(termKv.first) != keep_sites.end()) {
newTerm.insert({termKv.first, termKv.second});
}
if (Z2_dict.count(termKv.first)) {
phase *= Z2_dict[termKv.first];
}
}
reduced += PauliOperator(newTerm, phase * term.coeff());
}
}
// Get the ground state energy to check if this is the
// minimizing sector
auto reducedEnergy = computeGroundStateEnergy(reduced, n);
if (reducedEnergy < energy) {
energy = reducedEnergy;
actualReduced = reduced;
}
}
counter = 0;
std::map<int, int> keepSites2Logical;
for (auto &i : keep_sites) {
keepSites2Logical.insert({i, counter});
counter++;
}
actualReduced.mapQubitSites(keepSites2Logical);
std::stringstream s;
s << std::setprecision(12) << energy;
xacc::info("Reduced Hamiltonian:" + actualReduced.toString() +
", with energy = " + s.str());
if (xacc::optionExists("qubit-tapering-show")) {
xacc::info("Exiting XACC.");
xacc::Finalize();
exit(0);
}
auto newIR = actualReduced.toXACCIR();
// See if we have an ansatz and if so grab
// it and add it to the reduced IR
auto ansatz = std::dynamic_pointer_cast<Function>(
ir->getKernels()[0]->getInstruction(0));
if (ansatz) {
for (auto &k : newIR->getKernels()) {
k->insertInstruction(0, ansatz);
}
}
return newIR;
}
const double QubitTapering::computeGroundStateEnergy(PauliOperator &op,
const int n) {
auto data = op.toDenseMatrix(n).data();
Eigen::MatrixXcd A = Eigen::Map<Eigen::MatrixXcd>(data, std::pow(2,n),std::pow(2,n));
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXcd> es(A);
auto reducedEnergy = es.eigenvalues()[0];
return reducedEnergy;
}
} // namespace vqe
} // namespace xacc
| 29.223926 | 89 | 0.580875 | [
"vector",
"transform"
] |
f371731579c566719c1909ee456570960ee02e35 | 86 | cc | C++ | test/vector-pair.cc | digiperfect/ecolab | 52751dfa805b67b775ea50e37c5d02c2735ed0d2 | [
"MIT"
] | 10 | 2017-04-19T15:02:23.000Z | 2021-02-18T05:03:56.000Z | test/vector-pair.cc | digiperfect/ecolab | 52751dfa805b67b775ea50e37c5d02c2735ed0d2 | [
"MIT"
] | 9 | 2016-01-17T21:14:29.000Z | 2020-01-28T13:18:28.000Z | test/vector-pair.cc | digiperfect/ecolab | 52751dfa805b67b775ea50e37c5d02c2735ed0d2 | [
"MIT"
] | 10 | 2016-01-17T20:32:04.000Z | 2021-11-29T19:11:21.000Z | #include "vector-pair.h"
#include <ecolab_epilogue.h>
VectorPair vp;
make_model(vp);
| 14.333333 | 28 | 0.755814 | [
"vector"
] |
f3764e627b9517d5c11cbc6121bbc4316738d047 | 7,829 | cpp | C++ | pom/sandbox/coloration.cpp | e-Sharp/pom_gen_proc | cef7a57620d52631c1e94f71c71e0455f9e1b653 | [
"MIT"
] | null | null | null | pom/sandbox/coloration.cpp | e-Sharp/pom_gen_proc | cef7a57620d52631c1e94f71c71e0455f9e1b653 | [
"MIT"
] | null | null | null | pom/sandbox/coloration.cpp | e-Sharp/pom_gen_proc | cef7a57620d52631c1e94f71c71e0455f9e1b653 | [
"MIT"
] | null | null | null | #include "pom/io_qt/all.hpp"
#include "pom/io_std/all.hpp"
#include "pom/io_format/srtm/all.hpp"
#include "pom/io_format/wavefront/all.hpp"
#include "pom/maths/matrix/interpolation.hpp"
#include "pom/maths/vector/all.hpp"
#include "pom/maths/gradient.hpp"
#include "pom/maths/noise.hpp"
#include "pom/maths/numeric.hpp"
#include "pom/terrain/all.hpp"
#include "pom/terrain/examples.hpp"
#include "pom/terrain/imports.hpp"
#include "pom/terrain/paths.hpp"
#include "pom/terrain/terrain_test.hpp"
#include <cmath>
#include <iostream>
#include <vector>
#include <fstream>
#include <stdlib.h>
using namespace pom;
using namespace pom::maths;
using namespace pom::maths;
using namespace pom::terrain;
template<typename Ty>
constexpr auto pi = static_cast<Ty>(3.14159265359L);
//lerp
static_vector<float, 3> lerp(static_vector<float, 3> l, static_vector<float, 3> r, float t) {
auto x = at(l, 0) * (1 - t) + at(r, 0) * t;
auto y = at(l, 1) * (1 - t) + at(r, 1) * t;
auto z = at(l, 2) * (1 - t) + at(r, 2) * t;
auto vec = maths::vector<3>({x, y, z});
return vec;
}
float randMap() {
float min = 0;
float max = 1;
return min + (float)(rand()) / ((float)(RAND_MAX / (max - min)));
}
// void sandTexture() {
// auto white = maths_impl::vector<3>({1.F, 1.0F, 1.0F});
// const int size = 1024;
// float xPeriod = 5;
// float yPeriod = 10;
// std::vector<float> tex(size);
// for(auto i = 0; i < size; ++i) {
// for(auto j = 0; j < size; ++j) {
// float xy = i * xPeriod + j * yPeriod;
// tex[size * j + i] = randMap() * white * sin(xy * pi<float> / 10);
// }
// }
// }
static_vector<float, 3> color(static_vector<float, 3> xyz, float slope) {
//////////////////////////////////////////////////////////////////////////////////////////////// PAR ICI
// auto hmax = 10000;
// auto ground = 0;
// auto snow = 2000;
// auto rock = 3000;
// auto grass = 1500;
// auto elevation = at(xyz, 2);
auto black = maths_impl::vector<3>({.0F, .0F, .0F});
auto white = maths_impl::vector<3>({1.F, 1.0F, 1.0F});
auto grey = maths_impl::vector<3>({.41F, .41F, .41F});
//Grayscale slope
return lerp(black, white, slope);
// Grayscale height
// if(elevation > ground) {
// float t = (elevation - ground) / (hmax - ground);
// return lerp(black, white, t);
// }
//Snow
// if(slope < 0.35) {
// auto blendAmount = slope / 0.35;
// return lerp(grey, white, blendAmount);
// }
// else if(slope >= 0.35) {
// auto t = (elevation - ground) / (hmax - ground);
// return lerp(grey, black, t);
// }
//Snow and grass
//snow = 2000
//grass = 1500
// auto darkgreen = maths_impl::vector<3>({.49F, .55F, .3F});
// auto green = maths_impl::vector<3>({.71F, .73F, .38F});
// auto darkbrown = maths_impl::vector<3>({.22F, .16F, .11F});
// auto brown = maths_impl::vector<3>({.45F, .33F, .16F});
// auto beige = maths_impl::vector<3>({.9F, .85F, .76F});
// auto skyblue = maths_impl::vector<3>({.71F, .89F, .86F});
// if(elevation > ground) {
// if(slope < 0.35 && elevation > snow) {
// auto blendAmount = slope / 0.35;
// return lerp(grey, white, blendAmount);
// }
// else if(slope < 0.3 && elevation < grass) {
// auto blendAmount = slope / 0.3;
// return lerp(darkgreen, green, blendAmount);
// }
// else
// return lerp(darkbrown, grey, slope);
// }
//desert
//sand texture test
// float xPeriod = 5;
// float yPeriod = 10;
// auto x = at(xyz, 0);
// auto y = at(xyz, 1);
// float xy = x * xPeriod + y * yPeriod;
// return randMap() * white * sin(xy * pi<float> / 10);
}
vec3f color(const himalayas& hs, vec2f xy) {
auto h = height(hs, xy);
auto g = gradient(hs, xy);
auto n = normal(hs, xy);
//float slope = 1 - at(n, 2);
float slope = atan(sqrt(at(n, 0) * at(n, 0) + at(n, 1) * at(n, 1)) / at(n, 2));
slope = (slope / (pi<float> / 2));
return color({at(xy, 0), at(xy, 1), h}, slope);
}
void throwing_main() {
auto h = dune();
auto hf = heightfield{};
{ // Reading data.
hf.heights = matrix_cr<float>(1000, 1000);
hf.x_domain = h.x_domain;
auto ci_to_x = maths::mapping(maths::interval_0_n(col_count(hf.heights)), hf.x_domain);
hf.y_domain = h.y_domain;
auto ri_to_y = maths::mapping(maths::interval_0_n(row_count(hf.heights)), hf.y_domain);
for(auto ri : maths::row_indexes(hf.heights)) {
auto y = ri_to_y(ri);
for(auto ci : maths::col_indexes(hf.heights)) {
auto x = ci_to_x(ci);
at_cr(hf.heights, ci, ri) = height({x, y});
}
}
}
{ // Outputing mesh.
auto chunk_side = std::size_t{512};
auto cmax = positive_ceiled_quotient(col_count(hf.heights), chunk_side);
auto rmax = positive_ceiled_quotient(row_count(hf.heights), chunk_side);
auto w = wavefront(view_cr(hf.heights, {0, 0}, {1, 1}));
auto ci_to_x = ci_to_x_mapping(hf);
auto ri_to_y = ri_to_y_mapping(hf);
auto ci_to_u = ci_to_u_mapping(hf);
auto ri_to_v = ri_to_v_mapping(hf);
for(std::size_t ri = 0; ri < rmax; ++ri) {
auto r1 = ri * chunk_side;
auto r2 = std::min(r1 + chunk_side, row_count(hf.heights) - 1);
for(std::size_t ci = 0; ci < cmax; ++ci) {
auto c1 = ci * chunk_side;
auto c2 = std::min(c1 + chunk_side, col_count(hf.heights) - 1);
if(c1 != c2 && r1 != r2){
auto f = io_std::open_file(std::string(output_folder) + "/mesh_" + std::to_string(ci) + "_" + std::to_string(ri) + ".obj", std::ios::out);
w.heights = view_cr(hf.heights, {c1, r1}, {c2 - c1, r2 - r1});
w.x_domain = {ci_to_x(c1), ci_to_x(c2)};
w.y_domain = {ri_to_y(r1), ri_to_y(r2)};
w.u_domain = {ci_to_u(c1), ci_to_u(c2)};
w.v_domain = {ri_to_v(r1), ri_to_v(r2)};
io_format::wavefront::write(f, w);
}
}
}
}
{ // Outputing normals.
auto ns = maths::same_size_matrix<vec3f>(hf.heights);
auto ci_to_x = maths::mapping(maths::interval_0_n(col_count(ns) - 1), h.x_domain);
auto ri_to_y = maths::mapping(maths::interval_0_n(row_count(ns) - 1), h.y_domain);
for(auto ri : maths::row_indexes(ns))
for(auto ci : maths::col_indexes(ns)) {
auto n = normal(h, {ci_to_x(ci), ri_to_y(ri)}) / 2.f + 0.5f;
at_cr(ns, ci, ri) = n;
}
io_qt::to_image(ns).save((std::string(output_folder) + "/normals.png").c_str());
}
{ // Outputing texture.
auto tx = maths::same_size_matrix<static_vector<float, 3>>(hf.heights);
auto ci_to_x = ci_to_x_mapping(hf);
auto ri_to_y = ri_to_y_mapping(hf);
for(auto ri : maths::row_indexes(hf.heights))
for(auto ci : maths::col_indexes(hf.heights)) {
auto x = ci_to_x(ci);
auto y = ri_to_y(ri);
auto z = at_cr(hf.heights, ci, ri);
at_cr(tx, ci, ri) = color(h, {x, y});
//at_cr(tx, ci, ri) = color({x, y, z});
}
io_qt::to_image(tx).save((std::string(output_folder) + "/texture.png").c_str());
}
}
int main() {
try {
throwing_main();
} catch(const std::exception& e) {
std::cerr << "std::exception: " << e.what() << std::endl;
} catch(...) {
std::cerr << "Unhandled exception." << std::endl;
return -1;
}
return 0;
}
| 34.187773 | 158 | 0.535317 | [
"mesh",
"vector"
] |
f377276a766e8eb2907394514fd8c9dd12b8f281 | 3,437 | cpp | C++ | boboleetcode/Play-Leetcode-master/0148-Sort-List/cpp-0148/main2.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2019-03-20T17:05:59.000Z | 2019-10-15T07:56:45.000Z | boboleetcode/Play-Leetcode-master/0148-Sort-List/cpp-0148/main2.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/0148-Sort-List/cpp-0148/main2.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/two-sum/description/
/// Author : liuyubobobo
/// Time : 2018-08-21
#include <iostream>
#include <vector>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class ListOp{
public:
// 根据n个元素的数组arr创建一个链表, 并返回链表的头
static ListNode* createLinkedList(const vector<int>& arr){
if(arr.size() == 0)
return NULL;
ListNode* head = new ListNode(arr[0]);
ListNode* curNode = head;
for(int i = 1 ; i < arr.size() ; i ++){
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}
// 打印以head为头结点的链表信息内容
static void printLinkedList(ListNode* head){
ListNode* curNode = head;
while(curNode){
cout << curNode->val << " -> ";
curNode = curNode->next;
}
cout << "NULL" << endl;
}
// 释放以head为头结点的链表空间
static void deleteLinkedList(ListNode* head){
ListNode* curNode = head;
while(curNode){
ListNode* delNode = curNode;
curNode = curNode->next;
delete delNode;
}
}
};
/// Merge Sort Bottom Up
/// Time Complexity: O(nlogn)
/// Space Complexity: O(1)
class Solution {
public:
ListNode* sortList(ListNode* head) {
ListNode* dummyHead = new ListNode(-1);
dummyHead->next = head;
int sz = 1;
while(true){
ListNode *pre = dummyHead, *cur = pre;
while(cur->next){
cur = pre;
for(int i = 0; i < sz && cur->next; i ++, cur = cur->next);
if(cur->next){
ListNode* pre2 = cur;
for(int i = 0; i < sz && cur->next; i ++, cur = cur->next);
ListNode* next = cur->next, *head2 = pre2->next;
pre2->next = NULL, cur->next = NULL;
ListNode* tail;
pre->next = merge(pre->next, head2, tail);
pre = tail;
pre->next = next;
}
else if(pre == dummyHead){
sz = 0;
break;
}
}
if(sz == 0) break;
else sz *= 2;
}
ListNode* ret = dummyHead->next;
delete dummyHead;
return ret;
}
private:
ListNode* merge(ListNode* a, ListNode* b, ListNode* &tail){
ListNode* dummyHead = new ListNode(-1);
ListNode *p1 = a, *p2 = b, *p = dummyHead;
while(p1 && p2)
if(p1->val < p2->val){
p->next = p1;
p1 = p1->next;
p = p->next;
p->next = NULL;
}
else{
p->next = p2;
p2 = p2->next;
p = p->next;
p->next = NULL;
}
if(p1) p->next = p1;
if(p2) p->next = p2;
tail = p;
while(tail->next) tail = tail->next;
ListNode* ret = dummyHead->next;
delete dummyHead;
return ret;
}
};
int main() {
vector<int> arr = {4, 2, 1, 3};
ListNode* head = Solution().sortList(ListOp::createLinkedList(arr));
ListOp::printLinkedList(head);
ListOp::deleteLinkedList(head);
return 0;
} | 24.204225 | 79 | 0.469596 | [
"vector"
] |
f379e2aad57a9c7a28c6d82d6b62f9c04a5f7cea | 1,346 | cpp | C++ | memfinder/memfinder.cpp | aroes/cryptaware | dfc2ae7635faca71df56430e4284d0d5613c9452 | [
"BSD-2-Clause"
] | null | null | null | memfinder/memfinder.cpp | aroes/cryptaware | dfc2ae7635faca71df56430e4284d0d5613c9452 | [
"BSD-2-Clause"
] | null | null | null | memfinder/memfinder.cpp | aroes/cryptaware | dfc2ae7635faca71df56430e4284d0d5613c9452 | [
"BSD-2-Clause"
] | null | null | null | // memfinder.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>
char* GetAddressOfData(DWORD pid, const char *data, size_t len)
{
HANDLE process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (process)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
MEMORY_BASIC_INFORMATION info;
std::vector<char> chunk;
char* p = 0;
while (p < si.lpMaximumApplicationAddress)
{
if (VirtualQueryEx(process, p, &info, sizeof(info)) == sizeof(info))
{
p = (char*)info.BaseAddress;
chunk.resize(info.RegionSize);
SIZE_T bytesRead;
if (ReadProcessMemory(process, p, &chunk[0], info.RegionSize, &bytesRead))
{
for (size_t i = 0; i < (bytesRead - len); ++i)
{
if (memcmp(data, &chunk[i], len) == 0)
{
return (char*)p + i;
}
}
}
p += info.RegionSize;
}
}
}
return 0;
}
int main()
{
const char someData[] = "sequence";
std::cout << "Local data address: " << (void*)someData << "\n";
//Pass whatever process id you like here instead.
DWORD pid = 16736;
char* ret = GetAddressOfData(pid, someData, sizeof(someData));
if (ret)
{
std::cout << "Found: " << (void*)ret << "\n";
}
else
{
std::cout << "Not found\n";
}
return 0;
} | 21.03125 | 87 | 0.621842 | [
"vector"
] |
f37b9416ae76b59905c376a085ba85753c37d756 | 122,979 | cpp | C++ | src/analyser.cpp | OpenCMISS-Dependencies2/libcellml | 9948e5fb6159bbe50bbe0f4bec883ed7190a51f7 | [
"Apache-2.0"
] | 1 | 2021-02-15T01:09:04.000Z | 2021-02-15T01:09:04.000Z | src/analyser.cpp | hsorby/libcellml | 27db3807c0c15591e251aa9fe411967b1cc2dab1 | [
"Apache-2.0"
] | 8 | 2019-09-01T23:37:50.000Z | 2021-05-27T21:20:34.000Z | src/analyser.cpp | hsorby/libcellml | 27db3807c0c15591e251aa9fe411967b1cc2dab1 | [
"Apache-2.0"
] | 1 | 2022-02-04T06:11:40.000Z | 2022-02-04T06:11:40.000Z | /*
Copyright libCellML Contributors
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 "libcellml/analyser.h"
#include "libcellml/analyserequation.h"
#include "libcellml/analyserequationast.h"
#include "libcellml/analyserexternalvariable.h"
#include "libcellml/analysermodel.h"
#include "libcellml/analyservariable.h"
#include "libcellml/component.h"
#include "libcellml/model.h"
#include "libcellml/units.h"
#include "libcellml/validator.h"
#include "libcellml/variable.h"
#include <cmath>
#include "analyserequation_p.h"
#include "analyserequationast_p.h"
#include "analysermodel_p.h"
#include "analyservariable_p.h"
#include "anycellmlelement_p.h"
#include "generator_p.h"
#include "issue_p.h"
#include "logger_p.h"
#include "utilities.h"
#include "xmldoc.h"
#include "xmlutils.h"
#ifdef TRUE
# undef TRUE
#endif
#ifdef FALSE
# undef FALSE
#endif
#ifdef NAN
# undef NAN
#endif
namespace libcellml {
struct AnalyserInternalEquation;
struct AnalyserInternalVariable;
using AnalyserInternalEquationPtr = std::shared_ptr<AnalyserInternalEquation>;
using AnalyserInternalVariablePtr = std::shared_ptr<AnalyserInternalVariable>;
struct AnalyserInternalVariable
{
enum struct Type
{
UNKNOWN,
SHOULD_BE_STATE,
VARIABLE_OF_INTEGRATION,
STATE,
CONSTANT,
COMPUTED_TRUE_CONSTANT,
COMPUTED_VARIABLE_BASED_CONSTANT,
ALGEBRAIC,
OVERCONSTRAINED
};
size_t mIndex = MAX_SIZE_T;
Type mType = Type::UNKNOWN;
VariablePtr mInitialisingVariable;
VariablePtr mVariable;
static AnalyserInternalVariablePtr create(const VariablePtr &variable);
void setVariable(const VariablePtr &variable,
bool checkInitialValue = true);
void makeVoi();
void makeState();
};
AnalyserInternalVariablePtr AnalyserInternalVariable::create(const VariablePtr &variable)
{
auto res = std::shared_ptr<AnalyserInternalVariable> {new AnalyserInternalVariable {}};
res->setVariable(variable);
return res;
}
void AnalyserInternalVariable::setVariable(const VariablePtr &variable,
bool checkInitialValue)
{
if (checkInitialValue && !variable->initialValue().empty()) {
// The variable has an initial value, so it can either be a constant or
// a state. By default, we consider it to be a constant and, if we find
// an ODE for that variable, we will know that it was actually a state.
mType = Type::CONSTANT;
mInitialisingVariable = variable;
}
mVariable = variable;
}
void AnalyserInternalVariable::makeVoi()
{
mType = Type::VARIABLE_OF_INTEGRATION;
}
void AnalyserInternalVariable::makeState()
{
if (mType == Type::UNKNOWN) {
mType = Type::SHOULD_BE_STATE;
} else if (mType == Type::CONSTANT) {
mType = Type::STATE;
}
}
struct AnalyserInternalEquation
{
enum struct Type
{
UNKNOWN,
TRUE_CONSTANT,
VARIABLE_BASED_CONSTANT,
RATE,
ALGEBRAIC
};
size_t mOrder = MAX_SIZE_T;
Type mType = Type::UNKNOWN;
VariablePtrs mDependencies;
AnalyserEquationAstPtr mAst;
std::vector<AnalyserInternalVariablePtr> mVariables;
std::vector<AnalyserInternalVariablePtr> mOdeVariables;
std::vector<AnalyserInternalVariablePtr> mAllVariables;
AnalyserInternalVariablePtr mVariable;
ComponentPtr mComponent = nullptr;
bool mComputedTrueConstant = true;
bool mComputedVariableBasedConstant = true;
static AnalyserInternalEquationPtr create(const ComponentPtr &component);
static AnalyserInternalEquationPtr create(const AnalyserInternalVariablePtr &variable);
void addVariable(const AnalyserInternalVariablePtr &variable);
void addOdeVariable(const AnalyserInternalVariablePtr &odeVariable);
static bool isKnownVariable(const AnalyserInternalVariablePtr &variable);
static bool isKnownOdeVariable(const AnalyserInternalVariablePtr &odeVariable);
static bool hasKnownVariables(const std::vector<AnalyserInternalVariablePtr> &variables);
static bool hasNonConstantVariables(const std::vector<AnalyserInternalVariablePtr> &variables);
bool check(size_t &equationOrder, size_t &stateIndex, size_t &variableIndex,
const AnalyserModelPtr &model);
};
AnalyserInternalEquationPtr AnalyserInternalEquation::create(const ComponentPtr &component)
{
auto res = std::shared_ptr<AnalyserInternalEquation> {new AnalyserInternalEquation {}};
res->mAst = AnalyserEquationAst::create();
res->mComponent = component;
return res;
}
AnalyserInternalEquationPtr AnalyserInternalEquation::create(const AnalyserInternalVariablePtr &variable)
{
auto res = std::shared_ptr<AnalyserInternalEquation> {new AnalyserInternalEquation {}};
res->mVariable = variable;
res->mComponent = owningComponent(variable->mVariable);
return res;
}
void AnalyserInternalEquation::addVariable(const AnalyserInternalVariablePtr &variable)
{
if (std::find(mVariables.begin(), mVariables.end(), variable) == mVariables.end()) {
mVariables.push_back(variable);
mAllVariables.push_back(variable);
}
}
void AnalyserInternalEquation::addOdeVariable(const AnalyserInternalVariablePtr &odeVariable)
{
if (std::find(mOdeVariables.begin(), mOdeVariables.end(), odeVariable) == mOdeVariables.end()) {
mOdeVariables.push_back(odeVariable);
mAllVariables.push_back(odeVariable);
}
}
bool AnalyserInternalEquation::isKnownVariable(const AnalyserInternalVariablePtr &variable)
{
return variable->mType != AnalyserInternalVariable::Type::UNKNOWN;
}
bool AnalyserInternalEquation::isKnownOdeVariable(const AnalyserInternalVariablePtr &odeVariable)
{
return odeVariable->mIndex != MAX_SIZE_T;
}
bool AnalyserInternalEquation::hasKnownVariables(const std::vector<AnalyserInternalVariablePtr> &variables)
{
return std::find_if(variables.begin(), variables.end(), [](const AnalyserInternalVariablePtr &variable) {
return isKnownVariable(variable);
})
!= std::end(variables);
}
bool AnalyserInternalEquation::hasNonConstantVariables(const std::vector<AnalyserInternalVariablePtr> &variables)
{
return std::find_if(variables.begin(), variables.end(), [](const AnalyserInternalVariablePtr &variable) {
return (variable->mType != AnalyserInternalVariable::Type::UNKNOWN)
&& (variable->mType != AnalyserInternalVariable::Type::CONSTANT)
&& (variable->mType != AnalyserInternalVariable::Type::COMPUTED_TRUE_CONSTANT)
&& (variable->mType != AnalyserInternalVariable::Type::COMPUTED_VARIABLE_BASED_CONSTANT);
})
!= std::end(variables);
}
bool AnalyserInternalEquation::check(size_t &equationOrder, size_t &stateIndex,
size_t &variableIndex,
const AnalyserModelPtr &model)
{
// Nothing to check if the equation has already been given an order (i.e.
// everything is fine).
if (mOrder != MAX_SIZE_T) {
return false;
}
// Determine, from the (new) known (ODE) variables, whether the equation is
// used to compute a true constant or a variable-based constant.
mComputedTrueConstant = mComputedTrueConstant
&& !hasKnownVariables(mVariables)
&& !hasKnownVariables(mOdeVariables);
mComputedVariableBasedConstant = mComputedVariableBasedConstant
&& !hasNonConstantVariables(mVariables)
&& !hasNonConstantVariables(mOdeVariables);
// Add, as a dependency, the variables used to compute the (new) known (ODE)
// variables.
for (const auto &variable : mVariables) {
if (isKnownVariable(variable)) {
mDependencies.push_back(variable->mVariable);
}
}
// Stop tracking (new) known (ODE) variables.
mVariables.erase(std::remove_if(mVariables.begin(), mVariables.end(), isKnownVariable), mVariables.end());
mOdeVariables.erase(std::remove_if(mOdeVariables.begin(), mOdeVariables.end(), isKnownOdeVariable), mOdeVariables.end());
// If there is no (ODE) variable left then it means that the equation is
// overconstrained).
auto unknownVariablesOrOdeVariablesLeft = mVariables.size() + mOdeVariables.size();
if (unknownVariablesOrOdeVariablesLeft == 0) {
for (const auto &variable : mAllVariables) {
variable->mType = AnalyserInternalVariable::Type::OVERCONSTRAINED;
}
return false;
}
// If there is one (ODE) variable left then update its variable (to be the
// corresponding one in the component in which the equation is), its type
// (if it is currently unknown), determine its index and determine the type
// of our equation and set its order, if the (ODE) variable is a state,
// computed constant or algebraic variable.
if (unknownVariablesOrOdeVariablesLeft == 1) {
auto variable = mVariables.empty() ? mOdeVariables.front() : mVariables.front();
for (size_t i = 0; i < mComponent->variableCount(); ++i) {
auto localVariable = mComponent->variable(i);
if (model->areEquivalentVariables(variable->mVariable, localVariable)) {
variable->setVariable(localVariable, false);
break;
}
}
if (variable->mType == AnalyserInternalVariable::Type::UNKNOWN) {
variable->mType = mComputedTrueConstant ?
AnalyserInternalVariable::Type::COMPUTED_TRUE_CONSTANT :
mComputedVariableBasedConstant ?
AnalyserInternalVariable::Type::COMPUTED_VARIABLE_BASED_CONSTANT :
AnalyserInternalVariable::Type::ALGEBRAIC;
}
if ((variable->mType == AnalyserInternalVariable::Type::STATE)
|| (variable->mType == AnalyserInternalVariable::Type::COMPUTED_TRUE_CONSTANT)
|| (variable->mType == AnalyserInternalVariable::Type::COMPUTED_VARIABLE_BASED_CONSTANT)
|| (variable->mType == AnalyserInternalVariable::Type::ALGEBRAIC)) {
variable->mIndex = (variable->mType == AnalyserInternalVariable::Type::STATE) ?
++stateIndex :
++variableIndex;
mOrder = ++equationOrder;
mType = (variable->mType == AnalyserInternalVariable::Type::STATE) ?
Type::RATE :
(variable->mType == AnalyserInternalVariable::Type::COMPUTED_TRUE_CONSTANT) ?
Type::TRUE_CONSTANT :
(variable->mType == AnalyserInternalVariable::Type::COMPUTED_VARIABLE_BASED_CONSTANT) ?
Type::VARIABLE_BASED_CONSTANT :
Type::ALGEBRAIC;
mVariable = variable;
return true;
}
}
return false;
}
/**
* @brief The Analyser::AnalyserImpl class.
*
* The private implementation for the Analyser class.
*/
using UnitsMap = std::map<std::string, double>;
using UnitsMaps = std::vector<UnitsMap>;
using UnitsMultipliers = std::vector<double>;
class Analyser::AnalyserImpl: public Logger::LoggerImpl
{
public:
Analyser *mAnalyser = nullptr;
AnalyserModelPtr mModel = AnalyserModel::AnalyserModelImpl::create();
std::vector<AnalyserExternalVariablePtr> mExternalVariables;
std::vector<AnalyserInternalVariablePtr> mInternalVariables;
std::vector<AnalyserInternalEquationPtr> mInternalEquations;
GeneratorPtr mGenerator = libcellml::Generator::create();
std::map<std::string, UnitsPtr> mStandardUnits;
std::map<AnalyserEquationAstPtr, UnitsWeakPtr> mCiCnUnits;
AnalyserImpl();
~AnalyserImpl();
static bool compareVariablesByComponentAndName(const AnalyserInternalVariablePtr &variable1,
const AnalyserInternalVariablePtr &variable2);
static bool isStateVariable(const AnalyserInternalVariablePtr &variable);
static bool isConstantOrAlgebraicVariable(const AnalyserInternalVariablePtr &variable);
static bool compareVariablesByTypeAndIndex(const AnalyserInternalVariablePtr &variable1,
const AnalyserInternalVariablePtr &variable2);
static bool compareEquationsByVariable(const AnalyserInternalEquationPtr &equation1,
const AnalyserInternalEquationPtr &equation2);
size_t mathmlChildCount(const XmlNodePtr &node) const;
XmlNodePtr mathmlChildNode(const XmlNodePtr &node, size_t index) const;
AnalyserInternalVariablePtr internalVariable(const VariablePtr &variable);
VariablePtr voiFirstOccurrence(const VariablePtr &variable,
const ComponentPtr &component);
void analyseNode(const XmlNodePtr &node, AnalyserEquationAstPtr &ast,
const AnalyserEquationAstPtr &astParent,
const ComponentPtr &component,
const AnalyserInternalEquationPtr &equation);
void analyseComponent(const ComponentPtr &component);
void doEquivalentVariables(const VariablePtr &variable,
VariablePtrs &equivalentVariables) const;
VariablePtrs equivalentVariables(const VariablePtr &variable) const;
void analyseEquationAst(const AnalyserEquationAstPtr &ast);
void updateUnitsMapWithStandardUnit(const std::string &unitsName,
UnitsMap &unitsMap,
double unitsExponent);
void updateUnitsMap(const ModelPtr &model, const std::string &unitsName,
UnitsMap &unitsMap, bool userUnitsMap = false,
double unitsExponent = 1.0,
double unitsMultiplier = 0.0);
UnitsMap multiplyDivideUnitsMaps(const UnitsMap &firstUnitsMap,
const UnitsMap &secondUnitsMap,
bool multiply);
UnitsMaps multiplyDivideUnitsMaps(const UnitsMaps &firstUnitsMaps,
const UnitsMaps &secondUnitsMaps,
bool multiply = true);
UnitsMaps multiplyDivideUnitsMaps(const UnitsMaps &unitsMaps,
double factor, bool multiply);
double multiplyDivideUnitsMultipliers(double firstUnitsMultiplier,
double secondUnitsMultiplier,
bool multiply);
UnitsMultipliers multiplyDivideUnitsMultipliers(const UnitsMultipliers &firstUnitsMultipliers,
const UnitsMultipliers &secondUnitsMultipliers,
bool multiply = true);
UnitsMultipliers multiplyDivideUnitsMultipliers(double firstUnitsMultiplier,
const UnitsMultipliers &secondUnitsMultipliers,
bool multiply);
UnitsMultipliers powerRootUnitsMultipliers(const UnitsMultipliers &unitsMultipliers,
double factor, bool power);
bool areSameUnitsMaps(const UnitsMaps &firstUnitsMaps,
const UnitsMaps &secondUnitsMaps);
bool isDimensionlessUnitsMaps(const UnitsMaps &unitsMaps);
bool areSameUnitsMultipliers(const UnitsMultipliers &firstUnitsMultipliers,
const UnitsMultipliers &secondUnitsMultipliers);
void updateUnitsMultiplier(const ModelPtr &model,
const std::string &unitsName,
double &newUnitsMultiplier,
double unitsExponent = 1.0,
double unitsMultiplier = 0.0);
std::string componentName(const AnalyserEquationAstPtr &ast);
double powerValue(const AnalyserEquationAstPtr &ast);
std::string expression(const AnalyserEquationAstPtr &ast,
bool includeHierarchy = true);
std::string expressionUnits(const UnitsMaps &unitsMaps,
const UnitsMultipliers &unitsMultipliers = {});
std::string expressionUnits(const AnalyserEquationAstPtr &ast,
const UnitsMaps &unitsMaps,
const UnitsMaps &userUnitsMaps,
const UnitsMultipliers &unitsMultipliers);
void defaultUnitsMapsAndMultipliers(UnitsMaps &unitsMaps,
UnitsMaps &userUnitsMaps,
UnitsMultipliers &unitsMultipliers);
void analyseEquationUnits(const AnalyserEquationAstPtr &ast,
UnitsMaps &unitsMaps, UnitsMaps &userUnitsMaps,
UnitsMultipliers &unitsMultipliers,
Strings &issueDescriptions);
double scalingFactor(const VariablePtr &variable);
void scaleAst(const AnalyserEquationAstPtr &ast,
const AnalyserEquationAstPtr &astParent,
double scalingFactor);
void scaleEquationAst(const AnalyserEquationAstPtr &ast);
bool isStateRateBased(const AnalyserEquationPtr &equation,
std::vector<AnalyserEquationPtr> &checkedEquations);
void analyseModel(const ModelPtr &model);
std::vector<AnalyserExternalVariablePtr>::const_iterator findExternalVariable(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName) const;
std::vector<AnalyserExternalVariablePtr>::const_iterator findExternalVariable(const AnalyserExternalVariablePtr &externalVariable) const;
};
Analyser::AnalyserImpl::AnalyserImpl()
{
// Customise our generator's profile.
auto profile = mGenerator->profile();
profile->setAbsoluteValueString("abs");
profile->setNaturalLogarithmString("ln");
profile->setCommonLogarithmString("log");
profile->setRemString("rem");
profile->setAsinString("arcsin");
profile->setAcosString("arccos");
profile->setAtanString("arctan");
profile->setAsecString("arcsec");
profile->setAcscString("arccsc");
profile->setAcotString("arccot");
profile->setAsinhString("arcsinh");
profile->setAcoshString("arccosh");
profile->setAtanhString("arctanh");
profile->setAsechString("arcsech");
profile->setAcschString("arccsch");
profile->setAcothString("arccoth");
profile->setTrueString("true");
profile->setFalseString("false");
profile->setEString("exponentiale");
profile->setPiString("pi");
profile->setInfString("infinity");
profile->setNanString("notanumber");
// Retrieve our generator's profile.
mGenerator->mPimpl->retrieveLockedModelAndProfile();
}
Analyser::AnalyserImpl::~AnalyserImpl()
{
// Reset our generator's profile.
mGenerator->mPimpl->resetLockedModelAndProfile();
}
bool Analyser::AnalyserImpl::compareVariablesByComponentAndName(const AnalyserInternalVariablePtr &variable1,
const AnalyserInternalVariablePtr &variable2)
{
auto realComponent1 = owningComponent(variable1->mVariable);
auto realComponent2 = owningComponent(variable2->mVariable);
if (realComponent1->name() == realComponent2->name()) {
return variable1->mVariable->name() < variable2->mVariable->name();
}
return realComponent1->name() < realComponent2->name();
}
bool Analyser::AnalyserImpl::isStateVariable(const AnalyserInternalVariablePtr &variable)
{
return variable->mType == AnalyserInternalVariable::Type::STATE;
}
bool Analyser::AnalyserImpl::isConstantOrAlgebraicVariable(const AnalyserInternalVariablePtr &variable)
{
return (variable->mType == AnalyserInternalVariable::Type::CONSTANT)
|| (variable->mType == AnalyserInternalVariable::Type::COMPUTED_TRUE_CONSTANT)
|| (variable->mType == AnalyserInternalVariable::Type::COMPUTED_VARIABLE_BASED_CONSTANT)
|| (variable->mType == AnalyserInternalVariable::Type::ALGEBRAIC);
}
bool Analyser::AnalyserImpl::compareVariablesByTypeAndIndex(const AnalyserInternalVariablePtr &variable1,
const AnalyserInternalVariablePtr &variable2)
{
if (isStateVariable(variable1) && isConstantOrAlgebraicVariable(variable2)) {
return true;
}
if (isConstantOrAlgebraicVariable(variable1) && isStateVariable(variable2)) {
return false;
}
return variable1->mIndex < variable2->mIndex;
}
bool Analyser::AnalyserImpl::compareEquationsByVariable(const AnalyserInternalEquationPtr &equation1,
const AnalyserInternalEquationPtr &equation2)
{
return compareVariablesByTypeAndIndex(equation1->mVariable, equation2->mVariable);
}
size_t Analyser::AnalyserImpl::mathmlChildCount(const XmlNodePtr &node) const
{
// Return the number of child elements, in the MathML namespace, for the
// given node.
auto childNode = node->firstChild();
size_t res = childNode->isMathmlElement() ? 1 : 0;
while (childNode != nullptr) {
childNode = childNode->next();
if (childNode && childNode->isMathmlElement()) {
++res;
}
}
return res;
}
XmlNodePtr Analyser::AnalyserImpl::mathmlChildNode(const XmlNodePtr &node,
size_t index) const
{
// Return the nth child element of the given node, skipping anything that is
// not in the MathML namespace.
auto res = node->firstChild();
auto childNodeIndex = res->isMathmlElement() ? 0 : MAX_SIZE_T;
while ((res != nullptr) && (childNodeIndex != index)) {
res = res->next();
if (res && res->isMathmlElement()) {
++childNodeIndex;
}
}
return res;
}
AnalyserInternalVariablePtr Analyser::AnalyserImpl::internalVariable(const VariablePtr &variable)
{
// Find and return, if there is one, the internal variable associated with
// the given variable.
AnalyserInternalVariablePtr res = nullptr;
for (const auto &internalVariable : mInternalVariables) {
if (mModel->areEquivalentVariables(variable, internalVariable->mVariable)) {
res = internalVariable;
break;
}
}
if (res != nullptr) {
return res;
}
// No internal variable exists for the given variable, so create one, track
// it and return it.
res = AnalyserInternalVariable::create(variable);
mInternalVariables.push_back(res);
return res;
}
VariablePtr Analyser::AnalyserImpl::voiFirstOccurrence(const VariablePtr &variable,
const ComponentPtr &component)
{
// Recursively look for the first occurrence of the given variable in the
// given component.
for (size_t i = 0; i < component->variableCount(); ++i) {
auto componentVariable = component->variable(i);
if (mModel->areEquivalentVariables(variable, componentVariable)) {
return componentVariable;
}
}
VariablePtr res = nullptr;
for (size_t i = 0; i < component->componentCount() && res == nullptr; ++i) {
res = voiFirstOccurrence(variable, component->component(i));
}
return res;
}
void Analyser::AnalyserImpl::analyseNode(const XmlNodePtr &node,
AnalyserEquationAstPtr &ast,
const AnalyserEquationAstPtr &astParent,
const ComponentPtr &component,
const AnalyserInternalEquationPtr &equation)
{
// Create the AST, if needed.
if (ast.get() == nullptr) {
ast.reset(new AnalyserEquationAst {});
}
// Basic content elements.
if (node->isMathmlElement("apply")) {
// We may have 2, 3 or more child nodes, e.g.
//
// +--------+
// | + |
// "+a" ==> | / \ |
// | a nil |
// +--------+
//
// +-------+
// | + |
// "a+b" ==> | / \ |
// | a b |
// +-------+
//
// +-------------+
// | + |
// | / \ |
// | a + |
// | / \ |
// "a+b+c+d+e" ==> | b + |
// | / \ |
// | c + |
// | / \ |
// | d e |
// +-------------+
auto childCount = mathmlChildCount(node);
analyseNode(mathmlChildNode(node, 0), ast, astParent, component, equation);
analyseNode(mathmlChildNode(node, 1), ast->mPimpl->mOwnedLeftChild, ast, component, equation);
if (childCount >= 3) {
AnalyserEquationAstPtr astRightChild;
AnalyserEquationAstPtr tempAst;
analyseNode(mathmlChildNode(node, childCount - 1), astRightChild, nullptr, component, equation);
for (auto i = childCount - 2; i > 1; --i) {
tempAst = AnalyserEquationAst::create();
analyseNode(mathmlChildNode(node, 0), tempAst, nullptr, component, equation);
analyseNode(mathmlChildNode(node, i), tempAst->mPimpl->mOwnedLeftChild, tempAst, component, equation);
astRightChild->mPimpl->mParent = tempAst;
tempAst->mPimpl->mOwnedRightChild = astRightChild;
astRightChild = tempAst;
}
if (astRightChild != nullptr) {
astRightChild->mPimpl->mParent = ast;
}
ast->mPimpl->mOwnedRightChild = astRightChild;
}
// Assignment, and relational and logical operators.
} else if (node->isMathmlElement("eq")) {
// This element is used both to describe "a = b" and "a == b". We can
// distinguish between the two by checking its grand-parent. If it's a
// "math" element then it means that it is used to describe "a = b"
// otherwise it is used to describe "a == b". In the former case, there
// is nothing more we need to do since `ast` is already of
// AnalyserEquationAst::Type::ASSIGNMENT type.
if (!node->parent()->parent()->isMathmlElement("math")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::EQ, astParent);
mModel->mPimpl->mNeedEqFunction = true;
}
} else if (node->isMathmlElement("neq")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::NEQ, astParent);
mModel->mPimpl->mNeedNeqFunction = true;
} else if (node->isMathmlElement("lt")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::LT, astParent);
mModel->mPimpl->mNeedLtFunction = true;
} else if (node->isMathmlElement("leq")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::LEQ, astParent);
mModel->mPimpl->mNeedLeqFunction = true;
} else if (node->isMathmlElement("gt")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::GT, astParent);
mModel->mPimpl->mNeedGtFunction = true;
} else if (node->isMathmlElement("geq")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::GEQ, astParent);
mModel->mPimpl->mNeedGeqFunction = true;
} else if (node->isMathmlElement("and")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::AND, astParent);
mModel->mPimpl->mNeedAndFunction = true;
} else if (node->isMathmlElement("or")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::OR, astParent);
mModel->mPimpl->mNeedOrFunction = true;
} else if (node->isMathmlElement("xor")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::XOR, astParent);
mModel->mPimpl->mNeedXorFunction = true;
} else if (node->isMathmlElement("not")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::NOT, astParent);
mModel->mPimpl->mNeedNotFunction = true;
// Arithmetic operators.
} else if (node->isMathmlElement("plus")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::PLUS, astParent);
} else if (node->isMathmlElement("minus")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::MINUS, astParent);
} else if (node->isMathmlElement("times")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::TIMES, astParent);
} else if (node->isMathmlElement("divide")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::DIVIDE, astParent);
} else if (node->isMathmlElement("power")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::POWER, astParent);
} else if (node->isMathmlElement("root")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ROOT, astParent);
} else if (node->isMathmlElement("abs")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ABS, astParent);
} else if (node->isMathmlElement("exp")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::EXP, astParent);
} else if (node->isMathmlElement("ln")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::LN, astParent);
} else if (node->isMathmlElement("log")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::LOG, astParent);
} else if (node->isMathmlElement("ceiling")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::CEILING, astParent);
} else if (node->isMathmlElement("floor")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::FLOOR, astParent);
} else if (node->isMathmlElement("min")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::MIN, astParent);
mModel->mPimpl->mNeedMinFunction = true;
} else if (node->isMathmlElement("max")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::MAX, astParent);
mModel->mPimpl->mNeedMaxFunction = true;
} else if (node->isMathmlElement("rem")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::REM, astParent);
// Calculus elements.
} else if (node->isMathmlElement("diff")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::DIFF, astParent);
// Trigonometric operators.
} else if (node->isMathmlElement("sin")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::SIN, astParent);
} else if (node->isMathmlElement("cos")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::COS, astParent);
} else if (node->isMathmlElement("tan")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::TAN, astParent);
} else if (node->isMathmlElement("sec")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::SEC, astParent);
mModel->mPimpl->mNeedSecFunction = true;
} else if (node->isMathmlElement("csc")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::CSC, astParent);
mModel->mPimpl->mNeedCscFunction = true;
} else if (node->isMathmlElement("cot")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::COT, astParent);
mModel->mPimpl->mNeedCotFunction = true;
} else if (node->isMathmlElement("sinh")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::SINH, astParent);
} else if (node->isMathmlElement("cosh")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::COSH, astParent);
} else if (node->isMathmlElement("tanh")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::TANH, astParent);
} else if (node->isMathmlElement("sech")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::SECH, astParent);
mModel->mPimpl->mNeedSechFunction = true;
} else if (node->isMathmlElement("csch")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::CSCH, astParent);
mModel->mPimpl->mNeedCschFunction = true;
} else if (node->isMathmlElement("coth")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::COTH, astParent);
mModel->mPimpl->mNeedCothFunction = true;
} else if (node->isMathmlElement("arcsin")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ASIN, astParent);
} else if (node->isMathmlElement("arccos")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ACOS, astParent);
} else if (node->isMathmlElement("arctan")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ATAN, astParent);
} else if (node->isMathmlElement("arcsec")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ASEC, astParent);
mModel->mPimpl->mNeedAsecFunction = true;
} else if (node->isMathmlElement("arccsc")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ACSC, astParent);
mModel->mPimpl->mNeedAcscFunction = true;
} else if (node->isMathmlElement("arccot")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ACOT, astParent);
mModel->mPimpl->mNeedAcotFunction = true;
} else if (node->isMathmlElement("arcsinh")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ASINH, astParent);
} else if (node->isMathmlElement("arccosh")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ACOSH, astParent);
} else if (node->isMathmlElement("arctanh")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ATANH, astParent);
} else if (node->isMathmlElement("arcsech")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ASECH, astParent);
mModel->mPimpl->mNeedAsechFunction = true;
} else if (node->isMathmlElement("arccsch")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ACSCH, astParent);
mModel->mPimpl->mNeedAcschFunction = true;
} else if (node->isMathmlElement("arccoth")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::ACOTH, astParent);
mModel->mPimpl->mNeedAcothFunction = true;
// Piecewise statement.
} else if (node->isMathmlElement("piecewise")) {
auto childCount = mathmlChildCount(node);
ast->mPimpl->populate(AnalyserEquationAst::Type::PIECEWISE, astParent);
analyseNode(mathmlChildNode(node, 0), ast->mPimpl->mOwnedLeftChild, ast, component, equation);
if (childCount >= 2) {
AnalyserEquationAstPtr astRight;
AnalyserEquationAstPtr tempAst;
analyseNode(mathmlChildNode(node, childCount - 1), astRight, nullptr, component, equation);
for (auto i = childCount - 2; i > 0; --i) {
tempAst = AnalyserEquationAst::create();
tempAst->mPimpl->populate(AnalyserEquationAst::Type::PIECEWISE, astParent);
analyseNode(mathmlChildNode(node, i), tempAst->mPimpl->mOwnedLeftChild, tempAst, component, equation);
astRight->mPimpl->mParent = tempAst;
tempAst->mPimpl->mOwnedRightChild = astRight;
astRight = tempAst;
}
astRight->mPimpl->mParent = ast;
ast->mPimpl->mOwnedRightChild = astRight;
}
} else if (node->isMathmlElement("piece")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::PIECE, astParent);
analyseNode(mathmlChildNode(node, 0), ast->mPimpl->mOwnedLeftChild, ast, component, equation);
analyseNode(mathmlChildNode(node, 1), ast->mPimpl->mOwnedRightChild, ast, component, equation);
} else if (node->isMathmlElement("otherwise")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::OTHERWISE, astParent);
analyseNode(mathmlChildNode(node, 0), ast->mPimpl->mOwnedLeftChild, ast, component, equation);
// Token elements.
} else if (node->isMathmlElement("ci")) {
auto variableName = node->firstChild()->convertToStrippedString();
auto variable = component->variable(variableName);
// Note: we always have a variable. Indeed, if we were not to have one,
// it would mean that `variableName` is the name of a variable
// that is referenced in an equation, but not defined anywhere,
// something that is not allowed in CellML and will therefore be
// reported when we validate the model.
// Have our equation track the (ODE) variable (by ODE variable, we mean
// a variable that is used in a "diff" element).
if (node->parent()->firstChild()->isMathmlElement("diff")) {
equation->addOdeVariable(internalVariable(variable));
} else if (!(node->parent()->isMathmlElement("bvar")
&& node->parent()->parent()->firstChild()->isMathmlElement("diff"))) {
equation->addVariable(internalVariable(variable));
}
// Add the variable to our AST and keep track of its unit.
ast->mPimpl->populate(AnalyserEquationAst::Type::CI, variable, astParent);
mCiCnUnits.emplace(ast, variable->units());
} else if (node->isMathmlElement("cn")) {
// Add the number to our AST and keep track of its unit. Note that in
// the case of a standard unit, we need to create a units since it's
// not declared in the model.
if (mathmlChildCount(node) == 1) {
// We are dealing with an e-notation based CN value.
ast->mPimpl->populate(AnalyserEquationAst::Type::CN, node->firstChild()->convertToStrippedString() + "e" + node->firstChild()->next()->next()->convertToStrippedString(), astParent);
} else {
ast->mPimpl->populate(AnalyserEquationAst::Type::CN, node->firstChild()->convertToStrippedString(), astParent);
}
std::string unitsName = node->attribute("units");
if (isStandardUnitName(unitsName)) {
auto iter = mStandardUnits.find(unitsName);
if (iter == mStandardUnits.end()) {
auto units = libcellml::Units::create(unitsName);
mCiCnUnits.emplace(ast, units);
mStandardUnits.emplace(unitsName, units);
} else {
mCiCnUnits.emplace(ast, iter->second);
}
} else {
mCiCnUnits.emplace(ast, owningModel(component)->units(unitsName));
}
// Qualifier elements.
} else if (node->isMathmlElement("degree")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::DEGREE, astParent);
analyseNode(mathmlChildNode(node, 0), ast->mPimpl->mOwnedLeftChild, ast, component, equation);
} else if (node->isMathmlElement("logbase")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::LOGBASE, astParent);
analyseNode(mathmlChildNode(node, 0), ast->mPimpl->mOwnedLeftChild, ast, component, equation);
} else if (node->isMathmlElement("bvar")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::BVAR, astParent);
analyseNode(mathmlChildNode(node, 0), ast->mPimpl->mOwnedLeftChild, ast, component, equation);
auto rightNode = mathmlChildNode(node, 1);
if (rightNode != nullptr) {
analyseNode(rightNode, ast->mPimpl->mOwnedRightChild, ast, component, equation);
}
// Constants.
} else if (node->isMathmlElement("true")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::TRUE, astParent);
} else if (node->isMathmlElement("false")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::FALSE, astParent);
} else if (node->isMathmlElement("exponentiale")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::E, astParent);
} else if (node->isMathmlElement("pi")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::PI, astParent);
} else if (node->isMathmlElement("infinity")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::INF, astParent);
} else if (node->isMathmlElement("notanumber")) {
ast->mPimpl->populate(AnalyserEquationAst::Type::NAN, astParent);
}
}
void Analyser::AnalyserImpl::analyseComponent(const ComponentPtr &component)
{
// Retrieve the math string associated with the given component and analyse
// it, one equation at a time, keeping in mind that it may consist of
// several <math> elements, hence our use of multiRootXml().
if (!component->math().empty()) {
for (const auto &doc : multiRootXml(component->math())) {
for (auto node = doc->rootNode()->firstChild(); node != nullptr; node = node->next()) {
if (node->isMathmlElement()) {
// Create and keep track of the equation associated with the
// given node.
auto internalEquation = AnalyserInternalEquation::create(component);
mInternalEquations.push_back(internalEquation);
// Actually analyse the node.
analyseNode(node, internalEquation->mAst, internalEquation->mAst->parent(), component, internalEquation);
}
}
}
}
// Go through the given component's variables and make sure that everything
// makes sense.
for (size_t i = 0; i < component->variableCount(); ++i) {
// Retrieve the variable's corresponding internal variable.
auto variable = component->variable(i);
auto internalVariable = Analyser::AnalyserImpl::internalVariable(variable);
// If `variable` has an initial value and the variable held by
// `internalVariable` doesn't, then replace the variable held by
// `internalVariable`. If `variable` and the variable held by
// `internalVariable` are different and both of them have an initial
// value then generate an error.
if (!variable->initialValue().empty()
&& internalVariable->mVariable->initialValue().empty()) {
internalVariable->setVariable(variable);
} else if ((variable != internalVariable->mVariable)
&& !variable->initialValue().empty()
&& !internalVariable->mVariable->initialValue().empty()) {
auto issue = Issue::IssueImpl::create();
auto trackedVariableComponent = owningComponent(internalVariable->mVariable);
issue->mPimpl->setDescription("Variable '" + variable->name()
+ "' in component '" + component->name()
+ "' and variable '" + internalVariable->mVariable->name()
+ "' in component '" + trackedVariableComponent->name()
+ "' are equivalent and cannot therefore both be initialised.");
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::ANALYSER_VARIABLE_INITIALISED_MORE_THAN_ONCE);
issue->mPimpl->mItem->mPimpl->setVariable(variable);
addIssue(issue);
}
if (!internalVariable->mVariable->initialValue().empty()
&& !isCellMLReal(internalVariable->mVariable->initialValue())) {
// The initial value is not a double, so it has to be an existing
// variable of constant type.
// Note: we always have an initialising variable. Indeed, if we were
// not to have one, it would mean that the variable is
// initialised using a reference to a variable that is not
// defined anywhere, something that is not allowed in CellML
// and will therefore be reported when we validate the model.
auto initialisingComponent = owningComponent(internalVariable->mVariable);
auto initialisingVariable = initialisingComponent->variable(internalVariable->mVariable->initialValue());
auto initialisingInternalVariable = Analyser::AnalyserImpl::internalVariable(initialisingVariable);
if (initialisingInternalVariable->mType != AnalyserInternalVariable::Type::CONSTANT) {
auto issue = Issue::IssueImpl::create();
issue->mPimpl->setDescription("Variable '" + variable->name()
+ "' in component '" + component->name()
+ "' is initialised using variable '" + internalVariable->mVariable->initialValue()
+ "', which is not a constant.");
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::ANALYSER_VARIABLE_NON_CONSTANT_INITIALISATION);
issue->mPimpl->mItem->mPimpl->setVariable(variable);
addIssue(issue);
}
}
}
// Do the same for the components encapsulated by the given component.
for (size_t i = 0; i < component->componentCount(); ++i) {
analyseComponent(component->component(i));
}
}
void Analyser::AnalyserImpl::doEquivalentVariables(const VariablePtr &variable,
VariablePtrs &equivalentVariables) const
{
for (size_t i = 0; i < variable->equivalentVariableCount(); ++i) {
auto equivalentVariable = variable->equivalentVariable(i);
if (std::find(equivalentVariables.begin(), equivalentVariables.end(), equivalentVariable) == equivalentVariables.end()) {
equivalentVariables.push_back(equivalentVariable);
doEquivalentVariables(equivalentVariable, equivalentVariables);
}
}
}
VariablePtrs Analyser::AnalyserImpl::equivalentVariables(const VariablePtr &variable) const
{
VariablePtrs res = {variable};
doEquivalentVariables(variable, res);
return res;
}
void Analyser::AnalyserImpl::analyseEquationAst(const AnalyserEquationAstPtr &ast)
{
// Make sure that we have an AST to analyse.
if (ast == nullptr) {
return;
}
// Look for the definition of a variable of integration and make sure that
// we don't have more than one of it and that it's not initialised.
auto astParent = ast->parent();
auto astGrandParent = (astParent != nullptr) ? astParent->parent() : nullptr;
auto astGreatGrandParent = (astGrandParent != nullptr) ? astGrandParent->parent() : nullptr;
if ((ast->mPimpl->mType == AnalyserEquationAst::Type::CI)
&& (astParent != nullptr) && (astParent->mPimpl->mType == AnalyserEquationAst::Type::BVAR)
&& (astGrandParent != nullptr) && (astGrandParent->mPimpl->mType == AnalyserEquationAst::Type::DIFF)) {
auto variable = ast->variable();
internalVariable(variable)->makeVoi();
// Note: we must make the variable a variable of integration in all
// cases (i.e. even if there is, for example, already another
// variable of integration) otherwise unnecessary issue messages
// may be reported (since the type of the variable would be
// unknown).
if (mModel->mPimpl->mVoi == nullptr) {
// We have found our variable of integration, but this may not be
// the one defined in our first component (i.e. the component under
// which we are likely to expect to see the variable of integration
// to be defined), so go through our components and look for the
// first occurrence of our variable of integration.
auto model = owningModel(variable);
for (size_t i = 0; i < model->componentCount(); ++i) {
auto voi = voiFirstOccurrence(variable, model->component(i));
if (voi != nullptr) {
// We have found the first occurrence of our variable of
// integration, but now we must ensure neither it (nor any
// of its equivalent variables) is initialised.
bool isVoiInitialised = false;
for (const auto &voiEquivalentVariable : equivalentVariables(voi)) {
if (!voiEquivalentVariable->initialValue().empty()) {
auto issue = Issue::IssueImpl::create();
issue->mPimpl->setDescription("Variable '" + voiEquivalentVariable->name()
+ "' in component '" + owningComponent(voiEquivalentVariable)->name()
+ "' cannot be both a variable of integration and initialised.");
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::ANALYSER_VOI_INITIALISED);
issue->mPimpl->mItem->mPimpl->setVariable(voiEquivalentVariable);
addIssue(issue);
isVoiInitialised = true;
}
}
if (!isVoiInitialised) {
mModel->mPimpl->mVoi = AnalyserVariable::AnalyserVariableImpl::create();
mModel->mPimpl->mVoi->mPimpl->populate(AnalyserVariable::Type::VARIABLE_OF_INTEGRATION,
0, nullptr, voi, nullptr);
}
break;
}
}
} else if (!mModel->areEquivalentVariables(variable, mModel->mPimpl->mVoi->variable())) {
auto issue = Issue::IssueImpl::create();
issue->mPimpl->setDescription("Variable '" + mModel->mPimpl->mVoi->variable()->name()
+ "' in component '" + owningComponent(mModel->mPimpl->mVoi->variable())->name()
+ "' and variable '" + variable->name()
+ "' in component '" + owningComponent(variable)->name()
+ "' cannot both be the variable of integration.");
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::ANALYSER_VOI_SEVERAL);
issue->mPimpl->mItem->mPimpl->setVariable(variable);
addIssue(issue);
}
}
// Make sure that we only use first-order ODEs.
if ((ast->mPimpl->mType == AnalyserEquationAst::Type::CN)
&& (astParent != nullptr) && (astParent->mPimpl->mType == AnalyserEquationAst::Type::DEGREE)
&& (astGrandParent != nullptr) && (astGrandParent->mPimpl->mType == AnalyserEquationAst::Type::BVAR)
&& (astGreatGrandParent != nullptr) && (astGreatGrandParent->mPimpl->mType == AnalyserEquationAst::Type::DIFF)) {
bool validValue;
double value = convertToDouble(ast->mPimpl->mValue, &validValue);
if (!validValue || !areEqual(value, 1.0)) {
auto issue = Issue::IssueImpl::create();
auto variable = astGreatGrandParent->mPimpl->mOwnedRightChild->variable();
issue->mPimpl->setDescription("The differential equation for variable '" + variable->name()
+ "' in component '" + owningComponent(variable)->name()
+ "' must be of the first order.");
issue->mPimpl->mItem->mPimpl->setMath(owningComponent(variable));
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::ANALYSER_ODE_NOT_FIRST_ORDER);
addIssue(issue);
}
}
// Make a variable a state if it is used in an ODE.
if ((ast->mPimpl->mType == AnalyserEquationAst::Type::CI)
&& (astParent != nullptr) && (astParent->mPimpl->mType == AnalyserEquationAst::Type::DIFF)) {
internalVariable(ast->variable())->makeState();
}
// Recursively check the given AST's children.
analyseEquationAst(ast->mPimpl->mOwnedLeftChild);
analyseEquationAst(ast->mPimpl->mOwnedRightChild);
}
void Analyser::AnalyserImpl::updateUnitsMapWithStandardUnit(const std::string &unitsName,
UnitsMap &unitsMap,
double unitsExponent)
{
// Update the given units map using the given standard unit.
for (const auto &iter : standardUnitsList.at(unitsName)) {
if (unitsMap.find(iter.first) == unitsMap.end()) {
unitsMap.emplace(iter.first, 0.0);
}
unitsMap[iter.first] += iter.second * unitsExponent;
}
}
void Analyser::AnalyserImpl::updateUnitsMap(const ModelPtr &model,
const std::string &unitsName,
UnitsMap &unitsMap,
bool userUnitsMap,
double unitsExponent,
double unitsMultiplier)
{
// Update the given units map using the given information.
if (userUnitsMap) {
if (unitsName != "dimensionless") {
unitsMap.emplace(unitsName, unitsExponent);
}
} else {
if (isStandardUnitName(unitsName)) {
updateUnitsMapWithStandardUnit(unitsName, unitsMap, unitsExponent);
} else {
UnitsPtr units = model->units(unitsName);
if (units->isBaseUnit()) {
auto iter = unitsMap.find(unitsName);
if (iter == unitsMap.end()) {
unitsMap.emplace(unitsName, unitsExponent);
} else {
unitsMap[iter->first] += unitsExponent;
}
} else {
std::string reference;
std::string prefix;
double exponent;
double multiplier;
std::string id;
for (size_t i = 0; i < units->unitCount(); ++i) {
units->unitAttributes(i, reference, prefix, exponent, multiplier, id);
if (isStandardUnitName(reference)) {
updateUnitsMapWithStandardUnit(reference, unitsMap, exponent * unitsExponent);
} else {
updateUnitsMap(model, reference, unitsMap, userUnitsMap,
exponent * unitsExponent,
unitsMultiplier + (std::log10(multiplier) + convertPrefixToInt(prefix)) * unitsExponent);
}
}
}
}
}
}
UnitsMap Analyser::AnalyserImpl::multiplyDivideUnitsMaps(const UnitsMap &firstUnitsMap,
const UnitsMap &secondUnitsMap,
bool multiply)
{
// Multiply/divide the given units maps together, following a multiplication
// (multiply = true) or a division (multiply = false).
UnitsMap res = firstUnitsMap;
double sign = multiply ? 1.0 : -1.0;
for (const auto &units : secondUnitsMap) {
auto it = res.find(units.first);
if (it == res.end()) {
res.emplace(units.first, sign * units.second);
} else {
it->second += sign * units.second;
if (areNearlyEqual(it->second, 0.0)) {
// The units has now an exponent value of zero, so no need to
// track it anymore.
res.erase(it);
}
}
}
return res;
}
UnitsMaps Analyser::AnalyserImpl::multiplyDivideUnitsMaps(const UnitsMaps &firstUnitsMaps,
const UnitsMaps &secondUnitsMaps,
bool multiply)
{
// Multiply/divide the given units maps together, following a multiplication
// (multiply = true) or a division (multiply = false).
UnitsMaps res;
for (const auto &firstUnitsMap : firstUnitsMaps) {
for (const auto &secondUnitsMap : secondUnitsMaps) {
res.push_back(multiplyDivideUnitsMaps(firstUnitsMap, secondUnitsMap, multiply));
}
}
return res;
}
UnitsMaps Analyser::AnalyserImpl::multiplyDivideUnitsMaps(const UnitsMaps &unitsMaps,
double factor,
bool multiply)
{
// Multiply/divide the given units maps by the given factor, following a
// multiplication (multiply = true) or a division (multiply = false).
UnitsMaps res = unitsMaps;
double realFactor = multiply ? factor : 1.0 / factor;
for (auto &unitsMap : res) {
for (auto &unitsItem : unitsMap) {
unitsItem.second *= realFactor;
}
}
return res;
}
double Analyser::AnalyserImpl::multiplyDivideUnitsMultipliers(double firstUnitsMultiplier,
double secondUnitsMultiplier,
bool multiply)
{
// Multiply/divide the given units multipliers together, following a
// multiplication (multiply = true) or a division (multiply = false).
return firstUnitsMultiplier + (multiply ? 1.0 : -1.0) * secondUnitsMultiplier;
}
UnitsMultipliers Analyser::AnalyserImpl::multiplyDivideUnitsMultipliers(const UnitsMultipliers &firstUnitsMultipliers,
const UnitsMultipliers &secondUnitsMultipliers,
bool multiply)
{
// Multiply/divide the given units multipliers together, following a
// multiplication (multiply = true) or a division (multiply = false).
UnitsMultipliers res;
for (const auto &firstUnitsMultiplier : firstUnitsMultipliers) {
for (const auto &secondUnitsMultiplier : secondUnitsMultipliers) {
res.push_back(multiplyDivideUnitsMultipliers(firstUnitsMultiplier,
secondUnitsMultiplier,
multiply));
}
}
return res;
}
UnitsMultipliers Analyser::AnalyserImpl::multiplyDivideUnitsMultipliers(double firstUnitsMultiplier,
const UnitsMultipliers &secondUnitsMultipliers,
bool multiply)
{
// Multiply/divide the given units multipliers together, following a
// multiplication (multiply = true) or a division (multiply = false).
UnitsMultipliers res;
for (const auto &secondUnitsMultiplier : secondUnitsMultipliers) {
res.push_back(multiplyDivideUnitsMultipliers(firstUnitsMultiplier,
secondUnitsMultiplier,
multiply));
}
return res;
}
UnitsMultipliers Analyser::AnalyserImpl::powerRootUnitsMultipliers(const UnitsMultipliers &unitsMultipliers,
double factor,
bool power)
{
// Power/root the given units multipliers to the given factor, following a
// power (power = true) or a root (power = false) operation.
UnitsMultipliers res;
double realFactor = power ? factor : 1.0 / factor;
for (const auto &unitsMultiplier : unitsMultipliers) {
res.push_back(realFactor * unitsMultiplier);
}
return res;
}
bool Analyser::AnalyserImpl::areSameUnitsMaps(const UnitsMaps &firstUnitsMaps,
const UnitsMaps &secondUnitsMaps)
{
// Check whether the given units maps are the same by checking their
// exponents.
for (const auto &firstUnitsMap : firstUnitsMaps) {
for (const auto &secondUnitsMap : secondUnitsMaps) {
UnitsMap unitsMap;
for (const auto &units : firstUnitsMap) {
if (units.first != "dimensionless") {
unitsMap[units.first] += units.second;
}
}
for (const auto &units : secondUnitsMap) {
if (units.first != "dimensionless") {
unitsMap[units.first] -= units.second;
}
}
for (const auto &unitsItem : unitsMap) {
if (!areNearlyEqual(unitsItem.second, 0.0)) {
return false;
}
}
}
}
return true;
}
bool Analyser::AnalyserImpl::isDimensionlessUnitsMaps(const UnitsMaps &unitsMaps)
{
// Check whether the given units maps is dimensionless.
for (const auto &unitsMap : unitsMaps) {
for (const auto &unitsItem : unitsMap) {
if (unitsItem.first != "dimensionless") {
return false;
}
}
}
return true;
}
bool Analyser::AnalyserImpl::areSameUnitsMultipliers(const UnitsMultipliers &firstUnitsMultipliers,
const UnitsMultipliers &secondUnitsMultipliers)
{
// Return whether the units multipliers are equals.
for (const auto &firstUnitsMultiplier : firstUnitsMultipliers) {
for (const auto &secondUnitsMultiplier : secondUnitsMultipliers) {
if (!areNearlyEqual(firstUnitsMultiplier, secondUnitsMultiplier)) {
return false;
}
}
}
return true;
}
void Analyser::AnalyserImpl::updateUnitsMultiplier(const ModelPtr &model,
const std::string &unitsName,
double &newUnitsMultiplier,
double unitsExponent,
double unitsMultiplier)
{
// Update the given units multiplier using the given information.
if (isStandardUnitName(unitsName)) {
newUnitsMultiplier += unitsMultiplier + standardMultiplierList.at(unitsName);
} else {
UnitsPtr units = model->units(unitsName);
if (units->isBaseUnit()) {
newUnitsMultiplier += unitsMultiplier;
} else {
std::string reference;
std::string prefix;
double exponent;
double multiplier;
std::string id;
for (size_t i = 0; i < units->unitCount(); ++i) {
units->unitAttributes(i, reference, prefix, exponent, multiplier, id);
if (isStandardUnitName(reference)) {
newUnitsMultiplier += unitsMultiplier + (standardMultiplierList.at(reference) + std::log10(multiplier) + convertPrefixToInt(prefix)) * exponent * unitsExponent;
} else {
updateUnitsMultiplier(model, reference, newUnitsMultiplier,
exponent * unitsExponent,
unitsMultiplier + (std::log10(multiplier) + convertPrefixToInt(prefix)) * unitsExponent);
}
}
}
}
}
std::string Analyser::AnalyserImpl::componentName(const AnalyserEquationAstPtr &ast)
{
// Return the name of the component in which the given AST is, by going
// through the AST, if needed, and returning the component of the first
// variable we find on the LHS/RHS.
auto variable = ast->variable();
if (variable != nullptr) {
return std::dynamic_pointer_cast<Component>(variable->parent())->name();
}
auto res = (ast->mPimpl->mOwnedLeftChild != nullptr) ?
componentName(ast->mPimpl->mOwnedLeftChild) :
"";
if (res.empty()) {
res = (ast->mPimpl->mOwnedRightChild != nullptr) ?
componentName(ast->mPimpl->mOwnedRightChild) :
"";
}
return res;
}
double Analyser::AnalyserImpl::powerValue(const AnalyserEquationAstPtr &ast)
{
// Return the power value for the given AST.
if (ast == nullptr) {
return 0.0;
}
if (ast->value().empty()) {
if ((ast->mPimpl->mOwnedLeftChild == nullptr) && (ast->mPimpl->mOwnedRightChild == nullptr)) {
return 0.0;
}
if (ast->mPimpl->mType == AnalyserEquationAst::Type::TIMES) {
return powerValue(ast->mPimpl->mOwnedLeftChild) * powerValue(ast->mPimpl->mOwnedRightChild);
}
if (ast->mPimpl->mType == AnalyserEquationAst::Type::DIVIDE) {
return areNearlyEqual(powerValue(ast->mPimpl->mOwnedRightChild), 0.0) ?
0.0 :
powerValue(ast->mPimpl->mOwnedLeftChild) / powerValue(ast->mPimpl->mOwnedRightChild);
}
if (ast->mPimpl->mType == AnalyserEquationAst::Type::PLUS) {
return powerValue(ast->mPimpl->mOwnedLeftChild) + powerValue(ast->mPimpl->mOwnedRightChild);
}
if (ast->mPimpl->mType == AnalyserEquationAst::Type::MINUS) {
return powerValue(ast->mPimpl->mOwnedLeftChild) - powerValue(ast->mPimpl->mOwnedRightChild);
}
if (ast->mPimpl->mType == AnalyserEquationAst::Type::DEGREE) {
return powerValue(ast->mPimpl->mOwnedLeftChild);
}
return 0.0;
}
return std::stod(ast->value());
}
std::string Analyser::AnalyserImpl::expression(const AnalyserEquationAstPtr &ast,
bool includeHierarchy)
{
// Return the generated code for the given AST, specifying the equation and
// component in which it is, if needed and requested.
std::string res = "'" + mGenerator->mPimpl->generateCode(ast) + "'";
if (includeHierarchy) {
AnalyserEquationAstPtr equationAst = ast;
AnalyserEquationAstPtr equationAstParent = ast->parent();
AnalyserEquationAstPtr equationAstGrandParent = (equationAstParent != nullptr) ?
equationAstParent->parent() :
nullptr;
while (equationAstParent != nullptr) {
equationAst = equationAstParent;
equationAstParent = equationAstGrandParent;
equationAstGrandParent = (equationAstParent != nullptr) ?
equationAstParent->parent() :
nullptr;
res += std::string(" in")
+ (((equationAstParent == nullptr) && equationAstGrandParent == nullptr) ? " equation" : "")
+ " '" + mGenerator->mPimpl->generateCode(equationAst) + "'";
}
res += " in component '" + componentName(equationAst) + "'";
}
return res;
}
std::string Analyser::AnalyserImpl::expressionUnits(const UnitsMaps &unitsMaps,
const UnitsMultipliers &unitsMultipliers)
{
// Return a string version of the given units maps and units multipliers.
Strings units;
for (size_t i = 0; i < unitsMaps.size(); ++i) {
auto unitsMap = unitsMaps[i];
std::string unit;
if (!unitsMultipliers.empty()) {
auto intExponent = int(unitsMultipliers[i]);
auto exponent = areNearlyEqual(unitsMultipliers[i], intExponent) ?
convertToString(intExponent) :
convertToString(unitsMultipliers[i], false);
if (exponent != "0") {
unit += "10";
if (exponent != "1") {
unit += "^" + exponent;
}
}
}
for (const auto &unitsItem : unitsMap) {
if ((unitsItem.first != "dimensionless")
&& !areNearlyEqual(unitsItem.second, 0.0)) {
auto intExponent = int(unitsItem.second);
auto exponent = areNearlyEqual(unitsItem.second, intExponent) ?
convertToString(intExponent) :
convertToString(unitsItem.second, false);
if (!unit.empty()) {
unit += " x ";
}
unit += unitsItem.first;
if (exponent != "1") {
unit += "^" + exponent;
}
}
}
if (!unit.empty()) {
units.push_back(unit);
}
}
std::string unitsString;
for (size_t i = 0; i < units.size(); ++i) {
if (i > 0) {
unitsString += (i == units.size() - 1) ? " and " : ", ";
}
unitsString += "'" + units[i] + "'";
}
return unitsString;
}
std::string Analyser::AnalyserImpl::expressionUnits(const AnalyserEquationAstPtr &ast,
const UnitsMaps &unitsMaps,
const UnitsMaps &userUnitsMaps,
const UnitsMultipliers &unitsMultipliers)
{
// Return a string version of the given AST and (user) units maps and units
// multipliers.
auto res = expression(ast, false) + " is ";
auto unitsString = expressionUnits(unitsMaps, unitsMultipliers);
auto userUnitsString = expressionUnits(userUnitsMaps);
if (userUnitsString.empty()) {
res += "'dimensionless'";
} else {
res += "in " + userUnitsString;
if (!unitsString.empty() && (unitsString != userUnitsString)) {
res += " (i.e. " + unitsString + ")";
}
}
return res;
}
void Analyser::AnalyserImpl::defaultUnitsMapsAndMultipliers(UnitsMaps &unitsMaps,
UnitsMaps &userUnitsMaps,
UnitsMultipliers &unitsMultipliers)
{
// Default units maps and multipliers.
unitsMaps = {UnitsMap()};
userUnitsMaps = {UnitsMap()};
unitsMultipliers = {0.0};
}
void Analyser::AnalyserImpl::analyseEquationUnits(const AnalyserEquationAstPtr &ast,
UnitsMaps &unitsMaps,
UnitsMaps &userUnitsMaps,
UnitsMultipliers &unitsMultipliers,
Strings &issueDescriptions)
{
// Analyse the units used with different MathML elements (table 2.1 of the
// CellML 2.0 normative specification; see https://bit.ly/3vBbyO5):
// - Simple operands ('ci' and 'cn'; note: 'sep' is not relevant here): the
// operand can have any unit.
// - Basic structural (note: 'apply' is not relevant here):
// - 'piecewise': the returned value of the different 'piece' and
// 'otherwise' statements should have equivalent units.
// - 'piece': the returned value can have any unit while the condition
// should be dimensionless.
// - 'otherwise': the returned value can have any unit.
// - Relational operators ('eq', 'neq', 'gt', 'lt', 'geq' and 'leq'): the
// two operands should have equivalent units. (The result of the
// comparison is dimensionless.)
// - Logical operators:
// - 'and', 'or', 'xor': the two operands should be dimensionless.
// - 'not': the operand should be dimensionless.
// - Arithmetic operators:
// - 'plus': the two operands should have equivalent units.
// - 'minus': if there is one operand, then it can have any unit. If
// there are two operands, then they should have equivalent units.
// - 'times' and 'divide': the two operands can have any units.
// - 'power': the base can have any unit while the exponent should be
// dimensionless.
// - 'root': the base can have any unit while the exponent, if present,
// should be dimensionless.
// - 'abs': the argument can have any unit.
// - 'exp' and 'ln': the argument should be dimensionless.
// - 'log': the argument and the base, if present, should be
// dimensionless.
// - 'floor' and 'ceiling': the argument can have any unit.
// - 'min' and 'max': all the arguments should have equivalent units.
// - 'rem': the two arguments should have equivalent units.
// - Calculus elements ('diff'): the differentiated variable can have any
// unit. (See 'bvar' below for the bounding variable.)
// - Qualifier elements:
// - 'bvar': a bounding variable can have any unit.
// - 'degree': a degree should be dimensionless.
// - 'logbase': a base should be dimensionless.
// - Trigonometric operators ('sin', 'cos', 'tan', etc.): the argument
// should be dimensionless.
// - Mathematical and logical constants ('pi', 'exponentiale',
// 'notanumber','infinity', 'true' and 'false'): those constants are
// dimensionless.
// Make sure that we have an AST to analyse.
if (ast == nullptr) {
unitsMaps = {};
userUnitsMaps = {};
unitsMultipliers = {};
return;
}
// Check whether we are dealing with a CI/CN element and, if so, retrieve
// both its units maps and multipliers.
if ((ast->mPimpl->mType == AnalyserEquationAst::Type::CI)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::CN)) {
auto units = mCiCnUnits[ast].lock();
auto model = owningModel(units);
defaultUnitsMapsAndMultipliers(unitsMaps, userUnitsMaps, unitsMultipliers);
for (auto &unitsMap : unitsMaps) {
updateUnitsMap(model, units->name(), unitsMap);
}
for (auto &userUnitsMap : userUnitsMaps) {
updateUnitsMap(model, units->name(), userUnitsMap, true);
}
for (auto &unitsMultiplier : unitsMultipliers) {
updateUnitsMultiplier(model, units->name(), unitsMultiplier);
}
return;
}
// Check the left and right children.
auto oldNbOfIssueDescriptions = issueDescriptions.size();
UnitsMaps rightUnitsMaps;
UnitsMaps rightUserUnitsMaps;
UnitsMultipliers rightUnitsMultipliers;
analyseEquationUnits(ast->mPimpl->mOwnedLeftChild, unitsMaps, userUnitsMaps, unitsMultipliers, issueDescriptions);
analyseEquationUnits(ast->mPimpl->mOwnedRightChild, rightUnitsMaps, rightUserUnitsMaps, rightUnitsMultipliers, issueDescriptions);
if ((ast->mPimpl->mType == AnalyserEquationAst::Type::ASSIGNMENT)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::EQ)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::NEQ)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::LT)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::LEQ)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::GT)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::GEQ)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::PLUS)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::MINUS)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::MIN)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::MAX)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::REM)) {
bool sameUnitsMaps = rightUnitsMaps.empty()
|| areSameUnitsMaps(unitsMaps, rightUnitsMaps);
bool sameUnitsMultipliers = rightUnitsMaps.empty()
|| areSameUnitsMultipliers(unitsMultipliers, rightUnitsMultipliers);
if (sameUnitsMaps && sameUnitsMultipliers) {
// Relational operators result in a dimensionless unit.
if ((ast->mPimpl->mType == AnalyserEquationAst::Type::EQ)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::NEQ)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::LT)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::LEQ)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::GT)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::GEQ)) {
defaultUnitsMapsAndMultipliers(unitsMaps, userUnitsMaps, unitsMultipliers);
}
} else if (issueDescriptions.size() == oldNbOfIssueDescriptions) {
// Only report inner issues.
std::string issueDescription = "The units in " + expression(ast) + " are not equivalent. ";
issueDescription += expressionUnits(ast->mPimpl->mOwnedLeftChild, unitsMaps, userUnitsMaps, unitsMultipliers) + " while "
+ expressionUnits(ast->mPimpl->mOwnedRightChild, rightUnitsMaps, rightUserUnitsMaps, rightUnitsMultipliers) + ".";
issueDescriptions.push_back(issueDescription);
}
} else if (ast->mPimpl->mType == AnalyserEquationAst::Type::PIECEWISE) {
unitsMaps.insert(std::end(unitsMaps),
std::begin(rightUnitsMaps),
std::end(rightUnitsMaps));
userUnitsMaps.insert(std::end(userUnitsMaps),
std::begin(rightUserUnitsMaps),
std::end(rightUserUnitsMaps));
unitsMultipliers.insert(std::end(unitsMultipliers),
std::begin(rightUnitsMultipliers),
std::end(rightUnitsMultipliers));
} else if (ast->mPimpl->mType == AnalyserEquationAst::Type::PIECE) {
if (!Analyser::AnalyserImpl::isDimensionlessUnitsMaps(rightUnitsMaps)) {
issueDescriptions.push_back("The unit of " + expression(ast->mPimpl->mOwnedRightChild)
+ " is not dimensionless. "
+ expressionUnits(ast->mPimpl->mOwnedRightChild, rightUnitsMaps, rightUserUnitsMaps, rightUnitsMultipliers) + ".");
}
} else if ((ast->mPimpl->mType == AnalyserEquationAst::Type::AND)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::OR)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::XOR)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::NOT)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::EXP)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::LN)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::LOG)) {
bool isDimensionlessUnitsMaps = Analyser::AnalyserImpl::isDimensionlessUnitsMaps(unitsMaps);
bool isDimensionlessRightUnitsMaps = Analyser::AnalyserImpl::isDimensionlessUnitsMaps(rightUnitsMaps);
if (!isDimensionlessUnitsMaps || !isDimensionlessRightUnitsMaps) {
std::string issueDescription = "The unit";
if (!isDimensionlessUnitsMaps && !isDimensionlessRightUnitsMaps) {
issueDescription += "s";
}
issueDescription += " of ";
if (!isDimensionlessUnitsMaps) {
issueDescription += expression(ast->mPimpl->mOwnedLeftChild, false);
}
if (!isDimensionlessUnitsMaps && !isDimensionlessRightUnitsMaps) {
issueDescription += " and ";
}
if (!isDimensionlessRightUnitsMaps) {
issueDescription += expression(ast->mPimpl->mOwnedRightChild, false);
}
issueDescription += " in " + expression(ast);
if (!isDimensionlessUnitsMaps && !isDimensionlessRightUnitsMaps) {
issueDescription += " are ";
} else {
issueDescription += " is ";
}
issueDescription += "not dimensionless. ";
if (!isDimensionlessUnitsMaps) {
issueDescription += expressionUnits(ast->mPimpl->mOwnedLeftChild, unitsMaps, userUnitsMaps, unitsMultipliers);
}
if (!isDimensionlessUnitsMaps && !isDimensionlessRightUnitsMaps) {
issueDescription += " while ";
}
if (!isDimensionlessRightUnitsMaps) {
issueDescription += expressionUnits(ast->mPimpl->mOwnedRightChild, rightUnitsMaps, rightUserUnitsMaps, rightUnitsMultipliers);
}
issueDescription += ".";
issueDescriptions.push_back(issueDescription);
}
} else if ((ast->mPimpl->mType == AnalyserEquationAst::Type::TIMES)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::DIVIDE)) {
unitsMaps = multiplyDivideUnitsMaps(unitsMaps, rightUnitsMaps,
ast->mPimpl->mType == AnalyserEquationAst::Type::TIMES);
userUnitsMaps = multiplyDivideUnitsMaps(userUnitsMaps, rightUserUnitsMaps,
ast->mPimpl->mType == AnalyserEquationAst::Type::TIMES);
unitsMultipliers = multiplyDivideUnitsMultipliers(unitsMultipliers, rightUnitsMultipliers,
ast->mPimpl->mType == AnalyserEquationAst::Type::TIMES);
} else if ((ast->mPimpl->mType == AnalyserEquationAst::Type::POWER)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ROOT)) {
bool isDimensionlessExponent = true;
if ((ast->mPimpl->mType == AnalyserEquationAst::Type::POWER)
|| (ast->mPimpl->mOwnedLeftChild->type() == AnalyserEquationAst::Type::DEGREE)) {
isDimensionlessExponent = Analyser::AnalyserImpl::isDimensionlessUnitsMaps((ast->mPimpl->mType == AnalyserEquationAst::Type::POWER) ?
rightUnitsMaps :
unitsMaps);
if (!isDimensionlessExponent) {
auto baseAst = (ast->mPimpl->mType == AnalyserEquationAst::Type::POWER) ?
ast->mPimpl->mOwnedRightChild :
ast->mPimpl->mOwnedLeftChild;
auto exponentUnitsMaps = (ast->mPimpl->mType == AnalyserEquationAst::Type::POWER) ?
rightUnitsMaps :
unitsMaps;
auto exponentUserUnitsMaps = (ast->mPimpl->mType == AnalyserEquationAst::Type::POWER) ?
rightUserUnitsMaps :
userUnitsMaps;
auto exponentUnitsMultipliers = (ast->mPimpl->mType == AnalyserEquationAst::Type::POWER) ?
rightUnitsMultipliers :
unitsMultipliers;
issueDescriptions.push_back("The unit of " + expression(baseAst)
+ " is not dimensionless. "
+ expressionUnits(baseAst, exponentUnitsMaps, exponentUserUnitsMaps, exponentUnitsMultipliers) + ".");
}
}
// Retrieve the exponent and apply it to our units maps and multipliers.
if (isDimensionlessExponent) {
double powerRootValue = 0.0;
if (ast->mPimpl->mType == AnalyserEquationAst::Type::POWER) {
powerRootValue = Analyser::AnalyserImpl::powerValue(ast->mPimpl->mOwnedRightChild);
} else {
// Root case.
if (ast->mPimpl->mOwnedLeftChild->type() == AnalyserEquationAst::Type::DEGREE) {
unitsMaps = rightUnitsMaps;
userUnitsMaps = rightUserUnitsMaps;
unitsMultipliers = rightUnitsMultipliers;
powerRootValue = Analyser::AnalyserImpl::powerValue(ast->mPimpl->mOwnedLeftChild);
} else {
// No DEGREE element, which means that we are dealing with a
// square root.
powerRootValue = 2.0;
}
}
unitsMaps = multiplyDivideUnitsMaps(unitsMaps, powerRootValue,
ast->mPimpl->mType == AnalyserEquationAst::Type::POWER);
userUnitsMaps = multiplyDivideUnitsMaps(userUnitsMaps, powerRootValue,
ast->mPimpl->mType == AnalyserEquationAst::Type::POWER);
unitsMultipliers = powerRootUnitsMultipliers(unitsMultipliers, powerRootValue,
ast->mPimpl->mType == AnalyserEquationAst::Type::POWER);
}
} else if ((ast->mPimpl->mType == AnalyserEquationAst::Type::SIN)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::COS)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::TAN)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::SEC)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::CSC)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::COT)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::SINH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::COSH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::TANH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::SECH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::CSCH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::COTH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ASIN)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ACOS)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ATAN)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ASEC)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ACSC)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ACOT)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ASINH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ACOSH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ATANH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ASECH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ACSCH)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::ACOTH)) {
if (!Analyser::AnalyserImpl::isDimensionlessUnitsMaps(unitsMaps)) {
issueDescriptions.push_back("The unit of " + expression(ast->mPimpl->mOwnedLeftChild)
+ " is not dimensionless. "
+ expressionUnits(ast->mPimpl->mOwnedLeftChild, unitsMaps, userUnitsMaps, unitsMultipliers) + ".");
}
} else if (ast->mPimpl->mType == AnalyserEquationAst::Type::DIFF) {
unitsMaps = multiplyDivideUnitsMaps(unitsMaps, rightUnitsMaps);
userUnitsMaps = multiplyDivideUnitsMaps(userUnitsMaps, rightUserUnitsMaps);
unitsMultipliers = multiplyDivideUnitsMultipliers(unitsMultipliers, rightUnitsMultipliers);
} else if (ast->mPimpl->mType == AnalyserEquationAst::Type::BVAR) {
for (auto &unitsMap : unitsMaps) {
for (auto &unitsItem : unitsMap) {
unitsItem.second *= -1.0;
}
}
for (auto &userUnitsMap : userUnitsMaps) {
for (auto &userUnits : userUnitsMap) {
userUnits.second *= -1.0;
}
}
unitsMultipliers = multiplyDivideUnitsMultipliers(0.0, unitsMultipliers, false);
} else if ((ast->mPimpl->mType == AnalyserEquationAst::Type::TRUE)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::FALSE)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::E)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::PI)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::INF)
|| (ast->mPimpl->mType == AnalyserEquationAst::Type::NAN)) {
defaultUnitsMapsAndMultipliers(unitsMaps, userUnitsMaps, unitsMultipliers);
}
}
double Analyser::AnalyserImpl::scalingFactor(const VariablePtr &variable)
{
return Units::scalingFactor(variable->units(), internalVariable(variable)->mVariable->units());
}
void Analyser::AnalyserImpl::scaleAst(const AnalyserEquationAstPtr &ast,
const AnalyserEquationAstPtr &astParent,
double scalingFactor)
{
// Scale the given AST using the given scaling factor.
auto scaledAst = AnalyserEquationAst::create();
scaledAst->mPimpl->populate(AnalyserEquationAst::Type::TIMES, astParent);
scaledAst->mPimpl->mOwnedLeftChild = AnalyserEquationAst::create();
scaledAst->mPimpl->mOwnedRightChild = ast;
scaledAst->mPimpl->mOwnedLeftChild->mPimpl->populate(AnalyserEquationAst::Type::CN, convertToString(scalingFactor), scaledAst);
ast->mPimpl->mParent = scaledAst;
if (astParent->mPimpl->mOwnedLeftChild == ast) {
astParent->mPimpl->mOwnedLeftChild = scaledAst;
} else {
astParent->mPimpl->mOwnedRightChild = scaledAst;
}
}
void Analyser::AnalyserImpl::scaleEquationAst(const AnalyserEquationAstPtr &ast)
{
// Make sure that we have an AST to scale.
if (ast == nullptr) {
return;
}
// Recursively scale the given AST's children.
scaleEquationAst(ast->mPimpl->mOwnedLeftChild);
scaleEquationAst(ast->mPimpl->mOwnedRightChild);
// If the given AST node is a variable (i.e. a CI node) then we may need to
// do some scaling.
if (ast->mPimpl->mType == AnalyserEquationAst::Type::CI) {
// The kind of scaling we may end up doing depends on whether we are
// dealing with a rate or some other variable, i.e. whether or not it
// has a DIFF node as a parent.
auto astParent = ast->parent();
if (astParent->mPimpl->mType == AnalyserEquationAst::Type::DIFF) {
// We are dealing with a rate, so retrieve the scaling factor for
// its corresponding variable of integration and apply it, if
// needed.
auto scalingFactor = Analyser::AnalyserImpl::scalingFactor(astParent->mPimpl->mOwnedLeftChild->mPimpl->mOwnedLeftChild->variable());
if (!areNearlyEqual(scalingFactor, 1.0)) {
// We need to scale using the inverse of the scaling factor, but
// how we do it depends on whether the rate is to be computed or
// used.
auto astGrandParent = astParent->parent();
if ((astGrandParent->mPimpl->mType == AnalyserEquationAst::Type::ASSIGNMENT)
&& (astGrandParent->mPimpl->mOwnedLeftChild == astParent)) {
scaleAst(astGrandParent->mPimpl->mOwnedRightChild, astGrandParent, 1.0 / scalingFactor);
} else {
scaleAst(astParent, astGrandParent, 1.0 / scalingFactor);
}
}
}
if (((astParent->mPimpl->mType != AnalyserEquationAst::Type::ASSIGNMENT)
|| (astParent->mPimpl->mOwnedLeftChild != ast))
&& (astParent->mPimpl->mType != AnalyserEquationAst::Type::BVAR)) {
// We are dealing with a variable which is neither a computed
// variable nor our variable of integration, so retrieve its scaling
// factor and apply it, if needed, distinguishing between a rate
// variable and an algebraic variable.
auto scalingFactor = Analyser::AnalyserImpl::scalingFactor(ast->variable());
if (!areNearlyEqual(scalingFactor, 1.0)) {
if (astParent->mPimpl->mType == AnalyserEquationAst::Type::DIFF) {
scaleAst(astParent, astParent->parent(), scalingFactor);
} else {
scaleAst(ast, astParent, scalingFactor);
}
}
}
}
}
bool Analyser::AnalyserImpl::isStateRateBased(const AnalyserEquationPtr &equation,
std::vector<AnalyserEquationPtr> &checkedEquations)
{
if (std::find(checkedEquations.begin(), checkedEquations.end(), equation) != checkedEquations.end()) {
return false;
}
checkedEquations.push_back(equation);
for (const auto &dependency : equation->dependencies()) {
if ((dependency->type() == AnalyserEquation::Type::RATE)
|| isStateRateBased(dependency, checkedEquations)) {
return true;
}
}
return false;
}
void Analyser::AnalyserImpl::analyseModel(const ModelPtr &model)
{
// Reset a few things in case this analyser was to be used to analyse more
// than one model.
mModel = AnalyserModel::AnalyserModelImpl::create();
mInternalVariables.clear();
mInternalEquations.clear();
mCiCnUnits.clear();
// Recursively analyse the model's components, so that we end up with an AST
// for each of the model's equations.
for (size_t i = 0; i < model->componentCount(); ++i) {
analyseComponent(model->component(i));
}
// Some more analysis is needed, but it can only be done if we didn't come
// across any errors during the analysis of our components.
if (mAnalyser->errorCount() == 0) {
// Analyse our different equations' AST to determine the type of our
// variables.
for (const auto &internalEquation : mInternalEquations) {
analyseEquationAst(internalEquation->mAst);
}
}
if (mAnalyser->errorCount() == 0) {
// Analyse our different equations' units to make sure that everything
// is consistent.
for (const auto &internalEquation : mInternalEquations) {
UnitsMaps unitsMaps;
UnitsMaps userUnitsMaps;
UnitsMultipliers unitsMultipliers;
Strings issueDescriptions;
analyseEquationUnits(internalEquation->mAst, unitsMaps,
userUnitsMaps, unitsMultipliers,
issueDescriptions);
for (const auto &issueDescription : issueDescriptions) {
auto issue = Issue::IssueImpl::create();
issue->mPimpl->setDescription(issueDescription);
issue->mPimpl->setLevel(Issue::Level::WARNING);
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::ANALYSER_UNITS);
addIssue(issue);
}
}
}
// Some post-analysis is now needed, but it can only be done if we didn't
// come across any errors during the analysis of our equations' AST.
if (mAnalyser->errorCount() == 0) {
// Sort our variables, determine the index of our constant variables and
// then loop over our equations, checking which variables, if any, can
// be determined using a given equation.
std::sort(mInternalVariables.begin(), mInternalVariables.end(),
compareVariablesByComponentAndName);
auto variableIndex = MAX_SIZE_T;
for (const auto &internalVariable : mInternalVariables) {
if (internalVariable->mType == AnalyserInternalVariable::Type::CONSTANT) {
internalVariable->mIndex = ++variableIndex;
}
}
auto equationOrder = MAX_SIZE_T;
auto stateIndex = MAX_SIZE_T;
bool relevantCheck;
do {
relevantCheck = false;
for (const auto &internalEquation : mInternalEquations) {
relevantCheck = internalEquation->check(equationOrder, stateIndex, variableIndex, mModel)
|| relevantCheck;
}
} while (relevantCheck);
// Make sure that our variables are valid.
for (const auto &internalVariable : mInternalVariables) {
std::string issueType;
Issue::ReferenceRule referenceRule = Issue::ReferenceRule::UNSPECIFIED;
if (internalVariable->mType == AnalyserInternalVariable::Type::UNKNOWN) {
issueType = "is unused";
referenceRule = Issue::ReferenceRule::ANALYSER_VARIABLE_UNUSED;
} else if (internalVariable->mType == AnalyserInternalVariable::Type::SHOULD_BE_STATE) {
issueType = "is used in an ODE, but it is not initialised";
referenceRule = Issue::ReferenceRule::ANALYSER_STATE_NOT_INITIALISED;
} else if (internalVariable->mType == AnalyserInternalVariable::Type::OVERCONSTRAINED) {
issueType = "is computed more than once";
referenceRule = Issue::ReferenceRule::ANALYSER_VARIABLE_COMPUTED_MORE_THAN_ONCE;
}
if (!issueType.empty()) {
auto issue = Issue::IssueImpl::create();
auto realVariable = internalVariable->mVariable;
issue->mPimpl->setDescription("Variable '" + realVariable->name()
+ "' in component '" + owningComponent(realVariable)->name()
+ "' " + issueType + ".");
issue->mPimpl->setReferenceRule(referenceRule);
issue->mPimpl->mItem->mPimpl->setVariable(realVariable);
addIssue(issue);
}
}
// Determine the type of our model.
auto hasUnderconstrainedVariables = std::find_if(mInternalVariables.begin(), mInternalVariables.end(), [](const AnalyserInternalVariablePtr &variable) {
return (variable->mType == AnalyserInternalVariable::Type::UNKNOWN)
|| (variable->mType == AnalyserInternalVariable::Type::SHOULD_BE_STATE);
})
!= std::end(mInternalVariables);
auto hasOverconstrainedVariables = std::find_if(mInternalVariables.begin(), mInternalVariables.end(), [](const AnalyserInternalVariablePtr &variable) {
return variable->mType == AnalyserInternalVariable::Type::OVERCONSTRAINED;
})
!= std::end(mInternalVariables);
if (hasUnderconstrainedVariables) {
if (hasOverconstrainedVariables) {
mModel->mPimpl->mType = AnalyserModel::Type::UNSUITABLY_CONSTRAINED;
} else {
mModel->mPimpl->mType = AnalyserModel::Type::UNDERCONSTRAINED;
}
} else if (hasOverconstrainedVariables) {
mModel->mPimpl->mType = AnalyserModel::Type::OVERCONSTRAINED;
} else if (mModel->mPimpl->mVoi != nullptr) {
mModel->mPimpl->mType = AnalyserModel::Type::ODE;
} else if (!mInternalVariables.empty()) {
mModel->mPimpl->mType = AnalyserModel::Type::ALGEBRAIC;
}
} else {
mModel->mPimpl->mType = AnalyserModel::Type::INVALID;
}
// Some final post-analysis is now needed, if we have a valid model.
if ((mModel->mPimpl->mType == AnalyserModel::Type::ODE)
|| (mModel->mPimpl->mType == AnalyserModel::Type::ALGEBRAIC)) {
// Add a dummy equation for each of our true (i.e. non-computed)
// constants.
// Note: this is only so that we can mark a constant as an external
// variable.
for (const auto &internalVariable : mInternalVariables) {
if (internalVariable->mType == AnalyserInternalVariable::Type::CONSTANT) {
mInternalEquations.push_back(AnalyserInternalEquation::create(internalVariable));
}
}
// Mark some variables as external variables, if needed.
std::map<AnalyserInternalVariablePtr, VariablePtrs> externalVariables;
if (!mExternalVariables.empty()) {
// Check whether an external variable belongs to the model being
// analysed, or whether it is marked as an external variable more
// than once through equivalence or is (equivalent to) the variable
// of integration.
std::map<VariablePtr, VariablePtrs> primaryExternalVariables;
for (const auto &externalVariable : mExternalVariables) {
auto variable = externalVariable->variable();
if (variable != nullptr) {
if (owningModel(variable) != model) {
auto issue = Issue::IssueImpl::create();
issue->mPimpl->setDescription("Variable '" + variable->name()
+ "' in component '" + owningComponent(variable)->name()
+ "' is marked as an external variable, but it belongs to a different model and will therefore be ignored.");
issue->mPimpl->setLevel(Issue::Level::MESSAGE);
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::ANALYSER_EXTERNAL_VARIABLE_DIFFERENT_MODEL);
issue->mPimpl->mItem->mPimpl->setVariable(variable);
addIssue(issue);
} else {
auto internalVariable = Analyser::AnalyserImpl::internalVariable(variable);
primaryExternalVariables[internalVariable->mVariable].push_back(variable);
if (((mModel->mPimpl->mVoi == nullptr)
|| (internalVariable->mVariable != mModel->mPimpl->mVoi->variable()))
&& (externalVariables.count(internalVariable) == 0)) {
VariablePtrs dependencies;
for (const auto &dependency : externalVariable->dependencies()) {
dependencies.push_back(Analyser::AnalyserImpl::internalVariable(dependency)->mVariable);
}
externalVariables.emplace(internalVariable, dependencies);
}
}
}
}
for (const auto &primaryExternalVariable : primaryExternalVariables) {
std::string description;
auto isVoi = (mModel->mPimpl->mVoi != nullptr)
&& (primaryExternalVariable.first == mModel->mPimpl->mVoi->variable());
auto equivalentVariableCount = primaryExternalVariable.second.size();
auto hasPrimaryVariable = std::find(primaryExternalVariable.second.begin(),
primaryExternalVariable.second.end(),
primaryExternalVariable.first)
!= primaryExternalVariable.second.end();
if (isVoi || (equivalentVariableCount > 1) || !hasPrimaryVariable) {
description += (equivalentVariableCount == 2) ? "Both " : "";
for (size_t i = 0; i < equivalentVariableCount; ++i) {
if (i != 0) {
description += (i != equivalentVariableCount - 1) ? ", " : " and ";
}
auto variableString = ((i == 0) && (equivalentVariableCount != 2)) ?
std::string("Variable") :
std::string("variable");
description += variableString + " '" + primaryExternalVariable.second[i]->name()
+ "' in component '" + owningComponent(primaryExternalVariable.second[i])->name()
+ "'";
}
Issue::ReferenceRule referenceRule;
if (isVoi) {
description += (equivalentVariableCount == 1) ?
" is marked as an external variable, but it is" :
" are marked as external variables, but they are";
if ((equivalentVariableCount == 1) && hasPrimaryVariable) {
description += " the";
} else {
description += " equivalent to variable '" + primaryExternalVariable.first->name()
+ "' in component '" + owningComponent(primaryExternalVariable.first)->name()
+ "', the primary";
}
description += " variable of integration which cannot be used as an external variable.";
referenceRule = Issue::ReferenceRule::ANALYSER_EXTERNAL_VARIABLE_VOI;
} else {
description += (equivalentVariableCount == 1) ?
" is marked as an external variable, but it is not a primary variable." :
" are marked as external variables, but they are";
description += (equivalentVariableCount > 2) ? " all" : "";
description += (equivalentVariableCount == 1) ? "" : " equivalent.";
description += " Variable '" + primaryExternalVariable.first->name()
+ "' in component '" + owningComponent(primaryExternalVariable.first)->name()
+ "' is";
description += hasPrimaryVariable ?
" the" :
(equivalentVariableCount == 1) ?
" its corresponding" :
" their corresponding";
description += " primary variable and will therefore be the one used as an external variable.";
referenceRule = Issue::ReferenceRule::ANALYSER_EXTERNAL_VARIABLE_USE_PRIMARY_VARIABLE;
}
auto issue = Issue::IssueImpl::create();
issue->mPimpl->setDescription(description);
issue->mPimpl->setLevel(Issue::Level::MESSAGE);
issue->mPimpl->setReferenceRule(referenceRule);
issue->mPimpl->mItem->mPimpl->setVariable(primaryExternalVariable.first);
addIssue(issue);
}
}
}
// Carry on, but only if there are no errors (i.e. warnings are fine).
if (mAnalyser->errorCount() == 0) {
// Make it known through our API whether the model has some external
// variables.
mModel->mPimpl->mHasExternalVariables = !externalVariables.empty();
// Sort our internal variables and equations.
std::sort(mInternalVariables.begin(), mInternalVariables.end(),
compareVariablesByTypeAndIndex);
std::sort(mInternalEquations.begin(), mInternalEquations.end(),
compareEquationsByVariable);
std::map<VariablePtr, AnalyserEquationPtr> equationMappings;
std::map<AnalyserEquationPtr, AnalyserVariablePtr> variableMappings;
for (const auto &internalEquation : mInternalEquations) {
equationMappings.emplace(internalEquation->mVariable->mVariable, std::shared_ptr<AnalyserEquation> {new AnalyserEquation {}});
}
// Make our internal variables available through our API.
auto stateIndex = MAX_SIZE_T;
auto variableIndex = MAX_SIZE_T;
for (const auto &internalVariable : mInternalVariables) {
// Determine the type of the variable.
AnalyserVariable::Type type;
if (externalVariables.count(internalVariable) == 1) {
type = AnalyserVariable::Type::EXTERNAL;
} else if (internalVariable->mType == AnalyserInternalVariable::Type::STATE) {
type = AnalyserVariable::Type::STATE;
} else if (internalVariable->mType == AnalyserInternalVariable::Type::CONSTANT) {
type = AnalyserVariable::Type::CONSTANT;
} else if ((internalVariable->mType == AnalyserInternalVariable::Type::COMPUTED_TRUE_CONSTANT)
|| (internalVariable->mType == AnalyserInternalVariable::Type::COMPUTED_VARIABLE_BASED_CONSTANT)) {
type = AnalyserVariable::Type::COMPUTED_CONSTANT;
} else if (internalVariable->mType == AnalyserInternalVariable::Type::ALGEBRAIC) {
type = AnalyserVariable::Type::ALGEBRAIC;
} else {
// This is the variable of integration, so skip it.
continue;
}
// Populate and keep track of the state/variable.
auto stateOrVariable = AnalyserVariable::AnalyserVariableImpl::create();
auto equation = equationMappings[internalVariable->mVariable];
stateOrVariable->mPimpl->populate(type,
(type == AnalyserVariable::Type::STATE) ?
++stateIndex :
++variableIndex,
(type == AnalyserVariable::Type::EXTERNAL) ?
nullptr :
internalVariable->mInitialisingVariable,
internalVariable->mVariable,
equation);
variableMappings.emplace(equation, stateOrVariable);
if (type == AnalyserVariable::Type::STATE) {
mModel->mPimpl->mStates.push_back(stateOrVariable);
} else {
mModel->mPimpl->mVariables.push_back(stateOrVariable);
}
}
// Make our internal equations available through our API.
std::vector<AnalyserInternalVariablePtr> externallyDependentVariables;
for (const auto &internalEquation : mInternalEquations) {
// Determine the type of the equation.
auto equation = equationMappings[internalEquation->mVariable->mVariable];
auto stateOrVariable = variableMappings[equation];
AnalyserEquation::Type type;
if (stateOrVariable->type() == AnalyserVariable::Type::EXTERNAL) {
type = AnalyserEquation::Type::EXTERNAL;
} else if (internalEquation->mType == AnalyserInternalEquation::Type::TRUE_CONSTANT) {
type = AnalyserEquation::Type::TRUE_CONSTANT;
} else if (internalEquation->mType == AnalyserInternalEquation::Type::VARIABLE_BASED_CONSTANT) {
// An equation for a variable-based constant may now rely on
// external variables, be it directly or indirectly. If this
// is the case then we need to requalify that equation as an
// algebraic equation.
type = AnalyserEquation::Type::VARIABLE_BASED_CONSTANT;
for (const auto &variable : internalEquation->mAllVariables) {
if ((externalVariables.count(variable) == 1)
|| (std::find(externallyDependentVariables.begin(), externallyDependentVariables.end(), variable) != externallyDependentVariables.end())) {
type = AnalyserEquation::Type::ALGEBRAIC;
stateOrVariable->mPimpl->mType = AnalyserVariable::Type::ALGEBRAIC;
externallyDependentVariables.push_back(internalEquation->mVariable);
break;
}
}
} else if (internalEquation->mType == AnalyserInternalEquation::Type::RATE) {
type = AnalyserEquation::Type::RATE;
} else if (internalEquation->mType == AnalyserInternalEquation::Type::ALGEBRAIC) {
type = AnalyserEquation::Type::ALGEBRAIC;
} else {
// The equation type is unknown, which means that it is a
// dummy equation for a true (i.e. non-computed) constant
// (so that it could have been marked as an external
// variable), so we skip it since the constant wasn't marked
// as an external variable.
continue;
}
// Scale our internal equation's AST to take into account the
// fact that we may have mapped variables that use compatible
// units rather than equivalent ones.
scaleEquationAst(internalEquation->mAst);
// Determine the equation's dependencies, i.e. the equations for
// the variables on which this equation depends.
// Note: an equation may depend on the variable of integration,
// for which there is no equation, hence we need to test
// equationDependency against nullptr.
VariablePtrs variableDependencies = (type == AnalyserEquation::Type::EXTERNAL) ?
externalVariables.find(internalEquation->mVariable)->second :
internalEquation->mDependencies;
std::vector<AnalyserEquationPtr> equationDependencies;
for (const auto &variableDependency : variableDependencies) {
auto equationDependency = equationMappings[variableDependency];
if (equationDependency != nullptr) {
equationDependencies.push_back(equationDependency);
}
}
// Populate and keep track of the equation.
equation->mPimpl->populate(type,
(type == AnalyserEquation::Type::EXTERNAL) ?
nullptr :
internalEquation->mAst,
equationDependencies,
stateOrVariable);
mModel->mPimpl->mEquations.push_back(equation);
}
// Clean up our equations' dependencies.
// Note: indeed, some equations may have a dependency on one or
// several true (i.e. non-computed) constants, for which there
// are no proper equations. So, we need to remove those
// dependencies, and obviously this can only be done once all
// our equations are ready.
for (const auto &equation : mModel->mPimpl->mEquations) {
equation->mPimpl->cleanUpDependencies();
}
// Determine whether our equations are state/rate based.
// Note: obviously, this can only be done once all our equations are
// ready.
for (const auto &equation : mModel->mPimpl->mEquations) {
std::vector<AnalyserEquationPtr> checkedEquations;
equation->mPimpl->mIsStateRateBased = isStateRateBased(equation, checkedEquations);
}
}
}
}
std::vector<AnalyserExternalVariablePtr>::const_iterator Analyser::AnalyserImpl::findExternalVariable(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName) const
{
return std::find_if(mExternalVariables.begin(), mExternalVariables.end(), [=](const AnalyserExternalVariablePtr &ev) {
auto v = ev->variable();
return (v != nullptr)
&& (owningModel(v) == model)
&& (owningComponent(v)->name() == componentName)
&& (v->name() == variableName);
});
}
std::vector<AnalyserExternalVariablePtr>::const_iterator Analyser::AnalyserImpl::findExternalVariable(const AnalyserExternalVariablePtr &externalVariable) const
{
return std::find_if(mExternalVariables.begin(), mExternalVariables.end(), [=](const AnalyserExternalVariablePtr &ev) {
return ev == externalVariable;
});
}
Analyser::AnalyserImpl *Analyser::pFunc()
{
return reinterpret_cast<Analyser::AnalyserImpl *>(Logger::pFunc());
}
const Analyser::AnalyserImpl *Analyser::pFunc() const
{
return reinterpret_cast<Analyser::AnalyserImpl const *>(Logger::pFunc());
}
Analyser::Analyser()
: Logger(new Analyser::AnalyserImpl())
{
pFunc()->mAnalyser = this;
}
Analyser::~Analyser()
{
delete pFunc();
}
AnalyserPtr Analyser::create() noexcept
{
return std::shared_ptr<Analyser> {new Analyser {}};
}
void Analyser::analyseModel(const ModelPtr &model)
{
// Make sure that we have a model and that it is valid before analysing it.
pFunc()->removeAllIssues();
if (model == nullptr) {
auto issue = Issue::IssueImpl::create();
issue->mPimpl->setDescription("The model is null.");
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::INVALID_ARGUMENT);
pFunc()->addIssue(issue);
return;
}
auto validator = Validator::create();
validator->validateModel(model);
if (validator->issueCount() > 0) {
// The model is not valid, so retrieve the validation issues and make
// them our own.
for (size_t i = 0; i < validator->issueCount(); ++i) {
pFunc()->addIssue(validator->issue(i));
}
pFunc()->mModel->mPimpl->mType = AnalyserModel::Type::INVALID;
}
// Check for non-validation errors that will render the given model invalid
// for analysis.
if (model->hasUnlinkedUnits()) {
auto issue = Issue::IssueImpl::create();
issue->mPimpl->setDescription("The model has units which are not linked together.");
issue->mPimpl->setReferenceRule(Issue::ReferenceRule::ANALYSER_UNLINKED_UNITS);
pFunc()->addIssue(issue);
}
// Analyse the model, but only if we didn't come across any issues.
if (issueCount() == 0) {
pFunc()->analyseModel(model);
}
}
bool Analyser::addExternalVariable(const AnalyserExternalVariablePtr &externalVariable)
{
if (std::find(pFunc()->mExternalVariables.begin(), pFunc()->mExternalVariables.end(), externalVariable) == pFunc()->mExternalVariables.end()) {
pFunc()->mExternalVariables.push_back(externalVariable);
return true;
}
return false;
}
bool Analyser::removeExternalVariable(size_t index)
{
if (index < pFunc()->mExternalVariables.size()) {
pFunc()->mExternalVariables.erase(pFunc()->mExternalVariables.begin() + ptrdiff_t(index));
return true;
}
return false;
}
bool Analyser::removeExternalVariable(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName)
{
auto result = pFunc()->findExternalVariable(model, componentName, variableName);
if (result != pFunc()->mExternalVariables.end()) {
pFunc()->mExternalVariables.erase(result);
return true;
}
return false;
}
bool Analyser::removeExternalVariable(const AnalyserExternalVariablePtr &externalVariable)
{
auto result = pFunc()->findExternalVariable(externalVariable);
if (result != pFunc()->mExternalVariables.end()) {
pFunc()->mExternalVariables.erase(result);
return true;
}
return false;
}
void Analyser::removeAllExternalVariables()
{
pFunc()->mExternalVariables.clear();
}
bool Analyser::containsExternalVariable(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName) const
{
return pFunc()->findExternalVariable(model, componentName, variableName) != pFunc()->mExternalVariables.end();
}
bool Analyser::containsExternalVariable(const AnalyserExternalVariablePtr &externalVariable) const
{
return pFunc()->findExternalVariable(externalVariable) != pFunc()->mExternalVariables.end();
}
AnalyserExternalVariablePtr Analyser::externalVariable(size_t index) const
{
if (index < pFunc()->mExternalVariables.size()) {
return pFunc()->mExternalVariables[index];
}
return nullptr;
}
AnalyserExternalVariablePtr Analyser::externalVariable(const ModelPtr &model,
const std::string &componentName,
const std::string &variableName) const
{
auto result = pFunc()->findExternalVariable(model, componentName, variableName);
if (result != pFunc()->mExternalVariables.end()) {
return *result;
}
return nullptr;
}
size_t Analyser::externalVariableCount() const
{
return pFunc()->mExternalVariables.size();
}
AnalyserModelPtr Analyser::model() const
{
return pFunc()->mModel;
}
} // namespace libcellml
| 42.641817 | 193 | 0.586921 | [
"render",
"vector",
"model"
] |
3ce225c4fd24f2d5f9f9457ee0288d59c897d06a | 65,435 | cpp | C++ | src/engine/src/host_cmd.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/engine/src/host_cmd.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/engine/src/host_cmd.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "tier0/vprof.h"
#include "server.h"
#include "host_cmd.h"
#include "keys.h"
#include "screen.h"
#include "vengineserver_impl.h"
#include "host_saverestore.h"
#include "sv_filter.h"
#include "gl_matsysiface.h"
#include "pr_edict.h"
#include "world.h"
#include "checksum_engine.h"
#include "const.h"
#include "sv_main.h"
#include "host.h"
#include "demo.h"
#include "cdll_int.h"
#include "networkstringtableserver.h"
#include "networkstringtableclient.h"
#include "host_state.h"
#include "string_t.h"
#include "tier0/dbg.h"
#include "testscriptmgr.h"
#include "r_local.h"
#include "PlayerState.h"
#include "enginesingleuserfilter.h"
#include "profile.h"
#include "proto_version.h"
#include "protocol.h"
#include "cl_main.h"
#include "sv_steamauth.h"
#include "zone.h"
#include "datacache/idatacache.h"
#include "sys_dll.h"
#include "cmd.h"
#include "tier0/icommandline.h"
#include "filesystem.h"
#include "filesystem_engine.h"
#include "icliententitylist.h"
#include "icliententity.h"
#include "GameEventManager.h"
#include "hltvserver.h"
#if defined( REPLAY_ENABLED )
#include "replay_internal.h"
#include "replayserver.h"
#endif
#include "cdll_engine_int.h"
#include "cl_steamauth.h"
#ifndef SWDS
#include "vgui_baseui_interface.h"
#endif
#include "sound.h"
#include "voice.h"
#include "sv_rcon.h"
#if defined( _X360 )
#include "xbox/xbox_console.h"
#include "xbox/xbox_launch.h"
#endif
#include "filesystem/IQueuedLoader.h"
#include "sys.h"
#include "rebuiltin//version.h"
#include "ixboxsystem.h"
extern IXboxSystem *g_pXboxSystem;
#include <sys/stat.h>
#include <stdio.h>
#ifdef POSIX
// sigh, microsoft put _ in front of its type defines for stat
#define _stat stat
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define STEAM_PREFIX "STEAM_"
#define STATUS_COLUMN_LENGTH_LINEPREFIX 1
#define STATUS_COLUMN_LENGTH_USERID 6
#define STATUS_COLUMN_LENGTH_USERID_STR "6"
#define STATUS_COLUMN_LENGTH_NAME 19
#define STATUS_COLUMN_LENGTH_STEAMID 19
#define STATUS_COLUMN_LENGTH_TIME 9
#define STATUS_COLUMN_LENGTH_PING 4
#define STATUS_COLUMN_LENGTH_PING_STR "4"
#define STATUS_COLUMN_LENGTH_LOSS 4
#define STATUS_COLUMN_LENGTH_LOSS_STR "4"
#define STATUS_COLUMN_LENGTH_STATE 6
#define STATUS_COLUMN_LENGTH_ADDR 21
#define KICKED_BY_CONSOLE "Kicked from server"
#ifndef SWDS
bool g_bInEditMode = false;
bool g_bInCommentaryMode = false;
#endif
static void host_name_changed_f(IConVar *var, const char *pOldValue, float flOldValue) {
Steam3Server().NotifyOfServerNameChange();
}
ConVar host_name("hostname", "", 0, "Hostname for server.", host_name_changed_f);
ConVar host_map("host_map", "", 0, "Current map name.");
void Host_VoiceRecordStop_f(void);
static void voiceconvar_file_changed_f(IConVar *pConVar, const char *pOldValue, float flOldValue) {
#ifndef SWDS
ConVarRef var(pConVar);
if (var.GetInt() == 0) {
// Force voice recording to stop if they turn off voice_inputfromfile or if sv_allow_voice_from_file is set to 0.
// Prevents an exploit where clients turn it on, start voice sending a long file, and then turn it off immediately.
Host_VoiceRecordStop_f();
}
#endif
}
ConVar voice_recordtofile("voice_recordtofile", "0", 0,
"Record mic data and decompressed voice data into 'voice_micdata.wav' and 'voice_decompressed.wav'");
ConVar voice_inputfromfile("voice_inputfromfile", "0", 0,
"Get voice input from 'voice_input.wav' rather than from the microphone.",
&voiceconvar_file_changed_f);
ConVar sv_allow_voice_from_file("sv_allow_voice_from_file", "0", FCVAR_REPLICATED,
"Allow or disallow clients from using voice_inputfromfile on this server.",
&voiceconvar_file_changed_f);
class CStatusLineBuilder {
public:
CStatusLineBuilder() { Reset(); }
void Reset() {
m_curPosition = 0;
m_szLine[0] = '\0';
}
void AddColumnText(const char *pszText, unsigned int columnWidth) {
size_t len = strlen(m_szLine);
if (m_curPosition > len) {
for (size_t i = len; i < m_curPosition; i++) {
m_szLine[i] = ' ';
}
m_szLine[m_curPosition] = '\0';
} else if (len != 0) {
// There is always at least one space between columns.
m_szLine[len] = ' ';
m_szLine[len + 1] = '\0';
}
V_strncat(m_szLine, pszText, sizeof(m_szLine));
m_curPosition += columnWidth + 1;
}
void InsertEmptyColumn(unsigned int columnWidth) {
m_curPosition += columnWidth + 1;
}
const char *GetLine() { return m_szLine; }
private:
size_t m_curPosition;
char m_szLine[512];
};
uint GetSteamAppID() {
static uint sunAppID = 0;
static bool bHaveValidSteamInterface = false;
if (!bHaveValidSteamInterface) {
#ifndef SWDS
if (Steam3Client().SteamUtils()) {
bHaveValidSteamInterface = true;
sunAppID = Steam3Client().SteamUtils()->GetAppID();
}
#endif
if (Steam3Server().SteamGameServerUtils()) {
bHaveValidSteamInterface = true;
sunAppID = Steam3Server().SteamGameServerUtils()->GetAppID();
}
if (!sunAppID)
sunAppID = 215; // defaults to Source SDK Base (215) if no steam.inf can be found.
}
return sunAppID;
}
EUniverse GetSteamUniverse() {
#ifndef SWDS
if (Steam3Client().SteamUtils())
return Steam3Client().SteamUtils()->GetConnectedUniverse();
#endif
if (Steam3Server().SteamGameServerUtils())
return Steam3Server().SteamGameServerUtils()->GetConnectedUniverse();
return k_EUniverseInvalid;
}
// Globals
int gHostSpawnCount = 0;
// If any quit handlers balk, then aborts quit sequence
bool EngineTool_CheckQuitHandlers();
#if defined( _X360 )
CON_COMMAND(quit_x360, "")
{
int launchFlags = LF_EXITFROMGAME;
// allocate the full payload
int nPayloadSize = XboxLaunch()->MaxPayloadSize();
byte* pPayload = (byte*)stackalloc(nPayloadSize);
V_memset(pPayload, 0, sizeof(nPayloadSize));
// payload is at least the command line
// any user data needed must be placed AFTER the command line
const char* pCmdLine = CommandLine()->GetCmdLine();
int nCmdLineLength = (int)strlen(pCmdLine) + 1;
V_memcpy(pPayload, pCmdLine, min(nPayloadSize, nCmdLineLength));
// add any other data here to payload, after the command line
// ...
// storage device may have changed since previous launch
XboxLaunch()->SetStorageID(XBX_GetStorageDeviceId());
// Close the storage devices
g_pXboxSystem->CloseContainers();
// persist the user id
bool bInviteRestart = args.FindArg("invite");
DWORD nUserID = (bInviteRestart) ? XBX_GetInvitedUserId() : XBX_GetPrimaryUserId();
XboxLaunch()->SetUserID(nUserID);
if (args.FindArg("restart"))
{
launchFlags |= LF_GAMERESTART;
}
// If we're relaunching due to invite
if (bInviteRestart)
{
launchFlags |= LF_INVITERESTART;
XNKID nSessionID = XBX_GetInviteSessionId();
XboxLaunch()->SetInviteSessionID(&nSessionID);
}
bool bLaunch = XboxLaunch()->SetLaunchData(pPayload, nPayloadSize, launchFlags);
if (bLaunch)
{
COM_TimestampedLog("Launching: \"%s\" Flags: 0x%8.8x", pCmdLine, XboxLaunch()->GetLaunchFlags());
g_pMaterialSystem->PersistDisplay();
XBX_DisconnectConsoleMonitor();
XboxLaunch()->Launch();
}
}
#endif
/*
==================
Host_Quit_f
==================
*/
void Host_Quit_f(const CCommand &args) {
#if !defined(SWDS)
if (args.FindArg("prompt")) {
// confirm they want to quit
EngineVGui()->ConfirmQuit();
return;
}
if (!EngineTool_CheckQuitHandlers()) {
return;
}
#endif
IGameEvent *event = g_GameEventManager.CreateEvent("host_quit");
if (event) {
g_GameEventManager.FireEventClientSide(event);
}
HostState_Shutdown();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND(_restart, "Shutdown and restart the engine.") {
/*
// FIXME: How to handle restarts?
#ifndef SWDS
if ( !EngineTool_CheckQuitHandlers() )
{
return;
}
#endif
*/
HostState_Restart();
}
#ifndef SWDS
//-----------------------------------------------------------------------------
// A console command to spew out driver information
//-----------------------------------------------------------------------------
void Host_LightCrosshair(void);
static ConCommand light_crosshair("light_crosshair", Host_LightCrosshair, "Show texture color at crosshair",
FCVAR_CHEAT);
void Host_LightCrosshair(void) {
Vector endPoint;
Vector lightmapColor;
// max_range * sqrt(3)
VectorMA(MainViewOrigin(), COORD_EXTENT * 1.74f, MainViewForward(), endPoint);
R_LightVec(MainViewOrigin(), endPoint, true, lightmapColor);
int r = LinearToTexture(lightmapColor.x);
int g = LinearToTexture(lightmapColor.y);
int b = LinearToTexture(lightmapColor.z);
ConMsg("Luxel Value: %d %d %d\n", r, g, b);
}
#endif
/*
==================
Host_Status_PrintClient
Print client info to console
==================
*/
void Host_Status_PrintClient(IClient *client, bool bShowAddress, void (*print)(const char *fmt, ...)) {
INetChannelInfo *nci = client->GetNetChannel();
const char *state = "challenging";
if (client->IsActive())
state = "active";
else if (client->IsSpawned())
state = "spawning";
else if (client->IsConnected())
state = "connecting";
CStatusLineBuilder builder;
builder.AddColumnText("#", STATUS_COLUMN_LENGTH_LINEPREFIX);
builder.AddColumnText(va("%" STATUS_COLUMN_LENGTH_USERID_STR "i", client->GetUserID()),
STATUS_COLUMN_LENGTH_USERID);
builder.AddColumnText(va("\"%s\"", client->GetClientName()), STATUS_COLUMN_LENGTH_NAME);
builder.AddColumnText(client->GetNetworkIDString(), STATUS_COLUMN_LENGTH_STEAMID);
if (nci != NULL) {
builder.AddColumnText(COM_FormatSeconds(nci->GetTimeConnected()), STATUS_COLUMN_LENGTH_TIME);
builder.AddColumnText(
va("%" STATUS_COLUMN_LENGTH_PING_STR "i", (int) (1000.0f * nci->GetAvgLatency(FLOW_OUTGOING))),
STATUS_COLUMN_LENGTH_PING);
builder.AddColumnText(
va("%" STATUS_COLUMN_LENGTH_LOSS_STR "i", (int) (100.0f * nci->GetAvgLoss(FLOW_INCOMING))),
STATUS_COLUMN_LENGTH_LOSS);
builder.AddColumnText(state, STATUS_COLUMN_LENGTH_STATE);
if (bShowAddress)
builder.AddColumnText(nci->GetAddress(), STATUS_COLUMN_LENGTH_ADDR);
} else {
builder.InsertEmptyColumn(STATUS_COLUMN_LENGTH_TIME);
builder.InsertEmptyColumn(STATUS_COLUMN_LENGTH_PING);
builder.InsertEmptyColumn(STATUS_COLUMN_LENGTH_LOSS);
builder.AddColumnText(state, STATUS_COLUMN_LENGTH_STATE);
}
print("%s\n", builder.GetLine());
}
void Host_Client_Printf(const char *fmt, ...) {
va_list argptr;
char string[1024];
va_start(argptr, fmt);
Q_vsnprintf(string, sizeof(string), fmt, argptr);
va_end(argptr);
host_client->ClientPrintf("%s", string);
}
#define LIMIT_PER_CLIENT_COMMAND_EXECUTION_ONCE_PER_INTERVAL(seconds) \
{ \
static float g_flLastTime__Limit[ABSOLUTE_PLAYER_LIMIT] = { 0.0f }; /* we don't have access to any of the three MAX_PLAYERS #define's here unfortunately */ \
int playerindex = cmd_clientslot; \
if ( playerindex >= 0 && playerindex < (ARRAYSIZE(g_flLastTime__Limit)) && realtime - g_flLastTime__Limit[playerindex] > (seconds) ) \
{ \
g_flLastTime__Limit[playerindex] = realtime; \
} \
else \
{ \
return; \
} \
}
//-----------------------------------------------------------------------------
// Host_Status_f
//-----------------------------------------------------------------------------
CON_COMMAND(status, "Display map and connection status.") {
IClient *client;
int j;
void (*print)(const char *fmt, ...);
#if defined( _X360 )
Vector org;
QAngle ang;
const char* pName;
if (cl.IsActive())
{
pName = cl.m_szLevelNameShort;
org = MainViewOrigin();
VectorAngles(MainViewForward(), ang);
IClientEntity* localPlayer = entitylist->GetClientEntity(cl.m_nPlayerSlot + 1);
if (localPlayer)
{
org = localPlayer->GetAbsOrigin();
}
}
else
{
pName = "";
org.Init();
ang.Init();
}
// send to vxconsole
xMapInfo_t mapInfo;
mapInfo.position[0] = org[0];
mapInfo.position[1] = org[1];
mapInfo.position[2] = org[2];
mapInfo.angle[0] = ang[0];
mapInfo.angle[1] = ang[1];
mapInfo.angle[2] = ang[2];
mapInfo.build = build_number();
mapInfo.skill = skill.GetInt();
// generate the qualified path where .sav files are expected to be written
char savePath[MAX_PATH];
V_snprintf(savePath, sizeof(savePath), "%s", saverestore->GetSaveDir());
V_StripTrailingSlash(savePath);
g_pFileSystem->RelativePathToFullPath(savePath, "MOD", mapInfo.savePath, sizeof(mapInfo.savePath));
V_FixSlashes(mapInfo.savePath);
if (pName[0])
{
// generate the qualified path from where the map was loaded
char mapPath[MAX_PATH];
Q_snprintf(mapPath, sizeof(mapPath), "maps/%s.360.bsp", pName);
g_pFileSystem->GetLocalPath(mapPath, mapInfo.mapPath, sizeof(mapInfo.mapPath));
Q_FixSlashes(mapInfo.mapPath);
}
else
{
mapInfo.mapPath[0] = '\0';
}
XBX_rMapInfo(&mapInfo);
#endif
if (cmd_source == src_command) {
if (!sv.IsActive()) {
Cmd_ForwardToServer(args);
return;
}
print = ConMsg;
} else {
print = Host_Client_Printf;
// limit this to once per 5 seconds
LIMIT_PER_CLIENT_COMMAND_EXECUTION_ONCE_PER_INTERVAL(5.0);
}
// ============================================================
// Server status information.
print("hostname: %s\n", host_name.GetString());
const char *pchSecureReasonString = "";
const char *pchUniverse = "";
bool bGSSecure = Steam3Server().BSecure();
if (!bGSSecure && Steam3Server().BWantsSecure()) {
if (Steam3Server().BLoggedOn()) {
pchSecureReasonString = " (secure mode enabled, connected to Steam3)";
} else {
pchSecureReasonString = " (secure mode enabled, disconnected from Steam3)";
}
}
switch (GetSteamUniverse()) {
case k_EUniversePublic:
pchUniverse = "";
break;
case k_EUniverseBeta:
pchUniverse = " (beta)";
break;
case k_EUniverseInternal:
pchUniverse = " (internal)";
break;
case k_EUniverseDev:
pchUniverse = " (dev)";
break;
default:
pchUniverse = " (unknown)";
break;
}
print("version : %s/%d %d %s%s%s\n", GetSteamInfIDVersionInfo().szVersionString,
PROTOCOL_VERSION, build_number(), bGSSecure ? "secure" : "insecure", pchSecureReasonString, pchUniverse);
if (NET_IsMultiplayer()) {
CUtlString sPublicIPInfo;
if (!Steam3Server().BLanOnly()) {
uint32 unPublicIP = Steam3Server().GetPublicIP();
if (unPublicIP != 0) {
netadr_t addr;
addr.SetIP(unPublicIP);
sPublicIPInfo.Format(" (public ip: %s)", addr.ToString(true));
}
}
print("udp/ip : %s:%i%s\n", net_local_adr.ToString(true), sv.GetUDPPort(), sPublicIPInfo.String());
if (!Steam3Server().BLanOnly()) {
if (Steam3Server().BLoggedOn())
print("steamid : %s (%llu)\n", Steam3Server().SteamGameServer()->GetSteamID().Render(),
Steam3Server().SteamGameServer()->GetSteamID().ConvertToUint64());
else
print("steamid : not logged in\n");
}
}
// Check if this game uses server registration, then output status
ConVarRef sv_registration_successful("sv_registration_successful", true);
if (sv_registration_successful.IsValid()) {
CUtlString sExtraInfo;
ConVarRef sv_registration_message("sv_registration_message", true);
if (sv_registration_message.IsValid()) {
const char *msg = sv_registration_message.GetString();
if (msg && *msg) {
sExtraInfo.Format(" (%s)", msg);
}
}
if (sv_registration_successful.GetBool()) {
print("account : logged in%s\n", sExtraInfo.String());
} else {
print("account : not logged in%s\n", sExtraInfo.String());
}
}
print("map : %s at: %d x, %d y, %d z\n", sv.GetMapName(), (int) MainViewOrigin()[0], (int) MainViewOrigin()[1],
(int) MainViewOrigin()[2]);
static ConVarRef sv_tags("sv_tags");
print("tags : %s\n", sv_tags.GetString());
if (hltv && hltv->IsActive()) {
print("sourcetv: port %i, delay %.1fs\n", hltv->GetUDPPort(), hltv->GetDirector()->GetDelay());
}
#if defined( REPLAY_ENABLED )
if (replay && replay->IsActive()) {
print("replay : %s\n", replay->IsRecording() ? "recording" : "not recording");
}
#endif
int players = sv.GetNumClients();
int nBots = sv.GetNumFakeClients();
int nHumans = players - nBots;
print("players : %i humans, %i bots (%i max)\n", nHumans, nBots, sv.GetMaxClients());
// ============================================================
print("edicts : %d used of %d max\n", sv.num_edicts - sv.free_edicts, sv.max_edicts);
if ((g_iServerGameDLLVersion >= 10) && serverGameDLL) {
serverGameDLL->Status(print);
}
// Early exit for this server.
if (args.ArgC() == 2) {
if (!Q_stricmp(args[1], "short")) {
for (j = 0; j < sv.GetClientCount(); j++) {
client = sv.GetClient(j);
if (!client->IsActive())
continue;
print("#%i - %s\n", j + 1, client->GetClientName());
}
return;
}
}
// the header for the status rows
// print( "# userid %-19s %-19s connected ping loss state%s\n", "name", "uniqueid", cmd_source == src_command ? " adr" : "" );
CStatusLineBuilder header;
header.AddColumnText("#", STATUS_COLUMN_LENGTH_LINEPREFIX);
header.AddColumnText("userid", STATUS_COLUMN_LENGTH_USERID);
header.AddColumnText("name", STATUS_COLUMN_LENGTH_NAME);
header.AddColumnText("uniqueid", STATUS_COLUMN_LENGTH_STEAMID);
header.AddColumnText("connected", STATUS_COLUMN_LENGTH_TIME);
header.AddColumnText("ping", STATUS_COLUMN_LENGTH_PING);
header.AddColumnText("loss", STATUS_COLUMN_LENGTH_LOSS);
header.AddColumnText("state", STATUS_COLUMN_LENGTH_STATE);
if (cmd_source == src_command) {
header.AddColumnText("adr", STATUS_COLUMN_LENGTH_ADDR);
}
print("%s\n", header.GetLine());
for (j = 0; j < sv.GetClientCount(); j++) {
client = sv.GetClient(j);
if (!client->IsConnected())
continue; // not connected yet, maybe challenging
Host_Status_PrintClient(client, (cmd_source == src_command), print);
}
}
//-----------------------------------------------------------------------------
// Host_Ping_f
//-----------------------------------------------------------------------------
CON_COMMAND(ping, "Display ping to server.") {
if (cmd_source == src_command) {
Cmd_ForwardToServer(args);
return;
}
// limit this to once per 5 seconds
LIMIT_PER_CLIENT_COMMAND_EXECUTION_ONCE_PER_INTERVAL(5.0);
host_client->ClientPrintf("Client ping times:\n");
for (int i = 0; i < sv.GetClientCount(); i++) {
IClient *client = sv.GetClient(i);
if (!client->IsConnected() || client->IsFakeClient())
continue;
host_client->ClientPrintf("%4.0f ms : %s\n",
1000.0f * client->GetNetChannel()->GetAvgLatency(FLOW_OUTGOING),
client->GetClientName());
}
}
bool CL_HL2Demo_MapCheck(const char *name) {
if (IsPC() && CL_IsHL2Demo() && !sv.IsDedicated()) {
if (!Q_stricmp(name, "d1_trainstation_01") ||
!Q_stricmp(name, "d1_trainstation_02") ||
!Q_stricmp(name, "d1_town_01") ||
!Q_stricmp(name, "d1_town_01a") ||
!Q_stricmp(name, "d1_town_02") ||
!Q_stricmp(name, "d1_town_03") ||
!Q_stricmp(name, "background01") ||
!Q_stricmp(name, "background03")
) {
return true;
}
return false;
}
return true;
}
bool CL_PortalDemo_MapCheck(const char *name) {
if (IsPC() && CL_IsPortalDemo() && !sv.IsDedicated()) {
if (!Q_stricmp(name, "testchmb_a_00") ||
!Q_stricmp(name, "testchmb_a_01") ||
!Q_stricmp(name, "testchmb_a_02") ||
!Q_stricmp(name, "testchmb_a_03") ||
!Q_stricmp(name, "testchmb_a_04") ||
!Q_stricmp(name, "testchmb_a_05") ||
!Q_stricmp(name, "testchmb_a_06") ||
!Q_stricmp(name, "background1")
) {
return true;
}
return false;
}
return true;
}
int _Host_Map_f_CompletionFunc(char const *cmdname, char const *partial,
char commands[COMMAND_COMPLETION_MAXITEMS][COMMAND_COMPLETION_ITEM_LENGTH]);
// Note, leaves name alone if no match possible
static bool Host_Map_Helper_FuzzyName(const CCommand &args, char *name, size_t bufsize) {
char commands[COMMAND_COMPLETION_MAXITEMS][COMMAND_COMPLETION_ITEM_LENGTH];
CUtlString argv0;
argv0 = args.Arg(0);
argv0 += " ";
if (_Host_Map_f_CompletionFunc(argv0, args.ArgS(), commands) > 0) {
Q_strncpy(name, &commands[0][argv0.Length()], bufsize);
return true;
}
return false;
}
void Host_Map_Helper(const CCommand &args, bool bEditmode, bool bBackground, bool bCommentary) {
if (cmd_source != src_command)
return;
if (args.ArgC() < 2) {
Warning("No map specified\n");
return;
}
const char *pszReason = NULL;
if ((g_iServerGameDLLVersion >= 10) && !serverGameDLL->IsManualMapChangeOkay(&pszReason)) {
if (pszReason && pszReason[0]) {
Warning("%s\n", pszReason);
}
return;
}
char szMapName[MAX_QPATH] = {0};
V_strncpy(szMapName, args[1], sizeof(szMapName));
// Call find map, proceed for any value besides NotFound
IVEngineServer::eFindMapResult eResult = g_pVEngineServer->FindMap(szMapName, sizeof(szMapName));
if (eResult == IVEngineServer::eFindMap_NotFound) {
Warning("map load failed: %s not found or invalid\n", args[1]);
return;
}
COM_TimestampedLog("*** Map Load: %s", szMapName);
// There is a precision issue here, as described Bruce Dawson's blog.
// In our case, we don't care because we're looking for anything on the order of second precision, which
// covers runtime up to around 4 months.
static ConVarRef dev_loadtime_map_start("dev_loadtime_map_start");
dev_loadtime_map_start.SetValue((float) Plat_FloatTime());
// If I was in edit mode reload config file
// to overwrite WC edit key bindings
#if !defined(SWDS)
if (!bEditmode) {
if (g_bInEditMode) {
// Re-read config from disk
Host_ReadConfiguration();
g_bInEditMode = false;
}
} else {
g_bInEditMode = true;
}
g_bInCommentaryMode = bCommentary;
#endif
if (!CL_HL2Demo_MapCheck(szMapName)) {
Warning("map load failed: %s not found or invalid\n", szMapName);
return;
}
if (!CL_PortalDemo_MapCheck(szMapName)) {
Warning("map load failed: %s not found or invalid\n", szMapName);
return;
}
#if defined( REPLAY_ENABLED )
// If we're recording the game, finalize the replay so players can download it.
if (g_pReplay && g_pReplay->IsRecording()) {
g_pReplay->SV_EndRecordingSession();
}
#endif
// Stop demo loop
cl.demonum = -1;
Host_Disconnect(false); // stop old game
HostState_NewGame(szMapName, false, bBackground);
if (args.ArgC() == 10) {
if (Q_stricmp(args[2], "setpos") == 0
&& Q_stricmp(args[6], "setang") == 0) {
Vector newpos;
newpos.x = atof(args[3]);
newpos.y = atof(args[4]);
newpos.z = atof(args[5]);
QAngle newangle;
newangle.x = atof(args[7]);
newangle.y = atof(args[8]);
newangle.z = atof(args[9]);
HostState_SetSpawnPoint(newpos, newangle);
}
}
}
/*
======================
Host_Map_f
handle a
map <servername>
command from the console. Active clients are kicked off.
======================
*/
void Host_Map_f(const CCommand &args) {
Host_Map_Helper(args, false, false, false);
}
//-----------------------------------------------------------------------------
// handle a map_edit <servername> command from the console.
// Active clients are kicked off.
// UNDONE: protect this from use if not in dev. mode
//-----------------------------------------------------------------------------
#ifndef SWDS
CON_COMMAND(map_edit, "") {
Host_Map_Helper(args, true, false, false);
}
#endif
//-----------------------------------------------------------------------------
// Purpose: Runs a map as the background
//-----------------------------------------------------------------------------
void Host_Map_Background_f(const CCommand &args) {
Host_Map_Helper(args, false, true, false);
}
//-----------------------------------------------------------------------------
// Purpose: Runs a map in commentary mode
//-----------------------------------------------------------------------------
void Host_Map_Commentary_f(const CCommand &args) {
Host_Map_Helper(args, false, false, true);
}
//-----------------------------------------------------------------------------
// Restarts the current server for a dead player
//-----------------------------------------------------------------------------
CON_COMMAND(restart, "Restart the game on the same level (add setpos to jump to current view position on restart).") {
if (
#if !defined(SWDS)
demoplayer->IsPlayingBack() ||
#endif
!sv.IsActive())
return;
if (sv.IsMultiplayer())
return;
if (cmd_source != src_command)
return;
bool bRememberLocation = (args.ArgC() == 2 && !Q_stricmp(args[1], "setpos"));
Host_Disconnect(false); // stop old game
if (!CL_HL2Demo_MapCheck(sv.GetMapName())) {
Warning("map load failed: %s not found or invalid\n", sv.GetMapName());
return;
}
if (!CL_PortalDemo_MapCheck(sv.GetMapName())) {
Warning("map load failed: %s not found or invalid\n", sv.GetMapName());
return;
}
HostState_NewGame(sv.GetMapName(), bRememberLocation, false);
}
//-----------------------------------------------------------------------------
// Restarts the current server for a dead player
//-----------------------------------------------------------------------------
CON_COMMAND(reload, "Reload the most recent saved game (add setpos to jump to current view position on reload).") {
#ifndef SWDS
const char *pSaveName;
char name[MAX_OSPATH];
#endif
if (
#if !defined(SWDS)
demoplayer->IsPlayingBack() ||
#endif
!sv.IsActive())
return;
if (sv.IsMultiplayer())
return;
if (cmd_source != src_command)
return;
bool remember_location = false;
if (args.ArgC() == 2 &&
!Q_stricmp(args[1], "setpos")) {
remember_location = true;
}
// See if there is a most recently saved game
// Restart that game if there is
// Otherwise, restart the starting game map
#ifndef SWDS
pSaveName = saverestore->FindRecentSave(name, sizeof(name));
// Put up loading plaque
SCR_BeginLoadingPlaque();
Host_Disconnect(false); // stop old game
if (pSaveName && saverestore->SaveFileExists(pSaveName)) {
HostState_LoadGame(pSaveName, remember_location);
} else
#endif
{
if (!CL_HL2Demo_MapCheck(host_map.GetString())) {
Warning("map load failed: %s not found or invalid\n", host_map.GetString());
return;
}
if (!CL_PortalDemo_MapCheck(host_map.GetString())) {
Warning("map load failed: %s not found or invalid\n", host_map.GetString());
return;
}
HostState_NewGame(host_map.GetString(), remember_location, false);
}
}
//-----------------------------------------------------------------------------
// Purpose: Goes to a new map, taking all clients along
// Output : void Host_Changelevel_f
//-----------------------------------------------------------------------------
void Host_Changelevel_f(const CCommand &args) {
if (args.ArgC() < 2) {
ConMsg("changelevel <levelname> : continue game on a new level\n");
return;
}
if (!sv.IsActive()) {
ConMsg("Can't changelevel, not running server\n");
return;
}
char szName[MAX_PATH] = {0};
V_strncpy(szName, args[1], sizeof(szName));
// Call find map to attempt to resolve fuzzy/non-canonical map names
IVEngineServer::eFindMapResult eResult = g_pVEngineServer->FindMap(szName, sizeof(szName));
if (eResult == IVEngineServer::eFindMap_NotFound) {
// Warn, but but proceed even if the map is not found, such that we hit the proper server_levelchange_failed
// codepath and event later on.
Warning("Failed to find map %s\n", args[1]);
}
if (!CL_HL2Demo_MapCheck(szName)) {
Warning("changelevel failed: %s not found\n", szName);
return;
}
if (!CL_PortalDemo_MapCheck(szName)) {
Warning("changelevel failed: %s not found\n", szName);
return;
}
const char *pszReason = NULL;
if ((g_iServerGameDLLVersion >= 10) && !serverGameDLL->IsManualMapChangeOkay(&pszReason)) {
if (pszReason && pszReason[0]) {
Warning("%s", pszReason);
}
return;
}
HostState_ChangeLevelMP(szName, args[2]);
}
//-----------------------------------------------------------------------------
// Purpose: Changing levels within a unit, uses save/restore
//-----------------------------------------------------------------------------
void Host_Changelevel2_f(const CCommand &args) {
if (args.ArgC() < 2) {
ConMsg("changelevel2 <levelname> : continue game on a new level in the unit\n");
return;
}
if (!sv.IsActive() || sv.IsMultiplayer()) {
ConMsg("Can't changelevel2, not in a single-player map\n");
return;
}
char szName[MAX_PATH] = {0};
V_strncpy(szName, args[1], sizeof(szName));
IVEngineServer::eFindMapResult eResult = g_pVEngineServer->FindMap(szName, sizeof(szName));
if (eResult == IVEngineServer::eFindMap_NotFound) {
if (!CL_IsHL2Demo() ||
(CL_IsHL2Demo() && !(!Q_stricmp(szName, "d1_trainstation_03") || !Q_stricmp(szName, "d1_town_02a")))) {
Warning("changelevel2 failed: %s not found\n", szName);
return;
}
}
#if !defined(SWDS)
// needs to be before CL_HL2Demo_MapCheck() check as d1_trainstation_03 isn't a valid map
if (IsPC() && CL_IsHL2Demo() && !sv.IsDedicated() && !Q_stricmp(szName, "d1_trainstation_03")) {
void CL_DemoTransitionFromTrainstation();
CL_DemoTransitionFromTrainstation();
return;
}
// needs to be before CL_HL2Demo_MapCheck() check as d1_trainstation_03 isn't a valid map
if (IsPC() && CL_IsHL2Demo() && !sv.IsDedicated() && !Q_stricmp(szName, "d1_town_02a") &&
!Q_stricmp(args[2], "d1_town_02_02a")) {
void CL_DemoTransitionFromRavenholm();
CL_DemoTransitionFromRavenholm();
return;
}
if (IsPC() && CL_IsPortalDemo() && !sv.IsDedicated() && !Q_stricmp(szName, "testchmb_a_07")) {
void CL_DemoTransitionFromTestChmb();
CL_DemoTransitionFromTestChmb();
return;
}
#endif
// allow a level transition to d1_trainstation_03 so the Host_Changelevel() can act on it
if (!CL_HL2Demo_MapCheck(szName)) {
Warning("changelevel failed: %s not found\n", szName);
return;
}
HostState_ChangeLevelSP(szName, args[2]);
}
//-----------------------------------------------------------------------------
// Purpose: Shut down client connection and any server
//-----------------------------------------------------------------------------
void Host_Disconnect(bool bShowMainMenu, const char *pszReason) {
if (IsX360()) {
g_pQueuedLoader->EndMapLoading(false);
}
#ifndef SWDS
if (!sv.IsDedicated()) {
cl.Disconnect(pszReason, bShowMainMenu);
}
#endif
Host_AllowQueuedMaterialSystem(false);
HostState_GameShutdown();
}
void Disconnect() {
cl.demonum = -1;
Host_Disconnect(true);
#if defined( REPLAY_ENABLED )
// Finalize the recording replay on the server, if is recording.
// NOTE: We don't want this in Host_Disconnect() as that would be called more
// than necessary.
if (g_pReplay && g_pReplay->IsReplayEnabled() && sv.IsDedicated()) {
g_pReplay->SV_EndRecordingSession();
}
#endif
}
//-----------------------------------------------------------------------------
// Kill the client and any local server.
//-----------------------------------------------------------------------------
CON_COMMAND(disconnect, "Disconnect game from server.") {
#if !defined( SWDS )
// Just run the regular Disconnect function if we're not the client or the client didn't handle it for us
if (!g_ClientDLL || !g_ClientDLL->DisconnectAttempt()) {
Disconnect();
}
#else
Disconnect();
#endif
}
#ifdef _WIN32
// manually pull in the GetEnvironmentVariableA defn so we don't need to include windows.h
extern "C"
{
DWORD __declspec(dllimport) __stdcall GetEnvironmentVariableA(const char *, char *, DWORD);
}
#endif // _WIN32
CON_COMMAND(version, "Print version info string.") {
ConMsg("Source Engine Rebuild: %8s # Source Engine Rebuild version\n", SOURCEENGINEREBUILD_VERSION_TEXT);
ConMsg("Build Num: %8d # rebuild number\n", source_build_number());
ConMsg("Protocol version: %8d # High level network protocol version\n", PROTOCOL_VERSION);
// if (sv.IsDedicated() || serverGameDLL) {
// ConMsg("Server version: %8i\n", GetSteamInfIDVersionInfo().ServerVersion);
// ConMsg("Server AppID: %8i\n", GetSteamInfIDVersionInfo().ServerAppID);
// }
// if (!sv.IsDedicated()) {
// ConMsg("Client version: %8i\n", GetSteamInfIDVersionInfo().ClientVersion);
// ConMsg("Client AppID: %8i\n", GetSteamInfIDVersionInfo().AppID);
// }
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND(pause, "Toggle the server pause state.") {
#ifndef SWDS
if (!sv.IsDedicated()) {
if (!cl.m_szLevelFileName[0])
return;
}
#endif
if (cmd_source == src_command) {
Cmd_ForwardToServer(args);
return;
}
if (!sv.IsPausable())
return;
// toggle paused state
sv.SetPaused(!sv.IsPaused());
// send text messaage who paused the game
sv.BroadcastPrintf("%s %s the game\n", host_client->GetClientName(), sv.IsPaused() ? "paused" : "unpaused");
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND(setpause, "Set the pause state of the server.") {
#ifndef SWDS
if (!cl.m_szLevelFileName[0])
return;
#endif
if (cmd_source == src_command) {
Cmd_ForwardToServer(args);
return;
}
sv.SetPaused(true);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND(unpause, "Unpause the game.") {
#ifndef SWDS
if (!cl.m_szLevelFileName[0])
return;
#endif
if (cmd_source == src_command) {
Cmd_ForwardToServer(args);
return;
}
sv.SetPaused(false);
}
// No non-testing use for this at the moment, though server mods in public will expose similar functionality
#if defined( STAGING_ONLY ) || defined( _DEBUG )
//-----------------------------------------------------------------------------
// Purpose: Send a string command to a client by userid
//-----------------------------------------------------------------------------
CON_COMMAND(clientcmd, "Send a clientside command to a player by userid")
{
if (args.ArgC() <= 2)
{
ConMsg("Usage: clientcmd < userid > { command string }\n");
return;
}
// Args
int userid = Q_atoi(args[1]);
int messageArgStart = 2;
// Concatenate other arguments into string
CUtlString commandString;
commandString.SetLength(Q_strlen(args.ArgS()));
commandString.Set(args[messageArgStart]);
for (int i = messageArgStart + 1; i < args.ArgC(); i++)
{
commandString.Append(" ");
commandString.Append(args[i]);
}
// find client
IClient* client = NULL;
for (int i = 0; i < sv.GetClientCount(); i++)
{
IClient* searchclient = sv.GetClient(i);
if (!searchclient->IsConnected())
continue;
if (userid != -1 && searchclient->GetUserID() == userid)
{
client = searchclient;
break;
}
}
if (!client)
{
ConMsg("userid \"%d\" not found\n", userid);
return;
}
NET_StringCmd cmdMsg(commandString);
client->SendNetMsg(cmdMsg, true);
}
#endif // defined( STAGING_ONLY ) || defined( _DEBUG )
//-----------------------------------------------------------------------------
// Kicks a user off of the server using their userid or uniqueid
//-----------------------------------------------------------------------------
CON_COMMAND(kickid, "Kick a player by userid or uniqueid, with a message.") {
char *who = NULL;
const char *pszArg1 = NULL, *pszMessage = NULL;
IClient *client = NULL;
int iSearchIndex = -1;
char szSearchString[128];
int argsStartNum = 1;
bool bSteamID = false;
int i = 0;
if (args.ArgC() <= 1) {
ConMsg("Usage: kickid < userid | uniqueid > { message }\n");
return;
}
// get the first argument
pszArg1 = args[1];
// if the first letter is a character then
// we're searching for a uniqueid ( e.g. STEAM_ )
if (*pszArg1 < '0' || *pszArg1 > '9') {
// SteamID (need to reassemble it)
if (!Q_strnicmp(pszArg1, STEAM_PREFIX, strlen(STEAM_PREFIX)) && Q_strstr(args[2], ":")) {
Q_snprintf(szSearchString, sizeof(szSearchString), "%s:%s:%s", pszArg1, args[3], args[5]);
argsStartNum = 5;
bSteamID = true;
}
// some other ID (e.g. "UNKNOWN", "STEAM_ID_PENDING", "STEAM_ID_LAN")
// NOTE: assumed to be one argument
else {
Q_snprintf(szSearchString, sizeof(szSearchString), "%s", pszArg1);
}
}
// this is a userid
else {
iSearchIndex = Q_atoi(pszArg1);
}
// check for a message
if (args.ArgC() > argsStartNum) {
int j;
int dataLen = 0;
pszMessage = args.ArgS();
for (j = 1; j <= argsStartNum; j++) {
dataLen += Q_strlen(args[j]) + 1; // +1 for the space between args
}
if (bSteamID) {
dataLen -= 5; // SteamIDs don't have spaces between the args[) values
}
if (dataLen > Q_strlen(pszMessage)) // saftey check
{
pszMessage = NULL;
} else {
pszMessage += dataLen;
}
}
// find this client
for (i = 0; i < sv.GetClientCount(); i++) {
client = sv.GetClient(i);
if (!client->IsConnected())
continue;
#if defined( REPLAY_ENABLED )
if (client->IsReplay())
continue;
#endif
if (client->IsHLTV())
continue;
// searching by UserID
if (iSearchIndex != -1) {
if (client->GetUserID() == iSearchIndex) {
// found!
break;
}
}
// searching by UniqueID
else {
if (Q_stricmp(client->GetNetworkIDString(), szSearchString) == 0) {
// found!
break;
}
}
}
// now kick them
if (i < sv.GetClientCount()) {
if (cmd_source != src_command) {
who = host_client->m_Name;
}
// can't kick yourself!
if (cmd_source != src_command && host_client == client && !sv.IsDedicated()) {
return;
}
if (iSearchIndex != -1 || !client->IsFakeClient()) {
if (who == NULL) {
if (pszMessage) {
client->Disconnect("%s", pszMessage);
} else {
client->Disconnect(KICKED_BY_CONSOLE);
}
} else {
if (pszMessage) {
client->Disconnect("Kicked by %s : %s", who, pszMessage);
} else {
client->Disconnect("Kicked by %s", who);
}
}
}
} else {
if (iSearchIndex != -1) {
ConMsg("userid \"%d\" not found\n", iSearchIndex);
} else {
ConMsg("uniqueid \"%s\" not found\n", szSearchString);
}
}
}
/*
==================
Host_Kick_f
Kicks a user off of the server using their name
==================
*/
CON_COMMAND(kick, "Kick a player by name.") {
char *who = NULL;
char *pszName = NULL;
IClient *client = NULL;
int i = 0;
char name[64];
if (args.ArgC() <= 1) {
ConMsg("Usage: kick < name >\n");
return;
}
// copy the name to a local buffer
memset(name, 0, sizeof(name));
Q_strncpy(name, args.ArgS(), sizeof(name));
pszName = name;
// safety check
if (pszName && pszName[0] != 0) {
//HACK-HACK
// check for the name surrounded by quotes (comes in this way from rcon)
int len = Q_strlen(pszName) - 1; // (minus one since we start at 0)
if (pszName[0] == '"' && pszName[len] == '"') {
// get rid of the quotes at the beginning and end
pszName[len] = 0;
pszName++;
}
for (i = 0; i < sv.GetClientCount(); i++) {
client = sv.GetClient(i);
if (!client->IsConnected())
continue;
#if defined( REPLAY_ENABLED )
if (client->IsReplay())
continue;
#endif
if (client->IsHLTV())
continue;
// found!
if (Q_strcasecmp(client->GetClientName(), pszName) == 0)
break;
}
// now kick them
if (i < sv.GetClientCount()) {
if (cmd_source != src_command) {
who = host_client->m_Name;
}
// can't kick yourself!
if (cmd_source != src_command && host_client == client && !sv.IsDedicated())
return;
if (who) {
client->Disconnect("Kicked by %s", who);
} else {
client->Disconnect(KICKED_BY_CONSOLE);
}
} else {
ConMsg("name \"%s\" not found\n", pszName);
}
}
}
//-----------------------------------------------------------------------------
// Kicks all users off of the server
//-----------------------------------------------------------------------------
CON_COMMAND(kickall, "Kicks everybody connected with a message.") {
char *who = NULL;
IClient *client = NULL;
int i = 0;
char szMessage[128];
// copy the message to a local buffer
memset(szMessage, 0, sizeof(szMessage));
V_strcpy_safe(szMessage, args.ArgS());
if (cmd_source != src_command) {
who = host_client->m_Name;
}
for (i = 0; i < sv.GetClientCount(); i++) {
client = sv.GetClient(i);
if (!client->IsConnected())
continue;
// can't kick yourself!
if (cmd_source != src_command && host_client == client && !sv.IsDedicated())
continue;
#if defined( REPLAY_ENABLED )
if (client->IsReplay())
continue;
#endif
if (client->IsHLTV())
continue;
if (who) {
if (szMessage[0]) {
client->Disconnect("Kicked by %s : %s", who, szMessage);
} else {
client->Disconnect("Kicked by %s", who);
}
} else {
if (szMessage[0]) {
client->Disconnect("%s", szMessage);
} else {
client->Disconnect(KICKED_BY_CONSOLE);
}
}
}
}
/*
===============================================================================
DEBUGGING TOOLS
===============================================================================
*/
//-----------------------------------------------------------------------------
// Dump memory stats
//-----------------------------------------------------------------------------
CON_COMMAND(memory, "Print memory stats.") {
#if !defined(NO_MALLOC_OVERRIDE)
ConMsg("Heap Used:\n");
int nTotal = MemAlloc_GetSize(0);
if (nTotal == -1) {
ConMsg("Corrupted!\n");
} else {
ConMsg("%5.2f MB (%d bytes)\n", nTotal / (1024.0f * 1024.0f), nTotal);
}
#endif
#ifdef VPROF_ENABLED
ConMsg("\nVideo Memory Used:\n");
CVProfile *pProf = &g_VProfCurrentProfile;
int prefixLen = strlen("TexGroup_Global_");
float total = 0.0f;
for (int i = 0; i < pProf->GetNumCounters(); i++) {
if (pProf->GetCounterGroup(i) == COUNTER_GROUP_TEXTURE_GLOBAL) {
float value = pProf->GetCounterValue(i) * (1.0f / (1024.0f * 1024.0f));
total += value;
const char *pName = pProf->GetCounterName(i);
if (!Q_strnicmp(pName, "TexGroup_Global_", prefixLen)) {
pName += prefixLen;
}
ConMsg("%5.2f MB: %s\n", value, pName);
}
}
ConMsg("------------------\n");
ConMsg("%5.2f MB: total\n", total);
#endif
ConMsg("\nHunk Memory Used:\n");
Hunk_Print();
}
/*
===============================================================================
DEMO LOOP CONTROL
===============================================================================
*/
#ifndef SWDS
//MOTODO move all demo commands to demoplayer
//-----------------------------------------------------------------------------
// Purpose: Gets number of valid demo names
// Output : int
//-----------------------------------------------------------------------------
int Host_GetNumDemos() {
int c = 0;
#ifndef SWDS
for (int i = 0; i < MAX_DEMOS; ++i) {
const char *demoname = cl.demos[i].Get();
if (!demoname[0])
break;
++c;
}
#endif
return c;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void Host_PrintDemoList() {
int count = Host_GetNumDemos();
int next = cl.demonum;
if (next >= count || next < 0) {
next = 0;
}
#ifndef SWDS
for (int i = 0; i < MAX_DEMOS; ++i) {
const char *demoname = cl.demos[i].Get();
if (!demoname[0])
break;
bool isnextdemo = next == i ? true : false;
DevMsg("%3s % 2i : %20s\n", isnextdemo ? "-->" : " ", i, cl.demos[i].Get());
}
#endif
if (!count) {
DevMsg("No demos in list, use startdemos <demoname> <demoname2> to specify\n");
}
}
#ifndef SWDS
//-----------------------------------------------------------------------------
//
// Con commands related to demos, not available on dedicated servers
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Purpose: Specify list of demos for the "demos" command
//-----------------------------------------------------------------------------
CON_COMMAND(startdemos, "Play demos in demo sequence.") {
int c = args.ArgC() - 1;
if (c > MAX_DEMOS) {
Msg("Max %i demos in demoloop\n", MAX_DEMOS);
c = MAX_DEMOS;
}
Msg("%i demo(s) in loop\n", c);
for (int i = 1; i < c + 1; i++) {
cl.demos[i - 1] = args[i];
}
cl.demonum = 0;
Host_PrintDemoList();
if (!sv.IsActive() && !demoplayer->IsPlayingBack()) {
CL_NextDemo();
} else {
cl.demonum = -1;
}
}
//-----------------------------------------------------------------------------
// Purpose: Return to looping demos, optional resume demo index
//-----------------------------------------------------------------------------
CON_COMMAND(demos, "Demo demo file sequence.") {
int oldn = cl.demonum;
cl.demonum = -1;
Host_Disconnect(false);
cl.demonum = oldn;
if (cl.demonum == -1)
cl.demonum = 0;
if (args.ArgC() == 2) {
int numdemos = Host_GetNumDemos();
if (numdemos >= 1) {
cl.demonum = clamp(Q_atoi(args[1]), 0, numdemos - 1);
DevMsg("Jumping to %s\n", cl.demos[cl.demonum].Get());
}
}
Host_PrintDemoList();
CL_NextDemo();
}
//-----------------------------------------------------------------------------
// Purpose: Stop current demo
//-----------------------------------------------------------------------------
CON_COMMAND_F(stopdemo, "Stop playing back a demo.", FCVAR_DONTRECORD) {
if (!demoplayer->IsPlayingBack())
return;
Host_Disconnect(true);
}
//-----------------------------------------------------------------------------
// Purpose: Skip to next demo
//-----------------------------------------------------------------------------
CON_COMMAND(nextdemo, "Play next demo in sequence.") {
if (args.ArgC() == 2) {
int numdemos = Host_GetNumDemos();
if (numdemos >= 1) {
cl.demonum = clamp(Q_atoi(args[1]), 0, numdemos - 1);
DevMsg("Jumping to %s\n", cl.demos[cl.demonum].Get());
}
}
Host_EndGame(false, "Moving to next demo...");
}
//-----------------------------------------------------------------------------
// Purpose: Print out the current demo play order
//-----------------------------------------------------------------------------
CON_COMMAND(demolist, "Print demo sequence list.") {
Host_PrintDemoList();
}
//-----------------------------------------------------------------------------
// Purpose: Host_Soundfade_f
//-----------------------------------------------------------------------------
CON_COMMAND_F(soundfade, "Fade client volume.", FCVAR_SERVER_CAN_EXECUTE) {
float percent;
float inTime, holdTime, outTime;
if (args.ArgC() != 3 && args.ArgC() != 5) {
Msg("soundfade <percent> <hold> [<out> <int>]\n");
return;
}
percent = clamp((float) atof(args[1]), 0.0f, 100.0f);
holdTime = max(0., atof(args[2]));
inTime = 0.0f;
outTime = 0.0f;
if (args.ArgC() == 5) {
outTime = max(0., atof(args[3]));
inTime = max(0., atof(args[4]));
}
S_SoundFade(percent, holdTime, outTime, inTime);
}
#endif // !SWDS
#endif
//-----------------------------------------------------------------------------
// Shutdown the server
//-----------------------------------------------------------------------------
CON_COMMAND(killserver, "Shutdown the server.") {
Host_Disconnect(true);
if (!sv.IsDedicated()) {
// close network sockets
NET_SetMutiplayer(false);
}
}
#if !defined(SWDS)
void Host_VoiceRecordStart_f(void) {
#ifdef VOICE_VOX_ENABLE
ConVarRef voice_vox("voice_vox");
if (voice_vox.IsValid() && voice_vox.GetBool())
return;
#endif // VOICE_VOX_ENABLE
if (cl.IsActive()) {
const char *pUncompressedFile = NULL;
const char *pDecompressedFile = NULL;
const char *pInputFile = NULL;
if (voice_recordtofile.GetInt()) {
pUncompressedFile = "voice_micdata.wav";
pDecompressedFile = "voice_decompressed.wav";
}
if (voice_inputfromfile.GetInt()) {
pInputFile = "voice_input.wav";
}
if (!sv_allow_voice_from_file.GetBool()) {
pInputFile = NULL;
}
#if !defined( NO_VOICE )
if (Voice_RecordStart(pUncompressedFile, pDecompressedFile, pInputFile)) {
}
#endif
}
}
void Host_VoiceRecordStop_f(void) {
#ifdef VOICE_VOX_ENABLE
ConVarRef voice_vox("voice_vox");
if (voice_vox.IsValid() && voice_vox.GetBool())
return;
#endif // VOICE_VOX_ENABLE
if (cl.IsActive()) {
#if !defined( NO_VOICE )
if (Voice_IsRecording()) {
CL_SendVoicePacket(g_bUsingSteamVoice ? false : true);
Voice_UserDesiresStop();
}
#endif
}
}
#ifdef VOICE_VOX_ENABLE
void Host_VoiceToggle_f(const CCommand& args)
{
if (cl.IsActive())
{
#if !defined( NO_VOICE )
bool bToggle = false;
if (args.ArgC() == 2 && V_strcasecmp(args[1], "on") == 0)
{
bToggle = true;
}
if (Voice_IsRecording() && bToggle == false)
{
CL_SendVoicePacket(g_bUsingSteamVoice ? false : true);
Voice_UserDesiresStop();
}
else if (!Voice_IsRecording() && bToggle == true)
{
const char* pUncompressedFile = NULL;
const char* pDecompressedFile = NULL;
const char* pInputFile = NULL;
if (voice_recordtofile.GetInt())
{
pUncompressedFile = "voice_micdata.wav";
pDecompressedFile = "voice_decompressed.wav";
}
if (voice_inputfromfile.GetInt())
{
pInputFile = "voice_input.wav";
}
if (!sv_allow_voice_from_file.GetBool())
{
pInputFile = NULL;
}
Voice_RecordStart(pUncompressedFile, pDecompressedFile, pInputFile);
}
#endif // NO_VOICE
}
}
#endif // VOICE_VOX_ENABLE
#endif // SWDS
//-----------------------------------------------------------------------------
// Purpose: Wrapper for modelloader->Print() function call
//-----------------------------------------------------------------------------
CON_COMMAND(listmodels, "List loaded models.") {
modelloader->Print();
}
/*
==================
Host_IncrementCVar
==================
*/
CON_COMMAND_F(incrementvar, "Increment specified convar value.", FCVAR_DONTRECORD) {
if (args.ArgC() != 5) {
Warning("Usage: incrementvar varName minValue maxValue delta\n");
return;
}
const char *varName = args[1];
if (!varName) {
ConDMsg("Host_IncrementCVar_f without a varname\n");
return;
}
ConVar *var = (ConVar *) g_pCVar->FindVar(varName);
if (!var) {
ConDMsg("cvar \"%s\" not found\n", varName);
return;
}
float currentValue = var->GetFloat();
float startValue = atof(args[2]);
float endValue = atof(args[3]);
float delta = atof(args[4]);
float newValue = currentValue + delta;
if (newValue > endValue) {
newValue = startValue;
} else if (newValue < startValue) {
newValue = endValue;
}
// Conver incrementvar command to direct sets to avoid any problems with state in a demo loop.
Cbuf_AddText(va("%s %f", varName, newValue));
ConDMsg("%s = %f\n", var->GetName(), newValue);
}
//-----------------------------------------------------------------------------
// Host_MultiplyCVar_f
//-----------------------------------------------------------------------------
CON_COMMAND_F(multvar, "Multiply specified convar value.", FCVAR_DONTRECORD) {
if ((args.ArgC() != 5)) {
Warning("Usage: multvar varName minValue maxValue factor\n");
return;
}
const char *varName = args[1];
if (!varName) {
ConDMsg("multvar without a varname\n");
return;
}
ConVar *var = (ConVar *) g_pCVar->FindVar(varName);
if (!var) {
ConDMsg("cvar \"%s\" not found\n", varName);
return;
}
float currentValue = var->GetFloat();
float startValue = atof(args[2]);
float endValue = atof(args[3]);
float factor = atof(args[4]);
float newValue = currentValue * factor;
if (newValue > endValue) {
newValue = endValue;
} else if (newValue < startValue) {
newValue = startValue;
}
// Conver incrementvar command to direct sets to avoid any problems with state in a demo loop.
Cbuf_AddText(va("%s %f", varName, newValue));
ConDMsg("%s = %f\n", var->GetName(), newValue);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND(dumpstringtables, "Print string tables to console.") {
SV_PrintStringTables();
#ifndef SWDS
CL_PrintStringTables();
#endif
}
// Register shared commands
ConCommand quit("quit", Host_Quit_f, "Exit the engine.");
static ConCommand cmd_exit("exit", Host_Quit_f, "Exit the engine.");
#ifndef SWDS
#ifdef VOICE_OVER_IP
static ConCommand startvoicerecord("+voicerecord", Host_VoiceRecordStart_f);
static ConCommand endvoicerecord("-voicerecord", Host_VoiceRecordStop_f);
#ifdef VOICE_VOX_ENABLE
static ConCommand togglevoicerecord("voicerecord_toggle", Host_VoiceToggle_f);
#endif // VOICE_VOX_ENABLE
#endif // VOICE_OVER_IP
#endif // SWDS
#if defined( STAGING_ONLY )
// From Kyle: For the GC we added this so we could call it over and
// over until we got the crash reporter fixed.
// Visual studio optimizes this away unless we disable optimizations.
#pragma optimize( "", off )
class PureCallBase
{
public:
virtual void PureFunction() = 0;
PureCallBase()
{
NonPureFunction();
}
void NonPureFunction()
{
PureFunction();
}
};
class PureCallDerived : public PureCallBase
{
public:
void PureFunction() OVERRIDE
{
}
};
//-----------------------------------------------------------------------------
// Purpose: Force various crashes. useful for testing minidumps.
// crash : Write 0 to address 0.
// crash sys_error : Call Sys_Error().
// crash hang : Hang.
// crash purecall : Call virtual function in ctor.
//-----------------------------------------------------------------------------
CON_COMMAND(crash, "[ sys_error | hang | purecall | segfault | minidump ]: Cause the engine to crash.")
{
if (cmd_source != src_command)
return;
CUtlString cmd((args.ArgC() > 1) ? args[1] : "");
if (cmd == "hang")
{
// Hang. Useful to test watchdog code.
Msg("Hanging... Watchdog time: %d.\n ", Plat_GetWatchdogTime());
for (;; )
{
Msg("%d ", Plat_MSTime());
ThreadSleep(5000);
}
}
else if (cmd == "purecall")
{
Msg("Instantiating PureCallDerived_derived...\n");
PureCallDerived derived;
}
else if (cmd == "sys_error")
{
Msg("Calling Sys_Error...\n");
Sys_Error("%s: Sys_Error()!!!", __FUNCTION__);
}
else if (cmd == "minidump")
{
Msg("Forcing minidump. build_number: %d.\n", build_number());
SteamAPI_WriteMiniDump(0, NULL, build_number());
}
else
{
Msg("Segfault...\n");
char* p = 0;
*p = 0;
}
}
#pragma optimize( "", on )
#endif // STAGING_ONLY
CON_COMMAND_F(flush, "Flush unlocked cache memory.", FCVAR_CHEAT) {
#if !defined( SWDS )
g_ClientDLL->InvalidateMdlCache();
#endif // SWDS
serverGameDLL->InvalidateMdlCache();
g_pDataCache->Flush(true);
}
CON_COMMAND_F(flush_locked, "Flush unlocked and locked cache memory.", FCVAR_CHEAT) {
#if !defined( SWDS )
g_ClientDLL->InvalidateMdlCache();
#endif // SWDS
serverGameDLL->InvalidateMdlCache();
g_pDataCache->Flush(false);
}
CON_COMMAND(cache_print, "cache_print [section]\nPrint out contents of cache memory.") {
const char *pszSection = NULL;
if (args.ArgC() == 2) {
pszSection = args[1];
}
g_pDataCache->OutputReport(DC_DETAIL_REPORT, pszSection);
}
CON_COMMAND(cache_print_lru, "cache_print_lru [section]\nPrint out contents of cache memory.") {
const char *pszSection = NULL;
if (args.ArgC() == 2) {
pszSection = args[1];
}
g_pDataCache->OutputReport(DC_DETAIL_REPORT_LRU, pszSection);
}
CON_COMMAND(cache_print_summary, "cache_print_summary [section]\nPrint out a summary contents of cache memory.") {
const char *pszSection = NULL;
if (args.ArgC() == 2) {
pszSection = args[1];
}
g_pDataCache->OutputReport(DC_SUMMARY_REPORT, pszSection);
}
CON_COMMAND(sv_dump_edicts, "Display a list of edicts allocated on the server.") {
if (!sv.IsActive())
return;
CUtlMap<CUtlString, int> classNameCountMap;
classNameCountMap.SetLessFunc(UtlStringLessFunc);
Msg("\nCurrent server edicts:\n");
for (int i = 0; i < sv.num_edicts; ++i) {
CUtlMap<CUtlString, int>::IndexType_t index = classNameCountMap.Find(sv.edicts[i].GetClassName());
if (index == classNameCountMap.InvalidIndex()) {
index = classNameCountMap.Insert(sv.edicts[i].GetClassName(), 0);
}
classNameCountMap[index]++;
}
Msg("Count Classname\n");
FOR_EACH_MAP(classNameCountMap, i) {
Msg("%5d %s\n", classNameCountMap[i], classNameCountMap.Key(i).String());
}
Msg("NumEdicts: %d\n", sv.num_edicts);
Msg("FreeEdicts: %d\n\n", sv.free_edicts);
}
// make valve_ds only?
CON_COMMAND_F(memory_list, "dump memory list (linux only)", FCVAR_CHEAT) {
DumpMemoryLog(128 * 1024);
}
// make valve_ds only?
CON_COMMAND_F(memory_status, "show memory stats (linux only)", FCVAR_CHEAT) {
DumpMemorySummary();
}
// make valve_ds only?
CON_COMMAND_F(memory_mark, "snapshot current allocation status", FCVAR_CHEAT) {
SetMemoryMark();
}
// make valve_ds only?
CON_COMMAND_F(memory_diff, "show memory stats relative to snapshot", FCVAR_CHEAT) {
DumpChangedMemory(64 * 1024);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CON_COMMAND(namelockid, "Prevent name changes for this userID.") {
if (args.ArgC() <= 2) {
ConMsg("Usage: namelockid < userid > < 0 | 1 >\n");
return;
}
CBaseClient *pClient = NULL;
int iIndex = Q_atoi(args[1]);
if (iIndex > 0) {
for (int i = 0; i < sv.GetClientCount(); i++) {
pClient = static_cast<CBaseClient *>(sv.GetClient(i));
if (!pClient->IsConnected())
continue;
#if defined( REPLAY_ENABLED )
if (pClient->IsReplay())
continue;
#endif
if (pClient->IsHLTV())
continue;
if (pClient->GetUserID() == iIndex)
break;
pClient = NULL;
}
}
if (pClient) {
pClient->SetPlayerNameLocked((Q_atoi(args[2]) == 0) ? false : true);
} else {
ConMsg("Player id \"%d\" not found.\n", iIndex);
}
}
#if defined( STAGING_ONLY ) || defined( _DEBUG )
CON_COMMAND(fs_find, "Run virtual filesystem find")
{
if (args.ArgC() != 3)
{
ConMsg("Usage: fs_find wildcard pathid\n");
return;
}
const char* pWildcard = args.Arg(1);
const char* pPathID = args.Arg(2);
FileFindHandle_t findhandle;
const char* pFile = NULL;
size_t matches = 0;
for (pFile = g_pFullFileSystem->FindFirstEx(pWildcard, pPathID, &findhandle);
pFile;
pFile = g_pFullFileSystem->FindNext(findhandle))
{
ConMsg("%s\n", pFile);
matches++;
}
ConMsg(" %u matching files/directories\n", matches);
}
#endif // defined( STAGING_ONLY ) || defined( _DEBUG )
| 29.878995 | 165 | 0.548605 | [
"render",
"vector"
] |
3ce6cde52742af519328e261ea6322d201ee613f | 7,712 | cpp | C++ | libkra_cl/libkra_cl.cpp | 2shady4u/libkra | 85dd0049dfffd04afce6a31783a85170b8fb2bd1 | [
"MIT"
] | null | null | null | libkra_cl/libkra_cl.cpp | 2shady4u/libkra | 85dd0049dfffd04afce6a31783a85170b8fb2bd1 | [
"MIT"
] | null | null | null | libkra_cl/libkra_cl.cpp | 2shady4u/libkra | 85dd0049dfffd04afce6a31783a85170b8fb2bd1 | [
"MIT"
] | null | null | null | // ############################################################################ #
// Copyright © 2022 Piet Bronders & Jeroen De Geeter <piet.bronders@gmail.com>
// Licensed under the MIT License.
// See LICENSE in the project root for license information.
// ############################################################################ #
#include "../libkra/kra_utility.h"
#include "../libkra/kra_document.h"
#include "../libkra/kra_exported_layer.h"
#include "../libpng/png.h"
#include <iostream>
// ---------------------------------------------------------------------------------------------------------------------
// Export and save as a *.png-file with the help of the libpng-library.
// ---------------------------------------------------------------------------------------------------------------------
bool write_data_to_png(const char *filename, unsigned int width, unsigned int height, const uint8_t *data)
{
bool success = true;
FILE *fp = NULL;
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
png_bytep row = NULL;
unsigned int channelCount = 4;
int colorType = PNG_COLOR_TYPE_RGBA;
// Open file for writing (binary mode)
fp = fopen(filename, "wb");
if (fp == NULL)
{
std::cout << "Could not open file " << filename << " for writing" << std::endl;
success = false;
goto finalise;
}
// Initialize write structure
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL)
{
std::cout << "Could not allocate write struct" << std::endl;
success = false;
goto finalise;
}
// Initialize info structure
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
std::cout << "Could not allocate info struct" << std::endl;
success = false;
goto finalise;
}
// Setup Exception handling
if (setjmp(png_jmpbuf(png_ptr)))
{
std::cout << "Error during png creation" << std::endl;
success = false;
goto finalise;
}
png_init_io(png_ptr, fp);
/* Write header depending on the channel type, always in 8 bit colour depth. */
png_set_IHDR(png_ptr, info_ptr, width, height,
8, colorType, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
/* Allocate memory for one row */
row = (png_bytep)malloc(channelCount * width * sizeof(png_byte));
/* Write image data, one row at a time. */
unsigned int x, y;
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
memcpy(row, &data[channelCount * width * y], channelCount * width * sizeof(png_byte));
}
png_write_row(png_ptr, row);
}
/* End the png_ptrwrite operation */
png_write_end(png_ptr, NULL);
/* Clear up the memory from the heap */
finalise:
if (fp != NULL)
fclose(fp);
if (info_ptr != NULL)
png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
if (png_ptr != NULL)
png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
if (row != NULL)
std::free(row);
return success;
}
// ---------------------------------------------------------------------------------------------------------------------
// Get the important layer data and write this data to a .png-file
// ---------------------------------------------------------------------------------------------------------------------
void save_layer_to_image(const std::unique_ptr<kra::ExportedLayer> &layer)
{
unsigned int layer_width = (unsigned int)(layer->right - layer->left);
unsigned int layer_height = (unsigned int)(layer->bottom - layer->top);
const std::string file_name = layer->name + ".png";
/* Export the layer's data to a texture */
write_data_to_png(file_name.c_str(), layer_width, layer_height, layer->data.data());
}
// ---------------------------------------------------------------------------------------------------------------------
// Process each layer and, depending on the type, either call the saving method or recursively call this method again.
// ---------------------------------------------------------------------------------------------------------------------
void process_layer(const std::unique_ptr<kra::Document> &document, const std::unique_ptr<kra::ExportedLayer> &layer)
{
switch (layer->type)
{
case kra::PAINT_LAYER:
{
save_layer_to_image(layer);
break;
}
case kra::GROUP_LAYER:
for (auto const &uuid : layer->child_uuids)
{
std::unique_ptr<kra::ExportedLayer> child = document->get_exported_layer_with_uuid(uuid);
process_layer(document, child);
}
break;
}
}
// ---------------------------------------------------------------------------------------------------------------------
// Export the document as found at the given path
// ---------------------------------------------------------------------------------------------------------------------
int export_document(std::wstring p_file_name)
{
std::unique_ptr<kra::Document> document = std::make_unique<kra::Document>();
document->load(p_file_name);
if (document == NULL)
{
return 1;
}
switch (document->color_space)
{
case kra::ColorSpace::RGBA:
{
std::vector<std::unique_ptr<kra::ExportedLayer>> exported_layers = document->get_all_exported_layers();
for (auto const &layer : exported_layers)
{
process_layer(document, layer);
}
return 0;
}
default:
// NOTE: 16-bit integer images (RGBA16) can definitely be exported to PNG, but this is not implemented!
std::fprintf(stderr, "ERROR: Document with color space name '%s' cannot be exported to PNG.\n", kra::get_color_space_name(document->color_space).c_str());
return 1;
}
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
static void show_usage(std::string name)
{
// TODO: Allow multiple sources!
// TODO: Add a destination option at some point!
std::cerr << "Usage: " << name << " [options]\n"
<< "\n"
<< "General options:\n"
<< " -h, --help Display this help message.\n"
<< " -s, --source <source> Specify the KRA source file.\n"
<< " -q, --quiet Do not print anything in the console.\n"
<< " -v, --verbose Print additional logs in the console.\n";
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
int main(int argc, const char *argv[])
{
std::vector<std::string> sources;
// NOTE: Maybe we shouldn't hardcode this? This is here mainly for debugging purposes.
std::wstring file_name = L"..\\examples\\example_RGBA.kra";
for (int i = 1; i < argc; ++i)
{
std::string arg = argv[i];
if ((arg == "-h") || (arg == "--help"))
{
show_usage(argv[0]);
return 0;
}
else if ((arg == "-s") || (arg == "--source"))
{
// Make sure we aren't at the end of argv!
if (i + 1 < argc)
{
std::string str = argv[i + 1]; // Increment 'i' so we don't get the argument as the next argv[i].
file_name = std::wstring(str.begin(), str.end());
}
else
{ // Uh-oh, there was no argument to the source option.
std::cerr << "--source option requires one argument." << std::endl;
return 1;
}
}
else if ((arg == "-q") || (arg == "--quiet"))
{
kra::verbosity_level = kra::QUIET;
}
else if ((arg == "-v") || (arg == "--verbose"))
{
kra::verbosity_level = kra::VERBOSE;
}
else
{
sources.push_back(argv[i]);
}
}
const int result = export_document(file_name);
if (result != 0)
{
return result;
}
return 0;
} | 32.540084 | 156 | 0.520877 | [
"vector"
] |
3ce743dd21369363f5cd493ba8c164c8db70c819 | 579 | cpp | C++ | contest/1509/c/c.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | contest/1509/c/c.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | contest/1509/c/c.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define watch(x) std::cout << (#x) << " is " << (x) << std::endl
using LL = long long;
int main() {
//freopen("in", "r", stdin);
std::cin.tie(nullptr)->sync_with_stdio(false);
int n;
std::cin >> n;
std::vector<int> a(n);
for (auto &x : a) std::cin >> x;
std::sort(a.begin(), a.end());
std::vector<std::vector<LL>> dp(n, std::vector<LL>(n));
for (int i = 1; i < n; ++i) {
for (int j = 0; j + i < n; ++j) {
dp[j][i + j] = std::min(dp[j + 1][i + j], dp[j][i + j - 1]) + a[i + j] - a[j];
}
}
std::cout << dp[0][n - 1] << '\n';
return 0;
} | 27.571429 | 81 | 0.488774 | [
"vector"
] |
3ceb6329d953151b8be86d65028276420710ab4a | 6,732 | hpp | C++ | include/opengv/sac/implementation/SampleConsensusProblem.hpp | Byson-source/opengv | a87af73cc5896417fec9e013feef2fa2d9891e8d | [
"BSD-3-Clause"
] | 35 | 2018-11-09T07:19:26.000Z | 2021-12-12T02:41:01.000Z | include/opengv/sac/implementation/SampleConsensusProblem.hpp | Byson-source/opengv | a87af73cc5896417fec9e013feef2fa2d9891e8d | [
"BSD-3-Clause"
] | 3 | 2016-09-01T08:45:58.000Z | 2020-09-17T02:05:13.000Z | include/opengv/sac/implementation/SampleConsensusProblem.hpp | Byson-source/opengv | a87af73cc5896417fec9e013feef2fa2d9891e8d | [
"BSD-3-Clause"
] | 17 | 2018-11-17T16:06:58.000Z | 2022-02-22T09:51:02.000Z | /******************************************************************************
* Authors: Laurent Kneip & Paul Furgale *
* Contact: kneip.laurent@gmail.com *
* License: Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* * Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* * Neither the name of ANU 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 ANU OR THE CONTRIBUTORS BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY *
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
******************************************************************************/
//Note: has been derived from ROS
template<typename M>
opengv::sac::SampleConsensusProblem<M>::SampleConsensusProblem(
bool randomSeed) :
max_sample_checks_(10)
{
rng_dist_.reset(new std::uniform_int_distribution<>( 0, std::numeric_limits<int>::max() ));
// Create a random number generator object
if(randomSeed)
rng_alg_.seed(static_cast<unsigned> (std::time(0)));
else
rng_alg_.seed(12345u);
rng_gen_.reset(new std::function<int()>(std::bind(*rng_dist_, rng_alg_)));
}
template<typename M>
opengv::sac::SampleConsensusProblem<M>::~SampleConsensusProblem()
{}
template<typename M>
bool opengv::sac::SampleConsensusProblem<M>::isSampleGood(
const std::vector<int> & sample) const
{
// Default implementation
return true;
}
template<typename M>
void
opengv::sac::SampleConsensusProblem<M>::drawIndexSample(
std::vector<int> & sample)
{
size_t sample_size = sample.size();
size_t index_size = shuffled_indices_.size();
for( unsigned int i = 0; i < sample_size; ++i )
{
// The 1/(RAND_MAX+1.0) trick is when the random numbers are not uniformly
// distributed and for small modulo elements, that does not matter
// (and nowadays, random number generators are good)
//std::swap (shuffled_indices_[i], shuffled_indices_[i + (rand () % (index_size - i))]);
std::swap(
shuffled_indices_[i],
shuffled_indices_[i + (rnd() % (index_size - i))] );
}
std::copy(
shuffled_indices_.begin(),
shuffled_indices_.begin() + sample_size,
sample.begin() );
}
template<typename M>
void
opengv::sac::SampleConsensusProblem<M>::getSamples(
int &iterations, std::vector<int> &samples)
{
// We're assuming that indices_ have already been set in the constructor
if (indices_->size() < (size_t)getSampleSize())
{
fprintf( stderr,
"[sm::SampleConsensusModel::getSamples] Can not select %zu unique points out of %zu!\n",
(size_t) getSampleSize(), indices_->size() );
// one of these will make it stop :)
samples.clear();
iterations = std::numeric_limits<int>::max();
return;
}
// Get a second point which is different than the first
samples.resize( getSampleSize() );
for( int iter = 0; iter < max_sample_checks_; ++iter )
{
drawIndexSample(samples);
// If it's a good sample, stop here
if(isSampleGood(samples))
return;
}
fprintf( stdout,
"[sm::SampleConsensusModel::getSamples] WARNING: Could not select %d sample points in %d iterations!\n",
getSampleSize(), max_sample_checks_ );
samples.clear();
}
template<typename M>
std::shared_ptr< std::vector<int> >
opengv::sac::SampleConsensusProblem<M>::getIndices() const
{
return indices_;
}
template<typename M>
void
opengv::sac::SampleConsensusProblem<M>::getDistancesToModel(
const model_t & model_coefficients, std::vector<double> & distances )
{
getSelectedDistancesToModel( model_coefficients, *indices_, distances );
}
template<typename M>
void
opengv::sac::SampleConsensusProblem<M>::setUniformIndices(int N)
{
indices_.reset( new std::vector<int>() );
indices_->resize(N);
for( int i = 0; i < N; ++i )
(*indices_)[i] = i;
shuffled_indices_ = *indices_;
}
template<typename M>
void
opengv::sac::SampleConsensusProblem<M>::setIndices(
const std::vector<int> & indices )
{
indices_.reset( new std::vector<int>(indices) );
shuffled_indices_ = *indices_;
}
template<typename M>
int
opengv::sac::SampleConsensusProblem<M>::rnd()
{
return ((*rng_gen_)());
}
template<typename M>
void
opengv::sac::SampleConsensusProblem<M>::selectWithinDistance(
const model_t & model_coefficients,
const double threshold,
std::vector<int> &inliers )
{
std::vector<double> dist;
dist.reserve(indices_->size());
getDistancesToModel( model_coefficients, dist );
inliers.clear();
inliers.reserve(indices_->size());
for( size_t i = 0; i < dist.size(); ++i )
{
if( dist[i] < threshold )
inliers.push_back( (*indices_)[i] );
}
}
template<typename M>
int
opengv::sac::SampleConsensusProblem<M>::countWithinDistance(
const model_t & model_coefficients, const double threshold)
{
std::vector<double> dist;
dist.reserve(indices_->size());
getDistancesToModel( model_coefficients, dist );
int count = 0;
for( size_t i = 0; i < dist.size(); ++i )
{
if( dist[i] < threshold )
++count;
}
return count;
}
| 33.492537 | 110 | 0.633838 | [
"object",
"vector"
] |
3cebd8307f84b03d9517e16c3928b69b965e6d36 | 108,993 | cpp | C++ | addons/imguiyesaddons/imguisdf.cpp | tom-seddon/imgui | 5afd20af902c444d148f45edf6b41b63ea484a4e | [
"MIT"
] | null | null | null | addons/imguiyesaddons/imguisdf.cpp | tom-seddon/imgui | 5afd20af902c444d148f45edf6b41b63ea484a4e | [
"MIT"
] | null | null | null | addons/imguiyesaddons/imguisdf.cpp | tom-seddon/imgui | 5afd20af902c444d148f45edf6b41b63ea484a4e | [
"MIT"
] | null | null | null |
//- Common Code For All Addons needed just to ease inclusion as separate files in user code ----------------------
#include <imgui.h>
#undef IMGUI_DEFINE_PLACEMENT_NEW
#define IMGUI_DEFINE_PLACEMENT_NEW
#undef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#include <imgui_internal.h>
//-----------------------------------------------------------------------------------------------------------------
#include "imguisdf.h"
#include "../imguicodeeditor/utf8helper.h"
#ifdef NO_IMGUISTRING
#error imguistring is necessary
#endif //NO_IMGUISTRING
#include "../imguistring/imguistring.h"
#ifdef IMIMPL_SHADER_NONE
#warning Shaders are mandatory
#endif //IMIMPL_SHADER_NONE
#ifdef IMGUI_USE_DIRECT3D9_BINDING
#error Direct3D port is missing
#endif //IMGUI_USE_DIRECT3D9_BINDING
// TODO: try to reuse ImDrawList to do the drawing (instead of using vbos)
namespace ImGui {
static SdfTextColor gSdfTextDefaultColor(ImVec4(1,1,1,1));
class SdfVertexBuffer {
public:
void clear() {verts.clear();}
~SdfVertexBuffer() {if (vbo) glDeleteBuffers(1,&vbo);}
void updateBoundVbo() const {
const GLenum drawMode = preferStreamDrawBufferUsage ? GL_STREAM_DRAW : GL_STATIC_DRAW;
//glBufferData(GL_ARRAY_BUFFER, verts.size()*sizeof(VertexDeclaration),verts.size()!=0 ? &verts[0].posAndUV.x : NULL, drawMode);return;
if (maxVertsSize<verts.size()) maxVertsSize=verts.size();
glBufferData(GL_ARRAY_BUFFER, maxVertsSize*sizeof(VertexDeclaration), NULL, drawMode);
if (verts.size()>0) {
glBufferSubData(GL_ARRAY_BUFFER,0,verts.size()*sizeof(VertexDeclaration),&verts[0].posAndUV.x);
//fprintf(stderr,"%d indices\n",verts.size());
}
}
inline int getType() const {return type;}
inline void setType(int _type) {type=_type;}
inline const ImVec4* getColorOfVert(int num) const {return verts.size()>num*6 ? &verts[num*6].color : NULL;}
inline int size() const {return verts.size();}
inline int numChars() const {return verts.size()/6;}
#ifndef _MSC_VER // Not sure, but old cl compilers can have problems here
protected:
#endif //_MSC_VER
SdfVertexBuffer(int _type=SDF_BT_OUTLINE,bool _preferStreamDrawBufferUsage=false) : type(_type),preferStreamDrawBufferUsage(_preferStreamDrawBufferUsage) {maxVertsSize=0;vbo=0;}
struct VertexDeclaration {
ImVec4 posAndUV;
ImVec4 color;
};
ImVector<VertexDeclaration> verts;
GLuint vbo;
int type;
bool preferStreamDrawBufferUsage;
mutable int maxVertsSize;
friend struct SdfCharset;
friend struct SdfTextChunk;
friend void SdfRender(const ImVec4 *pViewportOverride);
friend bool SdfTextChunkEdit(SdfTextChunk* sdfTextChunk,char* buffer,int bufferSize);
};
struct SdfCharDescriptor
{
unsigned int Id; // The character id.
float X, Y; // The left and top position of the character image in the texture.
float Width, Height; // The width and height of the character image in the texture.
float XOffset, YOffset; // How much the current position should be offset when copying the image from the texture to the screen ( top/left offsets ).
float XOffset2, YOffset2; // How much the current position should be offset when copying the image from the texture to the screen ( lower/right offsets ).
float XAdvance; // How much the current position should be advanced after drawing the character.
unsigned char Page; // The texture page where the character image is found.
SdfCharDescriptor() : Id(0), X( 0 ), Y( 0 ), Width( 0 ), Height( 0 ), XOffset( 0 ), YOffset( 0 ), XOffset2( 0 ), YOffset2( 0 ),
XAdvance( 0 ), Page( 0 )
{ }
};
struct SdfAnimation {
//public:
SdfAnimation() {totalTime=0.f;}
SdfAnimation(const SdfAnimation& o) {*this=o;totalTime=0.f;}
SdfAnimation(const ImVector<SdfAnimationKeyFrame>& _keyFrames) {cloneKeyFramesFrom(_keyFrames);totalTime=0.f;looping=false;mustMuteAtEnd=true;}
~SdfAnimation() {}
const SdfAnimation& operator=(const SdfAnimation& o) {
cloneKeyFramesFrom(o.keyFrames);
return *this;
}
//protected:
ImVector<SdfAnimationKeyFrame> keyFrames;
float totalTime;
bool looping;
bool mustMuteAtEnd;
inline void cloneKeyFramesFrom(const ImVector<SdfAnimationKeyFrame>& _keyFrames) {
// deep clone keyframes
const int nkf = _keyFrames.size();
keyFrames.clear();keyFrames.reserve(nkf);
for (int i=0;i<nkf;i++) keyFrames[i] = _keyFrames[i];
}
inline float addKeyFrame(const SdfAnimationKeyFrame& kf) {
keyFrames.push_back(kf);
totalTime+=kf.timeInSeconds;
return totalTime;
}
inline bool removeKeyFrameAt(int i) {
if (i<0 || i>=keyFrames.size()) return false;
for (int j=i,jsz=keyFrames.size()-1;j<jsz;j++) keyFrames[j] = keyFrames[j+1];
keyFrames.pop_back();
update();
return true;
}
inline void clear() {keyFrames.clear();totalTime=0.f;}
inline void update() {
totalTime = 0.f;
for (int i=0,isz=keyFrames.size();i<isz;i++) {
totalTime+=keyFrames[i].timeInSeconds;
}
}
};
struct SdfTextChunk {
SdfTextChunkProperties props;
const SdfCharset* charset;
SdfVertexBuffer* buffer;
int numValidGlyphs;
mutable bool dirty;
ImVec2 shadowOffsetInPixels;
bool mute;
SDFAnimationMode animationMode;
SdfAnimation* manualAnimationRef;
float animationStartTime;
SdfAnimationParams animationParams;
SdfGlobalParams globalParams;
struct TextBit {
ImVectorEx<SdfCharDescriptor> charDescriptors;
ImVectorEx<float> kernings;
ImVec2 scaling;
SdfTextColor sdfTextColor;
bool italic;
int hAlignment;
};
ImVectorEx<TextBit> textBits;
SdfTextChunk() {charset=NULL;buffer=NULL;numValidGlyphs=0;shadowOffsetInPixels.x=shadowOffsetInPixels.y=4.f;mute = false;animationMode=SDF_AM_NONE;manualAnimationRef=NULL;animationStartTime=-1.f;tmpVisible = true;tmpLocalTime=0.f;}
SdfTextChunk(const SdfCharset* _charset,int bufferType,const SdfTextChunkProperties& properties=SdfTextChunkProperties(),bool preferStreamDrawBufferUsage=false) {
buffer = (SdfVertexBuffer*) ImGui::MemAlloc(sizeof(SdfVertexBuffer));
IM_PLACEMENT_NEW (buffer) SdfVertexBuffer(bufferType,preferStreamDrawBufferUsage);
IM_ASSERT(buffer);
charset = _charset;
IM_ASSERT(charset);
props = properties;
dirty = true;
numValidGlyphs=0;
shadowOffsetInPixels.x=shadowOffsetInPixels.y=4.f;
mute = false;
animationMode=SDF_AM_NONE;manualAnimationRef=NULL;animationStartTime=-1.f;
tmpVisible = true;tmpLocalTime=0.f;
}
~SdfTextChunk() {
if (buffer) {
buffer->~SdfVertexBuffer();
ImGui::MemFree(buffer);
buffer=NULL;
}
}
inline void setMute(bool flag) {
if (mute!=flag) {
animationStartTime = -1.f;
mute = flag;
}
}
// These tmp variables are valid per frame and set by next methods:
mutable bool tmpVisible;
mutable float tmpLocalTime;
mutable SdfAnimationKeyFrame tmpKeyFrame;
inline static float Lerp(float t,float v0,float v1) {return v0+t*(v1-v0);}
inline static int LerpInt(float t,int v0,int v1) {return v0+(int)((t*(float)(v1-v0))+0.5f);}
inline static void Lerp(float t,SdfAnimationKeyFrame& kfOut,const SdfAnimationKeyFrame& kf0,const SdfAnimationKeyFrame& kf1,int numGlyphs) {
kfOut.alpha = (kf0.alpha==kf1.alpha) ? kf0.alpha : Lerp(t,kf0.alpha,kf1.alpha);
kfOut.offset.x = (kf0.offset.x==kf1.offset.x) ? kf0.offset.x : Lerp(t,kf0.offset.x,kf1.offset.x);
kfOut.offset.y = (kf0.offset.y==kf1.offset.y) ? kf0.offset.y : Lerp(t,kf0.offset.y,kf1.offset.y);
kfOut.scale.x = (kf0.scale.x==kf1.scale.x) ? kf0.scale.x : Lerp(t,kf0.scale.x,kf1.scale.x);
kfOut.scale.y = (kf0.scale.y==kf1.scale.y) ? kf0.scale.y : Lerp(t,kf0.scale.y,kf1.scale.y);
kfOut.startChar = (kf0.startChar==kf1.startChar) ? kf0.startChar : LerpInt(t,kf0.startChar,kf1.startChar);
kfOut.endChar = (kf0.endChar==kf1.endChar) ? kf0.endChar : LerpInt(t,(kf0.endChar<0)?numGlyphs:kf0.endChar,(kf1.endChar<0)?numGlyphs:kf1.endChar);
}
inline bool checkVisibleAndEvalutateAnimationIfNecessary(float time) {
if (mute || (animationMode==SDF_AM_MANUAL && (!manualAnimationRef || manualAnimationRef->keyFrames.size()==0 || manualAnimationRef->totalTime==0.f))) return (tmpVisible=false);
if (animationStartTime < 0) animationStartTime = time;
tmpLocalTime=(time-animationStartTime)*animationParams.speed-animationParams.timeOffset;
if (tmpLocalTime<0) return (tmpVisible=false);
if (animationMode==SDF_AM_MANUAL && tmpLocalTime>manualAnimationRef->totalTime) {
// return (tmpVisible=false);
if (!manualAnimationRef->looping) {
animationStartTime=-1.f;animationMode=SDF_AM_NONE;
if (manualAnimationRef->mustMuteAtEnd) {setMute(true);return (tmpVisible=false);}
else {/*tmpKeyFrame = SdfAnimationKeyFrame();*/setMute(false);return (tmpVisible=true);}
}
else if (manualAnimationRef->totalTime>0.f) {
while (tmpLocalTime>manualAnimationRef->totalTime) {tmpLocalTime-=manualAnimationRef->totalTime;animationStartTime+=manualAnimationRef->totalTime;}
//fprintf(stderr,"time: %1.4f/%1.4f (%d frames)\n",tmpLocalTime,manualAnimationRef->totalTime,manualAnimationRef->keyFrames.size());
}
}
// evalutate animation here:
tmpKeyFrame = SdfAnimationKeyFrame();
switch (animationMode) {
case SDF_AM_FADE_IN: {if (tmpLocalTime<1.f) tmpKeyFrame.alpha = tmpLocalTime;else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_FADE_OUT: {if (tmpLocalTime<1.f) tmpKeyFrame.alpha = 1.f-tmpLocalTime;else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_ZOOM_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime = (2.0f-tmpLocalTime); // in [2,1]
tmpLocalTime = tmpLocalTime*tmpLocalTime*tmpLocalTime; // in [8,1]
tmpKeyFrame.scale.x=tmpKeyFrame.scale.y = tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_ZOOM_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = (1.0f+tmpLocalTime); // in [1,2]
tmpLocalTime = tmpLocalTime*tmpLocalTime*tmpLocalTime; // in [1,8]
tmpKeyFrame.scale.x=tmpKeyFrame.scale.y = tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_APPEAR_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.scale.y = tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_APPEAR_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.scale.y = tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_LEFT_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.x = -1.0f + tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_LEFT_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.x = -1.0f + tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_RIGHT_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.x = 1.0f - tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_RIGHT_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.x = 1.0f - tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_TOP_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.y = -1.0f + tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_TOP_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.y = -1.0f + tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_BOTTOM_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.y = 1.0f - tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_BOTTOM_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.y = 1.0f - tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_BLINK: {float tmp = (float) ((((int)(tmpLocalTime*100.f))%101)-50)*0.02f;tmpKeyFrame.alpha = tmp*tmp;}
break;
case SDF_AM_PULSE: {
tmpKeyFrame.scale.x=tmpKeyFrame.scale.y = 1.0f+((0.005f*20.f)/(float)(this->props.maxNumTextLines))*sinf(tmpLocalTime*10.0f);
}
break;
case SDF_AM_TYPING: {
static const float timePerChar = 0.15f;
const int numChars = buffer->numChars();
const float timeForAllChars = timePerChar * numChars;
if (timeForAllChars>0) {
if (tmpLocalTime<=timeForAllChars) {
tmpKeyFrame.endChar = (int)(((tmpLocalTime/timeForAllChars)*(float)(numChars))+0.5f);
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}
}
break;
case SDF_AM_MANUAL: {
const SdfAnimation& an = *manualAnimationRef;
const int nkf = an.keyFrames.size();
static SdfAnimationKeyFrame ZeroKF(0.f,0.f);
float sumTime = 0;int i=0;const SdfAnimationKeyFrame* kf = NULL;
for (i=0;i<nkf;i++) {
kf = &an.keyFrames[i];
if (kf->timeInSeconds==0.f) continue;
if (tmpLocalTime <= sumTime + kf->timeInSeconds) break;
sumTime+=kf->timeInSeconds;
}
//if (!kf) kf = (nkf>0 && animationParams.looping) ? &an.keyFrames[nkf-1] : &ZeroKF;
//fprintf(stderr,"FRAME: %d\n",i);
IM_ASSERT(kf && kf->timeInSeconds);
const SdfAnimationKeyFrame* kf_prev = (i>=1 ? &an.keyFrames[i-1] : (nkf>0 &&
(tmpLocalTime>manualAnimationRef->totalTime && manualAnimationRef->looping) // Not sure what I meant here... now I'm just correcting what it was: "tmpLocalTime>manualAnimationRef->looping", but looping is a bool. What did I mean ?
) ? &an.keyFrames[nkf-1] : &ZeroKF);
const float deltaTime = (tmpLocalTime-sumTime)/kf->timeInSeconds; // in [0,1]
IM_ASSERT(deltaTime>=0.f && deltaTime<=1.f);
Lerp(deltaTime,tmpKeyFrame,*kf_prev,*kf,buffer->numChars());
}
break;
default:
break;
}
const bool applyAnimationParams = true;
if (applyAnimationParams) {
// Here we apply animationParams to the calculated fields
tmpKeyFrame.alpha*=globalParams.alpha;
tmpKeyFrame.offset.x+=globalParams.offset.x;
tmpKeyFrame.offset.y+=globalParams.offset.y;
tmpKeyFrame.scale.x*=globalParams.scale.x;
tmpKeyFrame.scale.y*=globalParams.scale.y;
}
return (tmpVisible=(tmpLocalTime>=0));
}
inline bool setupUniformValuesAndDrawArrays(struct SdfShaderProgram* SP, bool shadowPass, const ImVec2 &screenSize);
inline void addText(const char* startText,bool _italic,const SdfTextColor* pSdfTextColor,const ImVec2* textScaling,const char* endText,const SDFHAlignment *phalignOverride, bool fakeBold);
inline void clearText() {
if (buffer) buffer->clear();
textBits.clear();
dirty=false;
numValidGlyphs=0;
}
inline void assignText(const char* startText,bool _italic,const SdfTextColor* pSdfTextColor,const ImVec2* textScaling,const char* endText,const SDFHAlignment *phalignOverride, bool fakeBold) {
clearText();
addText(startText,_italic,pSdfTextColor,textScaling,endText,phalignOverride,fakeBold);
}
bool endText(ImVec2 screenSize=ImVec2(-1,-1));
};
struct SdfShaderProgram {
GLuint program;
GLint uniformLocationOrthoMatrix;
GLint uniformLocationSampler;
GLint uniformLocationOffsetAndScale;
GLint uniformLocationAlphaAndShadow;
SdfShaderProgram() : program(0),uniformLocationOrthoMatrix(-1),uniformLocationSampler(-1),
uniformLocationOffsetAndScale(-1),uniformLocationAlphaAndShadow(-1) {}
~SdfShaderProgram() {destroy();}
void destroy() {
if (program) {glDeleteProgram(program);program=0;}
}
bool loadShaderProgram(bool forOutlineShaderProgram) {
if (program) return true;
program = CompileShaderProgramAndSetCorrectAttributeLocations(forOutlineShaderProgram);
if (program) {
uniformLocationOrthoMatrix = glGetUniformLocation(program,"ortho");
uniformLocationSampler = glGetUniformLocation(program,"Texture");
uniformLocationOffsetAndScale = glGetUniformLocation(program,"offsetAndScale");
uniformLocationAlphaAndShadow = glGetUniformLocation(program,"alphaAndShadow");
IM_ASSERT(uniformLocationOrthoMatrix!=-1);
IM_ASSERT(uniformLocationSampler!=-1);
IM_ASSERT(uniformLocationOffsetAndScale!=-1);
IM_ASSERT(uniformLocationAlphaAndShadow!=-1);
glUseProgram(program);
resetUniforms();
glUseProgram(0);
}
return program!=0;
}
void resetUniforms() {
resetUniformOrtho();
glUniform1i(uniformLocationSampler, 0);
setUniformOffsetAndScale();
setUniformAlphaAndShadow();
}
inline void setUniformOffsetAndScale(const ImVec2& offset=ImVec2(0,0),const ImVec2& scale=ImVec2(1,1)) {
glUniform4f(uniformLocationOffsetAndScale,offset.x,offset.y,scale.x,scale.y);
}
// Shadow must be < 1 only in the "shadow pass"
inline void setUniformAlphaAndShadow(const float alpha=1.f,const float shadow=1.f) {
glUniform2f(uniformLocationAlphaAndShadow,alpha,shadow);
}
void resetUniformOrtho() {
const float ortho[4][4] = {
{ 2.0f/ImGui::GetIO().DisplaySize.x, 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/-ImGui::GetIO().DisplaySize.y, 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{-1.0f, 1.0f, 0.0f, 1.0f },
};
glUniformMatrix4fv(uniformLocationOrthoMatrix, 1, GL_FALSE, &ortho[0][0]);
}
static const char** GetVertexShaderCodeForBothFonts() {
static const char* gVertexShaderSource[] = {
# ifdef IMIMPL_SHADER_GL3
# if (defined(IMIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 300 es\n"
# else //IMIMPL_SHADER_GLES
"#version 330\n"
# endif //IMIMPL_SHADER_GLES
"precision highp float;\n"
"uniform mat4 ortho;\n"
"uniform vec4 offsetAndScale;\n"
"layout (location = 0 ) in vec2 Position;\n"
"layout (location = 1 ) in vec2 UV;\n"
"layout (location = 2 ) in vec4 Colour;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Colour;\n"
# else //!IMIMPL_SHADER_GL3
# if (defined(IMIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 100\n"
"precision highp float;\n"
# endif //IMIMPL_SHADER_GLES
"uniform mat4 ortho;\n"
"uniform vec4 offsetAndScale;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Colour;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Colour;\n"
# endif //!IMIMPL_SHADER_GL3
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Colour = Colour;\n"
"\n"
" gl_Position = ortho*vec4(offsetAndScale.x+Position.x*offsetAndScale.z,offsetAndScale.y+Position.y*offsetAndScale.w,0,1);\n"
"}\n"
};
return &gVertexShaderSource[0];
}
static const char** GetFragmentShaderCodeForRegularFont() {
static const char* gFragmentShaderSource[] = {
# ifdef IMIMPL_SHADER_GL3
# if (defined(IMIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 300 es\n"
# else //IMIMPL_SHADER_GLES
"#version 330\n"
# endif //IMIMPL_SHADER_GLES
"precision mediump float;\n"
"uniform lowp sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Colour;\n"
"out vec4 FragColor;\n"
# else //!IMIMPL_SHADER_GL3
# if (defined(IMIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 100\n"
"#extension GL_OES_standard_derivatives : enable\n" // fwidth
"precision mediump float;\n"
# endif //IMIMPL_SHADER_GLES
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Colour;\n"
# endif //IMIMPL_SHADER_GL3
"uniform vec2 alphaAndShadow;\n"
# ifdef YES_IMGUISDF_MSDF_MODE // never tested
"float median(float r, float g, float b) {\n"
" return max(min(r, g), min(max(r, g), b));\n"
"}\n"
# endif //YES_IMGUISDF_MSDF_MODE
"void main(void) {\n"
# ifndef YES_IMGUISDF_MSDF_MODE
"float dist = texture2D(Texture, Frag_UV.st).a; // retrieve distance from texture\n"
# else //YES_IMGUISDF_MSDF_MODE // never tested
"vec3 dist3 = texture2D(Texture, Frag_UV.st).rgb; // retrieve distance from texture\n"
"float dist = median(dist3.r, dist3.g, dist3.b);// - 0.5;\n"
# endif //YES_IMGUISDF_MSDF_MODE
"float width = fwidth(dist);"
"\n"
"float alphaThreshold = 0.5;\n"
"\n"
"vec3 fragcolor = Frag_Colour.rgb;\n"
"float alpha = smoothstep(alphaThreshold - width, alphaThreshold + width, dist);\n"
"\n"
# ifdef IMIMPL_SHADER_GL3
"FragColor = vec4(fragcolor,alpha*Frag_Colour.a);\n"
# else //IMIMPL_SHADER_GL3
"gl_FragColor = vec4(fragcolor*alphaAndShadow.y,alpha*alphaAndShadow.x*Frag_Colour.a);\n"
# endif //IMIMPL_SHADER_GL3
"}\n"
};
return &gFragmentShaderSource[0];
}
static const char** GetFragmentShaderCodeForOutlineFont() {
static const char* gFragmentShaderSource[] = {
# ifdef IMIMPL_SHADER_GL3
# if (defined(IMIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 300 es\n"
# else //IMIMPL_SHADER_GLES
"#version 330\n"
# endif //IMIMPL_SHADER_GLES
"precision mediump float;\n"
"uniform lowp sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Colour;\n"
"out vec4 FragColor;\n"
# else //!IMIMPL_SHADER_GL3
# if (defined(IMIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 100\n"
"#extension GL_OES_standard_derivatives : enable\n" // fwidth
"precision mediump float;\n"
# endif //IMIMPL_SHADER_GLES
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Colour;\n"
# endif //IMIMPL_SHADER_GL3
"uniform vec2 alphaAndShadow;\n"
# ifdef YES_IMGUISDF_MSDF_MODE // never tested
"float median(float r, float g, float b) {\n"
" return max(min(r, g), min(max(r, g), b));\n"
"}\n"
# endif //YES_IMGUISDF_MSDF_MODE
"void main(void) {\n"
# ifndef YES_IMGUISDF_MSDF_MODE
"float dist = texture2D(Texture, Frag_UV.st).a; // retrieve distance from texture\n"
# else //YES_IMGUISDF_MSDF_MODE // never tested
"vec3 dist3 = texture2D(Texture, Frag_UV.st).rgb; // retrieve distance from texture\n"
"float dist = median(dist3.r, dist3.g, dist3.b);// - 0.5;\n"
# endif //YES_IMGUISDF_MSDF_MODE
"float width = fwidth(dist);"
"\n"
"float alphaThreshold = 0.4;\n"
"float outlineDarkeningFactor = 0.3;\n"
"float outlineThreshold = 0.5;" // 0.5f
"float inside = smoothstep(outlineThreshold - width, outlineThreshold + width, dist) ;\n"
"//float glow = 1.0-inside;//smoothstep (0.0 , 20.0 , dist ) ;\n"
"float glow = smoothstep (0.0 , 20.0 , dist ) ; // I don't understand this...\n"
"vec3 insidecolor = Frag_Colour.rgb;\n"
"vec3 outlinecolor = Frag_Colour.rgb*outlineDarkeningFactor;\n"
"vec3 fragcolor = mix ( glow * outlinecolor , insidecolor , inside ) ;\n"
"float alpha = smoothstep(alphaThreshold - width, alphaThreshold + width, dist);\n"
"\n"
# ifdef IMIMPL_SHADER_GL3
"FragColor = vec4(fragcolor*alphaAndShadow.y,alpha*alphaAndShadow.x*Frag_Colour.a);\n"
# else //IMIMPL_SHADER_GL3
"gl_FragColor = vec4(fragcolor*alphaAndShadow.y,alpha*alphaAndShadow.x*Frag_Colour.a);\n"
# endif //IMIMPL_SHADER_GL3
"}\n"
};
return &gFragmentShaderSource[0];
}
static GLuint CreateShader(GLenum type,const GLchar** shaderSource) {
GLuint shader( glCreateShader( type ) );
glShaderSource( shader, 1, shaderSource, NULL );
glCompileShader( shader );
// check
GLint bShaderCompiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &bShaderCompiled);
if (!bShaderCompiled) {
int i32InfoLogLength, i32CharsWritten;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &i32InfoLogLength);
ImVector<char> pszInfoLog; pszInfoLog.resize(i32InfoLogLength+2);pszInfoLog[0]='\0';
glGetShaderInfoLog(shader, i32InfoLogLength, &i32CharsWritten, &pszInfoLog[0]);
if (type == GL_VERTEX_SHADER) printf("********%s %s\n", "GL_VERTEX_SHADER", &pszInfoLog[0]);
else if (type == GL_FRAGMENT_SHADER) printf("********%s %s\n", "GL_FRAGMENT_SHADER", &pszInfoLog[0]);
else printf("******** %s\n", &pszInfoLog[0]);
fflush(stdout);
glDeleteShader(shader);shader=0;
}
return shader;
}
static GLuint CompileShaderProgramAndSetCorrectAttributeLocations(bool isOutlineShaderProgram) {
GLuint vs = CreateShader(GL_VERTEX_SHADER,GetVertexShaderCodeForBothFonts());
if (!vs) return 0;
GLuint fs = CreateShader(GL_FRAGMENT_SHADER,isOutlineShaderProgram ? GetFragmentShaderCodeForOutlineFont() : GetFragmentShaderCodeForRegularFont());
if (!fs) return 0;
GLuint program( glCreateProgram() );
glAttachShader( program, vs );
glAttachShader( program, fs );
// Bind attribute locations:
glBindAttribLocation(program,0,"Position");
glBindAttribLocation(program,1,"UV");
glBindAttribLocation(program,2,"Colour");
// Link
glLinkProgram( program );
// check
GLint bLinked;
glGetProgramiv(program, GL_LINK_STATUS, &bLinked);
if (!bLinked) {
int i32InfoLogLength, i32CharsWritten;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &i32InfoLogLength);
ImVector<char> pszInfoLog; pszInfoLog.resize(i32InfoLogLength+2);pszInfoLog[0]='\0';
glGetProgramInfoLog(program, i32InfoLogLength, &i32CharsWritten, &pszInfoLog[0]);
printf("********ShaderLinkerLog:\n%s\n", &pszInfoLog[0]);
fflush(stdout);
glDetachShader(program,vs);glDeleteShader(vs);vs=0;
glDetachShader(program,fs);glDeleteShader(fs);fs=0;
glDeleteProgram(program);program=0;
}
else {
glDeleteShader(vs);vs=0;
glDeleteShader(fs);fs=0;
}
return program;
}
};
SdfShaderProgram gSdfShaderPrograms[2]; // 0-Normal and 1-Outline font
#if (!defined(NO_IMGUISDF_LOAD) || (defined(IMGUIHELPER_H_) && !defined(NO_IMGUIHELPER_SERIALIZATION) && !defined(NO_IMGUIHELPER_SERIALIZATION_LOAD)))
#include <stdio.h> // FILE* used in SdfCharset::GetFileContent(...)
#endif // (!defined(NO_IMGUISDF_LOAD) ...)
struct SdfCharset {
float LineHeight;
float Base;
float Pages;
float FontSize;
float StretchH;
int GlyphsCount;
int KerningsCount;
ImTextureID fntTexture;
typedef SdfCharDescriptor CharDescriptor;
struct ImHashFunctionUnsignedInt {IMGUI_FORCE_INLINE ImHashInt operator()(unsigned int key) const {return (ImHashInt) (key%255);}};
typedef ImHashMap<unsigned int,CharDescriptor,ImHashFunctionUnsignedInt,ImHashMapKeyEqualityFunctionDefault<unsigned int>,
ImHashMapConstructorFunctionDummy<unsigned int>, ImHashMapDestructorFunctionDummy<unsigned int>, ImHashMapAssignmentFunctionDefault<unsigned int>,
ImHashMapConstructorFunctionDummy<CharDescriptor>, ImHashMapDestructorFunctionDummy<CharDescriptor>, ImHashMapAssignmentFunctionDefault<CharDescriptor>,
256> ImHashMapCharDescriptor; // map <char,int>. We can change the int to comsume less memory if needed
ImHashMapCharDescriptor Chars;
typedef ImHashMapImPairFast<unsigned int,unsigned int,float> ImHashMapKerning;
ImHashMapKerning Kernings;
SdfCharset() {clear();}
void clear() {
LineHeight=Base=0.f;Pages=GlyphsCount=KerningsCount=0;
Chars.clear();Kernings.clear();
FontSize = 0.f;
StretchH = 100.f;
}
IMGUI_API bool loadFromMemory(const void* data, size_t data_size,ImTextureID _fntTexture,const SdfCharsetProperties& properties) {
const bool isTextFontFile = (data_size>=5 && strncmp((const char*) data,"info ",5)==0);// text .fnt files start with "info " AFAIK
if (!isTextFontFile) {
fprintf(stderr,"SdfCharset::loadFromMemory(): Error: SDF Font is not a txt based AngelBitmap .fnt file.\n");
return false;
}
float ScaleW=0.f,ScaleH=0.f;
fntTexture = _fntTexture;
const char* pdata = (const char*) data;
// From now on we must use "pdata" and "data_size" only
// Here we must fill all the fields of "f" based on "pdata" and "data_size":
char tmp[1024];tmp[0]='\0';
int tmpi=0;size_t gsize=0,ksize=0;
CharDescriptor g;
const char* buf_end = pdata + data_size;
for (const char* line_start = pdata; line_start < buf_end; ) {
const char* line_end = line_start;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') line_end++;
if (strncmp(line_start,"char ",4)==0 && GlyphsCount>0) {
//char id=32 x=236 y=116 width=3 height=1 xoffset=-1 yoffset=15 xadvance=4 page=0 chnl=15
int a[7] = {0,0,0,0,0,0,0};
float b[3] = {0,0,0};
if (sscanf(&line_start[4], " id=%i x=%i y=%i width=%i height=%i xoffset=%f yoffset=%f xadvance=%f page=%i chnl=%i",
&a[0],&a[1],&a[2],&a[3],&a[4],&b[0],&b[1],&b[2],&a[5],&a[6]))
{
IM_ASSERT(ScaleW!=0 && ScaleH!=0);
g.Id = (unsigned int) a[0];
g.X = (float) a[1]/ScaleW;
g.Y = (float) a[2]/ScaleH;
g.Width = (float) a[3]/ScaleW;
g.Height = (float) a[4]/ScaleH;
IM_ASSERT(FontSize!=0);
g.XOffset = b[0]/FontSize;//(signed short) ROUNDCAST(b[0]);
g.YOffset = b[1]/FontSize;//(signed short) ROUNDCAST(b[1]);
g.XOffset2 = (b[0]+(float)a[3])/FontSize;//(signed short) ROUNDCAST(b[0]);
g.YOffset2 = (b[1]+(float)a[4])/FontSize;//(signed short) ROUNDCAST(b[1]);
if (properties.flipYOffset) g.YOffset = -g.YOffset;
g.XAdvance = b[2]/FontSize;//(signed short) ROUNDCAST(b[2]);
g.Page = (unsigned char) a[5];
Chars.put((unsigned int) a[0],g);
gsize++;
}
else fprintf(stderr,"Warning in SdfCharset::LoadTextFntFileFromMemory(\"glyph \"): skipped line [%.50s] (parsing error).\n",line_start);
}
else if (strncmp(line_start,"kerning ",7)==0 && KerningsCount>0) {
int a[3] = {0,0,0};
if (sscanf(&line_start[7]," first=%i second=%i amount=%i",&a[0],&a[1],&a[2]))
{
IM_ASSERT(FontSize!=0);
Kernings.put(ImPair<unsigned int,unsigned int>(a[0],a[1]),(float)a[2]/FontSize);
ksize++;
}
else fprintf(stderr,"Warning in SdfCharset::LoadTextFntFileFromMemory(\"glyph \"): skipped line [%.50s] (parsing error).\n",line_start);
}
else if (strncmp(line_start,"info ",5)==0) {
tmp[0]='\0';
char tmp2[1024];tmp2[0]='\0';
int a[14] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0};
const char* pline = NULL;
//We must skip the font name first (we store it inside tmp)
static const int quote = (int) '"';
const char* q1=NULL;const char* q2=NULL;
q1 = strchr((const char*) &line_start[5], quote ); // This method is better than sscanf, because the string can contain spaces
if (q1) {
const char* q11 = ++q1;
q2 = strchr(q11, quote);
if (q2) {
const size_t sz = q2-q11;
strncpy(tmp,q11,sz);
tmp[sz]='\0';
pline = ++q2;
}
}
if (pline && (sscanf(pline, " size=%i bold=%i italic=%i charset=%s unicode=%i stretchH=%i smooth=%i aa=%i padding=%i,%i,%i,%i spacing=%i,%i outline=%i",
&a[0],&a[1],&a[2],tmp2,&a[3],&a[4],&a[5],&a[6],&a[7],&a[8],&a[9],&a[10],&a[11],&a[12],&a[13])))
{
// This is necessary because often tmp2="", with quotes included:
size_t tmp2Size;
while ((tmp2Size=strlen(tmp2))>0 && tmp2[tmp2Size-1]=='"') tmp2[tmp2Size-1]='\0';
while ((tmp2Size=strlen(tmp2))>0 && tmp2[0]=='"') {static char tmp22[1024];strcpy(tmp22,&tmp2[1]);strcpy(tmp2,tmp22);}
FontSize = (float) a[0];
StretchH = (float) a[4];
//fprintf(stderr,"FontSize=%1.0f StretchH=%1.0f charset=\"%s\"\n",FontSize,StretchH,tmp2);
}
else fprintf(stderr,"Warning in SdfCharset::LoadTextFntFileFromMemory(\"info \"): skipped line [%.50s] (parsing error).\n",line_start);
}
else if (strncmp(line_start,"common ",7)==0) {
int a[10] = {0,0,0,0,0,0,0,0,0,0};
// common lineHeight=16 base=13 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0
if (sscanf(&line_start[7], " lineHeight=%i base=%i scaleW=%i scaleH=%i pages=%i packed=%i alphaChnl=%i redChnl=%i greenChnl=%i blueChnl=%i",
&a[0],&a[1],&a[2],&a[3],&a[4],&a[5],&a[6],&a[7],&a[8],&a[9]))
{
IM_ASSERT(FontSize!=0);
LineHeight = (float) a[0]/FontSize;
Base = (float) a[1]/FontSize;
ScaleW = (float) a[2];
ScaleH = (float) a[3];
Pages = (unsigned short) a[4];
}
else fprintf(stderr,"Warning in SdfCharset::LoadTextFntFileFromMemory(\"common \"): skipped line [%.50s] (parsing error).\n",line_start);
}
else if (strncmp(line_start,"page id=0 ",10)==0) {
#ifdef NEVER
// well, we just support one page, but maybe this is what "filenames" refer to
// we just fill the first filename we found in the line for now (I must see a file with more than one page to parse it correctly...):
if (f.filenames.size()==0) {
tmp[0]='\0';
static const int quote = (int) '"';
const char* q1=NULL;const char* q2=NULL;
q1 = strchr((const char*) &line_start[10], quote );
if (q1) {
const char* q11 = ++q1;
q2 = strchr(q11, quote);
if (q2) {
const size_t sz = q2-q11;
strncpy(tmp,q11,sz);
tmp[sz]='\0';
}
}
if (strlen(tmp)>0) {
size_t tmpSize;
while ( (tmpSize=strlen(tmp))>0 && tmp[tmpSize-1]=='\"') tmp[tmpSize-1]='\0';
gsize = f.filenames.size();
f.filenames.resize(gsize+1);
char* c = &f.filenames[gsize][0];
c[0]='\0';
if (strlen(tmp)<=MAX_FILENAME_SIZE) {
strcpy(c,tmp);
# ifdef DEBUG_PARSED_DATA
fprintf(stderr,"Filename = %s\n",c);
# endif //DEBUG_PARSED_DATA
}
}
else fprintf(stderr,"Warning in SdfCharset::LoadTextFntFileFromMemory(\"page \"): skipped line [%.50s] (parsing error).\n",line_start);
}
#endif //NEVER
}
else if (strncmp(line_start,"chars count=",12)==0) {
if (sscanf(line_start, "chars count=%i", &tmpi)) {
GlyphsCount = tmpi;
//f.glyphs.reserve(GlyphsCount);
}
else fprintf(stderr,"Warning in SdfCharset::LoadTextFntFileFromMemory(): skipped line [%.50s] (parsing error).\n",line_start);
}
else if (strncmp(line_start,"kernings count=",15)==0) {
if (sscanf(line_start, "kernings count=%i", &tmpi)) {
KerningsCount = tmpi;
}
else fprintf(stderr,"Warning in SdfCharset::LoadTextFntFileFromMemory(): skipped line [%.50s] (parsing error).\n",line_start);
}
line_start = line_end+1;
}
// Add extra codepoints:
CharDescriptor sp;
if (Chars.get((unsigned int)' ',sp)) {
CharDescriptor tab;
if (!Chars.get((unsigned int)'\t',tab)) {
tab = sp;tab.Id='\t';tab.XAdvance=sp.XAdvance*4.f;
Chars.put((unsigned int)'\t',tab);
}
sp.Width=0.f;Chars.put((unsigned int)' ',sp);
}
CharDescriptor lf;
if (!Chars.get((unsigned int)'\n',lf)) {
lf = sp;lf.Id='\n';lf.XAdvance=lf.Width=lf.XOffset=0.f;
}
if (!Chars.get((unsigned int)'\r',lf)) {
lf = sp;lf.Id='\r';lf.XAdvance=lf.Width=lf.XOffset=0.f;
}
return true;
}
# if (!defined(NO_IMGUISDF_LOAD) || (defined(IMGUIHELPER_H_) && !defined(NO_IMGUIHELPER_SERIALIZATION) && !defined(NO_IMGUIHELPER_SERIALIZATION_LOAD)))
// Cloned from imguihelper.h/cpp remove its dependency:
static bool GetFileContent(const char *filePath,ImVector<char> &contentOut,bool clearContentOutBeforeUsage,const char *modes="rb",bool appendTrailingZeroIfModesIsNotBinary=true) {
ImVector<char>& f_data = contentOut;
if (clearContentOutBeforeUsage) f_data.clear();
//----------------------------------------------------
if (!filePath) return false;
const bool appendTrailingZero = appendTrailingZeroIfModesIsNotBinary && modes && strlen(modes)>0 && modes[strlen(modes)-1]!='b';
FILE* f;
if ((f = ImFileOpen(filePath, modes)) == NULL) return false;
if (fseek(f, 0, SEEK_END)) {
fclose(f);
return false;
}
const long f_size_signed = ftell(f);
if (f_size_signed == -1) {
fclose(f);
return false;
}
size_t f_size = (size_t)f_size_signed;
if (fseek(f, 0, SEEK_SET)) {
fclose(f);
return false;
}
f_data.resize(f_size+(appendTrailingZero?1:0));
const size_t f_size_read = f_size>0 ? fread(&f_data[0], 1, f_size, f) : 0;
fclose(f);
if (f_size_read == 0 || f_size_read!=f_size) return false;
if (appendTrailingZero) f_data[f_size] = '\0';
//----------------------------------------------------
return true;
}
# endif //(!defined(NO_IMGUISDF_LOAD) ...)
};
void SdfTextChunk::addText(const char* startText, bool _italic, const SdfTextColor* pSdfTextColor, const ImVec2* textScaling, const char* endText,const SDFHAlignment *phalignOverride, bool fakeBold) {
IM_ASSERT(startText);
IM_ASSERT(charset);
const int textBitsSize = textBits.size();
textBits.push_back(TextBit());
TextBit& TB = textBits[textBitsSize];
TB.scaling = textScaling ? *textScaling : ImVec2(1,1);if (fakeBold) {TB.scaling.x*=1.2f;/*TB.scaling.y*=1.1f;*/}
TB.italic = _italic;
TB.sdfTextColor = pSdfTextColor ? *pSdfTextColor : gSdfTextDefaultColor;// change if fakeBold ?
TB.hAlignment = phalignOverride ? (int)(*phalignOverride) : -1;
SdfCharDescriptor cd; int lastCdId=0;
const bool useKernings = charset->KerningsCount>0;float kerning = 0;
uint32_t codePoint = 0, state = 0;
if (!endText) endText = startText+strlen(startText);
TB.charDescriptors.reserve(endText-startText);
if (useKernings) TB.kernings.reserve(endText-startText);
const unsigned char* endTextUC = (const unsigned char*) endText;
for(const unsigned char* p = (const unsigned char*) startText; p!=endTextUC; ++p)
{
if (UTF8Helper::decode(&state, &codePoint, *p)!=UTF8Helper::UTF8_ACCEPT) continue;
// Here we could count valid chars if we need it...
++numValidGlyphs;
if (!charset->Chars.get(codePoint,cd) && !charset->Chars.get('?',cd)) continue;
TB.charDescriptors.push_back(cd);
if (useKernings) {
if (lastCdId!=0 && charset->Kernings.get(ImPair<unsigned int,unsigned int>(lastCdId,cd.Id),kerning)) {
TB.kernings.push_back(kerning);
//fprintf(stderr,"%d) Kerning: %c->%c = %1.4f\n",TB.kernings.size()-1,(char)lastCdId,(char)cd.Id,kerning);
}
else TB.kernings.push_back(.0f);
}
lastCdId = cd.Id;
}
dirty = true;
}
bool SdfTextChunk::endText(ImVec2 screenSize) {
if (!dirty) return false;
dirty = false;
IM_ASSERT(buffer);
buffer->clear();
if (textBits.size()==0) return true;
if (screenSize.x<=0 || screenSize.y<=0) screenSize = ImGui::GetIO().DisplaySize;
const ImVec2 cursorXlimits((props.boundsCenter.x-props.boundsHalfSize.x)*screenSize.x,(props.boundsCenter.x+props.boundsHalfSize.x)*screenSize.x);
const ImVec2 cursorYlimits((props.boundsCenter.y-props.boundsHalfSize.y)*screenSize.y,(props.boundsCenter.y+props.boundsHalfSize.y)*screenSize.y);
//const float cursorXextent = cursorXlimits.y - cursorXlimits.x;
//const float cursorYextent = cursorYlimits.y - cursorYlimits.x;
//fprintf(stderr,"cursorXlimits(%1.0f,%1.0f) cursorYlimits(%1.0f,%1.0f) displaySize(%1.0f,%1.0f)\n",cursorXlimits.x,cursorXlimits.y,cursorYlimits.x,cursorYlimits.y,ImGui::GetIO().DisplaySize.x,ImGui::GetIO().DisplaySize.y);
IM_ASSERT(props.maxNumTextLines>0);
const float virtualLineHeight = props.lineHeightOverride>0.f?props.lineHeightOverride:charset->LineHeight;
const float numPixelsPerTextLine = screenSize.y/*cursorYextent*//(float)props.maxNumTextLines;
const float globalScale = numPixelsPerTextLine/virtualLineHeight; // globalScale translates quantities into pixels (it's the FontSize (or the FontHeight) in pixels)
const float BaseBase = globalScale*charset->Base;
const float LineHeightBase = globalScale*virtualLineHeight; // It's the Line Height in pixels
ImVec2 cursor = ImVec2(cursorXlimits.x,cursorYlimits.x);
ImVector<SdfVertexBuffer::VertexDeclaration>& vertexBuffer = buffer->verts;
int curVertexBufferSize = vertexBuffer.size();
const int startVertexBufferSize = curVertexBufferSize;
vertexBuffer.reserve(curVertexBufferSize+numValidGlyphs*6);
const bool useKernings = charset->KerningsCount>0;bool skipKerning = false;
SdfVertexBuffer::VertexDeclaration *pVert = NULL;
float XAdvance=0.f,XOffset0=0.f,YOffset0=0.f,XOffset1=0.f,YOffset1=0.f;
ImVec2 totalSizeInPixels(0.f,0.f);
bool mustEndOneLine = false;
ImVec2 localScaleXminmax(0.f,0.f),localScaleYminmax(0.f,0.f);
const SdfCharDescriptor* lastCd = NULL;
typedef struct _LineData{
ImVec2 sizeInPixels;
float Base;
float LineHeight;
int numGlyphs;
_LineData(float BaseBase,float LineHeightBase) : sizeInPixels(0.f,0.f),Base(BaseBase),LineHeight(LineHeightBase),numGlyphs(0) {lastTbScalingY=maxTbScalingY=1.f;pVertStartLine=pVertLastLineSplitter=NULL;cursorXAtLastLineSplitter=0.f;lastLineSplitterIsSpace=false;}
mutable float lastTbScalingY;
mutable float maxTbScalingY;
mutable SdfVertexBuffer::VertexDeclaration *pVertStartLine;
mutable SdfVertexBuffer::VertexDeclaration *pVertLastLineSplitter;
mutable float cursorXAtLastLineSplitter;
mutable bool lastLineSplitterIsSpace;
} LineData;
LineData lineData(BaseBase,LineHeightBase);
SDFHAlignment lastTBalignment = props.halign,halign = props.halign;bool mustStartNewAlignment = false;
for (int i=0,isz=textBits.size();i<isz;i++) {
const TextBit& TB = textBits[i];
halign = (TB.hAlignment==-1) ? props.halign : (SDFHAlignment)TB.hAlignment;
mustStartNewAlignment = (lastTBalignment!=halign);
if (mustStartNewAlignment) {
//------------------------------------------
if (totalSizeInPixels.x<lineData.sizeInPixels.x) totalSizeInPixels.x = lineData.sizeInPixels.x;
//totalSizeInPixels.y+= lineData.LineHeight;
// h alignment on lineData
// Horizontal alignment here---------------------------------
if (lineData.pVertStartLine && pVert) {
if (lastTBalignment==SDF_JUSTIFY) {
// horizontal alignment here---------------------------------
if (lineData.numGlyphs>1 && (/*!lastCd || lastCd->Id!='\n' ||*/ lineData.sizeInPixels.x>0.65f*(cursorXlimits.y - cursorXlimits.x))) {
const float deltaX = (cursorXlimits.y - cursorXlimits.x - lineData.sizeInPixels.x)/(float)(lineData.numGlyphs-1);
int cnt = 0;float addend = deltaX;
for (SdfVertexBuffer::VertexDeclaration* vd = (lineData.pVertStartLine+6);vd!=pVert;++vd) {
vd->posAndUV.x+=addend;
if (++cnt==6) {cnt=0;addend+=deltaX;}
}
}
}
else {
float offsetX=0.f;
if (lastTBalignment!=SDF_LEFT) {
offsetX = cursorXlimits.y - cursorXlimits.x - lineData.sizeInPixels.x;
if (lastTBalignment==SDF_CENTER) offsetX*=0.5f;
}
if (offsetX!=0.f) {
for (SdfVertexBuffer::VertexDeclaration* vd = lineData.pVertStartLine;vd!=pVert;++vd) {
vd->posAndUV.x+=offsetX;
}
}
}
}
//------------------------------------------------------------
//lineData = LineData(BaseBase,LineHeightBase);
lineData.pVertStartLine=lineData.pVertLastLineSplitter=NULL;
lineData.numGlyphs = 0;
lineData.sizeInPixels=ImVec2(0,0);
cursor.x = cursorXlimits.x;
//------------------------------------------------------------
lastTBalignment=halign;
}
const ImVec2 localScale = TB.scaling * globalScale //;
* ImVec2(TB.italic ? 0.925f : 1.f,1.f); // This line makes italic a bit slimmer than normal text
if (i==0) {
localScaleXminmax.x=localScaleXminmax.y=localScale.x;
localScaleYminmax.x=localScaleYminmax.y=localScale.y;
}
else {
if (localScaleXminmax.x>localScale.x) localScaleXminmax.x = localScale.x;
else if (localScaleXminmax.y<localScale.x) localScaleXminmax.y = localScale.x;
if (localScaleYminmax.x>localScale.y) localScaleYminmax.x = localScale.y;
else if (localScaleYminmax.y<localScale.y) localScaleYminmax.y = localScale.y;
}
//if (shadowOffsetInPixels.x<localScale.x) shadowOffsetInPixels.x = localScale.x;
//if (shadowOffsetInPixels.y<localScale.y) shadowOffsetInPixels.y = localScale.y;
if (lineData.lastTbScalingY!=TB.scaling.y) {
lineData.lastTbScalingY=TB.scaling.y;
if (lineData.maxTbScalingY<TB.scaling.y) {
if (TB.scaling.y > virtualLineHeight) {
//const float oldBaseBase = lineData.Base;
//const float oldLineHeight = lineData.LineHeight;
lineData.Base = BaseBase*TB.scaling.y;
lineData.LineHeight = LineHeightBase*TB.scaling.y;
// scale all glyphs from lineData.pVertStartLine to pVert
if (lineData.pVertStartLine && pVert) {
const float deltaY = (TB.scaling.y - lineData.maxTbScalingY) * globalScale;
for (SdfVertexBuffer::VertexDeclaration* vd = lineData.pVertStartLine;vd!=pVert;++vd) {
vd->posAndUV.y+=deltaY;
}
}
}
lineData.maxTbScalingY=TB.scaling.y;
}
}
const float& Base = lineData.Base;
const float& LineHeight = lineData.LineHeight;
const float italicAddend = TB.italic ? localScale.y * 0.125f : 0.f;
if (useKernings) {IM_ASSERT(TB.kernings.size()==TB.charDescriptors.size());}
for (int cdIndex=0,cdIndexSize = TB.charDescriptors.size();cdIndex<cdIndexSize;cdIndex++) {
const SdfCharDescriptor& cd = TB.charDescriptors[cdIndex];
const float kerning = (useKernings && !skipKerning) ? TB.kernings[cdIndex] : 0.f;
skipKerning = false;
//--------------------------------------------------------------------------------------------------------
XOffset0=cd.XOffset*localScale.x;
YOffset0=cd.YOffset*localScale.y;
XOffset1=cd.XOffset2*localScale.x;
YOffset1=cd.YOffset2*localScale.y;
if (useKernings) cursor.x += kerning*localScale.x;
XAdvance=cd.XAdvance*localScale.x;
//--------------------------------------------------------------------------------------------------------
mustEndOneLine = false;
bool mustSplitLine = false;
if (cd.Id=='\n') mustEndOneLine = true;
else if (cd.Id=='\r') {
lastCd = &cd;
continue;
}
if (cursor.x+XAdvance>cursorXlimits.y) {
// Word wrap: but we could just skip using "continue" here
mustSplitLine = lineData.pVertLastLineSplitter!=NULL;
mustEndOneLine = true;
}
if (mustEndOneLine) {
const float oldCursorX = cursor.x;
cursor.x=cursorXlimits.x;
cursor.y+=LineHeight;
skipKerning = true;
SdfVertexBuffer::VertexDeclaration* pLastVertOfLine = pVert;
LineData nextLineData(BaseBase,LineHeightBase); // reset it
if (TB.scaling.y>virtualLineHeight) {
nextLineData.Base = BaseBase*TB.scaling.y;
nextLineData.LineHeight = LineHeightBase*TB.scaling.y;
nextLineData.lastTbScalingY = nextLineData.maxTbScalingY = TB.scaling.y;
/*// scale all glyphs from lineData.pVertStartLine to pVert
if (lineData.pVertStartLine && pVert) {
const float deltaY = (TB.scaling.y - lineData.maxTbScalingY) * globalScale;
for (SdfVertexBuffer::VertexDeclaration* vd = lineData.pVertStartLine;vd!=pVert;++vd) {
vd->posAndUV.y+=deltaY;
}
}*/
}
if (mustSplitLine) {
nextLineData.numGlyphs = 0;
// lineData
for (SdfVertexBuffer::VertexDeclaration* vd = lineData.pVertLastLineSplitter;vd!=pVert;vd=vd+6) {
--lineData.numGlyphs;++nextLineData.numGlyphs;
}
pLastVertOfLine = lineData.pVertLastLineSplitter;
cursor.x = cursorXlimits.x + oldCursorX - lineData.cursorXAtLastLineSplitter;
lineData.sizeInPixels.x = lineData.cursorXAtLastLineSplitter - cursorXlimits.x;
// nextLineData
float deltaX = lineData.cursorXAtLastLineSplitter-cursorXlimits.x;
const float deltaY = LineHeight;
float deltaSizeX = 0.f;
ImVec2 yMinMax(lineData.pVertLastLineSplitter->posAndUV.y,lineData.pVertLastLineSplitter->posAndUV.y);
// How can I crop leading spaces here ?
nextLineData.pVertStartLine = pLastVertOfLine;
unsigned int cnt = 0;bool enableCutSpaces = true;
for (SdfVertexBuffer::VertexDeclaration* vd = lineData.pVertLastLineSplitter;vd!=pVert;++vd) {
if (enableCutSpaces && cnt==0 /*&& pVert!=vd+6*/) {
SdfVertexBuffer::VertexDeclaration* vd2 = vd+1;
SdfVertexBuffer::VertexDeclaration* vd6 = vd+6;
//fprintf(stderr,"%1.6f -> %1.6f\n",vd2->posAndUV.z-vd->posAndUV.z,vd6->posAndUV.x-vd->posAndUV.x);
if (vd2->posAndUV.z==vd->posAndUV.z) {
if (pVert!=vd+6) {
nextLineData.pVertStartLine+=6;--nextLineData.numGlyphs;
float cursorXdelta = (vd6->posAndUV.x-vd->posAndUV.x);
deltaSizeX+=cursorXdelta;
deltaX+=cursorXdelta;
cursor.x-=cursorXdelta;
}
else {
nextLineData.pVertStartLine=NULL;nextLineData.numGlyphs=0;
cursor.x=cursorXlimits.x;
//fprintf(stderr,"Border case to handle\n");
//vertexBuffer.resize(vertexBuffer.size()-6);
//curVertexBufferSize = vertexBuffer.size();
break;
}
// [Optional] Remove vertex from vertexarray:
/*for (SdfVertexBuffer::VertexDeclaration* p = vd;p!=pVert-6;++p) *p = *(p+6);
pVert = pVert-6;
vertexBuffer.resize(vertexBuffer.size()-6);
curVertexBufferSize = vertexBuffer.size();
vd=vd-1;cnt=0;continue;*/
}
else enableCutSpaces = false;
}
vd->posAndUV.x-=deltaX;
vd->posAndUV.y+=deltaY;
if (yMinMax.x>vd->posAndUV.y) yMinMax.x=vd->posAndUV.y;
else if (yMinMax.y<vd->posAndUV.y) yMinMax.y=vd->posAndUV.y;
if (++cnt==6) cnt=0;
}
/*
// This does not work and furthermore gives a Valgrind error
const float maxY = (yMinMax.y-yMinMax.x)/globalScale;
if (maxY > virtualLineHeight) {
nextLineData.maxTbScalingY = maxY;
nextLineData.lastTbScalingY = nextLineData.maxTbScalingY;
//nextLineData.Base = BaseBase*maxY;
//nextLineData.LineHeight = LineHeightBase*maxY;
}*/
nextLineData.sizeInPixels.x = cursor.x -cursorXlimits.x;
}
if (totalSizeInPixels.x<lineData.sizeInPixels.x) totalSizeInPixels.x = lineData.sizeInPixels.x;
totalSizeInPixels.y+= lineData.LineHeight;
// Horizontal alignment here---------------------------------
if (lineData.pVertStartLine && pLastVertOfLine) {
if (halign==SDF_JUSTIFY) {
// horizontal alignment here---------------------------------
if (lineData.numGlyphs>1 && (cd.Id!='\n' || lineData.sizeInPixels.x>0.65f*(cursorXlimits.y - cursorXlimits.x))) {
const float deltaX = (cursorXlimits.y - cursorXlimits.x - lineData.sizeInPixels.x)/(float)(lineData.numGlyphs-1);
int cnt = 0;float addend = deltaX;
for (SdfVertexBuffer::VertexDeclaration* vd = (lineData.pVertStartLine+6);vd!=pLastVertOfLine;++vd) {
vd->posAndUV.x+=addend;
if (++cnt==6) {cnt=0;addend+=deltaX;}
}
}
}
else {
float offsetX=0.f;
if (halign!=SDF_LEFT) {
offsetX = cursorXlimits.y - cursorXlimits.x - lineData.sizeInPixels.x;
if (halign==SDF_CENTER) offsetX*=0.5f;
}
if (offsetX!=0.f) {
for (SdfVertexBuffer::VertexDeclaration* vd = lineData.pVertStartLine;vd!=pLastVertOfLine;++vd) {
vd->posAndUV.x+=offsetX;
}
}
}
}
//------------------------------------------------------------
lineData = nextLineData;
if (cursor.y>=cursorYlimits.y) {
lastCd = &cd;
break;
}
if (cd.Id=='\n') {
lastCd = &cd;
continue; //consume one char
}
}
if (cursor.y+YOffset0<cursorYlimits.x) {
cursor.x += XAdvance;
lastCd = &cd;
continue;
}
// Eat starting space if necessary
if ((!lineData.pVertStartLine || cursor.x==cursorXlimits.x) && cd.Id==' ') {
lineData.pVertStartLine = NULL;
//if (lineData.pVertStartLine) lineData.pVertStartLine = lineData.pVertStartLine+6;
//lastCd = &cd;
continue;
}
if (pVert && ((cd.Id==' ' && (!lineData.lastLineSplitterIsSpace || !lastCd || lastCd->Id!=' ')) || cd.Id=='\t')) {
if (lineData.pVertLastLineSplitter!=pVert-1) {
lineData.pVertLastLineSplitter = pVert;
lineData.cursorXAtLastLineSplitter = cursor.x;
lineData.lastLineSplitterIsSpace = cd.Id==' ';
}
}
++lineData.numGlyphs;
/*
-------------------------------------------- ^
^ ^ |
| yoffset | |
| v |
| ----------------- |
| | ^
base | | lineHeight
| | |
| | | height |
| xoffset | | |
v<----------->| - - - - - - | |
| v |
<---------------> |
width |
--------------------------------------------- v
<----------------------------------> xadvance
*/
//if (cd.YOffset<0) cd.YOffset = 0;//-cd.YOffset; // This seems to improve alignment slightly in one of my fonts...
// TODO: Allow scaling from extern and update spacing and LineHeight
curVertexBufferSize = vertexBuffer.size();
vertexBuffer.resize(curVertexBufferSize+6); // We use GL_TRIANGLES, as GL_QUADS is not supported on some OpenGL implementations
pVert = &vertexBuffer[curVertexBufferSize];
if (!lineData.pVertStartLine) lineData.pVertStartLine = pVert;
//upper left
pVert->posAndUV.z = cd.X;
pVert->posAndUV.w = cd.Y;
pVert->posAndUV.x = cursor.x + XOffset0 + italicAddend;
pVert->posAndUV.y = cursor.y + YOffset0;
pVert->color = TB.sdfTextColor.colorTopLeft;
//fprintf(stderr,"%1.2f,%1.2f,%1.2f,%1.2f\n",pVert->posAndUV.x,pVert->posAndUV.y,pVert->posAndUV.z,pVert->posAndUV.w);
++pVert;
//upper right
pVert->posAndUV.z = cd.X+cd.Width;
pVert->posAndUV.w = cd.Y;
pVert->posAndUV.x = cursor.x + XOffset1 + italicAddend;
pVert->posAndUV.y = cursor.y + YOffset0;
pVert->color = TB.sdfTextColor.colorTopRight;
//fprintf(stderr,"%1.2f,%1.2f,%1.2f,%1.2f\n",pVert->posAndUV.x,pVert->posAndUV.y,pVert->posAndUV.z,pVert->posAndUV.w);
++pVert;
//lower right
pVert->posAndUV.z = cd.X+cd.Width;
pVert->posAndUV.w = cd.Y+cd.Height;
pVert->posAndUV.x = cursor.x + XOffset1;
pVert->posAndUV.y = cursor.y + YOffset1;
pVert->color = TB.sdfTextColor.colorBottomRight;
//fprintf(stderr,"%1.2f,%1.2f,%1.2f,%1.2f\n",pVert->posAndUV.x,pVert->posAndUV.y,pVert->posAndUV.z,pVert->posAndUV.w);
++pVert;
*pVert = *(pVert-1);++pVert;
//lower left
pVert->posAndUV.z = cd.X ;
pVert->posAndUV.w = cd.Y+cd.Height;
pVert->posAndUV.x = cursor.x + XOffset0;
pVert->posAndUV.y = cursor.y + YOffset1;
pVert->color = TB.sdfTextColor.colorBottomLeft;
//fprintf(stderr,"%1.2f,%1.2f,%1.2f,%1.2f\n",pVert->posAndUV.x,pVert->posAndUV.y,pVert->posAndUV.z,pVert->posAndUV.w);
++pVert;
*pVert = *(pVert-5);++pVert;
if (lineData.sizeInPixels.x < cursor.x + XOffset1 - cursorXlimits.x) lineData.sizeInPixels.x = cursor.x + XOffset1 - cursorXlimits.x;
if (lineData.sizeInPixels.y < cursor.y + YOffset1 - cursorXlimits.y) lineData.sizeInPixels.y = cursor.y + YOffset1 - cursorXlimits.y;
cursor.x += XAdvance;
if (cd.Id==',' || cd.Id=='.' || cd.Id==';' || cd.Id==':' ||
cd.Id=='?' || cd.Id=='!' || cd.Id=='-') {
if (lineData.pVertLastLineSplitter!=pVert-1) {
lineData.pVertLastLineSplitter = pVert;
lineData.cursorXAtLastLineSplitter = cursor.x;
lineData.lastLineSplitterIsSpace = false;
}
}
lastCd = &cd;
}
//--------------------------------------------------------------------------------------------------------
}
if (!mustEndOneLine) {
if (totalSizeInPixels.x<lineData.sizeInPixels.x) totalSizeInPixels.x = lineData.sizeInPixels.x;
totalSizeInPixels.y+= lineData.LineHeight;
// h alignment on lineData
// Horizontal alignment here---------------------------------
if (lineData.pVertStartLine && pVert) {
if (halign==SDF_JUSTIFY) {
// horizontal alignment here---------------------------------
if (lineData.numGlyphs>1 && (/*!lastCd || lastCd->Id!='\n' ||*/ lineData.sizeInPixels.x>0.65f*(cursorXlimits.y - cursorXlimits.x))) {
const float deltaX = (cursorXlimits.y - cursorXlimits.x - lineData.sizeInPixels.x)/(float)(lineData.numGlyphs-1);
int cnt = 0;float addend = deltaX;
for (SdfVertexBuffer::VertexDeclaration* vd = (lineData.pVertStartLine+6);vd!=pVert;++vd) {
vd->posAndUV.x+=addend;
if (++cnt==6) {cnt=0;addend+=deltaX;}
}
}
}
else {
float offsetX=0.f;
if (halign!=SDF_LEFT) {
offsetX = cursorXlimits.y - cursorXlimits.x - lineData.sizeInPixels.x;
if (halign==SDF_CENTER) offsetX*=0.5f;
}
if (offsetX!=0.f) {
for (SdfVertexBuffer::VertexDeclaration* vd = lineData.pVertStartLine;vd!=pVert;++vd) {
vd->posAndUV.x+=offsetX;
}
}
}
}
//------------------------------------------------------------
}
float offsetY=0.f;
if (props.valign!=SDF_TOP) {
offsetY = cursorYlimits.y - cursorYlimits.x - totalSizeInPixels.y;
if (props.valign==SDF_MIDDLE) offsetY*=0.5f;
}
if (offsetY!=0.f) {
for (int i = startVertexBufferSize,isz=vertexBuffer.size();i<isz;i++) {
SdfVertexBuffer::VertexDeclaration& V = vertexBuffer[i];
V.posAndUV.y+=offsetY;
}
}
/*const float soc = 0.0575f;
shadowOffsetInPixels.x*=soc;
shadowOffsetInPixels.y*=soc;*/
const float soc = 0.0625f;
shadowOffsetInPixels.x=soc*(0.75f*localScaleXminmax.x + 0.25f*localScaleXminmax.y);
shadowOffsetInPixels.y=soc*(0.75f*localScaleYminmax.x + 0.25f*localScaleYminmax.y);
//fprintf(stderr,"localScaleXminmax:(%1.3f,%1.3f) localScaleYminmax:(%1.3f,%1.3f)\n",localScaleXminmax.x,localScaleXminmax.y,localScaleYminmax.x,localScaleYminmax.y);
return true;
//buffer->updateBoundVbo();
}
struct SdfStaticStructs {
ImVector<SdfTextChunk*> gSdfTextChunks;
ImVectorEx<SdfCharset*> gSdfCharsets;
ImVectorEx<SdfAnimation*> gSdfAnimations;
SdfStaticStructs() {}
~SdfStaticStructs() {
DestroyAllAnimations();
DestroyAllTextChunks();
DestroyAllCharsets();
}
void DestroyAllAnimations();
void DestroyAllTextChunks();
void DestroyAllCharsets();
};
static SdfStaticStructs gSdfInit;
void SdfStaticStructs::DestroyAllAnimations() {
for (int i=0,isz=gSdfInit.gSdfAnimations.size();i<isz;i++) {
gSdfInit.gSdfAnimations[i]->~SdfAnimation();
ImGui::MemFree(gSdfInit.gSdfAnimations[i]);
gSdfInit.gSdfAnimations[i] = NULL;
}
gSdfInit.gSdfAnimations.clear();
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
SdfTextChunk* chunk = gSdfInit.gSdfTextChunks[i];
if (chunk->manualAnimationRef) {
if (chunk->animationMode==SDF_AM_MANUAL) {chunk->mute=true;chunk->animationStartTime=-1.f;}
chunk->manualAnimationRef=NULL;
}
}
}
void SdfStaticStructs::DestroyAllTextChunks() {
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
gSdfInit.gSdfTextChunks[i]->~SdfTextChunk();
ImGui::MemFree(gSdfInit.gSdfTextChunks[i]);
gSdfInit.gSdfTextChunks[i] = NULL;
}
gSdfInit.gSdfTextChunks.clear();
}
void SdfStaticStructs::DestroyAllCharsets() {
for (int i=0,isz=gSdfInit.gSdfCharsets.size();i<isz;i++) {
gSdfInit.gSdfCharsets[i]->~SdfCharset();
ImGui::MemFree(gSdfInit.gSdfCharsets[i]);
gSdfInit.gSdfCharsets[i] = NULL;
}
gSdfInit.gSdfCharsets.clear();
}
#if (!defined(NO_IMGUISDF_LOAD) || (defined(IMGUIHELPER_H_) && !defined(NO_IMGUIHELPER_SERIALIZATION) && !defined(NO_IMGUIHELPER_SERIALIZATION_LOAD)))
SdfCharset* SdfAddCharsetFromFile(const char* fntFilePath,ImTextureID fntTexture,const SdfCharsetProperties& properties) {
ImVector<char> contentOut;
if (!SdfCharset::GetFileContent(fntFilePath,contentOut,true,"r") || contentOut.size()==0) return NULL;
return SdfAddCharsetFromMemory(&contentOut[0],contentOut.size(),fntTexture,properties);
}
#endif // (!defined(NO_IMGUISDF_LOAD) ...)
SdfCharset* SdfAddCharsetFromMemory(const void* data,unsigned int data_size,ImTextureID fntTexture,const SdfCharsetProperties& properties) {
SdfCharset* p = (SdfCharset*) ImGui::MemAlloc(sizeof(SdfCharset));
IM_PLACEMENT_NEW (p) SdfCharset();
if (!p->loadFromMemory(data,data_size,fntTexture,properties)) {
p->~SdfCharset();
ImGui::MemFree(p);
return NULL;
}
gSdfInit.gSdfCharsets.push_back(p);
return p;
}
SdfTextChunk* SdfAddTextChunk(SdfCharset* charset, int sdfBufferType, const SdfTextChunkProperties& properties, bool preferStreamDrawBufferUsage) {
SdfTextChunk* p = (SdfTextChunk*) ImGui::MemAlloc(sizeof(SdfTextChunk));
IM_PLACEMENT_NEW (p) SdfTextChunk(charset,sdfBufferType,properties,preferStreamDrawBufferUsage);
gSdfInit.gSdfTextChunks.push_back(p);
return p;
}
SdfTextChunkProperties& SdfTextChunkGetProperties(SdfTextChunk* textChunk) {
textChunk->dirty = true;
return textChunk->props;
}
const SdfTextChunkProperties& SdfTextChunkGetProperties(const SdfTextChunk* textChunk) {
return textChunk->props;
}
void SdfTextChunkSetStyle(SdfTextChunk* textChunk,int sdfTextBufferType) {
textChunk->buffer->setType(sdfTextBufferType);
}
int SdfTextChunkGetStyle(const SdfTextChunk* textChunk) {
return textChunk->buffer->getType();
}
void SdfTextChunkSetMute(SdfTextChunk* textChunk,bool flag) {
textChunk->setMute(flag);
}
bool SdfTextChunkGetMute(const SdfTextChunk* textChunk) {
IM_ASSERT(textChunk);
return textChunk->mute;
}
void SdfRemoveTextChunk(SdfTextChunk* chunk) {
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
if (chunk == gSdfInit.gSdfTextChunks[i]) {
gSdfInit.gSdfTextChunks[i] = gSdfInit.gSdfTextChunks[isz-1];
gSdfInit.gSdfTextChunks.pop_back();
// destroy chunk
chunk->~SdfTextChunk();
ImGui::MemFree(chunk);
chunk=NULL;
break;
}
}
}
void SdfRemoveAllTextChunks() {
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
SdfTextChunk* chunk = gSdfInit.gSdfTextChunks[i];
// destroy chunk
chunk->~SdfTextChunk();
ImGui::MemFree(chunk);
}
gSdfInit.gSdfTextChunks.clear();
}
void SdfClearText(SdfTextChunk* chunk) {
IM_ASSERT(chunk);
chunk->clearText();
}
void SdfAddText(SdfTextChunk* chunk, const char* startText, bool italic, const SdfTextColor* pSdfTextColor, const ImVec2* textScaling, const char* endText,const SDFHAlignment *phalignOverride, bool fakeBold) {
IM_ASSERT(chunk);
chunk->addText(startText,italic,pSdfTextColor,textScaling,endText,phalignOverride,fakeBold);
}
void SdfAddTextWithTags(SdfTextChunk* chunk,const char* startText,const char* endText) {
IM_ASSERT(chunk);
if (!startText || startText==endText || startText[0]=='\0') return;
typedef struct _SdfTagState {
bool bold;
bool italic;
ImVector<SdfTextColor> color;
ImVector<ImVec2> scaling;
ImVector<SDFHAlignment> hAlign;
_SdfTagState() : bold(false),italic(false) {}
void SdfAddText(SdfTextChunk* chunk,const unsigned char* startText,const unsigned char* endText) const {
chunk->addText((const char*)startText,
italic,
color.size()>0?&color[color.size()-1]:NULL,
scaling.size()>0?&scaling[scaling.size()-1]:NULL,
(const char*)endText,
hAlign.size()>0?&hAlign[hAlign.size()-1]:NULL,
bold
);
}
} SdfTagState;
SdfTagState TS;
uint32_t state=UTF8Helper::UTF8_ACCEPT,codePoint=0,lastCodePoint=0,numGlyphs=0;
const uint32_t startTagCP = '<'; // Hp) startTagCP and endTagCP must be 1 bytes long (in UTF8)
const uint32_t endTagCP = '>';
const unsigned char* endTextUC = (const unsigned char*) (endText==NULL?(startText+strlen(startText)):endText);
const unsigned char* p = (const unsigned char*) startText;
const unsigned char* startTag=NULL;const unsigned char* endTag=NULL;const unsigned char* startSubchunk = p;
for(p = (const unsigned char*) startText; p!=endTextUC; ++p)
{
if (UTF8Helper::decode(&state, &codePoint, *p)!=UTF8Helper::UTF8_ACCEPT) continue;
++numGlyphs;
if (lastCodePoint == codePoint) continue;
lastCodePoint = codePoint;
if (codePoint==startTagCP) startTag = p;
else if (startTag && codePoint==endTagCP) {
endTag = p+1;
bool tagValid = true;
const char* s = (const char*) (startTag+1);
const char* e = (const char*) (endTag-1);
bool negate = false;bool hasEquality = false;
if (*s=='/') {negate=true;++s;if (s>=e) tagValid=false;}
const char* equality = e;
if (tagValid && !negate) {
equality = strchr(s,'=');
if (!equality || equality>=e) {
hasEquality = false;
equality = e;
}
else hasEquality = true;
}
if (tagValid) {
// Parse the two fields
static char field0[16];field0[0]='\0';
static char field1[16];field1[0]='\0';
int cnt=0;bool started = false;
for (const char* t=s;t!=equality && cnt<15;++t) {
if (*t==' ' || *t=='\t') {
if (!started) continue;
else break;
}
field0[cnt++]=tolower(*t); // <ctype.h> tolower()
started = true;
}
field0[cnt]='\0';
if (hasEquality) {
started = false;bool quoteStarted = false;
cnt=0;for (const char* t=equality+1;t!=e && cnt<15;++t) {
if (!quoteStarted && (*t==' ' || *t=='\t')) {
if (!started) continue;
else break;
}
if (*t=='\'' || *t=='"') {
if (!started) started = true;
if (quoteStarted) break;
quoteStarted = true;
continue;
}
field1[cnt++]=tolower(*t); // <ctype.h> tolower()
started = true;
}
field1[cnt]='\0';
}
//fprintf(stderr,"Found tag: %.*s (%d): field0:%s field1:%s hasEquality:%s negate:%s [Text before:\"%.*s\"]\n",(int)(e-s),s,(int)(e-s),field0,field1,hasEquality?"true":"false",negate?"true":"false",(int)(startTag-startSubchunk),startSubchunk);
TS.SdfAddText(chunk,startSubchunk,startTag);
startSubchunk = endTag;
// Process Tag and push or pop TS:
bool error = false;
if (strcmp(field0,"b")==0) TS.bold=!negate;
else if (strcmp(field0,"i")==0) TS.italic=!negate;
else if (strncmp(field0,"hal",3)==0) {
if (negate) {if (TS.hAlign.size()>0) TS.hAlign.pop_back();}
else if (hasEquality) {
SDFHAlignment hal=SDF_CENTER;
if (strncmp(field1,"l",1)==0) hal = SDF_LEFT;
else if (strncmp(field1,"c",1)==0) hal = SDF_CENTER;
else if (strncmp(field1,"r",1)==0) hal = SDF_RIGHT;
else if (strncmp(field1,"j",1)==0) hal = SDF_JUSTIFY;
else error = true;
if (!error) TS.hAlign.push_back(hal);
}
else error = true;
}
else if (strncmp(field0,"s",1)==0) {
ImVec2 scaling(1,1);
if (negate) {if (TS.scaling.size()>0) TS.scaling.pop_back();}
else if (hasEquality && sscanf(field1, "%f", &scaling.x)) {
scaling.y = scaling.x;
TS.scaling.push_back(scaling);
}
else error = true;
}
else if (strncmp(field0,"c",1)==0) {
ImU32 color;
if (negate) {if (TS.color.size()>0) TS.color.pop_back();}
else if (hasEquality && sscanf(field1, "%x", &color)) {
const bool mustInvertColor = true;
if (mustInvertColor) {
color = ((color << 8) & 0xFF00FF00 ) | ((color >> 8) & 0xFF00FF );
color = (color << 16) | (color >> 16);
// TODO: we should still invert R with B if IMGUI_USE_BGRA_PACKED_COLOR is defined!
}
TS.color.push_back(SdfTextColor(ImGui::ColorConvertU32ToFloat4(color)));
}
else error = true;
}
//TODO: other tags here (quad color, vAlign, etc.)
//if (error) {printf("SdfMarkupError: Can't understand tag: \"%.*s\"\n",(int)(e-s),s);fflush(stdout);}
}
startTag=endTag=NULL;
}
}
if (startSubchunk && p) TS.SdfAddText(chunk,startSubchunk,p);
}
void SdfTextColor::SetDefault(const SdfTextColor& defaultColor,bool updateAllExistingTextChunks) {
gSdfTextDefaultColor=defaultColor;
if (updateAllExistingTextChunks) {
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
gSdfInit.gSdfTextChunks[i]->dirty=true;
}
}
}
SdfAnimation* SdfAddAnimation() {
SdfAnimation* p = (SdfAnimation*) ImGui::MemAlloc(sizeof(SdfAnimation));
IM_PLACEMENT_NEW (p) SdfAnimation();
gSdfInit.gSdfAnimations.push_back(p);
return p;
}
void SdfAnimationSetLoopingParams(SdfAnimation* animation,bool mustLoop,bool mustHideTextWhenFinishedIfNotLooping) {
IM_ASSERT(animation);
animation->looping = mustLoop;
animation->mustMuteAtEnd = mustHideTextWhenFinishedIfNotLooping;
}
float SdfAnimationAddKeyFrame(SdfAnimation* animation,const SdfAnimationKeyFrame& keyFrame) {
IM_ASSERT(animation);
return animation->addKeyFrame(keyFrame);
}
void SdfAnimationClear(SdfAnimation* animation) {
IM_ASSERT(animation);
animation->clear();
}
void SdfRemoveAnimation(SdfAnimation* animation) {
IM_ASSERT(animation);
const bool checkItsNotSetToAnyChunk = true;
if (checkItsNotSetToAnyChunk) {
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
SdfTextChunk* chunk = gSdfInit.gSdfTextChunks[i];
if (chunk->manualAnimationRef==animation) {
if (chunk->animationMode==SDF_AM_MANUAL) {chunk->mute=true;chunk->animationStartTime=-1.f;}
chunk->manualAnimationRef=NULL;
}
}
}
for (int i=0,isz=gSdfInit.gSdfAnimations.size();i<isz;i++) {
SdfAnimation* anim = gSdfInit.gSdfAnimations[i];
if (anim == animation) {
// destroy animation
animation->~SdfAnimation();
ImGui::MemFree(animation);
// Swap with last element and pop_back
gSdfInit.gSdfAnimations[i] = gSdfInit.gSdfAnimations[isz-1];
gSdfInit.gSdfAnimations[isz-1] = NULL;
gSdfInit.gSdfAnimations.pop_back();
break;
}
}
}
void SdfRemoveAllAnimations() {
gSdfInit.DestroyAllAnimations();
}
void SdfTextChunkSetManualAnimation(struct SdfTextChunk* chunk,struct SdfAnimation* animation) {
IM_ASSERT(chunk && animation);
if (chunk->manualAnimationRef != animation) {
chunk->manualAnimationRef = animation;
chunk->animationStartTime = -1.f;
}
}
void SdfTextChunkSetAnimationParams(struct SdfTextChunk* chunk,const SdfAnimationParams& params) {
IM_ASSERT(chunk);
chunk->animationParams = params;
chunk->animationStartTime = -1.f;
}
void SdfTextChunkSetAnimationMode(struct SdfTextChunk* chunk,SDFAnimationMode mode) {
IM_ASSERT(chunk);
if (chunk->animationMode!=mode) {
chunk->animationMode=mode;
chunk->animationStartTime = -1.f;
}
}
SDFAnimationMode SdfTextChunkGetAnimationMode(struct SdfTextChunk* chunk) {
IM_ASSERT(chunk);
return chunk->animationMode;
}
const SdfAnimation* SdfTextChunkGetManualAnimation(const SdfTextChunk* chunk) {
IM_ASSERT(chunk);
return chunk->manualAnimationRef;
}
SdfAnimation* SdfTextChunkGetManualAnimation(SdfTextChunk* chunk) {
IM_ASSERT(chunk);
return chunk->manualAnimationRef;
}
const SdfAnimationParams& SdfTextChunkGetAnimationParams(const SdfTextChunk* chunk) {
IM_ASSERT(chunk);
return chunk->animationParams;
}
SdfAnimationParams& SdfTextChunkGetAnimationParams(SdfTextChunk* chunk) {
IM_ASSERT(chunk);
return chunk->animationParams;
}
void SdfTextChunkSetGlobalParams(struct SdfTextChunk* chunk,const SdfGlobalParams& params) {
IM_ASSERT(chunk);
chunk->globalParams = params;
}
const SdfGlobalParams& SdfTextChunkGetGlobalParams(const struct SdfTextChunk* chunk) {
IM_ASSERT(chunk);return chunk->globalParams;
}
SdfGlobalParams& SdfTextChunkGetGlobalParams(struct SdfTextChunk* chunk) {
IM_ASSERT(chunk);return chunk->globalParams;
}
bool SdfTextChunk::setupUniformValuesAndDrawArrays(SdfShaderProgram* SP,bool shadowPass,const ImVec2& screenSize) {
if (animationMode==SDF_AM_NONE || (animationParams.startChar==0 && animationParams.endChar==-1)) {
// is tmpKeyFrame always good even if animationMode==SDF_AM_NONE ?
if (tmpKeyFrame.alpha==0.f) return false;
const GLint startCharSize = (tmpKeyFrame.startChar>globalParams.startChar?tmpKeyFrame.startChar:globalParams.startChar)*6;
const GLint endCharSize1 = (tmpKeyFrame.endChar<0)?buffer->verts.size():(tmpKeyFrame.endChar*6);
GLint endCharSize = (globalParams.endChar<0)?buffer->verts.size():(globalParams.endChar*6);
if (endCharSize>=endCharSize1) endCharSize = endCharSize1;
if (endCharSize<=startCharSize) return false;
if (shadowPass) {
SP->setUniformOffsetAndScale(ImVec2((tmpKeyFrame.offset.x*screenSize.x)+shadowOffsetInPixels.x*tmpKeyFrame.scale.x
+(screenSize.x*(0.5f-0.5f*tmpKeyFrame.scale.x)) // scaling (not sure this is correct) [can be removed]
,(tmpKeyFrame.offset.y*screenSize.y)+shadowOffsetInPixels.y*tmpKeyFrame.scale.y
+(screenSize.y*(0.5f-0.5f*tmpKeyFrame.scale.y)) // scaling (not sure this is correct) [can be removed]
),tmpKeyFrame.scale);
SP->setUniformAlphaAndShadow(tmpKeyFrame.alpha*0.5f,0.2f);
}
else {
SP->setUniformOffsetAndScale(tmpKeyFrame.offset*screenSize+
(screenSize-screenSize*tmpKeyFrame.scale)*0.5f // scaling (not sure this is correct) [can be removed]
,tmpKeyFrame.scale);
SP->setUniformAlphaAndShadow(tmpKeyFrame.alpha,1.f);
}
glDrawArrays(GL_TRIANGLES,startCharSize,endCharSize-startCharSize);
}
else {
if (globalParams.alpha==0.f) return false;
// We have an animation, that must be limited to a subset of chars.
const GLint minStartSize = (globalParams.startChar<0)?0:(globalParams.startChar*6);
const GLint maxEndSize = (globalParams.endChar<0)?buffer->verts.size():(globalParams.endChar*6);
const int realAnimationParamsStartSize = (animationParams.startChar*6) > minStartSize ? (animationParams.startChar*6) : minStartSize;
const int realAnimationParamsEndSize = (animationParams.endChar<0 || animationParams.endChar*6 > maxEndSize) ? maxEndSize : (animationParams.endChar*6);
const int realTmpFrameStartSize = (tmpKeyFrame.startChar*6) > minStartSize ? (tmpKeyFrame.startChar*6) : minStartSize;
const int realTmpFrameEndSize = (tmpKeyFrame.endChar<0 || tmpKeyFrame.endChar*6 > maxEndSize) ? maxEndSize : (tmpKeyFrame.endChar*6);
// 1) draw non-animated edges:
{
if (shadowPass) {
SP->setUniformOffsetAndScale(ImVec2(globalParams.offset.x*screenSize.x+shadowOffsetInPixels.x*globalParams.scale.x
+(screenSize.x*(0.5f-0.5f*globalParams.scale.x)) // scaling (not sure this is correct) [can be removed]
,globalParams.offset.y*screenSize.y+shadowOffsetInPixels.y*globalParams.scale.y
+(screenSize.y*(0.5f-0.5f*globalParams.scale.y)) // scaling (not sure this is correct) [can be removed]
),globalParams.scale);
SP->setUniformAlphaAndShadow(globalParams.alpha*0.5f,0.2f);
}
else {
SP->setUniformOffsetAndScale(globalParams.offset*screenSize
+(screenSize-screenSize*globalParams.scale)*0.5f // scaling (not sure this is correct) [can be removed]
,globalParams.scale);
SP->setUniformAlphaAndShadow(globalParams.alpha,1.f);
}
// First edge:
if (realAnimationParamsStartSize>minStartSize) glDrawArrays(GL_TRIANGLES, minStartSize, realAnimationParamsStartSize-minStartSize);
// Last Edge:
if (maxEndSize-realAnimationParamsEndSize>0) glDrawArrays(GL_TRIANGLES, realAnimationParamsEndSize, maxEndSize-realAnimationParamsEndSize);
}
// 2) draw animated portion:
if (realTmpFrameStartSize<=realAnimationParamsEndSize && realTmpFrameEndSize>=realAnimationParamsStartSize)
{
if (shadowPass) {
SP->setUniformOffsetAndScale(ImVec2((tmpKeyFrame.offset.x*screenSize.x)+shadowOffsetInPixels.x*tmpKeyFrame.scale.x
+(screenSize.x*(0.5f-0.5f*tmpKeyFrame.scale.x)) // scaling (not sure this is correct) [can be removed]
,(tmpKeyFrame.offset.y*screenSize.y)+shadowOffsetInPixels.y*tmpKeyFrame.scale.y
+(screenSize.y*(0.5f-0.5f*tmpKeyFrame.scale.y)) // scaling (not sure this is correct) [can be removed]
),tmpKeyFrame.scale);
SP->setUniformAlphaAndShadow(tmpKeyFrame.alpha*0.5f,0.2f);
}
else {
SP->setUniformOffsetAndScale(tmpKeyFrame.offset*screenSize
+(screenSize-screenSize*tmpKeyFrame.scale)*0.5f // scaling (not sure this is correct) [can be removed]
,tmpKeyFrame.scale);
SP->setUniformAlphaAndShadow(tmpKeyFrame.alpha,1.f);
}
const GLint startAnimationCharIndex = realAnimationParamsStartSize>realTmpFrameStartSize?realAnimationParamsStartSize:realTmpFrameStartSize;
const GLint endAnimationCharIndex = realTmpFrameEndSize<realAnimationParamsEndSize?realTmpFrameEndSize:realAnimationParamsEndSize;
glDrawArrays(GL_TRIANGLES, startAnimationCharIndex, endAnimationCharIndex-startAnimationCharIndex);
}
}
return true;
}
void SdfRender(const ImVec4* pViewportOverride) {
ImGuiIO& io = ImGui::GetIO();
static ImVec2 displaySizeLast = io.DisplaySize;
const ImVec2 displaySize = pViewportOverride ? ImVec2(pViewportOverride->z,pViewportOverride->w) : io.DisplaySize;
if (displaySize.x==0 || displaySize.y==0) return;
const bool screenSizeChanged = displaySizeLast.x!=displaySize.x || displaySizeLast.y!=displaySize.y;
if (screenSizeChanged) {
displaySizeLast = displaySize;
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
gSdfInit.gSdfTextChunks[i]->dirty = true;
}
}
bool hasRegularFonts=false,hasOutlineFonts=false;float globalTime = ImGui::GetTime();
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
SdfTextChunk* c = gSdfInit.gSdfTextChunks[i];
if (c->textBits.size()==0 || !c->checkVisibleAndEvalutateAnimationIfNecessary(globalTime)) continue;
hasRegularFonts|=(c->buffer->type==0 || (c->buffer->type&(SDF_BT_SHADOWED)));
hasOutlineFonts|=(c->buffer->type&(SDF_BT_OUTLINE));
//if (hasRegularFonts && hasOutlineFonts) break; // We cannot exit early, because we must evalutate checkVisibleAndEvalutateAnimationIfNecessary(...) for all the text chunks
}
if (!hasRegularFonts && !hasOutlineFonts) return;
const float fb_x = pViewportOverride ? pViewportOverride->x*io.DisplayFramebufferScale.x : 0.f;
const float fb_y = pViewportOverride ? pViewportOverride->y*io.DisplayFramebufferScale.y : 0.f;
const float fb_height = displaySize.y * io.DisplayFramebufferScale.y; // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays)
const float fb_width = displaySize.x * io.DisplayFramebufferScale.x;
glViewport((GLint)fb_x, (GLint)fb_y, (GLsizei)fb_width, (GLsizei)fb_height);
//fprintf(stderr,"%d %d %d %d (%d %d)\n",(GLint)fb_x, (GLint)fb_y, (GLsizei)fb_width, (GLsizei)fb_height,(int)io.DisplaySize.x,(int)io.DisplaySize.y);
if (hasRegularFonts && !gSdfShaderPrograms[0].program) {
static bool done = false;
if (done) return;
done = true;
if (!gSdfShaderPrograms[0].loadShaderProgram(false)) return;
}
if (hasOutlineFonts && !gSdfShaderPrograms[1].program) {
static bool done = false;
if (done) return;
done = true;
if (!gSdfShaderPrograms[1].loadShaderProgram(true)) return;
}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glActiveTexture(GL_TEXTURE0);
glCullFace(GL_FRONT); // with this I can leave GL_CULL_FACE as it is
glDisable(GL_DEPTH_TEST);
//glEnable(GL_SCISSOR_TEST); // TO FIX: Does not work well with the y of the glScissor(...) call [when boundsCenter.y changes]
ImTextureID lastBoundTexture = 0;
const ImVec2 screenSize = displaySize; // For scissor test
const ImVec2 screenOffset = pViewportOverride ? ImVec2(pViewportOverride->x,pViewportOverride->y) : ImVec2(0,0);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
if (hasRegularFonts) {
SdfShaderProgram& SP = gSdfShaderPrograms[0];
glUseProgram(SP.program);
if (screenSizeChanged) SP.resetUniformOrtho();
bool isShadow = false;
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
SdfTextChunk* c = gSdfInit.gSdfTextChunks[i];
if (c->textBits.size()==0 || !c->tmpVisible) continue;
hasRegularFonts=(c->buffer->type!=SDF_BT_OUTLINE);
if (!hasRegularFonts) continue;
isShadow = (c->buffer->type&(SDF_BT_SHADOWED));
if (lastBoundTexture!=c->charset->fntTexture) {
lastBoundTexture=c->charset->fntTexture;
glBindTexture(GL_TEXTURE_2D,(unsigned long)c->charset->fntTexture);
}
if (!c->buffer->vbo) glGenBuffers(1,&c->buffer->vbo);
glBindBuffer(GL_ARRAY_BUFFER, c->buffer->vbo);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(SdfVertexBuffer::VertexDeclaration), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(SdfVertexBuffer::VertexDeclaration),(const void*) (2*sizeof(GLfloat)));
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(SdfVertexBuffer::VertexDeclaration), (const void*)(0 + 4*sizeof(GLfloat)));
if (c->endText(displaySize)) c->buffer->updateBoundVbo();
glScissor(screenOffset.x+(c->props.boundsCenter.x-c->props.boundsHalfSize.x)*screenSize.x,screenOffset.y+(c->props.boundsCenter.y-c->props.boundsHalfSize.y)*screenSize.y,
c->props.boundsHalfSize.x*screenSize.x*2.f,c->props.boundsHalfSize.y*screenSize.y*2.f);
if (isShadow) c->setupUniformValuesAndDrawArrays(&SP,true,screenSize);
if (!isShadow || (c->buffer->type==SDF_BT_SHADOWED)) c->setupUniformValuesAndDrawArrays(&SP,false,screenSize);
}
}
if (hasOutlineFonts) {
SdfShaderProgram& SP = gSdfShaderPrograms[1];
glUseProgram(SP.program);
if (screenSizeChanged) SP.resetUniformOrtho();
for (int i=0,isz=gSdfInit.gSdfTextChunks.size();i<isz;i++) {
SdfTextChunk* c = gSdfInit.gSdfTextChunks[i];
if (c->textBits.size()==0 || !c->tmpVisible) continue;
hasOutlineFonts=(c->buffer->type&(SDF_BT_OUTLINE));
if (!hasOutlineFonts) continue;
if (lastBoundTexture!=c->charset->fntTexture) {
lastBoundTexture=c->charset->fntTexture;
glBindTexture(GL_TEXTURE_2D,(unsigned long)c->charset->fntTexture);
}
if (!c->buffer->vbo) glGenBuffers(1,&c->buffer->vbo);
glBindBuffer(GL_ARRAY_BUFFER, c->buffer->vbo);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(SdfVertexBuffer::VertexDeclaration), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(SdfVertexBuffer::VertexDeclaration),(const void*) (2*sizeof(GLfloat)));
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(SdfVertexBuffer::VertexDeclaration), (const void*)(0 + 4*sizeof(GLfloat)));
if (c->endText(displaySize)) c->buffer->updateBoundVbo();
glScissor(screenOffset.x+(c->props.boundsCenter.x-c->props.boundsHalfSize.x)*screenSize.x,screenOffset.y+(c->props.boundsCenter.y-c->props.boundsHalfSize.y)*screenSize.y,
c->props.boundsHalfSize.x*screenSize.x*2.f,c->props.boundsHalfSize.y*screenSize.y*2.f);
c->setupUniformValuesAndDrawArrays(&SP,false,screenSize);
}
}
glBindTexture(GL_TEXTURE_2D,0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glUseProgram(0);
glEnable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
glCullFace(GL_BACK);
glDisable(GL_BLEND);
}
#ifndef NO_IMGUISDF_EDIT
inline bool SdfAnimationKeyFrameEdit(SdfAnimationKeyFrame* kf,bool isFirstFrame=false) {
IM_ASSERT(kf);
bool changed = false;
ImGui::PushID(kf);
ImGui::PushItemWidth(ImGui::GetWindowWidth()*0.2f);
changed|=ImGui::DragFloat("Alpha##SdfAlpha",&kf->alpha,0.01f,0.0f,1.f);
if (!(isFirstFrame && kf->timeInSeconds==0.f)) {
ImGui::SameLine();
changed|=ImGui::DragFloat("FrameTimeInSeconds##SdfFrameTimeInSeconds",&kf->timeInSeconds,0.01f,0.0f,60.f);
if (isFirstFrame && ImGui::IsItemHovered()) ImGui::SetTooltip("%s","You should set it to zero\nfor the first frame.");
}
changed|=ImGui::DragFloat2("Offset##SdfKeyFrameOffset",&kf->offset.x,0.01f,-1.0f,1.0f);
//
changed|=ImGui::DragFloat2("Scale##SdfKeyFrameScale",&kf->scale.x,0.001f,0.1f,5.0f);
changed|=ImGui::DragInt("StartChar##SdfStartChar",&kf->startChar,0.01f,0,2000);
ImGui::SameLine();
changed|=ImGui::DragInt("EndChar##SdfEndChar",&kf->endChar,0.01f,-1,2000);
ImGui::PopItemWidth();
ImGui::PopID();
return changed;
}
inline bool SdfAnimationEdit(SdfAnimation* an) {
IM_ASSERT(an);
bool changed = false;
ImGui::PushID(an);
changed|=ImGui::Checkbox("Looping##SdfAnimationLooping",&an->looping);
if (!an->looping) {
ImGui::SameLine();
changed|=ImGui::Checkbox("Must Hide Text At End##SdfAnimationMustHideTextAtEnd",&an->mustMuteAtEnd);
}
char name[65]="";
int kfri = -1;
for (int kfi=0,nkf=an->keyFrames.size();kfi<nkf;kfi++) {
SdfAnimationKeyFrame& kf = an->keyFrames[kfi];
ImGui::PushID(kfi);
sprintf(&name[0],"KeyFrame %.3d", kfi);
if (ImGui::TreeNode(name)) {
changed|= SdfAnimationKeyFrameEdit(&kf,kfi==0);
if (ImGui::SmallButton("Remove##SdfRemoveKeyFrame")) {changed = true;kfri=kfi;}
ImGui::TreePop();
}
ImGui::PopID();
}
ImGui::PushItemWidth(ImGui::GetWindowWidth()/10.f);
ImGui::Separator();
if (ImGui::Button("Add KeyFrame##SdfAddKeyFrame")) {
SdfAnimationKeyFrame kf(1.f);
if (an->keyFrames.size()==0) {kf.timeInSeconds=0.f;}
else {
kf = an->keyFrames[an->keyFrames.size()-1];
if (kf.timeInSeconds<=0.f) kf.timeInSeconds = 1.f;
}
an->addKeyFrame(kf);
changed = true;
}
ImGui::PopItemWidth();
ImGui::PopID();
if (kfri>=0) an->removeKeyFrameAt(kfri);
return changed;
}
bool SdfTextChunkEdit(SdfTextChunk* sdfTextChunk, char* buffer, int bufferSize) {
IM_ASSERT(sdfTextChunk && buffer && bufferSize>0);
ImGui::PushID(sdfTextChunk);
SdfTextChunkProperties& sdfLayoutProps = sdfTextChunk->props;
unsigned int flags = (unsigned int) sdfTextChunk->buffer->type;
bool changed = false,changed2=false;
static bool useMarkups = true;
changed2|=ImGui::Checkbox("Use markups",&useMarkups);
changed|=ImGui::CheckboxFlags("Outline##SDF_outline_style",&flags,ImGui::SDF_BT_OUTLINE);ImGui::SameLine();
changed|=ImGui::CheckboxFlags("Shadowed##SDF_shadowed_style",&flags,ImGui::SDF_BT_SHADOWED);
if (changed) ImGui::SdfTextChunkSetStyle(sdfTextChunk,(int)flags);
changed=changed2;changed2=false;
if (!useMarkups) ImGui::SameLine();
static bool italic = false;if (!useMarkups) changed|=ImGui::Checkbox("Italic##SDF_italic",&italic);
static ImVec4 color = sdfTextChunk->buffer->getColorOfVert(0) ? *sdfTextChunk->buffer->getColorOfVert(0) : SdfTextDefaultColor.colorTopLeft;
if (!useMarkups) {
ImGui::PushItemWidth(ImGui::GetWindowWidth()/3.f);
changed|=ImGui::ColorEdit4("Color##SDF_color",&color.x);
ImGui::PopItemWidth();
}
//ImGui::PushItemWidth(ImGui::GetWindowWidth()/6.f);
//static ImVec2 scaling(1.f,1.f);changed|=ImGui::DragFloat2("Scale##SDF_scale",&scaling.x,0.1f,0.25f,4.f);
//static float scaling(1.f);changed|=ImGui::DragFloat("Scale##SDF_scale",&scaling,0.1f,0.25f,4.f);
//ImGui::PopItemWidth();
ImGui::PushItemWidth(ImGui::GetWindowWidth()/10.f);
changed2|=ImGui::DragFloat("max num lines##SDF_maxnumlines",&sdfLayoutProps.maxNumTextLines,0.5f,1.0f,100.f);
ImGui::PopItemWidth();
ImGui::PushItemWidth(ImGui::GetWindowWidth()/6.f);
static const char* Halignments[] = {"LEFT","CENTER","RIGHT","JUSTIFY"};
static const char* Valignments[] = {"TOP","CENTER","BOTTOM"};
int halign = (int) sdfLayoutProps.halign;if (ImGui::Combo("Halignment##SDF_Halignment",&halign,&Halignments[0],4)) {changed2=true;sdfLayoutProps.halign = (ImGui::SDFHAlignment) halign;}
ImGui::SameLine();
int valign = (int) sdfLayoutProps.valign;if (ImGui::Combo("Valignment##SDF_Valignment",&valign,&Valignments[0],3)) {changed2=true;sdfLayoutProps.valign = (ImGui::SDFVAlignment) valign;}
changed2|=ImGui::DragFloat2("boundsCenter##SDF_boundsCenter",&sdfLayoutProps.boundsCenter.x,0.01f,0.0f,1.0f);
ImGui::SameLine();
changed2|=ImGui::DragFloat2("boundsHalfSize##SDF_boundsHalfSize",&sdfLayoutProps.boundsHalfSize.x,0.01f,0.001f,0.5f);
//changed2|=ImGui::DragFloat("lineHeightOvr##SDF_lineHeightOvr",&sdfLayoutProps.lineHeightOverride,0.01f,0.0f,2.f);
ImGui::PopItemWidth();
bool textChanged = false;
ImGui::PushItemWidth(-1.f);
changed|=textChanged=ImGui::InputTextMultiline("##SDF Text",buffer,bufferSize,ImVec2(0,0),ImGuiInputTextFlags_AllowTabInput);
ImGui::PopItemWidth();
if (changed || changed2) {
if (changed2) ImGui::SdfTextChunkGetProperties(sdfTextChunk) = sdfLayoutProps;
ImGui::SdfClearText(sdfTextChunk);
if (!useMarkups) {
ImGui::SdfTextColor textColor(color);
//ImVec2 scaling2D(scaling,scaling);
ImGui::SdfAddText(sdfTextChunk,buffer,italic,&textColor,NULL/*&scaling2D*/); // Actually we can append multiple of these calls together
}
else ImGui::SdfAddTextWithTags(sdfTextChunk,buffer,NULL);
}
// Animations:
ImGui::PushItemWidth(ImGui::GetWindowWidth()/6.f);
static const char* AnimationModeNames[SDF_AM_TYPING+1] = {"NONE","MANUAL",
"FADE_IN","ZOOM_IN","APPEAR_IN","LEFT_IN","RIGHT_IN","TOP_IN","BOTTOM_IN",
"FADE_OUT","ZOOM_OUT","APPEAR_OUT","LEFT_OUT","RIGHT_OUT","TOP_OUT","BOTTOM_OUT",
"BLINK","PULSE","TYPING"};
int animationMode = (int) ImGui::SdfTextChunkGetAnimationMode(sdfTextChunk);
if (ImGui::Combo("Animation Mode##SDFAnimationMode",&animationMode,&AnimationModeNames[0],sizeof(AnimationModeNames)/sizeof(AnimationModeNames[0]))) {
ImGui::SdfTextChunkSetAnimationMode(sdfTextChunk,(SDFAnimationMode)animationMode);
sdfTextChunk->setMute(false);
sdfTextChunk->animationStartTime = -1.f;
}
//ImGui::SameLine();
bool changed3 = false;
if (ImGui::TreeNode("Animation Params")) {
changed3|=ImGui::DragFloat("ASpeed##SdfAnimationSpeed",&sdfTextChunk->animationParams.speed,0.01f,0.2f,5.f);
//ImGui::SameLine();
//if (ImGui::Checkbox("ALoop##SdfAnimationLooping",&sdfTextChunk->animationParams.looping)) {changed3=true;sdfTextChunk->animationStartTime = -1.f;}
//if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s","Looping affects only\nmanual animations.");
//ImGui::SameLine();
bool hov1 = false;
ImGui::DragInt("AStartChar##SdfAStartChar",&sdfTextChunk->animationParams.startChar,0.01f,0,2000);
hov1|=ImGui::IsItemHovered();ImGui::SameLine();
ImGui::DragInt("AEndChar##SdfAEndChar",&sdfTextChunk->animationParams.endChar,0.01f,-1,2000);
hov1|=ImGui::IsItemHovered();if (hov1) ImGui::SetTooltip("%s","Useful only for partial\nanimations of the text.");
if (ImGui::SmallButton("Reset##SdfAnimationParams")) {changed3=true;sdfTextChunk->animationParams = SdfAnimationParams();}
ImGui::Separator();
ImGui::TreePop();
}
if (ImGui::TreeNode("Global Params")) {
ImGui::DragFloat("GAlpha##SdfGAlpha",&sdfTextChunk->globalParams.alpha,0.01f,0.0f,1.f);
ImGui::SameLine();
ImGui::DragFloat2("GOffset##SdfGKeyFrameOffset",&sdfTextChunk->globalParams.offset.x,0.01f,-1.0f,1.0f);
ImGui::DragFloat2("GScale##SdfGKeyFrameScale",&sdfTextChunk->globalParams.scale.x,0.001f,0.1f,5.0f);
//ImGui::SameLine();
bool hov2 = false;
ImGui::DragInt("GStartChar##SdfGStartChar",&sdfTextChunk->globalParams.startChar,0.01f,0,2000);
hov2|=ImGui::IsItemHovered();ImGui::SameLine();
ImGui::DragInt("GEndChar##SdfGEndChar",&sdfTextChunk->globalParams.endChar,0.01f,-1,2000);
hov2|=ImGui::IsItemHovered();if (hov2) ImGui::SetTooltip("%s","Useful only for partial\ndisplay of the text.");
//ImGui::SameLine();
if (ImGui::SmallButton("Reset##SdfGlobalParams")) {changed3=true;sdfTextChunk->globalParams = SdfGlobalParams();}
ImGui::Separator();
ImGui::TreePop();
}
if (changed3) {sdfTextChunk->setMute(false);sdfTextChunk->animationStartTime = -1.f;}
//ImGui::SameLine();
//ImGui::SameLine();ImGui::DragFloat2("Scale##SdfKeyFrameScale",&sdfTextChunk->animationParams.scale.x,0.01f,0.25f,2.5f);
ImGui::PopItemWidth();
//if (animationMode == SDF_AM_MANUAL) {
SdfAnimation* optAnimation = sdfTextChunk->manualAnimationRef;
if (optAnimation) {
if (ImGui::CollapsingHeader("Manual Animation##SdfManualAnimation")) {
if (SdfAnimationEdit(optAnimation)) {
optAnimation->update();
//sdfTextChunk->animationMode = SDF_AM_MANUAL;
sdfTextChunk->animationStartTime = -1.f;
sdfTextChunk->setMute(false);
}
ImGui::SameLine();
if (ImGui::Button("Restart##SdfManualAnimationRestart")) {
sdfTextChunk->setMute(false);sdfTextChunk->animationStartTime = -1.f;
sdfTextChunk->animationMode = SDF_AM_MANUAL;
}
}
}
/*
else {
ImGui::Text("You need to add to the text chunk a new animation to edit it.");
ImGui::Text("Please see: SdfAddAnimation() and");
ImGui::Text("SdfTextChunkSetManualAnimation(...).");
}
*/
// }
ImGui::PopID();
return textChanged;
}
#endif //NO_IMGUISDF_EDIT
} // namespace
| 47.887961 | 271 | 0.589368 | [
"3d"
] |
3cedf1fa4a9c8d37ca4c1c7da07655923c36d2b6 | 34,252 | cpp | C++ | exotica_core/src/problems/dynamic_time_indexed_shooting_problem.cpp | Tobias-Fischer/exotica | 3fb5484882e390e045c8213f21acc92d2d40ce28 | [
"BSD-3-Clause"
] | null | null | null | exotica_core/src/problems/dynamic_time_indexed_shooting_problem.cpp | Tobias-Fischer/exotica | 3fb5484882e390e045c8213f21acc92d2d40ce28 | [
"BSD-3-Clause"
] | null | null | null | exotica_core/src/problems/dynamic_time_indexed_shooting_problem.cpp | Tobias-Fischer/exotica | 3fb5484882e390e045c8213f21acc92d2d40ce28 | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright (c) 2019, Wolfgang Merkt
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of 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 <exotica_core/problems/dynamic_time_indexed_shooting_problem.h>
#include <exotica_core/setup.h>
#include <exotica_core/tools/conversions.h>
#include <exotica_core/tools/sparse_costs.h>
#include <cmath>
REGISTER_PROBLEM_TYPE("DynamicTimeIndexedShootingProblem", exotica::DynamicTimeIndexedShootingProblem)
namespace exotica
{
DynamicTimeIndexedShootingProblem::DynamicTimeIndexedShootingProblem()
{
this->flags_ = KIN_FK | KIN_J;
}
DynamicTimeIndexedShootingProblem::~DynamicTimeIndexedShootingProblem() = default;
void DynamicTimeIndexedShootingProblem::InstantiateCostTerms(const DynamicTimeIndexedShootingProblemInitializer& init)
{
loss_type_ = ControlCostLossTermType::Undefined;
// L2
if (parameters_.LossType == "L2") loss_type_ = ControlCostLossTermType::L2;
// L1
if (parameters_.LossType == "SmoothL1" || parameters_.LossType == "AdaptiveSmoothL1") loss_type_ = ControlCostLossTermType::SmoothL1;
if (parameters_.LossType == "AdaptiveSmoothL1")
{
smooth_l1_mean_ = Eigen::VectorXd::Zero(scene_->get_num_controls());
smooth_l1_std_ = Eigen::VectorXd::Zero(scene_->get_num_controls());
}
// Huber
if (parameters_.LossType == "Huber") loss_type_ = ControlCostLossTermType::Huber;
if (parameters_.LossType == "PseudoHuber") loss_type_ = ControlCostLossTermType::PseudoHuber;
// If still undefined, throw.
if (loss_type_ == ControlCostLossTermType::Undefined) ThrowPretty("Unknown loss type: " << parameters_.LossType);
// L1 Rate
if (parameters_.L1Rate.size() == 1)
{
l1_rate_.setConstant(scene_->get_num_controls(), parameters_.L1Rate(0));
}
else if (parameters_.L1Rate.size() == scene_->get_num_controls())
{
l1_rate_ = parameters_.L1Rate;
}
else if (parameters_.L1Rate.size() != 0)
{
ThrowPretty("L1Rate has wrong size: expected " << scene_->get_num_controls() << ", 1, or 0 (default), got " << parameters_.L1Rate.size());
}
// Default
else
{
l1_rate_.setConstant(scene_->get_num_controls(), 1);
}
// Huber Rate
if (parameters_.HuberRate.size() == 1)
{
huber_rate_.setConstant(scene_->get_num_controls(), parameters_.HuberRate(0));
}
else if (parameters_.HuberRate.size() == scene_->get_num_controls())
{
huber_rate_ = parameters_.HuberRate;
}
else if (parameters_.HuberRate.size() != 0)
{
ThrowPretty("HuberRate has wrong size: expected " << scene_->get_num_controls() << ", 1, or 0, got " << parameters_.HuberRate.size());
}
else
{
huber_rate_.setConstant(scene_->get_num_controls(), 1);
}
control_cost_weight_ = parameters_.ControlCostWeight;
}
void DynamicTimeIndexedShootingProblem::Instantiate(const DynamicTimeIndexedShootingProblemInitializer& init)
{
this->parameters_ = init;
if (!scene_->GetDynamicsSolver()) ThrowPretty("DynamicsSolver is not initialised!");
const int NX = scene_->get_num_positions() + scene_->get_num_velocities(),
NDX = 2 * scene_->get_num_velocities(),
NU = scene_->get_num_controls();
Qf_ = Eigen::MatrixXd::Identity(NDX, NDX);
if (this->parameters_.Qf.rows() > 0)
{
if (this->parameters_.Qf.rows() == NDX)
{
Qf_.diagonal() = this->parameters_.Qf;
}
else
{
ThrowNamed("Qf dimension mismatch! Expected " << NDX << ", got " << this->parameters_.Qf.rows());
}
}
Qf_ *= this->parameters_.Qf_rate;
R_ = Eigen::MatrixXd::Identity(scene_->get_num_controls(), scene_->get_num_controls());
if (this->parameters_.R.rows() > 0)
{
if (this->parameters_.R.rows() == scene_->get_num_controls())
{
R_.diagonal() = this->parameters_.R;
}
else
{
ThrowNamed("R dimension mismatch! Expected " << scene_->get_num_controls() << ", got " << this->parameters_.R.rows());
}
}
R_ *= this->parameters_.R_rate;
// Set up stochastic terms
// see https://homes.cs.washington.edu/~todorov/papers/TodorovNeuralComp05.pdf
// eq. 3.1 and the text before (search for 'column') to see why this makes sense
//
// We specify a matrix of size NX x NU from which the C matrices
// are extracted
//
// E.g. NU = 2, NX = 4
//
// The matrix is
// a b
// c d
// e f
// g h
//
// From which the Ci matrices become
// C0 = a b C1 = 0 0 C2 = 0 0 C3 = 0 0
// 0 0 c d 0 0 0 0
// 0 0 0 0 e f 0 0
// 0 0 0 0 0 0 g h
//
// If you specify C_rate, then this is equivalent to:
//
// C = 0 0
// 0 0
// c 0
// 0 c
//
// The velocities then take the noise terms in. For an
// underactuated system these are somewhat ill-defined. E.g.
// if above NU = 1 and you specify c:
//
// C = 0
// 0
// c
// 0
bool full_noise_set = false;
Ci_.assign(NX, Eigen::MatrixXd::Zero(NX, NU));
if (parameters_.C_rate != 0.0)
{
if (NU <= NX)
{
for (int i = 0; i < NU; ++i)
Ci_.at(NX - NU + i)(NX - NU + i, i) = parameters_.C_rate;
}
else
{
ThrowPretty("Noise does not work for systems that have NU > NX. This should be fixed in the future.");
}
}
if (this->parameters_.C.rows() > 0)
{
if (parameters_.C.rows() * parameters_.C.cols() == NX * NU)
{
Eigen::Map<Eigen::MatrixXd> C_map(parameters_.C.data(), NU, NX);
for (int i = 0; i < NX; ++i)
Ci_[i].row(i) = C_map.col(i).transpose(); // row over vs. col order
full_noise_set = true;
}
else
{
ThrowNamed("C dimension mismatch! Expected " << NX << "x" << NU << ", got " << parameters_.C.rows() << "x" << parameters_.C.cols());
}
}
CW_ = this->parameters_.CW_rate * Eigen::MatrixXd::Identity(NX, NX);
if (parameters_.CW.rows() > 0)
{
if (parameters_.CW.rows() == NX)
{
CW_.diagonal() = parameters_.CW;
full_noise_set = true;
}
else
{
ThrowNamed("CW dimension mismatch! Expected " << NX << ", got " << parameters_.R.rows());
}
}
if (parameters_.C_rate > 0 || parameters_.CW_rate > 0 || full_noise_set)
{
stochastic_matrices_specified_ = true;
stochastic_updates_enabled_ = true;
}
T_ = this->parameters_.T;
tau_ = this->parameters_.tau;
// For now, without inter-/extra-polation for integrators, assure that tau is a multiple of dt
const long double fmod_tau_dt = std::fmod(static_cast<long double>(1000. * tau_), static_cast<long double>(1000. * scene_->GetDynamicsSolver()->get_dt()));
if (fmod_tau_dt > 1e-5) ThrowPretty("tau is not a multiple of dt: tau=" << tau_ << ", dt=" << scene_->GetDynamicsSolver()->get_dt() << ", mod(" << fmod_tau_dt << ")");
// Initialize general costs
cost.Initialize(this->parameters_.Cost, shared_from_this(), cost_Phi);
ApplyStartState(false);
InstantiateCostTerms(init);
ReinitializeVariables();
}
void DynamicTimeIndexedShootingProblem::ReinitializeVariables()
{
if (debug_) HIGHLIGHT_NAMED("DynamicTimeIndexedShootingProblem", "Initialize problem with T=" << T_);
const int NX = scene_->get_num_positions() + scene_->get_num_velocities(), NDX = 2 * scene_->get_num_velocities(), NU = scene_->get_num_controls();
X_ = Eigen::MatrixXd::Zero(NX, T_);
X_star_ = Eigen::MatrixXd::Zero(NX, T_);
X_diff_ = Eigen::MatrixXd::Zero(NDX, T_);
U_ = Eigen::MatrixXd::Zero(scene_->get_num_controls(), T_ - 1);
// Set w component of quaternion by default
if (scene_->get_has_quaternion_floating_base())
{
for (int t = 0; t < T_; ++t)
{
SetDefaultQuaternionInConfigurationVector(X_.col(t));
SetDefaultQuaternionInConfigurationVector(X_star_.col(t));
}
}
// Set GoalState
if (this->parameters_.GoalState.rows() > 0)
{
Eigen::MatrixXd goal_state(X_star_);
if (this->parameters_.GoalState.rows() == NX)
{
goal_state.col(T_ - 1) = this->parameters_.GoalState;
}
else if (this->parameters_.GoalState.rows() == scene_->get_num_positions())
{
goal_state.col(T_ - 1).head(scene_->get_num_positions()) = this->parameters_.GoalState;
}
else if (this->parameters_.GoalState.rows() == NX * T_)
{
for (int t = 0; t < T_; ++t)
{
goal_state.col(t) = this->parameters_.GoalState.segment(t * NX, NX);
}
}
else
{
ThrowPretty("GoalState has " << this->parameters_.GoalState.rows() << " rows, but expected either NX=" << NX << " or NQ=" << scene_->get_num_positions() << ", or NX*T=" << NX * T_);
}
set_X_star(goal_state);
}
// Set StartState
if (this->parameters_.StartState.rows() > 0)
{
Eigen::MatrixXd start_state(X_);
if (this->parameters_.StartState.rows() == NX)
{
start_state = this->parameters_.StartState.replicate(1, T_);
}
else if (this->parameters_.StartState.rows() == scene_->get_num_positions())
{
for (int t = 0; t < T_; ++t)
{
start_state.col(t).head(scene_->get_num_positions()) = this->parameters_.StartState;
}
}
else if (this->parameters_.StartState.rows() == NX * T_)
{
for (int t = 0; t < T_; ++t)
{
start_state.col(t) = this->parameters_.StartState.segment(t * NX, NX);
}
}
else
{
ThrowPretty("StartState has " << this->parameters_.StartState.rows() << " rows, but expected either NX=" << NX << " or NQ=" << scene_->get_num_positions() << ", or NX*T=" << NX * T_);
}
set_X(start_state);
}
Eigen::MatrixXd Q = Eigen::MatrixXd::Identity(NDX, NDX);
if (this->parameters_.Q.rows() > 0)
{
if (this->parameters_.Q.rows() == NDX)
{
Q.diagonal() = this->parameters_.Q;
}
else
{
ThrowNamed("Q dimension mismatch! Expected " << NDX << ", got " << this->parameters_.Q.rows());
}
}
Q *= this->parameters_.Q_rate;
Q_.assign(T_, Q);
// Set final Q (Qf) -- the Qf variable has been populated in Instantiate
set_Qf(Qf_);
// Reinitialize general cost (via taskmaps)
num_tasks = tasks_.size();
length_Phi = 0;
length_jacobian = 0;
TaskSpaceVector y_ref_;
for (int i = 0; i < num_tasks; ++i)
{
AppendVector(y_ref_.map, tasks_[i]->GetLieGroupIndices());
length_Phi += tasks_[i]->length;
length_jacobian += tasks_[i]->length_jacobian;
}
// Initialize the TaskSpaceVector and its derivatives
y_ref_.SetZero(length_Phi);
Phi.assign(T_, y_ref_);
if (flags_ & KIN_J)
{
dPhi_dx.assign(T_, Eigen::MatrixXd(length_jacobian, scene_->get_num_state_derivative()));
dPhi_du.assign(T_, Eigen::MatrixXd(length_jacobian, scene_->get_num_controls()));
}
if (flags_ & KIN_H)
{
ddPhi_ddx.assign(T_, Hessian::Constant(length_jacobian, Eigen::MatrixXd::Zero(scene_->get_num_state_derivative(), scene_->get_num_state_derivative())));
ddPhi_ddu.assign(T_, Hessian::Constant(length_jacobian, Eigen::MatrixXd::Zero(scene_->get_num_controls(), scene_->get_num_controls())));
ddPhi_dxdu.assign(T_, Hessian::Constant(length_jacobian, Eigen::MatrixXd::Zero(scene_->get_num_state_derivative(), scene_->get_num_controls())));
}
cost.ReinitializeVariables(T_, shared_from_this(), cost_Phi);
// Initialise variables for state and control cost
// NB: To do this, we had to remove the "const" qualifier of the Hessian/Jacobian methods.
dxdiff_.assign(T_, Eigen::MatrixXd::Zero(NDX, NDX));
state_cost_jacobian_.assign(T_, Eigen::VectorXd::Zero(NDX));
state_cost_hessian_.assign(T_, Eigen::MatrixXd::Zero(NDX, NDX));
general_cost_jacobian_.assign(T_, Eigen::VectorXd::Zero(NDX));
general_cost_hessian_.assign(T_, Eigen::MatrixXd::Zero(NDX, NDX));
control_cost_jacobian_.assign(T_ - 1, Eigen::VectorXd::Zero(NU));
control_cost_hessian_.assign(T_ - 1, Eigen::MatrixXd::Zero(NU, NU));
PreUpdate();
}
const int& DynamicTimeIndexedShootingProblem::get_T() const
{
return T_;
}
void DynamicTimeIndexedShootingProblem::set_T(const int& T_in)
{
if (T_in <= 2)
{
ThrowNamed("Invalid number of timesteps: " << T_in);
}
T_ = T_in;
ReinitializeVariables();
}
const double& DynamicTimeIndexedShootingProblem::get_tau() const
{
return tau_;
}
void DynamicTimeIndexedShootingProblem::PreUpdate()
{
PlanningProblem::PreUpdate();
for (int i = 0; i < tasks_.size(); ++i) tasks_[i]->is_used = false;
cost.UpdateS();
// Create a new set of kinematic solutions with the size of the trajectory
// based on the lastest KinematicResponse in order to reflect model state
// updates etc.
kinematic_solutions_.clear();
kinematic_solutions_.resize(T_);
for (int i = 0; i < T_; ++i) kinematic_solutions_[i] = std::make_shared<KinematicResponse>(*scene_->GetKinematicTree().GetKinematicResponse());
if (this->parameters_.WarmStartWithInverseDynamics)
{
for (int t = 0; t < T_ - 1; ++t)
{
U_.col(t) = scene_->GetDynamicsSolver()->InverseDynamics(X_.col(t));
X_.col(t + 1) = scene_->GetDynamicsSolver()->Simulate(X_.col(t), U_.col(t), tau_);
}
}
}
Eigen::VectorXd DynamicTimeIndexedShootingProblem::ApplyStartState(bool update_traj)
{
PlanningProblem::ApplyStartState(update_traj);
return start_state_;
}
const Eigen::MatrixXd& DynamicTimeIndexedShootingProblem::get_X() const
{
return X_;
}
Eigen::VectorXd DynamicTimeIndexedShootingProblem::get_X(int t) const
{
ValidateTimeIndex(t);
return X_.col(t);
}
void DynamicTimeIndexedShootingProblem::set_X(Eigen::MatrixXdRefConst X_in)
{
if (X_in.rows() != X_.rows() || X_in.cols() != X_.cols()) ThrowPretty("Sizes don't match! " << X_.rows() << "x" << X_.cols() << " vs " << X_in.rows() << "x" << X_in.cols());
X_ = X_in;
// Normalize quaternion, if required.
if (scene_->get_has_quaternion_floating_base())
{
for (int t = 0; t < T_; ++t)
{
NormalizeQuaternionInConfigurationVector(X_.col(t));
}
}
}
const Eigen::MatrixXd& DynamicTimeIndexedShootingProblem::get_U() const
{
return U_;
}
Eigen::VectorXd DynamicTimeIndexedShootingProblem::get_U(int t) const
{
ValidateTimeIndex(t);
return U_.col(t);
}
void DynamicTimeIndexedShootingProblem::set_U(Eigen::MatrixXdRefConst U_in)
{
if (U_in.rows() != U_.rows() || U_in.cols() != U_.cols()) ThrowPretty("Sizes don't match! " << U_.rows() << "x" << U_.cols() << " vs " << U_in.rows() << "x" << U_in.cols());
U_ = U_in;
}
const Eigen::MatrixXd& DynamicTimeIndexedShootingProblem::get_X_star() const
{
return X_star_;
}
void DynamicTimeIndexedShootingProblem::set_X_star(Eigen::MatrixXdRefConst X_star_in)
{
if (X_star_in.rows() != X_star_.rows() || X_star_in.cols() != X_star_.cols()) ThrowPretty("Sizes don't match! " << X_star_.rows() << "x" << X_star_.cols() << " vs " << X_star_in.rows() << "x" << X_star_in.cols());
X_star_ = X_star_in;
// Normalize quaternion, if required.
if (scene_->get_has_quaternion_floating_base())
{
for (int t = 0; t < T_; ++t)
{
NormalizeQuaternionInConfigurationVector(X_star_.col(t));
}
}
}
const Eigen::MatrixXd& DynamicTimeIndexedShootingProblem::get_Q(int t) const
{
ValidateTimeIndex(t);
return Q_[t];
}
const Eigen::MatrixXd& DynamicTimeIndexedShootingProblem::get_Qf() const
{
return Q_[T_ - 1];
}
const Eigen::MatrixXd& DynamicTimeIndexedShootingProblem::get_R() const
{
return R_;
}
void DynamicTimeIndexedShootingProblem::set_Q(Eigen::MatrixXdRefConst Q_in, int t)
{
ValidateTimeIndex(t);
if (Q_in.rows() != Q_[t].rows() || Q_in.cols() != Q_[t].cols()) ThrowPretty("Dimension mismatch!");
Q_[t] = Q_in;
}
void DynamicTimeIndexedShootingProblem::set_Qf(Eigen::MatrixXdRefConst Q_in)
{
set_Q(Q_in, T_ - 1);
}
void DynamicTimeIndexedShootingProblem::Update(Eigen::VectorXdRefConst x_in, Eigen::VectorXdRefConst u_in, int t)
{
// We can only update t=0, ..., T-1 - the last state will be created from integrating u_{T-1} to get x_T
if (t >= (T_ - 1) || t < -1)
{
ThrowPretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T_ - 1);
}
else if (t == -1)
{
t = T_ - 2;
}
if (u_in.rows() != scene_->get_num_controls())
{
ThrowPretty("Mismatching in size of control vector: " << u_in.rows() << " given, expected: " << scene_->get_num_controls());
}
if (x_in.rows() != scene_->get_num_positions() + scene_->get_num_velocities())
{
ThrowPretty("Mismatching in size of state vector vector: " << x_in.rows() << " given, expected: " << scene_->get_num_positions() + scene_->get_num_velocities());
}
X_.col(t) = x_in;
U_.col(t) = u_in;
// Update xdiff
X_diff_.col(t) = scene_->GetDynamicsSolver()->StateDelta(X_.col(t), X_star_.col(t));
// Update current state kinematics and costs
if (num_tasks > 0) UpdateTaskMaps(X_.col(t), U_.col(t), t);
// Set the corresponding KinematicResponse for KinematicTree in order to
// have Kinematics elements updated based in x_in.
scene_->GetKinematicTree().SetKinematicResponse(kinematic_solutions_[t]);
// Pass the corresponding number of relevant task kinematics to the TaskMaps
// via the PlanningProblem::UpdateMultipleTaskKinematics method. For now we
// support passing _two_ timesteps - this can be easily changed later on.
std::vector<std::shared_ptr<KinematicResponse>> kinematics_solutions{kinematic_solutions_[t]};
// If the current timestep is 0, pass the 0th timestep's response twice.
// Otherwise pass the (t-1)th response.
kinematics_solutions.emplace_back((t == 0) ? kinematic_solutions_[t] : kinematic_solutions_[t - 1]);
// Actually update the tasks' kinematics mappings.
PlanningProblem::UpdateMultipleTaskKinematics(kinematics_solutions);
// Simulate for tau
X_.col(t + 1) = scene_->GetDynamicsSolver()->Simulate(X_.col(t), U_.col(t), tau_);
// Clamp!
if (scene_->GetDynamicsSolver()->get_has_state_limits())
{
scene_->GetDynamicsSolver()->ClampToStateLimits(X_.col(t + 1));
}
// Update xdiff
X_diff_.col(t + 1) = scene_->GetDynamicsSolver()->StateDelta(X_.col(t + 1), X_star_.col(t + 1));
// Stochastic noise, if enabled
if (stochastic_matrices_specified_ && stochastic_updates_enabled_)
{
Eigen::VectorXd noise(scene_->get_num_positions() + scene_->get_num_velocities());
for (int i = 0; i < scene_->get_num_positions() + scene_->get_num_velocities(); ++i)
noise(i) = standard_normal_noise_(generator_);
Eigen::VectorXd control_dependent_noise = std::sqrt(scene_->GetDynamicsSolver()->get_dt()) * get_F(t) * noise;
for (int i = 0; i < scene_->get_num_positions() + scene_->get_num_velocities(); ++i)
noise(i) = standard_normal_noise_(generator_);
Eigen::VectorXd white_noise = std::sqrt(scene_->GetDynamicsSolver()->get_dt()) * CW_ * noise;
X_.col(t + 1) = X_.col(t + 1) + white_noise + control_dependent_noise;
}
// Twice would not be necessary if "UpdateTerminalState" is used by the solver.
// However, as this is a recent addition, this check and update is required for
// backwards compatibility.
if (num_tasks > 0 && t == T_ - 2)
{
UpdateTaskMaps(X_.col(t + 1), Eigen::VectorXd::Zero(scene_->get_num_controls()), t + 1);
}
++number_of_problem_updates_;
}
void DynamicTimeIndexedShootingProblem::Update(Eigen::VectorXdRefConst u, int t)
{
// We can only update t=0, ..., T-1 - the last state will be created from integrating u_{T-1} to get x_T
if (t >= (T_ - 1) || t < -1)
{
ThrowPretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T_ - 1);
}
else if (t == -1)
{
t = T_ - 2;
}
return Update(X_.col(t), u, t);
}
void DynamicTimeIndexedShootingProblem::UpdateTerminalState(Eigen::VectorXdRefConst x_in)
{
int t = T_ - 1;
if (x_in.rows() != scene_->get_num_positions() + scene_->get_num_velocities())
{
ThrowPretty("Mismatching in size of state vector vector: " << x_in.rows() << " given, expected: " << scene_->get_num_positions() + scene_->get_num_velocities());
}
X_.col(t) = x_in;
X_diff_.col(t) = scene_->GetDynamicsSolver()->StateDelta(X_.col(t), X_star_.col(t));
// Set the corresponding KinematicResponse for KinematicTree in order to
// have Kinematics elements updated based in x_in.
scene_->GetKinematicTree().SetKinematicResponse(kinematic_solutions_[t]);
// Pass the corresponding number of relevant task kinematics to the TaskMaps
// via the PlanningProblem::UpdateMultipleTaskKinematics method. For now we
// support passing _two_ timesteps - this can be easily changed later on.
std::vector<std::shared_ptr<KinematicResponse>> kinematics_solutions{kinematic_solutions_[t]};
// If the current timestep is 0, pass the 0th timestep's response twice.
// Otherwise pass the (t-1)th response.
kinematics_solutions.emplace_back((t == 0) ? kinematic_solutions_[t] : kinematic_solutions_[t - 1]);
// Actually update the tasks' kinematics mappings.
PlanningProblem::UpdateMultipleTaskKinematics(kinematics_solutions);
if (num_tasks > 0) UpdateTaskMaps(X_.col(t), Eigen::VectorXd::Zero(scene_->get_num_controls()), t);
++number_of_problem_updates_;
}
void DynamicTimeIndexedShootingProblem::UpdateTaskMaps(Eigen::VectorXdRefConst x, Eigen::VectorXdRefConst u, int t)
{
ValidateTimeIndex(t);
// Update the kinematic scene based on the configuration.
// NB: The KinematicTree only understands a certain format for the configuration (RPY)
// => As a result, we need to use GetPosition to potentially convert.
const Eigen::VectorXd q = scene_->GetDynamicsSolver()->GetPosition(x);
scene_->Update(q, static_cast<double>(t) * tau_);
// Reset the task space vector and its derivatives for the current timestep
Phi[t].SetZero(length_Phi);
if (flags_ & KIN_J)
{
dPhi_dx[t].setZero();
dPhi_du[t].setZero();
}
if (flags_ & KIN_H)
{
for (int i = 0; i < length_jacobian; ++i)
{
ddPhi_ddx[t](i).setZero();
ddPhi_ddu[t](i).setZero();
ddPhi_dxdu[t](i).setZero();
}
}
// Update all task-maps
for (int i = 0; i < num_tasks; ++i)
{
// Only update TaskMap if rho is not 0
if (tasks_[i]->is_used)
{
if (flags_ & KIN_H)
{
tasks_[i]->Update(x, u,
Phi[t].data.segment(tasks_[i]->start, tasks_[i]->length),
dPhi_dx[t].middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian),
dPhi_du[t].middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian),
ddPhi_ddx[t].segment(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian),
ddPhi_ddu[t].segment(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian),
ddPhi_dxdu[t].segment(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian));
}
else if (flags_ & KIN_J)
{
tasks_[i]->Update(x, u,
Phi[t].data.segment(tasks_[i]->start, tasks_[i]->length),
dPhi_dx[t].middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian),
dPhi_du[t].middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian));
}
else
{
tasks_[i]->Update(x, u, Phi[t].data.segment(tasks_[i]->start, tasks_[i]->length));
}
}
}
// Update costs (TimeIndexedTask)
if (flags_ & KIN_H)
{
cost.Update(Phi[t], dPhi_dx[t], dPhi_du[t], ddPhi_ddx[t], ddPhi_ddu[t], ddPhi_dxdu[t], t);
}
else if (flags_ & KIN_J)
{
cost.Update(Phi[t], dPhi_dx[t], dPhi_du[t], t);
}
else
{
cost.Update(Phi[t], t);
}
}
double DynamicTimeIndexedShootingProblem::GetStateCost(int t) const
{
ValidateTimeIndex(t);
const double state_cost = X_diff_.col(t).transpose() * Q_[t] * X_diff_.col(t);
const double general_cost = cost.ydiff[t].transpose() * cost.S[t] * cost.ydiff[t];
return state_cost + general_cost; // TODO: ct scaling
}
Eigen::VectorXd DynamicTimeIndexedShootingProblem::GetStateCostJacobian(int t)
{
ValidateTimeIndex(t);
// (NDX,NDX)^T * (NDX,NDX) * (NDX,1) * (1,1) => (NDX,1), TODO: We should change this to RowVectorXd format
dxdiff_[t] = scene_->GetDynamicsSolver()->dStateDelta(X_.col(t), X_star_.col(t), ArgumentPosition::ARG0);
state_cost_jacobian_[t].noalias() = dxdiff_[t].transpose() * Q_[t] * X_diff_.col(t) * 2.0;
// m => dimension of task maps, "length_jacobian"
// (m,NQ)^T * (m,m) * (m,1) * (1,1) => (NQ,1), TODO: We should change this to RowVectorXd format
general_cost_jacobian_[t].noalias() = cost.dPhi_dx[t].transpose() * cost.S[t] * cost.ydiff[t] * 2.0;
return state_cost_jacobian_[t] + general_cost_jacobian_[t];
}
Eigen::MatrixXd DynamicTimeIndexedShootingProblem::GetStateCostHessian(int t)
{
ValidateTimeIndex(t);
// State Cost
dxdiff_[t] = scene_->GetDynamicsSolver()->dStateDelta(X_.col(t), X_star_.col(t), ArgumentPosition::ARG0);
state_cost_hessian_[t].noalias() = dxdiff_[t].transpose() * Q_[t] * dxdiff_[t];
// For non-Euclidean spaces (i.e. on manifolds), there exists a second derivative of the state delta
if (scene_->get_has_quaternion_floating_base())
{
Eigen::RowVectorXd xdiffTQ = X_diff_.col(t).transpose() * Q_[t]; // (1*ndx)
Hessian ddxdiff = scene_->GetDynamicsSolver()->ddStateDelta(X_.col(t), X_star_.col(t), ArgumentPosition::ARG0);
for (int i = 0; i < ddxdiff.size(); ++i)
{
state_cost_hessian_[t].noalias() += xdiffTQ(i) * ddxdiff(i);
}
}
// General Cost
general_cost_hessian_[t].noalias() = cost.dPhi_dx[t].transpose() * cost.S[t] * cost.dPhi_dx[t];
// Contract task-map Hessians
if (flags_ & KIN_H)
{
Eigen::RowVectorXd ydiffTS = cost.ydiff[t].transpose() * cost.S[t]; // (1*m)
for (int i = 0; i < cost.length_jacobian; ++i) // length m
{
general_cost_hessian_[t].noalias() += ydiffTS(i) * cost.ddPhi_ddx[t](i);
}
}
return 2.0 * state_cost_hessian_[t] + 2.0 * general_cost_hessian_[t];
}
Eigen::MatrixXd DynamicTimeIndexedShootingProblem::GetControlCostHessian(int t)
{
if (t >= T_ - 1 || t < -1)
{
ThrowPretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T_ - 1);
}
else if (t == -1)
{
t = T_ - 2;
}
// This allows composition of multiple functions
// useful when you want to apply different cost functions to different controls
// if (parameters_.LossType == "L2")
control_cost_hessian_[t] = R_ + R_.transpose();
// Sparsity-related control Hessian
for (int iu = 0; iu < scene_->get_num_controls(); ++iu)
{
if (loss_type_ == ControlCostLossTermType::SmoothL1)
control_cost_hessian_[t](iu, iu) += smooth_l1_hessian(U_.col(t)[iu], l1_rate_(iu));
// if huber_rate is 0, huber is undefined
// this is a shortcut for disabling the loss
else if (loss_type_ == ControlCostLossTermType::Huber && huber_rate_(iu) != 0)
control_cost_hessian_[t](iu, iu) += huber_hessian(U_.col(t)[iu], huber_rate_(iu));
else if (loss_type_ == ControlCostLossTermType::PseudoHuber && huber_rate_(iu) != 0)
control_cost_hessian_[t](iu, iu) += pseudo_huber_hessian(U_.col(t)[iu], huber_rate_(iu));
}
return control_cost_weight_ * control_cost_hessian_[t];
}
double DynamicTimeIndexedShootingProblem::GetControlCost(int t) const
{
if (t >= T_ - 1 || t < -1)
{
ThrowPretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T_ - 1);
}
else if (t == -1)
{
t = T_ - 2;
}
double cost = 0;
// This allows composition of multiple functions
// useful when you want to apply different cost functions to different controls
// if (parameters_.LossType == "L2")
cost += U_.col(t).transpose() * R_ * U_.col(t);
// Sparsity-related control cost
for (int iu = 0; iu < scene_->get_num_controls(); ++iu)
{
// if (U_.col(t)[iu] >= control_limits.col(1)[iu])
// continue;
if (loss_type_ == ControlCostLossTermType::SmoothL1)
cost += smooth_l1_cost(U_.col(t)[iu], l1_rate_(iu));
// if huber_rate is 0, huber is undefined
// this is a shortcut for disabling the loss
else if (loss_type_ == ControlCostLossTermType::Huber && huber_rate_(iu) != 0)
cost += huber_cost(U_.col(t)[iu], huber_rate_(iu));
else if (loss_type_ == ControlCostLossTermType::PseudoHuber && huber_rate_(iu) != 0)
cost += pseudo_huber_cost(U_.col(t)[iu], huber_rate_(iu));
}
if (!std::isfinite(cost))
{
cost = 0.0; // Likely "inf" as u is too small.
}
return control_cost_weight_ * cost;
}
Eigen::VectorXd DynamicTimeIndexedShootingProblem::GetControlCostJacobian(int t)
{
if (t >= T_ - 1 || t < -1)
{
ThrowPretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T_ - 1);
}
else if (t == -1)
{
t = T_ - 2;
}
// This allows composition of multiple functions
// useful when you want to apply different cost functions to different controls
// if (parameters_.LossType == "L2")
// control_cost_jacobian_[t] += 2.0 * U_.col(t).transpose() * R_; // Assumes R is diagonal
control_cost_jacobian_[t].noalias() = R_ * U_.col(t) + R_.transpose() * U_.col(t);
// Sparsity-related control cost Jacobian
for (int iu = 0; iu < scene_->get_num_controls(); ++iu)
{
// if (U_.col(t)[iu] >= control_limits.col(1)[iu])
// continue;
if (loss_type_ == ControlCostLossTermType::SmoothL1)
control_cost_jacobian_[t](iu) += smooth_l1_jacobian(U_.col(t)[iu], l1_rate_(iu));
// if huber_rate is 0, huber is undefined
// this is a shortcut for disabling the loss
else if (loss_type_ == ControlCostLossTermType::Huber && huber_rate_(iu) != 0)
control_cost_jacobian_[t](iu) += huber_jacobian(U_.col(t)[iu], huber_rate_(iu));
else if (loss_type_ == ControlCostLossTermType::PseudoHuber && huber_rate_(iu) != 0)
control_cost_jacobian_[t](iu) += pseudo_huber_jacobian(U_.col(t)[iu], huber_rate_(iu));
}
return control_cost_weight_ * control_cost_jacobian_[t];
}
Eigen::MatrixXd DynamicTimeIndexedShootingProblem::get_F(int t) const
{
if (t >= T_ - 1 || t < -1)
{
ThrowPretty("Requested t=" << t << " out of range, needs to be 0 =< t < " << T_ - 1);
}
const int NX = scene_->get_num_positions() + scene_->get_num_velocities();
Eigen::MatrixXd F(NX, NX);
for (int i = 0; i < NX; ++i)
F.col(i) = Ci_[i] * U_.col(t);
return F;
}
// F[i]_u
const Eigen::MatrixXd& DynamicTimeIndexedShootingProblem::GetControlNoiseJacobian(int column_idx) const
{
if (column_idx < 0 || column_idx >= scene_->get_num_velocities())
ThrowPretty("Requested column_idx=" << column_idx << " out of range; needs to be 0 <= column_idx < " << scene_->get_num_velocities() - 1);
return Ci_[column_idx];
}
void DynamicTimeIndexedShootingProblem::EnableStochasticUpdates()
{
stochastic_updates_enabled_ = true;
}
void DynamicTimeIndexedShootingProblem::DisableStochasticUpdates()
{
stochastic_updates_enabled_ = false;
}
} // namespace exotica
| 36.515991 | 217 | 0.626766 | [
"vector",
"model"
] |
3ceef5e8aa2bdfee616b0a7ccb18899a55baf856 | 6,267 | cpp | C++ | be/src/exec/vectorized/sorting/sort_column.cpp | mchades/starrocks | d77512f9f3f24e251ebf4ff23c1fee29ee87c760 | [
"Zlib",
"Apache-2.0",
"MIT"
] | null | null | null | be/src/exec/vectorized/sorting/sort_column.cpp | mchades/starrocks | d77512f9f3f24e251ebf4ff23c1fee29ee87c760 | [
"Zlib",
"Apache-2.0",
"MIT"
] | null | null | null | be/src/exec/vectorized/sorting/sort_column.cpp | mchades/starrocks | d77512f9f3f24e251ebf4ff23c1fee29ee87c760 | [
"Zlib",
"Apache-2.0",
"MIT"
] | null | null | null | // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "column/array_column.h"
#include "column/column.h"
#include "column/column_visitor_adapter.h"
#include "column/const_column.h"
#include "column/json_column.h"
#include "exec/vectorized/sorting/sort_helper.h"
#include "exec/vectorized/sorting/sort_permute.h"
#include "exec/vectorized/sorting/sorting.h"
namespace starrocks::vectorized {
class ColumnSorter final : public ColumnVisitorAdapter<ColumnSorter> {
public:
explicit ColumnSorter(const bool& cancel, bool is_asc_order, bool is_null_first, SmallPermutation& permutation,
Tie& tie, std::pair<int, int> range, bool build_tie)
: ColumnVisitorAdapter(this),
_cancel(cancel),
_is_asc_order(is_asc_order),
_is_null_first(is_null_first),
_permutation(permutation),
_tie(tie),
_range(range),
_build_tie(build_tie) {}
Status do_visit(const vectorized::NullableColumn& column) {
return sort_and_tie_helper_nullable(_cancel, &column, _is_asc_order, _is_null_first, _permutation, _tie, _range,
_build_tie);
}
Status do_visit(const vectorized::ConstColumn& column) {
// noop
return Status::OK();
}
Status do_visit(const vectorized::ArrayColumn& column) {
auto cmp = [&](const SmallPermuteItem& lhs, const SmallPermuteItem& rhs) {
return column.compare_at(lhs.index_in_chunk, rhs.index_in_chunk, column, _is_null_first ? -1 : 1);
};
return sort_and_tie_helper(_cancel, &column, _is_asc_order, _permutation, _tie, cmp, _range, _build_tie);
}
Status do_visit(const vectorized::BinaryColumn& column) {
DCHECK_GE(column.size(), _permutation.size());
using ItemType = InlinePermuteItem<Slice>;
auto cmp = [&](const ItemType& lhs, const ItemType& rhs) -> int {
return lhs.inline_value.compare(rhs.inline_value);
};
auto inlined = create_inline_permutation<Slice>(_permutation, column.get_data());
RETURN_IF_ERROR(sort_and_tie_helper(_cancel, &column, _is_asc_order, inlined, _tie, cmp, _range, _build_tie));
restore_inline_permutation(inlined, _permutation);
return Status::OK();
}
template <typename T>
Status do_visit(const vectorized::FixedLengthColumnBase<T>& column) {
DCHECK_GE(column.size(), _permutation.size());
using ItemType = InlinePermuteItem<T>;
auto cmp = [&](const ItemType& lhs, const ItemType& rhs) {
return SorterComparator<T>::compare(lhs.inline_value, rhs.inline_value);
};
auto inlined = create_inline_permutation<T>(_permutation, column.get_data());
RETURN_IF_ERROR(sort_and_tie_helper(_cancel, &column, _is_asc_order, inlined, _tie, cmp, _range, _build_tie));
restore_inline_permutation(inlined, _permutation);
return Status::OK();
}
template <typename T>
Status do_visit(const vectorized::ObjectColumn<T>& column) {
DCHECK(false) << "not support object column sort_and_tie";
return Status::NotSupported("not support object column sort_and_tie");
}
Status do_visit(const vectorized::JsonColumn& column) {
auto cmp = [&](const SmallPermuteItem& lhs, const SmallPermuteItem& rhs) {
return column.get_object(lhs.index_in_chunk)->compare(*column.get_object(rhs.index_in_chunk));
};
return sort_and_tie_helper(_cancel, &column, _is_asc_order, _permutation, _tie, cmp, _range, _build_tie);
}
private:
const bool& _cancel;
bool _is_asc_order;
bool _is_null_first;
SmallPermutation& _permutation;
Tie& _tie;
std::pair<int, int> _range;
bool _build_tie;
};
Status sort_and_tie_column(const bool& cancel, const ColumnPtr column, bool is_asc_order, bool is_null_first,
SmallPermutation& permutation, Tie& tie, std::pair<int, int> range, bool build_tie) {
ColumnSorter column_sorter(cancel, is_asc_order, is_null_first, permutation, tie, range, build_tie);
return column->accept(&column_sorter);
}
Status sort_and_tie_columns(const bool& cancel, const Columns& columns, const std::vector<int>& sort_orders,
const std::vector<int>& null_firsts, Permutation* permutation) {
if (columns.size() < 1) {
return Status::OK();
}
size_t num_rows = columns[0]->size();
Tie tie(num_rows, 1);
std::pair<int, int> range{0, num_rows};
SmallPermutation small_perm = create_small_permutation(num_rows);
for (int col_index = 0; col_index < columns.size(); col_index++) {
ColumnPtr column = columns[col_index];
bool is_asc_order = (sort_orders[col_index] == 1);
bool is_null_first = is_asc_order ? (null_firsts[col_index] == -1) : (null_firsts[col_index] == 1);
bool build_tie = col_index != columns.size() - 1;
RETURN_IF_ERROR(
sort_and_tie_column(cancel, column, is_asc_order, is_null_first, small_perm, tie, range, build_tie));
}
restore_small_permutation(small_perm, *permutation);
return Status::OK();
}
Status sort_and_tie_columns(const bool& cancel, const Columns& columns, const std::vector<int>& sort_orders,
const std::vector<int>& null_firsts, SmallPermutation* small_perm) {
if (columns.size() < 1) {
return Status::OK();
}
size_t num_rows = columns[0]->size();
DCHECK_EQ(num_rows, small_perm->size());
Tie tie(num_rows, 1);
std::pair<int, int> range{0, num_rows};
for (int col_index = 0; col_index < columns.size(); col_index++) {
ColumnPtr column = columns[col_index];
bool is_asc_order = (sort_orders[col_index] == 1);
bool is_null_first = is_asc_order ? (null_firsts[col_index] == -1) : (null_firsts[col_index] == 1);
bool build_tie = col_index != columns.size() - 1;
RETURN_IF_ERROR(
sort_and_tie_column(cancel, column, is_asc_order, is_null_first, *small_perm, tie, range, build_tie));
}
return Status::OK();
}
} // namespace starrocks::vectorized | 41.230263 | 120 | 0.667305 | [
"object",
"vector"
] |
3cf14f6a8540b55cdc6ef74768ca2774e84fe136 | 6,303 | cpp | C++ | agg24/src/ctrl/agg_cbox_ctrl.cpp | pierre-haessig/matplotlib | 0d945044ca3fbf98cad55912584ef80911f330c6 | [
"MIT",
"PSF-2.0",
"BSD-3-Clause"
] | 428 | 2015-01-05T17:13:54.000Z | 2022-03-31T08:25:47.000Z | agg24/src/ctrl/agg_cbox_ctrl.cpp | pierre-haessig/matplotlib | 0d945044ca3fbf98cad55912584ef80911f330c6 | [
"MIT",
"PSF-2.0",
"BSD-3-Clause"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | agg24/src/ctrl/agg_cbox_ctrl.cpp | pierre-haessig/matplotlib | 0d945044ca3fbf98cad55912584ef80911f330c6 | [
"MIT",
"PSF-2.0",
"BSD-3-Clause"
] | 90 | 2015-05-19T04:56:46.000Z | 2022-03-26T16:42:50.000Z | //----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// classes rbox_ctrl_impl, rbox_ctrl
//
//----------------------------------------------------------------------------
#include <string.h>
#include "ctrl/agg_cbox_ctrl.h"
namespace agg
{
//------------------------------------------------------------------------
cbox_ctrl_impl::cbox_ctrl_impl(double x, double y,
const char* l,
bool flip_y) :
ctrl(x, y, x + 9.0 * 1.5, y + 9.0 * 1.5, flip_y),
m_text_thickness(1.5),
m_text_height(9.0),
m_text_width(0.0),
m_status(false),
m_text_poly(m_text)
{
label(l);
}
//------------------------------------------------------------------------
void cbox_ctrl_impl::text_size(double h, double w)
{
m_text_width = w;
m_text_height = h;
}
//------------------------------------------------------------------------
void cbox_ctrl_impl::label(const char* l)
{
unsigned len = strlen(l);
if(len > 127) len = 127;
memcpy(m_label, l, len);
m_label[len] = 0;
}
//------------------------------------------------------------------------
bool cbox_ctrl_impl::on_mouse_button_down(double x, double y)
{
inverse_transform_xy(&x, &y);
if(x >= m_x1 && y >= m_y1 && x <= m_x2 && y <= m_y2)
{
m_status = !m_status;
return true;
}
return false;
}
//------------------------------------------------------------------------
bool cbox_ctrl_impl::on_mouse_move(double, double, bool)
{
return false;
}
//------------------------------------------------------------------------
bool cbox_ctrl_impl::in_rect(double x, double y) const
{
inverse_transform_xy(&x, &y);
return x >= m_x1 && y >= m_y1 && x <= m_x2 && y <= m_y2;
}
//------------------------------------------------------------------------
bool cbox_ctrl_impl::on_mouse_button_up(double, double)
{
return false;
}
//------------------------------------------------------------------------
bool cbox_ctrl_impl::on_arrow_keys(bool, bool, bool, bool)
{
return false;
}
//------------------------------------------------------------------------
void cbox_ctrl_impl::rewind(unsigned idx)
{
m_idx = idx;
double d2;
double t;
switch(idx)
{
default:
case 0: // Border
m_vertex = 0;
m_vx[0] = m_x1;
m_vy[0] = m_y1;
m_vx[1] = m_x2;
m_vy[1] = m_y1;
m_vx[2] = m_x2;
m_vy[2] = m_y2;
m_vx[3] = m_x1;
m_vy[3] = m_y2;
m_vx[4] = m_x1 + m_text_thickness;
m_vy[4] = m_y1 + m_text_thickness;
m_vx[5] = m_x1 + m_text_thickness;
m_vy[5] = m_y2 - m_text_thickness;
m_vx[6] = m_x2 - m_text_thickness;
m_vy[6] = m_y2 - m_text_thickness;
m_vx[7] = m_x2 - m_text_thickness;
m_vy[7] = m_y1 + m_text_thickness;
break;
case 1: // Text
m_text.text(m_label);
m_text.start_point(m_x1 + m_text_height * 2.0, m_y1 + m_text_height / 5.0);
m_text.size(m_text_height, m_text_width);
m_text_poly.width(m_text_thickness);
m_text_poly.line_join(round_join);
m_text_poly.line_cap(round_cap);
m_text_poly.rewind(0);
break;
case 2: // Active item
m_vertex = 0;
d2 = (m_y2 - m_y1) / 2.0;
t = m_text_thickness * 1.5;
m_vx[0] = m_x1 + m_text_thickness;
m_vy[0] = m_y1 + m_text_thickness;
m_vx[1] = m_x1 + d2;
m_vy[1] = m_y1 + d2 - t;
m_vx[2] = m_x2 - m_text_thickness;
m_vy[2] = m_y1 + m_text_thickness;
m_vx[3] = m_x1 + d2 + t;
m_vy[3] = m_y1 + d2;
m_vx[4] = m_x2 - m_text_thickness;
m_vy[4] = m_y2 - m_text_thickness;
m_vx[5] = m_x1 + d2;
m_vy[5] = m_y1 + d2 + t;
m_vx[6] = m_x1 + m_text_thickness;
m_vy[6] = m_y2 - m_text_thickness;
m_vx[7] = m_x1 + d2 - t;
m_vy[7] = m_y1 + d2;
break;
}
}
//------------------------------------------------------------------------
unsigned cbox_ctrl_impl::vertex(double* x, double* y)
{
unsigned cmd = path_cmd_line_to;
switch(m_idx)
{
case 0:
if(m_vertex == 0 || m_vertex == 4) cmd = path_cmd_move_to;
if(m_vertex >= 8) cmd = path_cmd_stop;
*x = m_vx[m_vertex];
*y = m_vy[m_vertex];
m_vertex++;
break;
case 1:
cmd = m_text_poly.vertex(x, y);
break;
case 2:
if(m_status)
{
if(m_vertex == 0) cmd = path_cmd_move_to;
if(m_vertex >= 8) cmd = path_cmd_stop;
*x = m_vx[m_vertex];
*y = m_vy[m_vertex];
m_vertex++;
}
else
{
cmd = path_cmd_stop;
}
break;
default:
cmd = path_cmd_stop;
break;
}
if(!is_stop(cmd))
{
transform_xy(x, y);
}
return cmd;
}
}
| 29.316279 | 87 | 0.400762 | [
"geometry"
] |
3cf1723767bda885b05bb14bedbdefd8092f3e1f | 11,688 | cpp | C++ | src/MPC.cpp | john-reilly/Self_Driving_Car_Nano_Degree_Term_2_Project_5_MPC | 8e21dad3e94fedcd86df97154e3df9159a0edad8 | [
"MIT"
] | null | null | null | src/MPC.cpp | john-reilly/Self_Driving_Car_Nano_Degree_Term_2_Project_5_MPC | 8e21dad3e94fedcd86df97154e3df9159a0edad8 | [
"MIT"
] | null | null | null | src/MPC.cpp | john-reilly/Self_Driving_Car_Nano_Degree_Term_2_Project_5_MPC | 8e21dad3e94fedcd86df97154e3df9159a0edad8 | [
"MIT"
] | null | null | null |
#include "MPC.h"
#include <cppad/cppad.hpp>
#include <cppad/ipopt/solve.hpp>
#include <iostream>
#include <string>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
using CppAD::AD;
using Eigen::VectorXd;
/**
* TODO: Set the timestep length and duration
*/
//from Q+A video
size_t N = 10;//10;
double dt = 0.05; //0.1
// This value assumes the model presented in the classroom is used.
//
// It was obtained by measuring the radius formed by running the vehicle in the
// simulator around in a circle with a constant steering angle and velocity on
// a flat terrain.
//
// Lf was tuned until the the radius formed by the simulating the model
// presented in the classroom matched the previous radius.
//
// This is the length from front to CoG that has a similar radius.
const double Lf = 2.67;
//from Q+A video
double ref_cte = 0 ;
double ref_epsi = 0 ;
double ref_v = 100 ;
size_t x_start = 0;
size_t y_start = x_start + N;
size_t psi_start = y_start + N;
size_t v_start = psi_start + N;
size_t cte_start = v_start + N;
size_t epsi_start = cte_start + N;
size_t delta_start = epsi_start + N;
size_t a_start = delta_start + N -1;
//end Q+A video
class FG_eval {
public:
// Fitted polynomial coefficients
VectorXd coeffs;
FG_eval(VectorXd coeffs) { this->coeffs = coeffs; }
typedef CPPAD_TESTVECTOR(AD<double>) ADvector;
void operator()(ADvector& fg, const ADvector& vars) {
/**
* TODO: implement MPC
* `fg` is a vector of the cost constraints, `vars` is a vector of variable
* values (state & actuators)
* NOTE: You'll probably go back and forth between this function and
* the Solver function below.
*/
//from Q+A video
fg[0] = 0;
////////////////
// This is the cost variables for below listed here for convience
//reference state costs
// I am using Q+ levels then doubleing and then halving them on first set of tests
double cte_ref_state_cost = 1000 ; //1000//4000 // 1000 //2000 in Q+A
double epsi_ref_state_cost = 1000 ;//1000 //4000 //2000 in Q+A
double v_ref_state_cots = 1 ; //1 in Q+A
//Acuators Cost
double delta_cost = 2500 ;//50 in Q+A
double a_cost = 150 ; //50 in Q+A
//Acuators Cost for time ahead t + 1
double delta_plus_cost = 10000;//1//250000 // 200 in Q+A
double a_plus_cost = 150; //1000;//1//5000 // 10 in Q+A
for(int i = 0; i < N ; i++)
{//2000 below is high weight
fg[0] += cte_ref_state_cost*CppAD::pow(vars[cte_start + i] - ref_cte,2);//was 2000
fg[0] += epsi_ref_state_cost*CppAD::pow(vars[epsi_start + i] - ref_epsi,2);//was 2000
fg[0] += v_ref_state_cots * CppAD::pow(vars[v_start + i] - ref_v,2); //had 1 instead of i
}
for(int i = 0; i < N -1; i++)
{
fg[0] += delta_cost * CppAD::pow(vars[delta_start + i],2);
fg[0] += a_cost * CppAD::pow(vars[a_start + i],2);
}
for(int i = 0; i < N -2; i++)
{
fg[0] += delta_plus_cost * CppAD::pow(vars[delta_start + i + 1] - vars[delta_start + i] , 2);//200
fg[0] += a_plus_cost * CppAD::pow(vars[a_start + i + 1] - vars[a_start + i],2);//10
}
//constraints
fg[1 + x_start] = vars[x_start];
fg[1 + y_start] = vars[y_start];
fg[1 + psi_start] = vars[psi_start];
fg[1 + v_start] = vars[v_start];
fg[1 + cte_start] = vars[cte_start];
fg[1 + epsi_start] = vars[epsi_start];
//for rest of constraints
for(int i = 0; i < N -1;i++)
{
AD<double> x1 = vars[x_start + i + 1];
AD<double> y1 = vars[y_start + i + 1];
AD<double> psi1 = vars[psi_start + i + 1];
AD<double> v1 = vars[v_start + i + 1];
AD<double> cte1 = vars[cte_start + i + 1];
AD<double> epsi1 = vars[epsi_start + i + 1];
// at time t
AD<double> x0 = vars[x_start + i];
AD<double> y0 = vars[y_start + i];
AD<double> psi0 = vars[psi_start + i];
AD<double> v0 = vars[v_start + i];
AD<double> cte0 = vars[cte_start + i];
AD<double> epsi0 = vars[epsi_start + i];
AD<double> delta0 = vars[delta_start + i];
AD<double> a0 = vars[a_start + i];
AD<double> f0 = coeffs[0] + coeffs[1] * x0 + coeffs[2] * x0 * x0 + coeffs[3] * x0 * x0 * x0 ;
// changing i to one as from advice from knowledge
AD<double> psides0 = CppAD::atan(3*coeffs[3] * x0 * x0 + 2 * coeffs[2] * x0 + coeffs[1]);
//hmmm not sure about above 2 lines
//changing 2 for 1 to try to fix index ewrror next 5 lines
fg[2 + x_start + i] = x1 - (x0 + v0 * CppAD::cos(psi0) * dt);
fg[2 + y_start + i] = y1 - (y0 + v0 * CppAD::sin(psi0) * dt);
fg[2 + psi_start + i] = psi1 - (psi0 - v0 * delta0/Lf * dt);
fg[2 + v_start + i] = v1 - (v0 + a0 *dt);
//fg[2 + cte_start + i ] = epsi1 - ((psi0 - psides0) - v0 * delta0 / Lf * dt);//wrong!!
fg[2 + cte_start + i ] = cte1 - ((f0 - y0) +(v0 * CppAD::sin(epsi0) * dt));
//am I missing this
fg[2 + epsi_start + i] = epsi1 - ((psi0 - psides0) - v0 / Lf * delta0 * dt);
}
}
};
//
// MPC class definition implementation.
//
MPC::MPC() {}
MPC::~MPC() {}
//this line is different in Q+A and might be casuing the Solve index problem also changed header file
//changing back vars seems emptry once solve working
//std::vector<double> MPC::Solve(const VectorXd &state, const VectorXd &coeffs) {
std::vector<double> MPC::Solve(Eigen::VectorXd state, Eigen::VectorXd coeffs){
std::cout << "line 137 in MPC SOLVE" << std::endl ;
bool ok = true;
typedef CPPAD_TESTVECTOR(double) Dvector;
//from Q+A
double x = state[0];
double y = state[1];
double psi = state[2];
double v = state[3];
double cte = state[4];
double epsi = state[5];
std::cout << "line 148 in MPC SOLVE" << std::endl ;
//end Q+A
/**
* TODO: Set the number of model variables (includes both states and inputs).
* For example: If the state is a 4 element vector, the actuators is a 2
* element vector and there are 10 timesteps. The number of variables is:
* 4 * 10 + 2 * 9
*///Q+A video
size_t n_vars = N * 6 + (N -1) *2; //from Q+A//0;
/**
* TODO: Set the number of constraints
*/
size_t n_constraints = N * 6;//from Q+A//0;
std::cout << "line 161 in MPC SOLVE" << std::endl ;
// Initial value of the independent variables.
// SHOULD BE 0 besides initial state.
Dvector vars(n_vars);
for (int i = 0; i < n_vars; i++) {//aaarrrgggghhh I had ++i instead of i++ gave wierd index error
vars[i] = 0;
}
std::cout << "line 168 in MPC SOLVE" << std::endl ;
Dvector vars_lowerbound(n_vars);
Dvector vars_upperbound(n_vars);
/**
* TODO: Set lower and upper limits for variables.
*/
std::cout << "line 161 in MPC SOLVE" << std::endl ;
//from Q+A
for(int i = 0; i<delta_start;i++)
{
vars_lowerbound[i] = -1.0e19;
vars_upperbound[i] = 1.0e19;
}
std::cout << "line 181 in MPC SOLVE" << std::endl ;
//also from Q+A
//delta -25 to 25 degrees values in radians
for(int i = delta_start; i < a_start;i++)
{
vars_lowerbound[i] = -0.436332 * Lf;
vars_upperbound[i] = 0.436332 * Lf;
}
std::cout << "line 189 in MPC SOLVE" << std::endl ;
//acclereration.deceleration upper and lower limit
for(int i = a_start; i< n_vars; i++)
{
vars_lowerbound[i] = -1;
vars_upperbound[i] = 1;
}
std::cout << "line 196 in MPC SOLVE" << std::endl ;
// Lower and upper limits for the constraints
// Should be 0 besides initial state.
Dvector constraints_lowerbound(n_constraints);
Dvector constraints_upperbound(n_constraints);
std::cout << "line 201 in MPC SOLVE" << std::endl ;
for (int i = 0; i < n_constraints; i++) { // ++i instead of i++ again argggghhhh
constraints_lowerbound[i] = 0;
constraints_upperbound[i] = 0;
}
std::cout << "line 206 in MPC SOLVE" << std::endl ;
//also from Q+A
constraints_lowerbound[x_start] = x;
constraints_lowerbound[y_start] = y;
constraints_lowerbound[psi_start] = psi;
constraints_lowerbound[v_start] = v;
constraints_lowerbound[cte_start] = cte;
constraints_lowerbound[epsi_start] = epsi;
std::cout << "line 214 in MPC SOLVE" << std::endl ;
constraints_upperbound[x_start] = x;
constraints_upperbound[y_start] = y;
constraints_upperbound[psi_start] = psi;
constraints_upperbound[v_start] = v;
constraints_upperbound[cte_start] = cte;
constraints_upperbound[epsi_start] = epsi;
std::cout << "line 222 in MPC SOLVE" << std::endl ;
// object that computes objective and constraints
FG_eval fg_eval(coeffs);
std::cout << "line 226 in MPC SOLVE" << std::endl ;
// NOTE: You don't have to worry about these options
// options for IPOPT solver
std::string options;
// Uncomment this if you'd like more print information
options += "Integer print_level 0\n";
// NOTE: Setting sparse to true allows the solver to take advantage
// of sparse routines, this makes the computation MUCH FASTER. If you can
// uncomment 1 of these and see if it makes a difference or not but if you
// uncomment both the computation time should go up in orders of magnitude.
options += "Sparse true forward\n";
options += "Sparse true reverse\n";
// NOTE: Currently the solver has a maximum time limit of 0.5 seconds.
// Change this as you see fit.
options += "Numeric max_cpu_time 0.5\n"; //maybe change in relation to N can get too long
std::cout << "line 241 in MPC SOLVE" << std::endl ;
// place to return solution
CppAD::ipopt::solve_result<Dvector> solution;
std::cout << "line 244 in MPC SOLVE" << std::endl ;
// solve the problem
//cout for all paramenteres here to try and find one causeing index problem
std::cout << "options size:" << options.size() << std::endl;
std::cout << "vars size :" << vars.size() << std::endl;
std::cout << "vars_lowerbound size:" << vars_lowerbound.size() << std::endl;
std::cout << "vars upperbound size :" << vars_upperbound.size() << std::endl;
std::cout << "constraints_lowerbound size :" << constraints_lowerbound.size() << std::endl;
std::cout << "constraints_upperbound size :" << constraints_upperbound.size() << std::endl;
//std::cout << "fgeval size :" << fg_eval.size() << std::endl;//no size() for this made error.....
//std::cout << "solution size :" << solution.size() << std::endl;//no size() for this
CppAD::ipopt::solve<Dvector, FG_eval>(
options, vars, vars_lowerbound, vars_upperbound, constraints_lowerbound,
constraints_upperbound, fg_eval, solution);
std::cout << "line 249 in MPC SOLVE" << std::endl ;
// Check some of the solution values
ok &= solution.status == CppAD::ipopt::solve_result<Dvector>::success;
std::cout << "line 252 in MPC SOLVE" << std::endl ;
// Cost
auto cost = solution.obj_value;
std::cout << "Cost " << cost << std::endl;
/**
* TODO: Return the first actuator values. The variables can be accessed with
* `solution.x[i]`.
*
* {...} is shorthand for creating a vector, so auto x1 = {1.0,2.0}
* creates a 2 element double vector.
*/
//from Q+A video
std::vector<double> result;
result.push_back(solution.x[delta_start]);
result.push_back(solution.x[a_start]);
// i want to check solution here
// hmmm solution is comming back all zeros
for(int i = 0; i < N-1; i ++)
{
std::cout << "Solution:" << i << " " << solution.x[ i] << std::endl ;
}
for(int i = 0; i < N-1; i ++)
{
result.push_back(solution.x[x_start + i + 1]);
result.push_back(solution.x[y_start + i + 1]);
}
return result; //{};
}
| 33.586207 | 104 | 0.622091 | [
"object",
"vector",
"model"
] |
3cf360f9c9e626e275af152540522b93eb2179b6 | 10,925 | cpp | C++ | routing/arouterex/src/grdr/IntraCellRouter.cpp | rbarzic/MAGICAL | 0510550b263913f8c62f46662a9dfa2ae94d2386 | [
"BSD-3-Clause"
] | null | null | null | routing/arouterex/src/grdr/IntraCellRouter.cpp | rbarzic/MAGICAL | 0510550b263913f8c62f46662a9dfa2ae94d2386 | [
"BSD-3-Clause"
] | null | null | null | routing/arouterex/src/grdr/IntraCellRouter.cpp | rbarzic/MAGICAL | 0510550b263913f8c62f46662a9dfa2ae94d2386 | [
"BSD-3-Clause"
] | null | null | null | #include "IntraCellRouter.h"
#include "util/ManSegment.h"
PROJECT_NAMESPACE_BEGIN
bool IntraCellRouter::intraCellRouteCMOS(IndexType gateTermIdx, IndexType drainTermIdx, IndexType sourceTermIdx)
{
auto &gate = _db.terminal(gateTermIdx);
auto &drain = _db.terminal(drainTermIdx);
auto &source = _db.terminal(sourceTermIdx);
Assert(gate.pinArray().size() > 0);
Assert(drain.pinArray().size() > 0);
Assert(source.pinArray().size() > 0);
// Assume drain and source are on M1 and gate is on PO
// Get the spacing for M1
WRN("%s: use min spacing for intra cell generation, should use EOL? \n", __FUNCTION__);
LocType m1Spacing = std::max(_instr.metalMinSpacing(1), _instr.cutConservativeSpacing(1)); // Pick the larger one: metal or cut spacing requirement
// sort the pins by xlo
auto func = [&] (IndexType lhs, IndexType rhs)
{
return _db.grDB().pin(lhs).shapeRects().front().xLo() < _db.grDB().pin(rhs).shapeRects().front().xLo();
};
std::sort(source.pinArray().begin(), source.pinArray().end(), func);
std::sort(drain.pinArray().begin(), drain.pinArray().end(), func);
std::sort(gate.pinArray().begin(), gate.pinArray().end(), func);
// Source: make it go up
Assert(_db.grDB().pin(source.pinArray().front()).shapeRects().size() == 1 );
const auto & beginRectSource = _db.grDB().pin(source.pinArray().front()).shapeRects().front();
const auto & endRectSource = _db.grDB().pin(source.pinArray().back()).shapeRects().front();
Assert(beginRectSource.yLo() == endRectSource.yLo());
Assert(beginRectSource.yHi() == endRectSource.yHi());
Assert(beginRectSource.xLen() == endRectSource.xLen());
LocType beginX = beginRectSource.xLo();
LocType endX = endRectSource.xHi();
LocType rectYHi = beginRectSource.yHi();
LocType segmentYLo = beginRectSource.yHi() + m1Spacing; //The y coordinate for the horizontal segment
LocType segmentWidth = beginRectSource.xLen();
// Add the horizontal segment (m1? maybe M2)
source.addIntraBox(Box<LocType>(beginX, segmentYLo, endX, segmentYLo + segmentWidth), 2, true, true);
source.setPrimarySearchPointShape(0);
// primary search point set to be the center
source.setPrimarySearchPoint(NetNodeLoc(source.intraCellRoute().back().box().center(), 1));
for (IndexType pinIdx : source.pinArray())
{
const auto & rect = _db.grDB().pin(pinIdx).shapeRects().front();
beginX = rect.xLo();
endX = rect.xHi();
source.addIntraBox(Box<LocType>(beginX, rectYHi, endX, segmentYLo), 2, false, true);
}
// Gate: make it above the source
Assert(_db.grDB().pin(gate.pinArray().front()).shapeRects().size() == 1 );
const auto & beginRectGate = _db.grDB().pin(gate.pinArray().front()).shapeRects().front();
const auto & endRectGate = _db.grDB().pin(gate.pinArray().back()).shapeRects().front();
Assert(beginRectGate.yLo() == endRectGate.yLo());
Assert(beginRectGate.yHi() == endRectGate.yHi());
Assert(beginRectGate.xLen() == endRectGate.xLen());
segmentYLo = segmentYLo + segmentWidth + m1Spacing; // Determined by the location of the source segment
beginX = beginRectGate.xLo();
endX = endRectGate.xHi();
rectYHi = beginRectGate.yHi();
segmentWidth = beginRectGate.xLen();
// Add the horizontal segment (PO)
gate.addIntraBox(Box<LocType>(beginX, segmentYLo, endX, segmentYLo + segmentWidth), 0, true, true);
// primary search point set to be the center
gate.setPrimarySearchPoint(NetNodeLoc(gate.intraCellRoute().back().box().center(), 0));
source.setPrimarySearchPointShape(0);
for (IndexType pinIdx : gate.pinArray())
{
const auto & rect = _db.grDB().pin(pinIdx).shapeRects().front();
beginX = rect.xLo();
endX = rect.xHi();
gate.addIntraBox(Box<LocType>(beginX, rectYHi, endX, segmentYLo), 0, false, true);
}
// Drain: make it go down
Assert(_db.grDB().pin(drain.pinArray().front()).shapeRects().size() == 1 );
const auto & beginRectDrain = _db.grDB().pin(drain.pinArray().front()).shapeRects().front();
const auto & endRectDrain = _db.grDB().pin(drain.pinArray().back()).shapeRects().front();
Assert(beginRectDrain.yLo() == endRectDrain.yLo());
Assert(beginRectDrain.yHi() == endRectDrain.yHi());
Assert(beginRectDrain.xLen() == endRectDrain.xLen());
beginX = beginRectDrain.xLo();
endX = endRectDrain.xHi();
LocType rectYLo = beginRectDrain.yLo();
LocType segmentYHi = rectYLo - m1Spacing;
segmentWidth = beginRectDrain.xLen();
// Add the horizontal segment (m1? maybe M2)
drain.addIntraBox(Box<LocType>(beginX, segmentYHi - segmentWidth, endX, segmentYHi), 2, true, true);
// primary search point set to be the center
drain.setPrimarySearchPoint(NetNodeLoc(drain.intraCellRoute().back().box().center(), 1));
source.setPrimarySearchPointShape(0);
for (IndexType pinIdx : drain.pinArray())
{
const auto & rect = _db.grDB().pin(pinIdx).shapeRects().front();
beginX = rect.xLo();
endX = rect.xHi();
drain.addIntraBox(Box<LocType>(beginX, segmentYHi, endX, rect.yLo()), 2, false, true);
}
// Process the pin shape and so on
return true;
}
bool IntraCellRouter::intraCellRouteDEFAULT(IndexType terminalIdx)
{
auto &term = _db.terminal(terminalIdx);
Assert(term.numPins() == 1 );
auto &pin = _db.grDB().pin(term.pin(0)); // should be only one pin in the terminal
IndexType shapeIdx = pin.defaultShapeIdx();
// Flag the shape in the pin as has been included in terminal
pin.setIncludeTermFlag(shapeIdx, true);
// add this shape in terminal
term.addIntraBox(pin.shapeRects().at(shapeIdx), DRUtil::routeLayer2AllLayer(pin.layer()), true, false);
// Set the search point
// Align with grid
/// TODO: replace hard-coded number
term.setPrimarySearchPoint(NetNodeLoc(_instr.alignGrid(pin.loc()), pin.layer()));
term.setPrimarySearchPointShape(shapeIdx);
// Add all other pin shapes
for (IndexType idx = 0; idx < pin.shapeRects().size(); ++idx)
{
if (idx == shapeIdx)
{
break;
}
term.addIntraBox(pin.shapeRects().at(idx), DRUtil::routeLayer2AllLayer(pin.layer()), true, false);
}
// Slice the search points
for (IndexType idx = 0; idx < term.numIntraShapes(); ++idx)
{
slicePinShape(terminalIdx, idx);
}
return true;
}
bool IntraCellRouter::slicePinShape(IndexType terminalIdx, IndexType shapeIdx)
{
auto &term = _db.terminal(terminalIdx);
//auto &ptArray = _db.drDB().processPinArray().at(pinIdx).searchPoints(); //< Store the pts here
IndexType routeLayer = DRUtil::allLayer2RouteLayer(term.intraShape(term.primarySearchPointShape()).layer());
AssertMsg(routeLayer < _instr.numRouteLayers() - 1, "Layer %d exceed the number of layers %d \n", routeLayer, _instr.numRouteLayers());
RouteDirType higherLayerRouteDir = _instr.routeDirection(routeLayer + 1);
Assert(higherLayerRouteDir == RouteDirType::HORIZONTAL || higherLayerRouteDir == RouteDirType::VERTICAL);
LocType lowerTrackWidth = _instr.metalMinSpacing(routeLayer) + _instr.metalMinWidth(routeLayer);
//LocType higherTrackWidth = _instr.metalMinSpacing(routeLayer + 1) + _instr.metalMinWidth(routeLayer + 1);
//LocType lowerTrackOffset = _db.drDB().roughGrid().trackOffset(routeLayer);
/*
LocType higherTrackOffset = 0;
if (higherLayerRouteDir == RouteDirType::HORIZONTAL)
{
higherTrackOffset = (_db.grDB().dieLL().y() + (higherTrackWidth) / 2);
}
else
{
higherTrackOffset = (_db.grDB().dieLL().x() + (higherTrackWidth) / 2);
}
*/
// Slices the shapes by the tracks of the higher layer
std::vector<ManSegment<LocType>> hitpoints; //< A vertical or horizontal interval
auto rect = term.intraCellRoute().at(shapeIdx).box();
/*
if (higherLayerRouteDir == RouteDirType::HORIZONTAL)
{
LocType startY = ((rect.yLo() - higherTrackOffset) / higherTrackWidth + 1) * higherTrackWidth + higherTrackOffset;
for (LocType sliceY = startY; sliceY < rect.yHi(); sliceY += higherTrackWidth)
{
hitpoints.emplace_back(ManSegment<LocType>(XY<LocType>(rect.xLo(), sliceY), XY<LocType>(rect.xHi(), sliceY)));
}
}
else
{
//Vertical
LocType startX = ((rect.xLo() - higherTrackOffset) / higherTrackWidth + 1) * higherTrackWidth + higherTrackOffset;
for (LocType sliceX = startX; sliceX < rect.xHi(); sliceX += higherTrackWidth)
{
hitpoints.emplace_back(ManSegment<LocType>(XY<LocType>(sliceX, rect.yLo()), XY<LocType>(sliceX, rect.yHi())));
}
}
*/
// Solve the situtation is no hit point is found
if (hitpoints.size() == 0)
{
//WRN("%s: pin shape does not hit a track, add the center points \n", __FUNCTION__);
//for (const auto &rect : pin.shapeRects())
//{
if (higherLayerRouteDir == RouteDirType::HORIZONTAL)
{
LocType centerY = ( rect.yLo() + rect.yHi() ) / 2;
hitpoints.emplace_back(ManSegment<LocType>(XY<LocType>(rect.xLo(), centerY), XY<LocType>(rect.xHi(), centerY)));
}
else
{
LocType centerX = ( rect.xLo() + rect.xHi() ) / 2;
hitpoints.emplace_back(ManSegment<LocType>(XY<LocType>(centerX, rect.yLo()), XY<LocType>(centerX, rect.yHi())));
}
//}
}
// Select the search points
// For short hitpoints, pick the center point
// For long hitpoints, partition into tracks and select the points
IndexType allLayer = term.primarySearchPoint().layer();
for (const auto & hp : hitpoints)
{
if (hp.length() > 5 * lowerTrackWidth)
{
// Just find the points of the tracks points
IndexType times = hp.length() / lowerTrackWidth;
for (IndexType idx = 0; idx < times; ++idx)
{
LocType pt = hp.begin() + idx * lowerTrackWidth + lowerTrackWidth / 2;
if (higherLayerRouteDir == RouteDirType::HORIZONTAL)
{
// The segment is horizontal
term.addOtherSearchPoint(NetNodeLoc(_instr.alignGrid(XY<LocType>(pt, hp.coordinate())), allLayer), term.primarySearchPointShape());
}
else
{
term.addOtherSearchPoint(NetNodeLoc(_instr.alignGrid(XY<LocType>(hp.coordinate(), pt)), allLayer), term.primarySearchPointShape());
}
}
}
else
{
term.addOtherSearchPoint(NetNodeLoc(_instr.alignGrid(XY<LocType>(hp.centerXY())), allLayer), term.primarySearchPointShape());
}
}
return true;
}
PROJECT_NAMESPACE_END
| 46.097046 | 151 | 0.645675 | [
"shape",
"vector"
] |
3cf377ffa40cd80bc3eb5c5c4f82e0fbf9197ec3 | 18,514 | cpp | C++ | src/AlphaVSS.Platform/Src/VssComponent.cpp | nefarius/AlphaVSS | a3e3c574f2b6539f8837e60abf2fc2e6479e9e37 | [
"MIT"
] | null | null | null | src/AlphaVSS.Platform/Src/VssComponent.cpp | nefarius/AlphaVSS | a3e3c574f2b6539f8837e60abf2fc2e6479e9e37 | [
"MIT"
] | null | null | null | src/AlphaVSS.Platform/Src/VssComponent.cpp | nefarius/AlphaVSS | a3e3c574f2b6539f8837e60abf2fc2e6479e9e37 | [
"MIT"
] | 1 | 2022-02-16T12:35:02.000Z | 2022-02-16T12:35:02.000Z | /* Copyright (c) 2008-2016 Peter Palotas
*
* 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 "StdAfx.h"
#include "VssComponent.h"
namespace Alphaleonis { namespace Win32 { namespace Vss
{
VssComponent^ VssComponent::Adopt(::IVssComponent *vssWriterComponents)
{
try
{
return gcnew VssComponent(vssWriterComponents);
}
catch (...)
{
vssWriterComponents->Release();
throw;
}
}
VssComponent::VssComponent(::IVssComponent *vssComponent)
: m_vssComponent(vssComponent),
m_alternateLocationMappings(nullptr),
m_directedTargets(nullptr),
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WIN2003
m_differencedFiles(nullptr),
#endif
m_restoreSubcomponents(nullptr),
m_partialFiles(nullptr),
m_newTargets(nullptr)
{
m_alternateLocationMappings = gcnew AlternateLocationMappingList(this);
m_directedTargets = gcnew DirectedTargetList(this);
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WIN2003
m_differencedFiles = gcnew DifferencedFileList(this);
#endif
m_restoreSubcomponents = gcnew RestoreSubcomponentList(this);
m_partialFiles = gcnew PartialFileList(this);
m_newTargets = gcnew NewTargetList(this);
}
VssComponent::~VssComponent()
{
this->!VssComponent();
}
VssComponent::!VssComponent()
{
if (m_vssComponent != 0)
{
m_vssComponent->Release();
m_vssComponent = 0;
}
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
if (m_IVssComponentEx != 0)
{
m_IVssComponentEx->Release();
m_IVssComponentEx = 0;
}
#endif
}
// TODO: Why is this #if 0'ed???
#if 0
void VssComponent::AddDifferencedFilesByLastModifyTime(String ^ path, String ^ fileSpec, bool recursive, DateTime lastModifyTime)
{
CheckCom(m_vssComponent->AddDifferencedFilesByLastModifyTime(NoNullAutoMStr(path),
NoNullAutoMStr(fileSpec), recursive,ToFileTime(lastModifyTime)));
}
void VssComponent::AddDifferencedFilesByLastModifyTime(VssDifferencedFileInfo^ differencedFile)
{
AddDifferencedFilesByLastModifyTime(differencedFile->Path, differencedFile->FileSpec, differencedFile->IsRecursive, differencedFile->LastModifyTime);
}
void VssComponent::AddDirectedTarget(String ^ sourcePath, String^ sourceFileName, String^ sourceRangeList, String^ destinationPath, String^ destinationFileName, String^ destinationRangeList)
{
CheckCom(m_vssComponent->AddDirectedTarget(
NoNullAutoMStr(sourcePath), NoNullAutoMStr(sourceFileName), NoNullAutoMStr(sourceRangeList),
NoNullAutoMStr(destinationPath), NoNullAutoMStr(destinationFileName), NoNullAutoMStr(destinationRangeList)));
}
void VssComponent::AddPartialFile(String^ path, String^ filename, String^ ranges, String^ metaData)
{
CheckCom(m_vssComponent->AddPartialFile(NoNullAutoMStr(path), NoNullAutoMStr(filename), NoNullAutoMStr(ranges), AutoMStr(metaData)));
}
void VssComponent::AddDirectedTarget(VssDirectedTargetInfo ^directedTarget)
{
AddDirectedTarget(directedTarget->SourcePath, directedTarget->SourceFileName, directedTarget->SourceRangeList,
directedTarget->DestinationPath, directedTarget->DestinationFileName, directedTarget->DestinationRangeList);
}
void VssComponent::AddParitalFile(VssPartialFileInfo^ partialFile)
{
AddPartialFile(partialFile->Path, partialFile->FileName, partialFile->Range, partialFile->Metadata);
}
String^ VssComponent::BackupMetadata::get()
{
AutoBStr bstrBackupMetadata;
CheckCom(m_vssComponent->GetBackupMetadata(&bstrBackupMetadata));
return bstrBackupMetadata;
}
String^ VssComponent::RestoreMetadata::get()
{
AutoBStr s;
CheckCom(m_vssComponent->GetRestoreMetadata(&s));
return s;
}
void VssComponent::SetBackupMetadata(String^ metadata)
{
CheckCom(m_vssComponent->SetBackupMetadata(NoNullAutoMStr(metadata)));
}
void VssComponent::SetBackupStamp(String^ stamp)
{
CheckCom(m_vssComponent->SetBackupStamp(NoNullAutoMStr(stamp)));
}
void VssComponent::SetPostRestoreFailureMsg(String^ msg)
{
CheckCom(m_vssComponent->SetPostRestoreFailureMsg(NoNullAutoMStr(msg)));
}
void VssComponent::SetPreRestoreFailureMsg(String^ msg)
{
CheckCom(m_vssComponent->SetPreRestoreFailureMsg(NoNullAutoMStr(msg)));
}
void VssComponent::SetRestoreMetadata(String^ metadata)
{
CheckCom(m_vssComponent->SetRestoreMetadata(NoNullAutoMStr(metadata)));
}
void VssComponent::SetRestoreTarget(VssRestoreTarget target)
{
CheckCom(m_vssComponent->SetRestoreTarget((VSS_RESTORE_TARGET)target));
}
#endif
bool VssComponent::AdditionalRestores::get()
{
bool bAdditionalRestores;
CheckCom(m_vssComponent->GetAdditionalRestores(&bAdditionalRestores));
return bAdditionalRestores;
}
String^ VssComponent::BackupOptions::get()
{
AutoBStr str;
CheckCom(m_vssComponent->GetBackupOptions(&str));
return str;
}
String^ VssComponent::BackupStamp::get()
{
AutoBStr str;
CheckCom(m_vssComponent->GetBackupStamp(&str));
return str;
}
bool VssComponent::BackupSucceeded::get()
{
bool b;
CheckCom(m_vssComponent->GetBackupSucceeded(&b));
return b;
}
String^ VssComponent::ComponentName::get()
{
AutoBStr str;
CheckCom(m_vssComponent->GetComponentName(&str));
return str;
}
VssComponentType VssComponent::ComponentType::get()
{
VSS_COMPONENT_TYPE type;
CheckCom(m_vssComponent->GetComponentType(&type));
return (VssComponentType)type;
}
VssFileRestoreStatus VssComponent::FileRestoreStatus::get()
{
VSS_FILE_RESTORE_STATUS status;
CheckCom(m_vssComponent->GetFileRestoreStatus(&status));
return (VssFileRestoreStatus)status;
}
String^ VssComponent::LogicalPath::get()
{
AutoBStr path;
CheckCom(m_vssComponent->GetLogicalPath(&path));
return path;
}
String^ VssComponent::PostRestoreFailureMsg::get()
{
AutoBStr s;
CheckCom(m_vssComponent->GetPostRestoreFailureMsg(&s));
return s;
}
String^ VssComponent::PreRestoreFailureMsg::get()
{
AutoBStr s;
CheckCom(m_vssComponent->GetPreRestoreFailureMsg(&s));
return s;
}
String^ VssComponent::PreviousBackupStamp::get()
{
AutoBStr s;
CheckCom(m_vssComponent->GetPreviousBackupStamp(&s));
return s;
}
String^ VssComponent::RestoreOptions::get()
{
AutoBStr s;
CheckCom(m_vssComponent->GetRestoreOptions(&s));
return s;
}
VssRestoreTarget VssComponent::RestoreTarget::get()
{
VSS_RESTORE_TARGET tgt;
CheckCom(m_vssComponent->GetRestoreTarget(&tgt));
return (VssRestoreTarget)tgt;
}
bool VssComponent::IsSelectedForRestore::get()
{
bool b;
CheckCom(m_vssComponent->IsSelectedForRestore(&b));
return b;
}
IList<VssDirectedTargetInfo^>^ VssComponent::DirectedTargets::get()
{
return m_directedTargets;
}
IList<VssPartialFileInfo^>^ VssComponent::PartialFiles::get()
{
return m_partialFiles;
}
IList<VssWMFileDescriptor^>^ VssComponent::NewTargets::get()
{
return m_newTargets;
}
IList<VssDifferencedFileInfo^>^ VssComponent::DifferencedFiles::get()
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WIN2003
return m_differencedFiles;
#else
throw gcnew UnsupportedOperatingSystemException();
#endif
}
IList<VssRestoreSubcomponentInfo^>^ VssComponent::RestoreSubcomponents::get()
{
return m_restoreSubcomponents;
}
IList<VssWMFileDescriptor^>^ VssComponent::AlternateLocationMappings::get()
{
return m_alternateLocationMappings;
}
//
// DirectedTargetList
//
VssComponent::DirectedTargetList::DirectedTargetList(VssComponent^ component)
: m_component(component)
{
}
int VssComponent::DirectedTargetList::Count::get()
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
UINT count;
CheckCom(m_component->m_vssComponent->GetDirectedTargetCount(&count));
return count;
}
VssDirectedTargetInfo^ VssComponent::DirectedTargetList::default::get(int index)
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
if (index < 0 || index >= Count)
throw gcnew ArgumentOutOfRangeException("index");
AutoBStr bsSourcePath, bsSourceFileName, bsSourceRangeList;
AutoBStr bsDestPath, bsDestFileName, bsDestRangeList;
CheckCom(m_component->m_vssComponent->GetDirectedTarget(index, &bsSourcePath, &bsSourceFileName, &bsSourceRangeList, &bsDestPath,
&bsDestFileName, &bsDestRangeList));
return gcnew VssDirectedTargetInfo(bsSourcePath, bsSourceFileName, bsSourceRangeList, bsDestPath, bsDestFileName, bsDestRangeList);
}
//
// NewTargetList
//
int VssComponent::NewTargetList::Count::get()
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
UINT count;
CheckCom(m_component->m_vssComponent->GetNewTargetCount(&count));
return count;
}
VssWMFileDescriptor^ VssComponent::NewTargetList::default::get(int index)
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
if (index < 0 || index >= Count)
throw gcnew ArgumentOutOfRangeException("index");
IVssWMFiledesc *vssWMFiledesc;
CheckCom(m_component->m_vssComponent->GetNewTarget(index, &vssWMFiledesc));
return CreateVssWMFileDescriptor(vssWMFiledesc);
}
VssComponent::NewTargetList::NewTargetList(VssComponent^ component)
: m_component(component)
{
}
//
// PartialFileList
//
int VssComponent::PartialFileList::Count::get()
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
UINT count;
CheckCom(m_component->m_vssComponent->GetPartialFileCount(&count));
return count;
}
VssPartialFileInfo^ VssComponent::PartialFileList::default::get(int index)
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
if (index < 0 || index >= Count)
throw gcnew ArgumentOutOfRangeException("index");
AutoBStr bsPath, bsFileName, bsRange, bsMetadata;
CheckCom(m_component->m_vssComponent->GetPartialFile(index, &bsPath, &bsFileName, &bsRange, &bsMetadata));
return gcnew VssPartialFileInfo(bsPath, bsFileName, bsRange, bsMetadata);
}
VssComponent::PartialFileList::PartialFileList(VssComponent^ component)
: m_component(component)
{
}
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WIN2003
//
// DifferencedFileList
//
int VssComponent::DifferencedFileList::Count::get()
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
UINT count;
CheckCom(m_component->m_vssComponent->GetDifferencedFilesCount(&count));
return count;
}
VssDifferencedFileInfo^ VssComponent::DifferencedFileList::default::get(int index)
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
if (index < 0 || index >= Count)
throw gcnew ArgumentOutOfRangeException("index");
AutoBStr bstrPath, bstrFilespec, bstrLsnString;
BOOL bRecursive;
FILETIME ftLastModifyTime;
CheckCom(m_component->m_vssComponent->GetDifferencedFile(index, &bstrPath, &bstrFilespec, &bRecursive, &bstrLsnString, &ftLastModifyTime));
return gcnew VssDifferencedFileInfo(bstrPath, bstrFilespec, bRecursive != 0, ToDateTime(ftLastModifyTime));
}
VssComponent::DifferencedFileList::DifferencedFileList(VssComponent^ component)
: m_component(component)
{
}
#endif
//
// RestoreSubcomponentList
//
int VssComponent::RestoreSubcomponentList::Count::get()
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
UINT count;
CheckCom(m_component->m_vssComponent->GetRestoreSubcomponentCount(&count));
return count;
}
VssRestoreSubcomponentInfo^ VssComponent::RestoreSubcomponentList::default::get(int index)
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
if (index < 0 || index >= Count)
throw gcnew ArgumentOutOfRangeException("index");
AutoBStr bsLogicalPath, bsComponentName;
bool bRepair;
CheckCom(m_component->m_vssComponent->GetRestoreSubcomponent(index, &bsLogicalPath, &bsComponentName, &bRepair));
return gcnew VssRestoreSubcomponentInfo(bsLogicalPath, bsComponentName);
}
VssComponent::RestoreSubcomponentList::RestoreSubcomponentList(VssComponent^ component)
: m_component(component)
{
}
//
// AlternateLocationMappingList
//
int VssComponent::AlternateLocationMappingList::Count::get()
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
UINT count;
CheckCom(m_component->m_vssComponent->GetAlternateLocationMappingCount(&count));
return count;
}
VssWMFileDescriptor^ VssComponent::AlternateLocationMappingList::default::get(int index)
{
if (m_component->m_vssComponent == 0)
throw gcnew ObjectDisposedException("Instance of IList used after the object creating it was disposed.");
if (index < 0 || index >= Count)
throw gcnew ArgumentOutOfRangeException("index");
IVssWMFiledesc *vssWMFiledesc;
CheckCom(m_component->m_vssComponent->GetAlternateLocationMapping(index, &vssWMFiledesc));
return CreateVssWMFileDescriptor(vssWMFiledesc);
}
VssComponent::AlternateLocationMappingList::AlternateLocationMappingList(VssComponent^ component)
: m_component(component)
{
}
bool VssComponent::IsAuthoritativeRestore::get()
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
bool bAuth;
if (SUCCEEDED(RequireIVssComponentEx()->GetAuthoritativeRestore(&bAuth)))
return bAuth;
#endif
return false;
}
String^ VssComponent::PostSnapshotFailureMsg::get()
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
AutoBStr bstrMsg;
if (SUCCEEDED(RequireIVssComponentEx()->GetPostSnapshotFailureMsg(&bstrMsg)))
return bstrMsg;
#endif
return nullptr;
}
String^ VssComponent::PrepareForBackupFailureMsg::get()
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
AutoBStr bstrMsg;
if (SUCCEEDED(RequireIVssComponentEx()->GetPrepareForBackupFailureMsg(&bstrMsg)))
return bstrMsg;
#endif
return nullptr;
}
String^ VssComponent::RestoreName::get()
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
AutoBStr bstrName;
if (SUCCEEDED(RequireIVssComponentEx()->GetRestoreName(&bstrName)))
return bstrName;
#endif
return nullptr;
}
String^ VssComponent::RollForwardRestorePoint::get()
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
VSS_ROLLFORWARD_TYPE eRollType;
AutoBStr bstrPoint;
if (SUCCEEDED(RequireIVssComponentEx()->GetRollForward(&eRollType, &bstrPoint)))
return bstrPoint;
#endif
return nullptr;
}
VssRollForwardType VssComponent::RollForwardType::get()
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
VSS_ROLLFORWARD_TYPE eRollType;
AutoBStr bstrPoint;
if (SUCCEEDED(RequireIVssComponentEx()->GetRollForward(&eRollType, &bstrPoint)))
return (VssRollForwardType)eRollType;
#endif
return VssRollForwardType::Undefined;
}
VssComponentFailure^ VssComponent::Failure::get()
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
HRESULT hr;
HRESULT hrApplication;
AutoBStr bstrApplicationMessage;
DWORD dwReserved;
CheckCom(RequireIVssComponentEx2()->GetFailure(&hr, &hrApplication, &bstrApplicationMessage, &dwReserved));
return gcnew VssComponentFailure(hr, hrApplication, bstrApplicationMessage);
#endif
return nullptr;
}
void VssComponent::Failure::set(VssComponentFailure^ failure)
{
#if ALPHAVSS_TARGET >= ALPHAVSS_TARGET_WINVISTAORLATER
if (failure == nullptr)
return;
CheckCom(RequireIVssComponentEx2()->SetFailure(failure->ErrorCode, failure->ApplicationErrorCode, AutoMBStr(failure->ApplicationMessage), 0));
#endif
}
}
} }
| 31.011725 | 193 | 0.711624 | [
"object"
] |
3cf6a283cb61bbbd6479d92baefd4fa905e417be | 19,111 | hpp | C++ | runtime/device/blit.hpp | braiam/ROCm-OpenCL-Runtime | a66edda66d98923e61fe97596c632eac743e63ed | [
"MIT"
] | null | null | null | runtime/device/blit.hpp | braiam/ROCm-OpenCL-Runtime | a66edda66d98923e61fe97596c632eac743e63ed | [
"MIT"
] | null | null | null | runtime/device/blit.hpp | braiam/ROCm-OpenCL-Runtime | a66edda66d98923e61fe97596c632eac743e63ed | [
"MIT"
] | null | null | null | //
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef BLIT_HPP_
#define BLIT_HPP_
#include "top.hpp"
#include "platform/command.hpp"
#include "device/device.hpp"
/*! \addtogroup GPU Blit Implementation
* @{
*/
//! GPU Blit Manager Implementation
namespace device {
//! Blit Manager Abstraction class
class BlitManager : public amd::HeapObject {
public:
//! HW accelerated setup
union Setup {
struct {
uint disableReadBuffer_ : 1;
uint disableReadBufferRect_ : 1;
uint disableReadImage_ : 1;
uint disableWriteBuffer_ : 1;
uint disableWriteBufferRect_ : 1;
uint disableWriteImage_ : 1;
uint disableCopyBuffer_ : 1;
uint disableCopyBufferRect_ : 1;
uint disableCopyImageToBuffer_ : 1;
uint disableCopyBufferToImage_ : 1;
uint disableCopyImage_ : 1;
uint disableFillBuffer_ : 1;
uint disableFillImage_ : 1;
uint disableCopyBufferToImageOpt_ : 1;
uint disableHwlCopyBuffer_ : 1;
};
uint32_t value_;
Setup() : value_(0) {}
void disableAll() { value_ = 0xffffffff; }
};
public:
//! Constructor
BlitManager(Setup setup = Setup() //!< Specifies HW accelerated blits
)
: setup_(setup), syncOperation_(false) {}
//! Destructor
virtual ~BlitManager() {}
//! Creates HostBlitManager object
virtual bool create(amd::Device& device) { return true; }
//! Copies a buffer object to system memory
virtual bool readBuffer(Memory& srcMemory, //!< Source memory object
void* dstHost, //!< Destination host memory
const amd::Coord3D& origin, //!< Source origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Copies a buffer object to system memory
virtual bool readBufferRect(Memory& srcMemory, //!< Source memory object
void* dstHost, //!< Destinaiton host memory
const amd::BufferRect& bufRect, //!< Source rectangle
const amd::BufferRect& hostRect, //!< Destination rectangle
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Copies an image object to system memory
virtual bool readImage(Memory& srcMemory, //!< Source memory object
void* dstHost, //!< Destination host memory
const amd::Coord3D& origin, //!< Source origin
const amd::Coord3D& size, //!< Size of the copy region
size_t rowPitch, //!< Row pitch for host memory
size_t slicePitch, //!< Slice pitch for host memory
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Copies system memory to a buffer object
virtual bool writeBuffer(const void* srcHost, //!< Source host memory
Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& origin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Copies system memory to a buffer object
virtual bool writeBufferRect(const void* srcHost, //!< Source host memory
Memory& dstMemory, //!< Destination memory object
const amd::BufferRect& hostRect, //!< Destination rectangle
const amd::BufferRect& bufRect, //!< Source rectangle
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Copies system memory to an image object
virtual bool writeImage(const void* srcHost, //!< Source host memory
Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& origin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
size_t rowPitch, //!< Row pitch for host memory
size_t slicePitch, //!< Slice pitch for host memory
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Copies a buffer object to another buffer object
virtual bool copyBuffer(Memory& srcMemory, //!< Source memory object
Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& srcOrigin, //!< Source origin
const amd::Coord3D& dstOrigin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Copies a buffer object to another buffer object
virtual bool copyBufferRect(Memory& srcMemory, //!< Source memory object
Memory& dstMemory, //!< Destination memory object
const amd::BufferRect& srcRect, //!< Source rectangle
const amd::BufferRect& dstRect, //!< Destination rectangle
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Copies an image object to a buffer object
virtual bool copyImageToBuffer(Memory& srcMemory, //!< Source memory object
Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& srcOrigin, //!< Source origin
const amd::Coord3D& dstOrigin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false, //!< Entire buffer will be updated
size_t rowPitch = 0, //!< Pitch for buffer
size_t slicePitch = 0 //!< Slice for buffer
) const = 0;
//! Copies a buffer object to an image object
virtual bool copyBufferToImage(Memory& srcMemory, //!< Source memory object
Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& srcOrigin, //!< Source origin
const amd::Coord3D& dstOrigin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false, //!< Entire buffer will be updated
size_t rowPitch = 0, //!< Pitch for buffer
size_t slicePitch = 0 //!< Slice for buffer
) const = 0;
//! Copies an image object to another image object
virtual bool copyImage(Memory& srcMemory, //!< Source memory object
Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& srcOrigin, //!< Source origin
const amd::Coord3D& dstOrigin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Fills a buffer memory with a pattern data
virtual bool fillBuffer(Memory& memory, //!< Memory object to fill with pattern
const void* pattern, //!< Pattern data
size_t patternSize, //!< Pattern size
const amd::Coord3D& origin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Fills an image memory with a pattern data
virtual bool fillImage(Memory& dstMemory, //!< Memory object to fill with pattern
const void* pattern, //!< Pattern data
const amd::Coord3D& origin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const = 0;
//! Enables synchronization on blit operations
void enableSynchronization() { syncOperation_ = true; }
//! Returns Xfer queue lock
virtual amd::Monitor* lockXfer() const { return nullptr; }
protected:
const Setup setup_; //!< HW accelerated blit requested
bool syncOperation_; //!< Blit operations are synchronized
private:
//! Disable copy constructor
BlitManager(const BlitManager&);
//! Disable operator=
BlitManager& operator=(const BlitManager&);
};
//! Host Blit Manager
class HostBlitManager : public device::BlitManager {
public:
//! Constructor
HostBlitManager(VirtualDevice& vdev, //!< Virtual GPU to be used for blits
Setup setup = Setup() //!< Specifies HW accelerated blits
);
//! Destructor
virtual ~HostBlitManager() {}
//! Creates HostBlitManager object
virtual bool create(amd::Device& device) { return true; }
//! Copies a buffer object to system memory
virtual bool readBuffer(device::Memory& srcMemory, //!< Source memory object
void* dstHost, //!< Destination host memory
const amd::Coord3D& origin, //!< Source origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
//! Copies a buffer object to system memory
virtual bool readBufferRect(device::Memory& srcMemory, //!< Source memory object
void* dstHost, //!< Destinaiton host memory
const amd::BufferRect& bufRect, //!< Source rectangle
const amd::BufferRect& hostRect, //!< Destination rectangle
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
//! Copies an image object to system memory
virtual bool readImage(device::Memory& srcMemory, //!< Source memory object
void* dstHost, //!< Destination host memory
const amd::Coord3D& origin, //!< Source origin
const amd::Coord3D& size, //!< Size of the copy region
size_t rowPitch, //!< Row pitch for host memory
size_t slicePitch, //!< Slice pitch for host memory
bool entire = false //!< Entire buffer will be updated
) const;
//! Copies system memory to a buffer object
virtual bool writeBuffer(const void* srcHost, //!< Source host memory
device::Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& origin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
//! Copies system memory to a buffer object
virtual bool writeBufferRect(const void* srcHost, //!< Source host memory
device::Memory& dstMemory, //!< Destination memory object
const amd::BufferRect& hostRect, //!< Destination rectangle
const amd::BufferRect& bufRect, //!< Source rectangle
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
//! Copies system memory to an image object
virtual bool writeImage(const void* srcHost, //!< Source host memory
device::Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& origin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
size_t rowPitch, //!< Row pitch for host memory
size_t slicePitch, //!< Slice pitch for host memory
bool entire = false //!< Entire buffer will be updated
) const;
//! Copies a buffer object to another buffer object
virtual bool copyBuffer(device::Memory& srcMemory, //!< Source memory object
device::Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& srcOrigin, //!< Source origin
const amd::Coord3D& dstOrigin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
//! Copies a buffer object to another buffer object
virtual bool copyBufferRect(device::Memory& srcMemory, //!< Source memory object
device::Memory& dstMemory, //!< Destination memory object
const amd::BufferRect& srcRect, //!< Source rectangle
const amd::BufferRect& dstRect, //!< Destination rectangle
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
//! Copies an image object to a buffer object
virtual bool copyImageToBuffer(device::Memory& srcMemory, //!< Source memory object
device::Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& srcOrigin, //!< Source origin
const amd::Coord3D& dstOrigin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false, //!< Entire buffer will be updated
size_t rowPitch = 0, //!< Pitch for buffer
size_t slicePitch = 0 //!< Slice for buffer
) const;
//! Copies a buffer object to an image object
virtual bool copyBufferToImage(device::Memory& srcMemory, //!< Source memory object
device::Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& srcOrigin, //!< Source origin
const amd::Coord3D& dstOrigin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false, //!< Entire buffer will be updated
size_t rowPitch = 0, //!< Pitch for buffer
size_t slicePitch = 0 //!< Slice for buffer
) const;
//! Copies an image object to another image object
virtual bool copyImage(device::Memory& srcMemory, //!< Source memory object
device::Memory& dstMemory, //!< Destination memory object
const amd::Coord3D& srcOrigin, //!< Source origin
const amd::Coord3D& dstOrigin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
//! Fills a buffer memory with a pattern data
virtual bool fillBuffer(device::Memory& memory, //!< Memory object to fill with pattern
const void* pattern, //!< Pattern data
size_t patternSize, //!< Pattern size
const amd::Coord3D& origin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
//! Fills an image memory with a pattern data
virtual bool fillImage(device::Memory& dstMemory, //!< Memory object to fill with pattern
const void* pattern, //!< Pattern data
const amd::Coord3D& origin, //!< Destination origin
const amd::Coord3D& size, //!< Size of the copy region
bool entire = false //!< Entire buffer will be updated
) const;
cl_uint sRGBmap(float fc) const;
protected:
VirtualDevice& vDev_; //!< Virtual device object
const amd::Device& dev_; //!< Physical device
private:
//! Disable copy constructor
HostBlitManager(const HostBlitManager&);
//! Disable operator=
HostBlitManager& operator=(const HostBlitManager&);
};
/*@}*/} // namespace device
#endif /*BLIT_HPP_*/
| 55.074928 | 99 | 0.500968 | [
"object"
] |
3cf77a8c786dc41d39a985e321e73c7b8324a9bf | 12,279 | cc | C++ | chrome/browser/ui/browser_live_tab_context.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/ui/browser_live_tab_context.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/ui/browser_live_tab_context.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // 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 "chrome/browser/ui/browser_live_tab_context.h"
#include <memory>
#include <utility>
#include "base/feature_list.h"
#include "base/token.h"
#include "base/values.h"
#include "chrome/browser/apps/app_service/web_contents_app_id_utils.h"
#include "chrome/browser/browser_features.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/closed_tab_cache.h"
#include "chrome/browser/sessions/closed_tab_cache_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_tab_strip_model_delegate.h"
#include "chrome/browser/ui/browser_tabrestore.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/tabs/tab_group.h"
#include "chrome/browser/ui/tabs/tab_group_model.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/web_applications/web_app_helpers.h"
#include "chrome/common/buildflags.h"
#include "components/sessions/content/content_live_tab.h"
#include "components/sessions/content/content_platform_specific_tab_data.h"
#include "components/tab_groups/tab_group_id.h"
#include "components/tab_groups/tab_group_visual_data.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/session_storage_namespace.h"
#if BUILDFLAG(ENABLE_SESSION_SERVICE)
#include "chrome/browser/sessions/tab_loader.h"
#endif
#if BUILDFLAG(ENABLE_SIDE_SEARCH)
#include "chrome/browser/ui/side_search/side_search_utils.h"
#endif
using content::NavigationController;
using content::SessionStorageNamespace;
using content::WebContents;
namespace {
// |app_name| can could be for an app that has been uninstalled. In that
// case we don't want to open an app window. Note that |app_name| is also used
// for other types of windows like dev tools and we always want to open an
// app window in those cases.
bool ShouldCreateAppWindowForAppName(Profile* profile,
const std::string& app_name) {
if (app_name.empty())
return false;
// Only need to check that the app is installed if |app_name| is for a
// platform app or web app. (|app_name| could also be for a devtools window.)
const std::string app_id = web_app::GetAppIdFromApplicationName(app_name);
if (app_id.empty())
return true;
return apps::IsInstalledApp(profile, app_id);
}
} // namespace
void BrowserLiveTabContext::ShowBrowserWindow() {
browser_->window()->Show();
}
SessionID BrowserLiveTabContext::GetSessionID() const {
return browser_->session_id();
}
int BrowserLiveTabContext::GetTabCount() const {
return browser_->tab_strip_model()->count();
}
int BrowserLiveTabContext::GetSelectedIndex() const {
return browser_->tab_strip_model()->active_index();
}
std::string BrowserLiveTabContext::GetAppName() const {
return browser_->app_name();
}
std::string BrowserLiveTabContext::GetUserTitle() const {
return browser_->user_title();
}
sessions::LiveTab* BrowserLiveTabContext::GetLiveTabAt(int index) const {
return sessions::ContentLiveTab::GetForWebContents(
browser_->tab_strip_model()->GetWebContentsAt(index));
}
sessions::LiveTab* BrowserLiveTabContext::GetActiveLiveTab() const {
return sessions::ContentLiveTab::GetForWebContents(
browser_->tab_strip_model()->GetActiveWebContents());
}
std::map<std::string, std::string> BrowserLiveTabContext::GetExtraDataForTab(
int index) const {
std::map<std::string, std::string> extra_data;
#if BUILDFLAG(ENABLE_SIDE_SEARCH)
if (IsSideSearchEnabled(browser_->profile())) {
absl::optional<std::pair<std::string, std::string>> side_search_data =
side_search::MaybeGetSideSearchTabRestoreData(
browser_->tab_strip_model()->GetWebContentsAt(index));
if (side_search_data.has_value())
extra_data.insert(side_search_data.value());
}
#endif // BUILDFLAG(ENABLE_SIDE_SEARCH)
return extra_data;
}
std::map<std::string, std::string>
BrowserLiveTabContext::GetExtraDataForWindow() const {
std::map<std::string, std::string> extra_data;
#if BUILDFLAG(ENABLE_SIDE_SEARCH)
if (IsSideSearchEnabled(browser_->profile())) {
side_search::MaybeAddSideSearchWindowRestoreData(
browser_->window()->IsSideSearchPanelVisible(), extra_data);
}
#endif // BUILDFLAG(ENABLE_SIDE_SEARCH)
return extra_data;
}
absl::optional<tab_groups::TabGroupId> BrowserLiveTabContext::GetTabGroupForTab(
int index) const {
return browser_->tab_strip_model()->GetTabGroupForTab(index);
}
const tab_groups::TabGroupVisualData*
BrowserLiveTabContext::GetVisualDataForGroup(
const tab_groups::TabGroupId& group) const {
return browser_->tab_strip_model()
->group_model()
->GetTabGroup(group)
->visual_data();
}
bool BrowserLiveTabContext::IsTabPinned(int index) const {
return browser_->tab_strip_model()->IsTabPinned(index);
}
void BrowserLiveTabContext::SetVisualDataForGroup(
const tab_groups::TabGroupId& group,
const tab_groups::TabGroupVisualData& visual_data) {
browser_->tab_strip_model()->group_model()->GetTabGroup(group)->SetVisualData(
std::move(visual_data));
}
const gfx::Rect BrowserLiveTabContext::GetRestoredBounds() const {
return browser_->window()->GetRestoredBounds();
}
ui::WindowShowState BrowserLiveTabContext::GetRestoredState() const {
return browser_->window()->GetRestoredState();
}
std::string BrowserLiveTabContext::GetWorkspace() const {
return browser_->window()->GetWorkspace();
}
sessions::LiveTab* BrowserLiveTabContext::AddRestoredTab(
const std::vector<sessions::SerializedNavigationEntry>& navigations,
int tab_index,
int selected_navigation,
const std::string& extension_app_id,
absl::optional<tab_groups::TabGroupId> group,
const tab_groups::TabGroupVisualData& group_visual_data,
bool select,
bool pin,
const sessions::PlatformSpecificTabData* tab_platform_data,
const sessions::SerializedUserAgentOverride& user_agent_override,
const std::map<std::string, std::string>& extra_data,
const SessionID* tab_id) {
SessionStorageNamespace* storage_namespace =
tab_platform_data
? static_cast<const sessions::ContentPlatformSpecificTabData*>(
tab_platform_data)
->session_storage_namespace()
: nullptr;
TabGroupModel* group_model = browser_->tab_strip_model()->group_model();
const bool first_tab_in_group =
group.has_value() ? !group_model->ContainsTabGroup(group.value()) : false;
bool restored_from_closed_tab_cache = false;
WebContents* web_contents = nullptr;
if (tab_id) {
// Try to restore the WebContents from the ClosedTabCache rather than
// creating it again.
ClosedTabCache& cache =
ClosedTabCacheServiceFactory::GetForProfile(browser_->profile())
->closed_tab_cache();
std::unique_ptr<WebContents> wc = cache.RestoreEntry(*tab_id);
if (wc) {
// Cache hit.
restored_from_closed_tab_cache = true;
web_contents = chrome::AddRestoredTabFromCache(
std::move(wc), browser_, tab_index, group, select, pin,
user_agent_override, extra_data);
}
}
if (!restored_from_closed_tab_cache) {
// Cache miss, ClosedTabCache feature disabled or non-existent |tab_id|.
web_contents = chrome::AddRestoredTab(
browser_, navigations, tab_index, selected_navigation, extension_app_id,
group, select, pin, base::TimeTicks(), storage_namespace,
user_agent_override, extra_data, false /* from_session_restore */);
}
// Only update the metadata if the group doesn't already exist since the
// existing group has the latest metadata, which may have changed from the
// time the tab was closed.
if (first_tab_in_group) {
const tab_groups::TabGroupVisualData new_data(
group_visual_data.title(), group_visual_data.color(), false);
group_model->GetTabGroup(group.value())->SetVisualData(new_data);
}
if (!restored_from_closed_tab_cache) {
#if BUILDFLAG(ENABLE_SESSION_SERVICE)
// The focused tab will be loaded by Browser, and TabLoader will load the
// rest.
if (!select) {
// Regression check: make sure that the tab hasn't started to load
// immediately.
DCHECK(web_contents->GetController().NeedsReload());
DCHECK(!web_contents->IsLoading());
}
std::vector<TabLoader::RestoredTab> restored_tabs;
restored_tabs.emplace_back(web_contents, select, !extension_app_id.empty(),
pin, group);
TabLoader::RestoreTabs(restored_tabs, base::TimeTicks::Now());
#else // BUILDFLAG(ENABLE_SESSION_SERVICE)
// Load the tab manually if there is no TabLoader.
web_contents->GetController().LoadIfNecessary();
#endif // BUILDFLAG(ENABLE_SESSION_SERVICE)
}
return sessions::ContentLiveTab::GetForWebContents(web_contents);
}
sessions::LiveTab* BrowserLiveTabContext::ReplaceRestoredTab(
const std::vector<sessions::SerializedNavigationEntry>& navigations,
absl::optional<tab_groups::TabGroupId> group,
int selected_navigation,
const std::string& extension_app_id,
const sessions::PlatformSpecificTabData* tab_platform_data,
const sessions::SerializedUserAgentOverride& user_agent_override,
const std::map<std::string, std::string>& extra_data) {
SessionStorageNamespace* storage_namespace =
tab_platform_data
? static_cast<const sessions::ContentPlatformSpecificTabData*>(
tab_platform_data)
->session_storage_namespace()
: nullptr;
WebContents* web_contents = chrome::ReplaceRestoredTab(
browser_, navigations, selected_navigation, extension_app_id,
storage_namespace, user_agent_override, extra_data,
false /* from_session_restore */);
return sessions::ContentLiveTab::GetForWebContents(web_contents);
}
void BrowserLiveTabContext::CloseTab() {
chrome::CloseTab(browser_);
}
// static
sessions::LiveTabContext* BrowserLiveTabContext::Create(
Profile* profile,
const std::string& app_name,
const gfx::Rect& bounds,
ui::WindowShowState show_state,
const std::string& workspace,
const std::string& user_title,
const std::map<std::string, std::string>& extra_data) {
std::unique_ptr<Browser::CreateParams> create_params;
if (ShouldCreateAppWindowForAppName(profile, app_name)) {
// Only trusted app popup windows should ever be restored.
create_params = std::make_unique<Browser::CreateParams>(
Browser::CreateParams::CreateForApp(app_name, true /* trusted_source */,
bounds, profile,
true /* user_gesture */));
} else {
create_params = std::make_unique<Browser::CreateParams>(
Browser::CreateParams(profile, true));
create_params->initial_bounds = bounds;
}
create_params->initial_show_state = show_state;
create_params->initial_workspace = workspace;
create_params->user_title = user_title;
Browser* browser = Browser::Create(*create_params.get());
#if BUILDFLAG(ENABLE_SIDE_SEARCH)
browser->window()->MaybeRestoreSideSearchStatePerWindow(extra_data);
#endif // BUILDFLAG(ENABLE_SIDE_SEARCH)
return browser->live_tab_context();
}
// static
sessions::LiveTabContext* BrowserLiveTabContext::FindContextForWebContents(
const WebContents* contents) {
Browser* browser = chrome::FindBrowserWithWebContents(contents);
return browser ? browser->live_tab_context() : nullptr;
}
// static
sessions::LiveTabContext* BrowserLiveTabContext::FindContextWithID(
SessionID desired_id) {
Browser* browser = chrome::FindBrowserWithID(desired_id);
return browser ? browser->live_tab_context() : nullptr;
}
// static
sessions::LiveTabContext* BrowserLiveTabContext::FindContextWithGroup(
tab_groups::TabGroupId group,
Profile* profile) {
Browser* browser = chrome::FindBrowserWithGroup(group, profile);
return browser ? browser->live_tab_context() : nullptr;
}
| 36.436202 | 80 | 0.740207 | [
"vector"
] |
3cff6bc1b184d94ec17a9fc90d40feef48920ad3 | 15,898 | cc | C++ | components/autofill_assistant/browser/web/element_finder.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill_assistant/browser/web/element_finder.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill_assistant/browser/web/element_finder.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 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/autofill_assistant/browser/web/element_finder.h"
#include "components/autofill_assistant/browser/devtools/devtools_client.h"
#include "components/autofill_assistant/browser/service.pb.h"
#include "components/autofill_assistant/browser/web/web_controller_util.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
namespace autofill_assistant {
namespace {
// Javascript code to get document root element.
const char* const kGetDocumentElement =
R"(
(function() {
return document.documentElement;
}())
)";
// Javascript code to query an elements for a selector, either the first
// (non-strict) or a single (strict) element.
//
// Returns undefined if no elements are found, TOO_MANY_ELEMENTS (18) if too
// many elements were found and strict mode is enabled.
const char* const kQuerySelector =
R"(function (selector, strictMode) {
var found = this.querySelectorAll(selector);
if(found.length == 0) return undefined;
if(found.length > 1 && strictMode) return 18;
return found[0];
})";
// Javascript code to query a visible elements for a selector, either the first
// (non-strict) or a single (strict) visible element.q
//
// Returns undefined if no elements are found, TOO_MANY_ELEMENTS (18) if too
// many elements were found and strict mode is enabled.
const char* const kQuerySelectorWithConditions =
R"(function (selector, strict, visible, inner_text_str, value_str) {
var found = this.querySelectorAll(selector);
var found_index = -1;
var inner_text_re = inner_text_str ? RegExp(inner_text_str) : undefined;
var value_re = value_str ? RegExp(value_str) : undefined;
var match = function(e) {
if (visible && e.getClientRects().length == 0) return false;
if (inner_text_re && !inner_text_re.test(e.innerText)) return false;
if (value_re && !value_re.test(e.value)) return false;
return true;
};
for (let i = 0; i < found.length; i++) {
if (match(found[i])) {
if (found_index != -1) return 18;
found_index = i;
if (!strict) break;
}
}
return found_index == -1 ? undefined : found[found_index];
})";
bool ConvertPseudoType(const PseudoType pseudo_type,
dom::PseudoType* pseudo_type_output) {
switch (pseudo_type) {
case PseudoType::UNDEFINED:
break;
case PseudoType::FIRST_LINE:
*pseudo_type_output = dom::PseudoType::FIRST_LINE;
return true;
case PseudoType::FIRST_LETTER:
*pseudo_type_output = dom::PseudoType::FIRST_LETTER;
return true;
case PseudoType::BEFORE:
*pseudo_type_output = dom::PseudoType::BEFORE;
return true;
case PseudoType::AFTER:
*pseudo_type_output = dom::PseudoType::AFTER;
return true;
case PseudoType::BACKDROP:
*pseudo_type_output = dom::PseudoType::BACKDROP;
return true;
case PseudoType::SELECTION:
*pseudo_type_output = dom::PseudoType::SELECTION;
return true;
case PseudoType::FIRST_LINE_INHERITED:
*pseudo_type_output = dom::PseudoType::FIRST_LINE_INHERITED;
return true;
case PseudoType::SCROLLBAR:
*pseudo_type_output = dom::PseudoType::SCROLLBAR;
return true;
case PseudoType::SCROLLBAR_THUMB:
*pseudo_type_output = dom::PseudoType::SCROLLBAR_THUMB;
return true;
case PseudoType::SCROLLBAR_BUTTON:
*pseudo_type_output = dom::PseudoType::SCROLLBAR_BUTTON;
return true;
case PseudoType::SCROLLBAR_TRACK:
*pseudo_type_output = dom::PseudoType::SCROLLBAR_TRACK;
return true;
case PseudoType::SCROLLBAR_TRACK_PIECE:
*pseudo_type_output = dom::PseudoType::SCROLLBAR_TRACK_PIECE;
return true;
case PseudoType::SCROLLBAR_CORNER:
*pseudo_type_output = dom::PseudoType::SCROLLBAR_CORNER;
return true;
case PseudoType::RESIZER:
*pseudo_type_output = dom::PseudoType::RESIZER;
return true;
case PseudoType::INPUT_LIST_BUTTON:
*pseudo_type_output = dom::PseudoType::INPUT_LIST_BUTTON;
return true;
}
return false;
}
} // namespace
ElementFinder::Result::Result() = default;
ElementFinder::Result::~Result() = default;
ElementFinder::Result::Result(const Result& to_copy) = default;
ElementFinder::ElementFinder(content::WebContents* web_contents,
DevtoolsClient* devtools_client,
const Selector& selector,
bool strict)
: web_contents_(web_contents),
devtools_client_(devtools_client),
selector_(selector),
strict_(strict),
element_result_(std::make_unique<Result>()) {}
ElementFinder::~ElementFinder() = default;
void ElementFinder::Start(Callback callback) {
callback_ = std::move(callback);
if (selector_.empty()) {
SendResult(ClientStatus(INVALID_SELECTOR));
return;
}
element_result_->container_frame_selector_index = 0;
element_result_->container_frame_host = web_contents_->GetMainFrame();
devtools_client_->GetRuntime()->Evaluate(
std::string(kGetDocumentElement), /* node_frame_id= */ std::string(),
base::BindOnce(&ElementFinder::OnGetDocumentElement,
weak_ptr_factory_.GetWeakPtr(), 0));
}
void ElementFinder::SendResult(const ClientStatus& status) {
DCHECK(callback_);
DCHECK(element_result_);
std::move(callback_).Run(status, std::move(element_result_));
}
void ElementFinder::OnGetDocumentElement(
size_t index,
const DevtoolsClient::ReplyStatus& reply_status,
std::unique_ptr<runtime::EvaluateResult> result) {
ClientStatus status =
CheckJavaScriptResult(reply_status, result.get(), __FILE__, __LINE__);
if (!status.ok()) {
VLOG(1) << __func__ << " Failed to get document root element.";
SendResult(status);
return;
}
std::string object_id;
if (!SafeGetObjectId(result->GetResult(), &object_id)) {
VLOG(1) << __func__ << " Failed to get document root element.";
SendResult(ClientStatus(ELEMENT_RESOLUTION_FAILED));
return;
}
RecursiveFindElement(object_id, index);
}
void ElementFinder::RecursiveFindElement(const std::string& object_id,
size_t index) {
std::vector<std::unique_ptr<runtime::CallArgument>> arguments;
AddRuntimeCallArgument(selector_.selectors[index], &arguments);
// For finding intermediate elements, strict mode would be more appropriate,
// as long as the logic does not support more than one intermediate match.
//
// TODO(b/129387787): first, add logging to figure out whether it matters and
// decide between strict mode and full support for multiple matching
// intermeditate elements.
AddRuntimeCallArgument(strict_, &arguments);
std::string function;
if (index == (selector_.selectors.size() - 1)) {
if (selector_.must_be_visible || !selector_.inner_text_pattern.empty() ||
!selector_.value_pattern.empty()) {
function.assign(kQuerySelectorWithConditions);
AddRuntimeCallArgument(selector_.must_be_visible, &arguments);
AddRuntimeCallArgument(selector_.inner_text_pattern, &arguments);
AddRuntimeCallArgument(selector_.value_pattern, &arguments);
}
}
if (function.empty()) {
function.assign(kQuerySelector);
}
devtools_client_->GetRuntime()->CallFunctionOn(
runtime::CallFunctionOnParams::Builder()
.SetObjectId(object_id)
.SetArguments(std::move(arguments))
.SetFunctionDeclaration(function)
.Build(),
element_result_->node_frame_id,
base::BindOnce(&ElementFinder::OnQuerySelectorAll,
weak_ptr_factory_.GetWeakPtr(), index));
}
void ElementFinder::OnQuerySelectorAll(
size_t index,
const DevtoolsClient::ReplyStatus& reply_status,
std::unique_ptr<runtime::CallFunctionOnResult> result) {
if (!result) {
// It is possible for a document element to already exist, but not be
// available yet to query because the document hasn't been loaded. This
// results in OnQuerySelectorAll getting a nullptr result. For this specific
// call, it is expected.
VLOG(1) << __func__ << ": Context doesn't exist yet to query selector "
<< index << " of " << selector_;
SendResult(ClientStatus(ELEMENT_RESOLUTION_FAILED));
return;
}
ClientStatus status =
CheckJavaScriptResult(reply_status, result.get(), __FILE__, __LINE__);
if (!status.ok()) {
VLOG(1) << __func__ << ": Failed to query selector " << index << " of "
<< selector_;
SendResult(status);
return;
}
int int_result;
if (SafeGetIntValue(result->GetResult(), &int_result)) {
DCHECK(int_result == TOO_MANY_ELEMENTS);
SendResult(ClientStatus(TOO_MANY_ELEMENTS));
return;
}
std::string object_id;
if (!SafeGetObjectId(result->GetResult(), &object_id)) {
SendResult(ClientStatus(ELEMENT_RESOLUTION_FAILED));
return;
}
if (selector_.selectors.size() == index + 1) {
// The pseudo type is associated to the final element matched by
// |selector_|, which means that we currently don't handle matching an
// element inside a pseudo element.
if (selector_.pseudo_type == PseudoType::UNDEFINED) {
// Return object id of the element.
element_result_->object_id = object_id;
SendResult(OkClientStatus());
return;
}
// We are looking for a pseudo element associated with this element.
dom::PseudoType pseudo_type;
if (!ConvertPseudoType(selector_.pseudo_type, &pseudo_type)) {
// Return empty result.
SendResult(ClientStatus(INVALID_ACTION));
return;
}
devtools_client_->GetDOM()->DescribeNode(
dom::DescribeNodeParams::Builder().SetObjectId(object_id).Build(),
element_result_->node_frame_id,
base::BindOnce(&ElementFinder::OnDescribeNodeForPseudoElement,
weak_ptr_factory_.GetWeakPtr(), pseudo_type));
return;
}
devtools_client_->GetDOM()->DescribeNode(
dom::DescribeNodeParams::Builder().SetObjectId(object_id).Build(),
element_result_->node_frame_id,
base::BindOnce(&ElementFinder::OnDescribeNode,
weak_ptr_factory_.GetWeakPtr(), object_id, index));
}
void ElementFinder::OnDescribeNodeForPseudoElement(
dom::PseudoType pseudo_type,
const DevtoolsClient::ReplyStatus& reply_status,
std::unique_ptr<dom::DescribeNodeResult> result) {
if (!result || !result->GetNode()) {
VLOG(1) << __func__ << " Failed to describe the node for pseudo element.";
SendResult(UnexpectedDevtoolsErrorStatus(reply_status, __FILE__, __LINE__));
return;
}
auto* node = result->GetNode();
if (node->HasPseudoElements()) {
for (const auto& pseudo_element : *(node->GetPseudoElements())) {
if (pseudo_element->HasPseudoType() &&
pseudo_element->GetPseudoType() == pseudo_type) {
devtools_client_->GetDOM()->ResolveNode(
dom::ResolveNodeParams::Builder()
.SetBackendNodeId(pseudo_element->GetBackendNodeId())
.Build(),
element_result_->node_frame_id,
base::BindOnce(&ElementFinder::OnResolveNodeForPseudoElement,
weak_ptr_factory_.GetWeakPtr()));
return;
}
}
}
// Failed to find the pseudo element: run the callback with empty result.
SendResult(ClientStatus(ELEMENT_RESOLUTION_FAILED));
}
void ElementFinder::OnResolveNodeForPseudoElement(
const DevtoolsClient::ReplyStatus& reply_status,
std::unique_ptr<dom::ResolveNodeResult> result) {
if (result && result->GetObject() && result->GetObject()->HasObjectId()) {
element_result_->object_id = result->GetObject()->GetObjectId();
}
SendResult(OkClientStatus());
}
void ElementFinder::OnDescribeNode(
const std::string& object_id,
size_t index,
const DevtoolsClient::ReplyStatus& reply_status,
std::unique_ptr<dom::DescribeNodeResult> result) {
if (!result || !result->GetNode()) {
VLOG(1) << __func__ << " Failed to describe the node.";
SendResult(UnexpectedDevtoolsErrorStatus(reply_status, __FILE__, __LINE__));
return;
}
auto* node = result->GetNode();
std::vector<int> backend_ids;
if (node->GetNodeName() == "IFRAME") {
DCHECK(node->HasFrameId()); // Ensure all frames have an id.
element_result_->container_frame_selector_index = index;
element_result_->container_frame_host =
FindCorrespondingRenderFrameHost(node->GetFrameId());
Result result_frame;
result_frame.container_frame_selector_index =
element_result_->container_frame_selector_index;
result_frame.container_frame_host = element_result_->container_frame_host;
result_frame.object_id = object_id;
element_result_->frame_stack.emplace_back(result_frame);
if (!element_result_->container_frame_host) {
VLOG(1) << __func__ << " Failed to find corresponding owner frame.";
SendResult(ClientStatus(FRAME_HOST_NOT_FOUND));
return;
}
if (node->HasContentDocument()) {
// If the frame has a ContentDocument it's considered a local frame. We
// don't need to assign the frame id, since devtools can just send the
// commands to the main session.
backend_ids.emplace_back(node->GetContentDocument()->GetBackendNodeId());
} else {
// If the frame has no ContentDocument, it's considered an
// OutOfProcessIFrame.
// See https://www.chromium.org/developers/design-documents/oop-iframes
// for full documentation.
// With the iFrame running in a different process it is necessary to pass
// the correct session id from devtools. We need to set the frame id,
// such that devtools can resolve the corresponding session id.
element_result_->node_frame_id = node->GetFrameId();
// Kick off another find element chain to walk down the OOP iFrame.
devtools_client_->GetRuntime()->Evaluate(
std::string(kGetDocumentElement), element_result_->node_frame_id,
base::BindOnce(&ElementFinder::OnGetDocumentElement,
weak_ptr_factory_.GetWeakPtr(), index + 1));
return;
}
}
if (node->HasShadowRoots()) {
// TODO(crbug.com/806868): Support multiple shadow roots.
backend_ids.emplace_back(
node->GetShadowRoots()->front()->GetBackendNodeId());
}
if (!backend_ids.empty()) {
devtools_client_->GetDOM()->ResolveNode(
dom::ResolveNodeParams::Builder()
.SetBackendNodeId(backend_ids[0])
.Build(),
element_result_->node_frame_id,
base::BindOnce(&ElementFinder::OnResolveNode,
weak_ptr_factory_.GetWeakPtr(), index));
return;
}
RecursiveFindElement(object_id, index + 1);
}
void ElementFinder::OnResolveNode(
size_t index,
const DevtoolsClient::ReplyStatus& reply_status,
std::unique_ptr<dom::ResolveNodeResult> result) {
if (!result || !result->GetObject() || !result->GetObject()->HasObjectId()) {
VLOG(1) << __func__ << " Failed to resolve object id from backend id.";
SendResult(UnexpectedDevtoolsErrorStatus(reply_status, __FILE__, __LINE__));
return;
}
RecursiveFindElement(result->GetObject()->GetObjectId(), ++index);
}
content::RenderFrameHost* ElementFinder::FindCorrespondingRenderFrameHost(
std::string frame_id) {
for (auto* frame : web_contents_->GetAllFrames()) {
if (frame->GetDevToolsFrameToken().ToString() == frame_id) {
return frame;
}
}
return nullptr;
}
} // namespace autofill_assistant
| 37.23185 | 80 | 0.686942 | [
"object",
"vector"
] |
a700742b0b2ec353dd5173120627c7db34ee318b | 3,478 | hpp | C++ | __unit_tests/gv_framework_unit_test/unit_test_importer_exporter.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | 2 | 2018-12-03T13:17:31.000Z | 2020-04-08T07:00:02.000Z | __unit_tests/gv_framework_unit_test/unit_test_importer_exporter.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | null | null | null | __unit_tests/gv_framework_unit_test/unit_test_importer_exporter.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | null | null | null |
namespace unit_test_importer_exporter
{
void main(gvt_array< gv_string >& args)
{
{
gv_unit_test_context_guard context;
//============>>INIT=================================================>>
sub_test_timer timer("test_importer_");
//init
m_sandbox->register_processor(gv_world::static_class(), gve_event_channel_world);
gv_world* my_world = gvt_cast< gv_world >(m_sandbox->get_event_processor(gve_event_channel_world));
gv_module* my_mod = m_sandbox->create_object< gv_module >(gv_id("mesh_test"));
gv_entity* my_entity = m_sandbox->create_object< gv_entity >(gv_id("entity"), NULL);
gv_com_static_mesh* pmesh0 = m_sandbox->create_object< gv_com_static_mesh >(my_entity);
gv_static_mesh* my_static_mesh = m_sandbox->create_object< gv_static_mesh >(my_mod);
gv_texture* my_texture = m_sandbox->create_object< gv_texture >(my_static_mesh);
gv_string_tmp tex_file_name = FILE_TEX_SNOW_CUBEMAP;
my_texture->set_file_name(tex_file_name);
gv_string_tmp file_name = FILE_OBJ_NINJA_HEAD;
if (args.size() >= 2)
args[1] >> file_name;
if (!m_sandbox->import_external_format(my_static_mesh, file_name))
{
gv_model* model = m_sandbox->create_object< gv_model >(my_mod);
m_sandbox->import_external_format(model, file_name);
if (model->get_nb_static_mesh())
my_static_mesh = model->get_static_mesh(0);
else if (model->get_nb_skeletal_mesh())
my_static_mesh = model->get_skeletal_mesh(0)->m_t_pose_mesh;
}
my_static_mesh->m_diffuse_texture = my_texture;
pmesh0->set_resource(my_static_mesh);
//set the renderer of the mesh, this is needed .
pmesh0->set_renderer_id(gve_render_pass_opaque, gv_id("gv_com_simple_shader_renderer"));
my_entity->add_component(pmesh0);
my_world->add_entity(my_entity);
//set camera!!
gv_entity* my_camera = m_sandbox->create_object< gv_entity >(gv_id("my_camera"), NULL);
my_camera->add_component(gv_id("gv_com_cam_fps_fly"));
gv_com_camera* camera = m_sandbox->create_object< gv_com_camera >(gv_id("main_camera"), my_camera);
my_camera->add_component(camera);
GVM_POST_EVENT(render_set_camera, render, (pe->camera = camera));
my_world->add_entity(my_camera);
camera->set_fov(60, 1.333f, 0.1f, 1000);
camera->set_look_at(gv_vector3(0, 0, 300), gv_vector3(0, 0, 0));
camera->update_projection_view_matrix();
//============>>GO GO GO !!
int loop = 1000;
bool quit = false;
if (args.size())
args[0] >> loop;
while (loop-- && !quit)
{
gv_string_tmp title = "do_ray_trace ,arrow to move , a,s to rotate ====>>";
gv_global::debug_draw.get()->draw_string(*title, gv_vector2i(100, 120), gv_color::RED());
if (loop == 1)
{
gv_object_event_render_uninit* pe = new gv_object_event_render_uninit;
m_sandbox->post_event(pe, gve_event_channel_render);
}
{
gv_vector3 v[3] = {gv_vector3(0, 0, 0.5f), gv_vector3(100, 100, 0.5f), gv_vector3(100, 0, 0.5f)};
gv_vector2 uv[3] = {gv_vector2(0, 0), gv_vector2(1, 1), gv_vector2(1, 0)};
gv_color color[3] = {gv_color::WHITE(), gv_color::WHITE(), gv_color::WHITE()};
get_debug_draw()->draw_tex_triangle(v, uv, color);
get_debug_draw()->set_debug_texture(my_texture);
gv_vector3 v2[3] = {gv_vector3(200, 0, 0.5f), gv_vector3(300, 100, 0.5f), gv_vector3(300, 0, 0.5f)};
get_debug_draw()->draw_tex_triangle(v2, uv, color);
}
quit = !m_sandbox->tick();
}
//================================================
m_sandbox->export_module(my_mod->get_name_id());
}
}
}
| 41.404762 | 104 | 0.695802 | [
"mesh",
"render",
"model"
] |
a7018d209c482969d8354b6961e7f84c5536c6c7 | 41,102 | cpp | C++ | src/base/command/CallFunction.cpp | Randl/GMAT | d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5 | [
"Apache-2.0"
] | 2 | 2020-01-01T13:14:57.000Z | 2020-12-09T07:05:07.000Z | src/base/command/CallFunction.cpp | rdadan/GMAT-R2016a | d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5 | [
"Apache-2.0"
] | 1 | 2018-03-15T08:58:37.000Z | 2018-03-20T20:11:26.000Z | src/base/command/CallFunction.cpp | rdadan/GMAT-R2016a | d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5 | [
"Apache-2.0"
] | 3 | 2019-10-13T10:26:49.000Z | 2020-12-09T07:06:55.000Z | //$Id$
//------------------------------------------------------------------------------
// CallFunction
//------------------------------------------------------------------------------
// 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG04CC06P
//
// Author: Allison Greene
// Created: 2004/09/22
//
/**
* Definition for the CallFunction command class
*/
//------------------------------------------------------------------------------
#include "CallFunction.hpp"
#include "BeginFunction.hpp"
#include "StringTokenizer.hpp"
#include "StringUtil.hpp" // for Replace()
#include "FileUtil.hpp" // for ParseFileName()
#include "FileManager.hpp" // for GetAllMatlabFunctionPaths()
#include "MessageInterface.hpp"
#include "GmatGlobal.hpp" // for IsWritingGmatKeyword()
#include <sstream>
//#define DEBUG_CALL_FUNCTION_PARAM
//#define DEBUG_CALL_FUNCTION_REF_OBJ
//#define DEBUG_CALL_FUNCTION_INIT
//#define DEBUG_CALL_FUNCTION_EXEC
//#define DEBUG_SEND_PARAM
//#define DEBUG_UPDATE_VAR
//#define DEBUG_UPDATE_OBJECT
//#define DEBUG_SHOW_ARRAY
//#define DEBUG_GET_OUTPUT
//#define DEBUG_OBJECT_MAP
//#define DEBUG_GLOBAL_OBJECT_MAP
//#define DEBUG_RUN_COMPLETE
//#define DEBUG_OBJECT_REF
//#define DEBUG_FUNCTION
//#ifndef DEBUG_MEMORY
//#define DEBUG_MEMORY
//#endif
//#ifndef DEBUG_TRACE
//#define DEBUG_TRACE
//#endif
#ifdef DEBUG_MEMORY
#include "MemoryTracker.hpp"
#endif
#ifdef DEBUG_TRACE
#include <ctime> // for clock()
#endif
//---------------------------------
// static data
//---------------------------------
const std::string
CallFunction::PARAMETER_TEXT[CallFunctionParamCount - GmatCommandParamCount] =
{
"FunctionName",
"AddInput",
"AddOutput",
"CommandStream",
};
const Gmat::ParameterType
CallFunction::PARAMETER_TYPE[CallFunctionParamCount - GmatCommandParamCount] =
{
Gmat::STRING_TYPE,
Gmat::STRINGARRAY_TYPE,
Gmat::STRINGARRAY_TYPE,
Gmat::OBJECT_TYPE,
};
//------------------------------------------------------------------------------
// CallFunction::CallFunction(const std::string &type)
//------------------------------------------------------------------------------
CallFunction::CallFunction(const std::string &type) :
GmatCommand (type),
callcmds (NULL),
mFunction (NULL),
mFunctionName (""),
mFunctionPathAndName (""),
isGmatFunction (false),
isMatlabFunction (false),
isBuiltinGmatFunction(false)
{
mNumInputParams = 0;
mNumOutputParams = 0;
parameterCount = CallFunctionParamCount;
objectTypeNames.push_back("CallFunction");
}
//------------------------------------------------------------------------------
// ~CallFunction()
//------------------------------------------------------------------------------
CallFunction::~CallFunction()
{
if (callcmds)
delete callcmds;
}
//------------------------------------------------------------------------------
// CallFunction(const CallFunction& cf) :
//------------------------------------------------------------------------------
CallFunction::CallFunction(const CallFunction& cf) :
GmatCommand (cf),
callcmds (NULL),
mFunction (cf.mFunction),
mFunctionName (cf.mFunctionName),
mFunctionPathAndName (cf.mFunctionPathAndName),
fm (cf.fm)
{
mNumInputParams = cf.mNumInputParams;
mNumOutputParams = cf.mNumOutputParams;
objectArray = cf.objectArray;
mInputList = cf.mInputList;
mOutputList = cf.mOutputList;
callcmds = NULL; // Commands must be reinitialized
isGmatFunction = cf.isGmatFunction;
isMatlabFunction = cf.isMatlabFunction;
isBuiltinGmatFunction = cf.isBuiltinGmatFunction;
mInputNames = cf.mInputNames;
mOutputNames = cf.mOutputNames;
parameterCount = CallFunctionParamCount;
}
//------------------------------------------------------------------------------
// CallFunction& operator=(const CallFunction& cf)
//------------------------------------------------------------------------------
CallFunction& CallFunction::operator=(const CallFunction& cf)
{
if (this == &cf)
return *this;
GmatCommand::operator=(cf);
mFunction = cf.mFunction;
mFunctionName = cf.mFunctionName;
mFunctionPathAndName = cf.mFunctionPathAndName;
mNumInputParams = cf.mNumInputParams;
mNumOutputParams = cf.mNumOutputParams;
objectArray = cf.objectArray;
mInputList = cf.mInputList;
mOutputList = cf.mOutputList;
callcmds = NULL; // Commands must be reinitialized
isGmatFunction = cf.isGmatFunction;
isMatlabFunction = cf.isMatlabFunction;
isBuiltinGmatFunction = cf.isBuiltinGmatFunction;
mInputNames = cf.mInputNames;
mOutputNames = cf.mOutputNames;
fm = cf.fm;
return *this;
}
//------------------------------------------------------------------------------
// std::string FormEvalString()
// String format
// [Out1, Out2] = FunctionName(In1, In2, In3);
//------------------------------------------------------------------------------
std::string CallFunction::FormEvalString()
{
#ifdef DEBUG_MATLAB_EVAL
MessageInterface::ShowMessage
("CallFunction::FormEvalString() entered, mFunction=<%p>'%s'\n",
mFunction, mFunction ? mFunction->GetName().c_str() : "NULL");
#endif
std::string evalString = "";
// left hand side of evaluation string and equals (if necessary)
if (mOutputList.size() > 1)
{
evalString = evalString + "[";
Parameter *param = (Parameter *)mOutputList[0];
evalString = evalString + param->GetName();
for (unsigned int i=1; i<mOutputList.size(); i++)
{
param = (Parameter *)mOutputList[i];
evalString = evalString +", " + param->GetName();
}
evalString = evalString + "] = ";
}
else if (mOutputList.size() == 1)
{
Parameter *param = (Parameter *)mOutputList[0];
evalString = "[" + evalString + param->GetName() + "]";
evalString = evalString +" = ";
}
else if (mOutputList.size() == 0)
{
// no left hand side
}
else
{
// need to throw an exception here
}
// right hand side of evaluation string
// function name and left parenthesis
evalString = evalString + mFunction->GetName().c_str() + "(";
// input parameters
if (mInputList.size() > 0)
{
Parameter *param = (Parameter *)mInputList[0];
evalString = evalString + param->GetName();
for (unsigned int i=1; i<mInputList.size(); i++)
{
param = (Parameter *)mInputList[i];
evalString = evalString + ", " + param->GetName();
}
}
// right parenthesis and semi-colon
evalString = evalString + ");";
return evalString;
}
//------------------------------------------------------------------------------
// bool AddInputParameter(const std::string ¶mName, Integer index)
//------------------------------------------------------------------------------
bool CallFunction::AddInputParameter(const std::string ¶mName, Integer index)
{
if (paramName != "" && index == mNumInputParams)
{
mInputNames.push_back(paramName);
mNumInputParams = mInputNames.size();
mInputList.push_back(NULL);
fm.AddInput(paramName);
return true;
}
return false;
}
//------------------------------------------------------------------------------
// bool AddOutputParameter(const std::string ¶mName, Integer index)
//------------------------------------------------------------------------------
bool CallFunction::AddOutputParameter(const std::string ¶mName, Integer index)
{
if (paramName != "" && index == mNumOutputParams)
{
mOutputNames.push_back(paramName);
mNumOutputParams = mOutputNames.size();
mOutputList.push_back(NULL);
fm.AddOutput(paramName);
return true;
}
return false;
}
//---------------------------------------------------------------------------
// bool HasOtherReferenceToObject(const std::string &withName)
//---------------------------------------------------------------------------
/*
* Determines whether or not this object has a hidden or indirect
* reference to the input object. This could be the case when a command has
* wrappers and one of those wrappers has the named object as a reference.
*
* @param withName the name of the object we're looking for
*
* @return true if it has a reference to the named object
*/
//---------------------------------------------------------------------------
bool CallFunction::HasOtherReferenceToObject(const std::string &withName)
{
#ifdef DEBUG_OBJECT_REF
MessageInterface::ShowMessage(
"Entering HasOtherReferenceToObject for item \"%s\" of type \"%s\" and withName \"%s\"\n",
instanceName.c_str(), typeName.c_str(), withName.c_str());
#endif
// Right now, for this class, we look at the parameters
StringArray paramNames = GetRefObjectNameArray(Gmat::PARAMETER);
Integer sz = (Integer) paramNames.size();
std::string objName = "";
StringArray byDots;
for (Integer ii = 0; ii < sz; ii++)
{
byDots = GmatStringUtil::SeparateDots(paramNames.at(ii));
// Check the first part of the name for the object we're looking for
objName = GmatStringUtil::Trim(GmatStringUtil::GetArrayName(byDots.at(0)));
#ifdef DEBUG_OBJECT_REF
MessageInterface::ShowMessage("for object %s, param name %d is: %s\n",
instanceName.c_str(), ii, paramNames.at(ii).c_str());
MessageInterface::ShowMessage("... and extracted name is: %s\n", objName.c_str());
#endif
if (objName == withName) return true;
// If there are more than two parts when separated by dots, then there is
// a dependency, so we need to check it for the object
if (byDots.size() > 2)
{
objName = GmatStringUtil::Trim(GmatStringUtil::GetArrayName(byDots.at(1)));
#ifdef DEBUG_OBJECT_REF
MessageInterface::ShowMessage("for object %s, param name %d is: %s\n",
instanceName.c_str(), ii, paramNames.at(ii).c_str());
MessageInterface::ShowMessage("... and 2nd extracted name is: %s\n", objName.c_str());
#endif
if (objName == withName) return true;
}
}
return false;
}
//------------------------------------------------------------------------------
// void SetObjectMap(std::map<std::string, GmatBase *> *map)
//------------------------------------------------------------------------------
/**
* Called by the Sandbox to set the local asset store used by the GmatCommand
*
* @param <map> Pointer to the local object map
*/
//------------------------------------------------------------------------------
void CallFunction::SetObjectMap(std::map<std::string, GmatBase *> *map)
{
GmatCommand::SetObjectMap(map);
fm.SetObjectMap(map);
}
//------------------------------------------------------------------------------
// void SetGlobalObjectMap(std::map<std::string, GmatBase *> *map)
//------------------------------------------------------------------------------
/**
* Called by the Sandbox to set the global asset store used by the GmatCommand
*
* @param <map> Pointer to the local object map
*/
//------------------------------------------------------------------------------
void CallFunction::SetGlobalObjectMap(std::map<std::string, GmatBase *> *map)
{
#ifdef DEBUG_GLOBAL_OBJECT_MAP
MessageInterface::ShowMessage
("CallFunction::SetGlobalObjectMap() entered, mFunctionName='%s', "
"map=<%p>\n", mFunctionName.c_str(), map);
#endif
GmatCommand::SetGlobalObjectMap(map);
// Now, find the function object
GmatBase *mapObj = FindObject(mFunctionName);
#ifdef DEBUG_GLOBAL_OBJECT_MAP
MessageInterface::ShowMessage
(" mapObj=<%p><%s>'%s'\n", mapObj,
mapObj ? mapObj->GetTypeName().c_str() : "NULL",
mapObj ? mapObj->GetName().c_str() : "NULL");
#endif
if (mapObj == NULL)
{
//throw CommandException("CallFunction command cannot find Function " +
// mFunctionName + "\n");
; // leave NULL for now
}
else
{
mFunction = (Function *)mapObj;
#ifdef DEBUG_GLOBAL_OBJECT_MAP
MessageInterface::ShowMessage
(" mFunction=<%p><%s>\n", mFunction, mFunction->GetName().c_str());
#endif
// Set GmatFunction to FunctionManager (loj: 2008.09.03)
// Set BuiltinGmatFunction to FunctionManager (loj: 2016.05.04)
//if (mapObj->GetTypeName() == "GmatFunction")
if (mapObj->IsOfType("GmatFunction") || mapObj->IsOfType("BuiltinGmatFunction"))
{
#ifdef DEBUG_FUNCTION
MessageInterface::ShowMessage
("CallFunction::SetGlobalObjectMap() setting function<%p>'%s' to FunctionManager\n",
mFunction, mFunction ? mFunction->GetName().c_str() : "NULL");
#endif
mFunction->SetCallDescription(GetGeneratingString(Gmat::NO_COMMENTS));
fm.SetFunction(mFunction);
}
}
fm.SetGlobalObjectMap(map);
#ifdef DEBUG_GLOBAL_OBJECT_MAP
MessageInterface::ShowMessage("CallFunction::SetGlobalObjectMap() exiting\n");
#endif
}
//------------------------------------------------------------------------------
// bool HasAFunction()
//------------------------------------------------------------------------------
bool CallFunction::HasAFunction()
{
return true;
}
//------------------------------------------------------------------------------
// virtual bool IsMatlabFunctionCall()
//------------------------------------------------------------------------------
bool CallFunction::IsMatlabFunctionCall()
{
if (isMatlabFunction)
return true;
else
return false;
}
//------------------------------------------------------------------------------
// GmatBase* Clone(void) const
//------------------------------------------------------------------------------
/**
* This method returns a clone of the CallFunction.
*
* @return clone of the CallFunction.
*
*/
//------------------------------------------------------------------------------
GmatBase* CallFunction::Clone() const
{
return (new CallFunction(*this));
}
//------------------------------------------------------------------------------
// std::string GetParameterText(const Integer id) const
//------------------------------------------------------------------------------
std::string CallFunction::GetParameterText(const Integer id) const
{
#ifdef DEBUG_CALL_FUNCTION_PARAM
MessageInterface::ShowMessage("CallFunction::GetParameterText\n");
#endif
if (id >= GmatCommandParamCount && id < CallFunctionParamCount)
return PARAMETER_TEXT[id - GmatCommandParamCount];
else
return GmatCommand::GetParameterText(id);
}
//------------------------------------------------------------------------------
// const std::string& GetGeneratingString()
//------------------------------------------------------------------------------
/**
* Method used to retrieve the string that was parsed to build this GmatCommand.
*
* This method is used to retrieve the GmatCommand string from the script that
* was parsed to build the GmatCommand. It is used to save the script line, so
* that the script can be written to a file without inverting the steps taken to
* set up the internal object data. As a side benefit, the script line is
* available in the GmatCommand structure for debugging purposes.
*
* @param mode Specifies the type of serialization requested.
* @param prefix Optional prefix appended to the object's name. (Used to
* indent commands)
* @param useName Name that replaces the object's name. (Not used in
* commands)
*
* @return The script line that, when interpreted, defines this CallFunction.
*/
//------------------------------------------------------------------------------
const std::string& CallFunction::GetGeneratingString(Gmat::WriteMode mode,
const std::string &prefix,
const std::string &useName)
{
std::string gen;
// Build the local string
if (mode != Gmat::NO_COMMENTS)
{
bool writeGmatKeyword = GmatGlobal::Instance()->IsWritingGmatKeyword();
// We now write out GMAT prefix on option from the startup file (see GMT-3233)
if (writeGmatKeyword)
gen = prefix + "GMAT ";
else
gen = prefix;
}
if (mOutputNames.size() > 0)
{
gen += "[";
for (StringArray::iterator i = mOutputNames.begin();
i != mOutputNames.end(); ++i)
{
if (i != mOutputNames.begin())
gen += ", ";
gen += *i;
}
gen += "] = ";
}
gen += mFunctionName;
if (mInputNames.size() > 0)
{
gen += "(";
for (StringArray::iterator i = mInputNames.begin();
i != mInputNames.end(); ++i)
{
if (i != mInputNames.begin())
gen += ", ";
gen += *i;
}
gen += ")";
}
generatingString = gen + ";";
if (mode == Gmat::NO_COMMENTS)
{
InsertCommandName(generatingString);
return generatingString;
}
// Then call the base class method
return GmatCommand::GetGeneratingString(mode, prefix, useName);
}
//------------------------------------------------------------------------------
// Integer GetParameterID(const std::string &str) const
//------------------------------------------------------------------------------
Integer CallFunction::GetParameterID(const std::string &str) const
{
#ifdef DEBUG_CALL_FUNCTION_PARAM
MessageInterface::ShowMessage("CallFunction::GetParameterID \n");
#endif
for (int i=GmatCommandParamCount; i<CallFunctionParamCount; i++)
{
if (str == PARAMETER_TEXT[i - GmatCommandParamCount])
return i;
}
return GmatCommand::GetParameterID(str);
}
//------------------------------------------------------------------------------
// Gmat::ParameterType GetParameterType(const Integer id) const
//------------------------------------------------------------------------------
Gmat::ParameterType CallFunction::GetParameterType(const Integer id) const
{
#ifdef DEBUG_CALL_FUNCTION_PARAM
MessageInterface::ShowMessage("CallFunction::GetParameterType\n");
#endif
if (id >= GmatCommandParamCount && id < CallFunctionParamCount)
return PARAMETER_TYPE[id - GmatCommandParamCount];
else
return GmatCommand::GetParameterType(id);
}
//------------------------------------------------------------------------------
// std::string GetParameterTypeString(const Integer id) const
//------------------------------------------------------------------------------
std::string CallFunction::GetParameterTypeString(const Integer id) const
{
#ifdef DEBUG_CALL_FUNCTION_PARAM
MessageInterface::ShowMessage("CallFunction::GetParameterTypeString\n");
#endif
if (id >= GmatCommandParamCount && id < CallFunctionParamCount)
return GmatBase::PARAM_TYPE_STRING[GetParameterType(id - GmatCommandParamCount)];
else
return GmatCommand::GetParameterTypeString(id);
}
//------------------------------------------------------------------------------
// std::string GetStringParameter(const Integer id) const
//------------------------------------------------------------------------------
std::string CallFunction::GetStringParameter(const Integer id) const
{
#ifdef DEBUG_CALL_FUNCTION_PARAM
MessageInterface::ShowMessage("CallFunction::GetStringParameter\n");
#endif
switch (id)
{
case FUNCTION_NAME:
return fm.GetFunctionName();
//return mFunctionName;
default:
return GmatCommand::GetStringParameter(id);
}
}
//------------------------------------------------------------------------------
// std::string GetStringParameter(const std::string &label) const
//------------------------------------------------------------------------------
std::string CallFunction::GetStringParameter(const std::string &label) const
{
return GetStringParameter(GetParameterID(label));
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const Integer id, const std::string &value)
//------------------------------------------------------------------------------
bool CallFunction::SetStringParameter(const Integer id, const std::string &value)
{
#ifdef DEBUG_CALL_FUNCTION_PARAM
MessageInterface::ShowMessage
("CallFunction::SetStringParameter with id = %d and value = %s\n",
id, value.c_str());
#endif
switch (id)
{
case FUNCTION_NAME:
mFunctionName = value;
mFunctionPathAndName = value;
fm.SetFunctionName(value);
return true;
case ADD_INPUT:
return AddInputParameter(value, mNumInputParams);
case ADD_OUTPUT:
return AddOutputParameter(value, mNumOutputParams);
default:
return GmatCommand::SetStringParameter(id, value);
}
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const std::string &label, const char *value)
//------------------------------------------------------------------------------
bool CallFunction::SetStringParameter(const std::string &label,
const char *value)
{
return SetStringParameter(GetParameterID(label), std::string(value));
}
//------------------------------------------------------------------------------
// bool SetStringParameter(const std::string &label,
// const std::string &value)
//------------------------------------------------------------------------------
bool CallFunction::SetStringParameter(const std::string &label,
const std::string &value)
{
return SetStringParameter(GetParameterID(label), value);
}
//------------------------------------------------------------------------------
// virtual bool SetStringParameter(const Integer id, const std::string &value,
// const Integer index)
//------------------------------------------------------------------------------
bool CallFunction::SetStringParameter(const Integer id, const std::string &value,
const Integer index)
{
switch (id)
{
case ADD_INPUT:
return AddInputParameter(value, index);
case ADD_OUTPUT:
return AddOutputParameter(value, index);
default:
return GmatCommand::SetStringParameter(id, value, index);
}
}
//------------------------------------------------------------------------------
// virtual bool SetStringParameter(const std::string &label,
// const std::string &value,
// const Integer index)
//------------------------------------------------------------------------------
bool CallFunction::SetStringParameter(const std::string &label,
const std::string &value,
const Integer index)
{
return SetStringParameter(GetParameterID(label), value, index);
}
//------------------------------------------------------------------------------
// const StringArray& GetStringArrayParameter(const Integer id) const
//------------------------------------------------------------------------------
const StringArray& CallFunction::GetStringArrayParameter(const Integer id) const
{
switch (id)
{
case ADD_INPUT:
return mInputNames;
case ADD_OUTPUT:
return mOutputNames;
default:
return GmatCommand::GetStringArrayParameter(id);
}
}
//------------------------------------------------------------------------------
// StringArray& GetStringArrayParameter(const std::string &label) const
//------------------------------------------------------------------------------
const StringArray& CallFunction::GetStringArrayParameter(const std::string &label) const
{
return GetStringArrayParameter(GetParameterID(label));
}
//------------------------------------------------------------------------------
// virtual bool TakeAction(const std::string &action,
// const std::string &actionData = "");
//------------------------------------------------------------------------------
/**
* This method performs action.
*
* @param <action> action to perform
* @param <actionData> action data associated with action
* @return true if action successfully performed
*
*/
//------------------------------------------------------------------------------
bool CallFunction::TakeAction(const std::string &action,
const std::string &actionData)
{
if (action == "ClearInput")
{
ClearInputParameters();
return true;
}
else if (action == "ClearOutput")
{
ClearOutputParameters();
return true;
}
else if (action == "Clear")
{
ClearInputParameters();
ClearOutputParameters();
objectArray.clear();
return true;
}
return GmatCommand::TakeAction(action, actionData);
}
//------------------------------------------------------------------------------
// StringArray GetRefObjectNameArray(const Gmat::ObjectType type) const
//------------------------------------------------------------------------------
const StringArray& CallFunction::GetRefObjectNameArray(const Gmat::ObjectType type)
{
refObjectNames.clear();
if (type == Gmat::PARAMETER)
{
for (unsigned int i=0; i<mInputNames.size(); i++)
refObjectNames.push_back(mInputNames[i]);
for (unsigned int i=0; i<mOutputNames.size(); i++)
refObjectNames.push_back(mOutputNames[i]);
return refObjectNames;
}
return refObjectNames;
}
//---------------------------------------------------------------------------
// bool RenameRefObject(const Gmat::ObjectType type,
// const std::string &oldName, const std::string &newName)
//---------------------------------------------------------------------------
bool CallFunction::RenameRefObject(const Gmat::ObjectType type,
const std::string &oldName,
const std::string &newName)
{
#ifdef DEBUG_RENAME
MessageInterface::ShowMessage
("CallFunction::RenameRefObject() type=%d, oldName='%s', newName='%s'\n",
type, oldName.c_str(), newName.c_str());
#endif
if (type == Gmat::FUNCTION)
{
if (mFunctionName == oldName)
mFunctionName = newName;
}
else if (type == Gmat::PARAMETER)
{
// parameters - go through input and output
for (unsigned int i=0; i<mInputNames.size(); i++)
{
if (mInputNames[i] == oldName)
{
mInputNames[i] = newName;
break;
}
std::string arrName = GmatStringUtil::GetArrayName(mInputNames[i], "[]");
if (arrName == oldName)
{
mInputNames[i] =
GmatStringUtil::Replace(mInputNames[i], oldName, newName);
}
}
for (unsigned int i=0; i<mOutputNames.size(); i++)
{
if (mOutputNames[i] == oldName)
{
mOutputNames[i] = newName;
break;
}
std::string arrName = GmatStringUtil::GetArrayName(mOutputNames[i], "[]");
if (arrName == oldName)
{
mOutputNames[i] =
GmatStringUtil::Replace(mOutputNames[i], oldName, newName);
}
}
}
// Since parameter name is composed of spacecraftName.dep.paramType or
// burnName.dep.paramType, check the type first
else if (type == Gmat::SPACECRAFT || type == Gmat::BURN ||
type == Gmat::HARDWARE || type == Gmat::IMPULSIVE_BURN ||
type == Gmat::COORDINATE_SYSTEM || type == Gmat::CALCULATED_POINT)
{
for (UnsignedInt i=0; i<mInputNames.size(); i++)
if (mInputNames[i].find(oldName) != std::string::npos)
mInputNames[i] =
GmatStringUtil::Replace(mInputNames[i], oldName, newName);
for (UnsignedInt i=0; i<mOutputNames.size(); i++)
if (mOutputNames[i].find(oldName) != std::string::npos)
mOutputNames[i] =
GmatStringUtil::Replace(mOutputNames[i], oldName, newName);
}
return true;
}
// Reference object accessor methods
//------------------------------------------------------------------------------
// GmatBase* GetRefObject(const Gmat::ObjectType type, const std::string &name)
//------------------------------------------------------------------------------
GmatBase* CallFunction::GetRefObject(const Gmat::ObjectType type,
const std::string &name)
{
switch (type)
{
case Gmat::PARAMETER:
for (int i=0; i<mNumInputParams; i++)
{
if (mInputNames[i] == name)
return mInputList[i];
}
for (int i=0; i<mNumOutputParams; i++)
{
if (mOutputNames[i] == name)
return mOutputList[i];
}
throw GmatBaseException("ReportFile::GetRefObject() the object name: "
+ name + "not found\n");
case Gmat::FUNCTION:
return mFunction;
case Gmat::COMMAND:
return callcmds;
default:
break;
}
// Not handled here -- invoke the next higher GetRefObject call
return GmatCommand::GetRefObject(type, name);
}
//------------------------------------------------------------------------------
// bool SetRefObject(GmatBase *obj, const Gmat::ObjectType type, ...
//------------------------------------------------------------------------------
/**
* Sets reference object pointer.
*
* @return true if object successfully set, false otherwise
*/
//------------------------------------------------------------------------------
bool CallFunction::SetRefObject(GmatBase *obj, const Gmat::ObjectType type,
const std::string &name)
{
#ifdef DEBUG_CALL_FUNCTION_REF_OBJ
MessageInterface::ShowMessage
("CallFunction::SetRefObject() entered, obj=<%p><%s>'%s', type=%d, name='%s'\n",
obj, obj ? obj->GetTypeName().c_str() : "NULL", obj ? obj->GetName().c_str() : "NULL",
type, name.c_str());
#endif
if (obj == NULL)
return false;
switch (type)
{
case Gmat::PARAMETER:
for (int i=0; i<mNumInputParams; i++)
{
if (mInputNames[i] == name)
{
mInputList[i] = (Parameter*)obj;
return true;
}
}
for (int i=0; i<mNumOutputParams; i++)
{
if (mOutputNames[i] == name)
{
mOutputList[i] = (Parameter*)obj;
return true;
}
}
case Gmat::FUNCTION:
if (name == mFunctionName)
{
mFunction = (Function *)obj;
if (mFunction)
{
mFunctionPathAndName = mFunction->GetFunctionPathAndName();
if (mFunction->IsOfType("BuiltinGmatFunction"))
{
#ifdef DEBUG_CALL_FUNCTION_REF_OBJ
MessageInterface::ShowMessage
("CallFunction::SetRefObject(), '%s' is builtin GMAT function\n",
mFunctionName.c_str());
MessageInterface::ShowMessage
(" Setting function<%p>'%s' to FunctionManager\n",
mFunction, mFunction ? mFunction->GetName().c_str() : "NULL");
#endif
fm.SetFunction(mFunction);
isGmatFunction = false;
isMatlabFunction = false;
isBuiltinGmatFunction = true;
}
else if (mFunction->GetTypeName() == "GmatFunction")
{
#ifdef DEBUG_FUNCTION
MessageInterface::ShowMessage
("CallFunction::SetRefObject() Setting function<%p>'%s' to FunctionManager\n",
mFunction, mFunction ? mFunction->GetName().c_str() : "NULL");
#endif
fm.SetFunction(mFunction);
isGmatFunction = true;
isMatlabFunction = false;
isBuiltinGmatFunction = false;
}
}
}
return true;
case Gmat::COMMAND:
if (callcmds)
delete callcmds;
callcmds = (GmatCommand*)obj;
return true;
default:
break;
}
// Not handled here -- invoke the next higher SetRefObject call
return GmatCommand::SetRefObject(obj, type, name);
}
//------------------------------------------------------------------------------
// virtual ObjectArray& GetRefObjectArray(const Gmat::ObjectType type)
//------------------------------------------------------------------------------
ObjectArray& CallFunction::GetRefObjectArray(const Gmat::ObjectType type)
{
switch (type)
{
case Gmat::PARAMETER:
objectArray.clear();
for (unsigned int i=0; i<mInputList.size(); i++)
objectArray.push_back(mInputList[i]);
for (unsigned int i=0; i<mOutputList.size(); i++)
objectArray.push_back(mOutputList[i]);
return objectArray;
default:
break;
}
// Not handled here -- invoke the next higher SetReferenceObject call
return GmatCommand::GetRefObjectArray(type);
}
//------------------------------------------------------------------------------
// bool Initialize()
//------------------------------------------------------------------------------
bool CallFunction::Initialize()
{
#ifdef DEBUG_CALL_FUNCTION_INIT
MessageInterface::ShowMessage
("CallFunction::Initialize() this=<%p> entered\n command = '%s'\n "
"function type is '%s', callingFunction is '%s', isBuiltinGmatFunction=%d\n",
this, GetGeneratingString(Gmat::NO_COMMENTS).c_str(),
mFunction ? mFunction->GetTypeName().c_str() : "NULL",
callingFunction? (callingFunction->GetFunctionName()).c_str() : "NULL",
isBuiltinGmatFunction);
#endif
GmatCommand::Initialize();
#ifdef DEBUG_OBJECT_MAP
ShowObjectMaps("In CallFunction::Initialize()");
#endif
isGmatFunction = false;
isMatlabFunction = false;
isBuiltinGmatFunction = false;
bool rv = true; // Initialization return value
if (!IsOfType("CallPythonFunction"))
{
if (mFunction == NULL)
throw CommandException("CallFunction::Initialize() the function pointer is NULL");
if (mFunction->IsOfType("BuiltinGmatFunction"))
isBuiltinGmatFunction = true;
else if (mFunction->GetTypeName() == "GmatFunction")
isGmatFunction = true;
else if (mFunction->GetTypeName() == "MatlabFunction")
isMatlabFunction = true;
if (!isGmatFunction && !isMatlabFunction && !isBuiltinGmatFunction)
throw CommandException
("CallFunction::Initialize() the function is not a GmatFunction, "
"MatlabFunction, or BuiltinGmatFunction");
mFunctionPathAndName = mFunction->GetFunctionPathAndName();
std::string fname = GmatFileUtil::ParseFileName(mFunctionPathAndName);
if (fname == "")
mFunctionPathAndName += mFunctionName;
#ifdef DEBUG_CALL_FUNCTION_INIT
MessageInterface::ShowMessage
("CallFunction::Initialize() returning %d, fname='%s', mFunctionName='%s', ...\n "
"mFunctionPathAndName='%s'\n", rv, fname.c_str(), mFunctionName.c_str(),
mFunctionPathAndName.c_str());
#endif
}
return rv;
}
//------------------------------------------------------------------------------
// bool Execute()
//------------------------------------------------------------------------------
bool CallFunction::Execute()
{
bool status = false;
if (mFunction == NULL)
throw CommandException("Function is not defined for CallFunction");
#ifdef DEBUG_TRACE
static Integer callCount = 0;
callCount++;
clock_t t1 = clock();
MessageInterface::ShowMessage
(">>>>> CallFunction::Execute() entered, '%s' Count = %d\n",
GetGeneratingString(Gmat::NO_COMMENTS).c_str(), callCount);
#endif
#ifdef DEBUG_CALL_FUNCTION_EXEC
MessageInterface::ShowMessage
("CallFunction::Execute() this=<%p> entered, command = '%s'\n "
"function type is '%s', callingFunction is '%s'\n", this,
GetGeneratingString(Gmat::NO_COMMENTS).c_str(), mFunction->GetTypeName().c_str(),
callingFunction? (callingFunction->GetFunctionName()).c_str() : "NULL");
#ifdef DEBUG_OBJECT_MAP
ShowObjectMaps("object maps at the start");
#endif
#endif
return status;
}
//------------------------------------------------------------------------------
// void RunComplete()
//------------------------------------------------------------------------------
void CallFunction::RunComplete()
{
#ifdef DEBUG_RUN_COMPLETE
MessageInterface::ShowMessage
("CallFunction::RunComplete() entered, this=<%p> '%s',\n "
"FCS %sfinalized\n", this, GetGeneratingString(Gmat::NO_COMMENTS).c_str(),
fm.IsFinalized() ? "already " : "NOT ");
#endif
if (!fm.IsFinalized())
{
#ifdef DEBUG_RUN_COMPLETE
MessageInterface::ShowMessage(" Calling FunctionManager::Finalize()\n");
#endif
fm.Finalize();
}
#ifdef DEBUG_RUN_COMPLETE
MessageInterface::ShowMessage(" Calling GmatCommand::RunComplete()\n");
#endif
GmatCommand::RunComplete();
#ifdef DEBUG_RUN_COMPLETE
MessageInterface::ShowMessage
("CallFunction::RunComplete() leaving, this=<%p> '%s',\n "
"FCS %sfinalized\n", this, GetGeneratingString(Gmat::NO_COMMENTS).c_str(),
fm.IsFinalized() ? "already " : "NOT ");
#endif
}
//------------------------------------------------------------------------------
// void ClearInputParameters()
//------------------------------------------------------------------------------
void CallFunction::ClearInputParameters()
{
mInputList.clear();
mInputNames.clear();
mNumInputParams = 0;
}
//------------------------------------------------------------------------------
// void ClearOutputParameters()
//------------------------------------------------------------------------------
void CallFunction::ClearOutputParameters()
{
mOutputList.clear();
mOutputNames.clear();
mNumOutputParams = 0;
}
//------------------------------------------------------------------------------
// void SetInternalCoordSystem(CoordinateSystem *cs)
//------------------------------------------------------------------------------
/**
* Sets the internal coordinate system used by the Sandbox.
*
* @param <cs> The internal coordinate system.
*/
//------------------------------------------------------------------------------
void CallFunction::SetInternalCoordSystem(CoordinateSystem *cs)
{
/// @todo Check initialization and cloning for the internal CoordinateSystem.
//internalCoordSys = (CoordinateSystem*)(cs->Clone());
internalCoordSys = cs;
fm.SetInternalCoordinateSystem(internalCoordSys);
}
//------------------------------------------------------------------------------
// void SetPublisher(Publisher *pub)
//------------------------------------------------------------------------------
/**
* Passes the Publisher used by the Sandbox to FunctionManager
*
* @param <pub> The publisher
*/
//------------------------------------------------------------------------------
void CallFunction::SetPublisher(Publisher *pub)
{
#ifdef DEBUG_PUBLISHER
MessageInterface::ShowMessage
("CallFunction::SetPublisher() setting publiser <%p> to FunctionManager\n", pub);
#endif
GmatCommand::SetPublisher(pub);
fm.SetPublisher(pub);
}
| 33.44345 | 102 | 0.52051 | [
"object"
] |
a70432c579edd3d52b5551bda4872e3928db2c1d | 941 | cpp | C++ | code/79.exist.cpp | T1mzhou/LeetCode | 574540d30f5696e55799831dc3c8d8b7246b74f1 | [
"MIT"
] | 1 | 2020-10-04T13:39:34.000Z | 2020-10-04T13:39:34.000Z | code/79.exist.cpp | T1mzhou/LeetCode | 574540d30f5696e55799831dc3c8d8b7246b74f1 | [
"MIT"
] | null | null | null | code/79.exist.cpp | T1mzhou/LeetCode | 574540d30f5696e55799831dc3c8d8b7246b74f1 | [
"MIT"
] | null | null | null | class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
if (dfs(board, word, 0, i, j)) return true;
}
}
return false;
}
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
bool dfs(vector<vector<char>>& board, string& word, int u, int x, int y) {
if (board[x][y] != word[u]) return false;
if (u == word.size() - 1) return true;
char t = board[x][y];
board[x][y] = '.';
for (int i = 0; i < 4; i++) {
int a = x + dx[i];
int b = y + dy[i];
if (a < 0 || a >= board.size() || b < 0 || b >= board[0].size() || board[a][b] == '.') continue;
if (dfs(board, word, u + 1, a, b)) return true;
}
board[x][y] = t;
return false;
}
}; | 31.366667 | 108 | 0.412327 | [
"vector"
] |
a709b20b900c1e50802ff8c3169a4469b421fdc5 | 10,847 | cc | C++ | paddle/fluid/operators/rnn_op.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 17,085 | 2016-11-18T06:40:52.000Z | 2022-03-31T22:52:32.000Z | paddle/fluid/operators/rnn_op.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 29,769 | 2016-11-18T06:35:22.000Z | 2022-03-31T16:46:15.000Z | paddle/fluid/operators/rnn_op.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 4,641 | 2016-11-18T07:43:33.000Z | 2022-03-31T15:15:02.000Z | /* Copyright (c) 2020 PaddlePaddle 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 "paddle/fluid/operators/rnn_op.h"
#include <memory>
#include <string>
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/op_version_registry.h"
namespace paddle {
namespace operators {
class RNNOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input", "RNN");
OP_INOUT_CHECK(ctx->HasInputs("PreState"), "Input", "PreState", "RNN");
OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "RNN");
OP_INOUT_CHECK(ctx->HasOutputs("State"), "Output", "State", "RNN");
auto in_dims = ctx->GetInputDim("Input");
auto pre_state_dims = ctx->GetInputsDim("PreState");
PADDLE_ENFORCE_EQ(in_dims.size(), 3,
platform::errors::InvalidArgument(
"The rank of Input in RNN must be 3. But "
"received Input's rank is %d.",
in_dims.size()));
if (ctx->HasInput("SequenceLength")) {
auto seq_dims = ctx->GetInputDim("SequenceLength");
PADDLE_ENFORCE_EQ(
in_dims[1], seq_dims[0],
platform::errors::InvalidArgument(
"The size of SequenceLength has to equal the batch_size. But "
"received batch_size is %d and the size of SequenceLength is %d.",
in_dims[1], seq_dims[0]));
}
PADDLE_ENFORCE_EQ(pre_state_dims[0].size(), 3,
platform::errors::InvalidArgument(
"The rank of PreState in RNN must be 3. But "
"the received rank is %d.",
pre_state_dims[0].size()));
size_t i = 0;
for (; i < pre_state_dims.size(); ++i) {
PADDLE_ENFORCE_EQ(
in_dims[1], pre_state_dims[i][1],
platform::errors::InvalidArgument(
"The second dimension size (representing for batch size) of "
"Input and PreState should be equal. But received %d and %d.",
in_dims[1], pre_state_dims[i][1]));
PADDLE_ENFORCE_EQ(
pre_state_dims[0], pre_state_dims[i],
platform::errors::InvalidArgument(
"The dims of all tensors in PreState should be same. But "
"received PreState[0] is %s and PreState[%d] is %s.",
pre_state_dims[0], i, pre_state_dims[i]));
}
auto mode = ctx->Attrs().Get<std::string>("mode");
size_t num_state = mode == "LSTM" ? 2 : 1;
PADDLE_ENFORCE_EQ(
i, num_state,
platform::errors::InvalidArgument(
"The number of tensors in PreState of %s should be %d, "
"but received %d.",
mode, 2, i));
auto out_dims = in_dims;
auto hidden_size = ctx->Attrs().Get<int>("hidden_size");
bool is_bidirec = ctx->Attrs().Get<bool>("is_bidirec");
out_dims[2] = is_bidirec ? hidden_size * 2 : hidden_size;
ctx->SetOutputDim("Out", out_dims);
ctx->SetOutputsDim("State", pre_state_dims);
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "Input"),
ctx.device_context());
}
};
class RNNOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput(
"Input",
"(Tensor) RNN input tensor, which support variable-time length input "
"sequence."
"The shape of the Tensor MUST be ( seq_len * batch_size * input_size)"
"seq_len is the total time step in this mini-batch (CAN be change in "
"different batch)"
"batch_size is the instance number of this batch"
"input_size is the hidden size of the input."
"input_size and the hidden_size in the next may not be same");
AddInput("PreState",
"(Tensor) the initial hidden state of the LSTM"
"input. This is a tensor with shape (num_layers x batch_size x "
"hidden_size)"
"and When is_bidirec is True, the shape will be (num_layers*2 x "
"batch_size x hidden_size)")
.AsDuplicable();
AddInput("WeightList",
"(vector<Tensor>), stores weight and bias data when the weight "
"use the list format. ")
.AsDuplicable();
AddInput("SequenceLength",
"(Tensor) When the input data is padding, "
"set this parameter. This parameter represents "
"the variable sequence lengths in a batch. "
"The size of the vector has to equal the batch_size.")
.AsDispensable();
AddOutput("DropoutState",
"Store the global drop state when training, needed by cudnn rnn.")
.AsDispensable();
// maybe need add intermediate outputs for cpu kernel
AddOutput("Reserve",
"(Tensor, a temporary output Tensor to store the reserve_data "
"of cudnn kernel.")
.AsIntermediate();
AddOutput("Out",
"(Tensor) the hidden state of LSTM operator. "
"The shape is ( seq_len x batch_size x hidden_size) if "
"is_bidirec is False"
"and When is_bidirec is True, the shape will be ( seq_len x "
"batch_size x hidden_size * 2) ");
AddOutput("State",
"(Tensor) the hidden state of the last step. "
"The shape is ( num_layers x batch_size x hidden_size) if "
"is_bidirec is False"
"and When is_bidirec is True, the shape will be (num_layers*2 x "
"batch_size x hidden_size)")
.AsDuplicable();
AddAttr<float>(
"dropout_prob",
"dropout prob of the dropout op"
"the dropout ONLY work between rnn layers, not between time steps"
"There is no dropout work on the Out tensor")
.SetDefault(0.0);
AddAttr<bool>("is_bidirec", "whether it is bidirectional rnn")
.SetDefault(false);
AddAttr<int>("input_size", "input size ot the Input Tensor").SetDefault(10);
AddAttr<int>("hidden_size", "hidden size of rnn").SetDefault(100);
AddAttr<int>("num_layers", "the total layer number").SetDefault(1);
AddAttr<std::string>(
"mode",
"(string) rnn types, including: LSTM, GRU, RNN_RELU, RNN_TANH.");
AddAttr<int>("seed", "seed to used if fix_seed is True").SetDefault(0);
AddAttr<bool>("is_test", "True if in test phase.")
.SetDefault(false)
.AsExtra();
AddComment(R"DOC(
)DOC");
}
};
class RNNGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input", "RNN");
OP_INOUT_CHECK(ctx->HasInputs("PreState"), "Input", "PreState", "RNN");
OP_INOUT_CHECK(ctx->HasInput("Out"), "Input", "Out", "RNN");
// OP_INOUT_CHECK(ctx->HasInputs("State"), "Input", "State", "RNN");
auto SetOutGradDim = [&ctx](const std::string& name) {
auto g_name = framework::GradVarName(name);
if (ctx->HasOutput(g_name)) {
ctx->SetOutputDim(g_name, ctx->GetInputDim(name));
}
};
SetOutGradDim("Input");
if (ctx->HasOutputs(framework::GradVarName("WeightList"))) {
ctx->SetOutputsDim(framework::GradVarName("WeightList"),
ctx->GetInputsDim("WeightList"));
}
if (ctx->HasOutputs(framework::GradVarName("PreState"))) {
ctx->SetOutputsDim(framework::GradVarName("PreState"),
ctx->GetInputsDim("PreState"));
}
}
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Out")),
ctx.device_context());
}
};
template <typename T>
class RNNGradOpMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("rnn_grad");
op->SetInput("Input", this->Input("Input"));
op->SetInput("PreState", this->Input("PreState"));
op->SetInput("WeightList", this->Input("WeightList"));
if (this->HasInput("SequenceLength")) {
op->SetInput("SequenceLength", this->Input("SequenceLength"));
}
op->SetInput("DropoutState", this->Output("DropoutState"));
op->SetInput("Reserve", this->Output("Reserve"));
op->SetInput("Out", this->Output("Out"));
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetInput(framework::GradVarName("State"), this->OutputGrad("State"));
op->SetOutput(framework::GradVarName("WeightList"),
this->InputGrad("WeightList", false));
op->SetOutput(framework::GradVarName("Input"), this->InputGrad("Input"));
op->SetOutput(framework::GradVarName("PreState"),
this->InputGrad("PreState", false));
op->SetAttrMap(this->Attrs());
}
};
template <typename T>
class NotImpleKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
PADDLE_THROW(platform::errors::Unimplemented(
"CPU is not support for this kernel now. Will be add in the future"));
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(rnn, ops::RNNOp, ops::RNNOpMaker,
ops::RNNGradOpMaker<paddle::framework::OpDesc>,
ops::RNNGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(rnn_grad, ops::RNNGradOp);
REGISTER_OP_CPU_KERNEL(
rnn, ops::RNNCPUKernel<paddle::platform::CPUDeviceContext, float>,
ops::RNNCPUKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
rnn_grad, ops::RNNCPUGradKernel<paddle::platform::CPUDeviceContext, float>,
ops::RNNCPUGradKernel<paddle::platform::CPUDeviceContext, double>);
| 41.087121 | 80 | 0.63566 | [
"shape",
"vector"
] |
a70b6dbc05881e9cf743321ec9e4d2d6d715dbc7 | 24,103 | cpp | C++ | components/gta-core-five/src/BlockLoadSetters.cpp | vladyslavkotyk/client | 06230ae612ae46f25b36046d488c88e0602945ac | [
"MIT"
] | 5 | 2017-07-19T16:42:12.000Z | 2021-01-19T22:46:43.000Z | components/gta-core-five/src/BlockLoadSetters.cpp | Zuiron/FiveM | 2e38beaf76d21a07be3bad6f4f00b68642e47edc | [
"MIT"
] | null | null | null | components/gta-core-five/src/BlockLoadSetters.cpp | Zuiron/FiveM | 2e38beaf76d21a07be3bad6f4f00b68642e47edc | [
"MIT"
] | 6 | 2017-01-24T22:11:17.000Z | 2020-07-07T19:53:18.000Z | /*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#include "StdInc.h"
#include "Hooking.h"
#include <atArray.h>
#include <sysAllocator.h>
#include <GameInit.h>
#include <nutsnbolts.h>
static hook::cdecl_stub<void()> lookAlive([] ()
{
return hook::pattern("48 8D 6C 24 A0 48 81 EC 60 01 00 00 E8").count(1).get(0).get<void>(-0xC);
});
// map init states to cater for additional '7' in one particular digital distribution version
static bool g_isDigitalDistrib = false;
static inline int MapInitState(int initState)
{
if (initState >= 7)
{
if (g_isDigitalDistrib)
{
initState += 1;
}
}
return initState;
}
static int* g_initState;
bool g_shouldSetState;
bool g_isInInitLoop; // to avoid some GFx crash?
static void WaitForInitLoop()
{
// run our loop
g_isInInitLoop = true;
while (*g_initState <= MapInitState(6))
{
lookAlive();
if (*g_initState <= MapInitState(6))
{
Sleep(15);
}
}
//*g_initState = 7;
}
static bool g_launchedGame = false;
static void WaitForInitLoopWrap()
{
// certain executables may recheck activation after connection, and want to perform this state change after 12 - ignore those cases
*g_initState = MapInitState(6);
WaitForInitLoop();
}
static bool(*g_callBeforeLoad)();
void FiveGameInit::LoadGameFirstLaunch(bool(*callBeforeLoad)())
{
g_callBeforeLoad = callBeforeLoad;
g_launchedGame = true;
OnGameFrame.Connect([=] ()
{
if (g_shouldSetState)
{
if (*g_initState == MapInitState(6))
{
*g_initState = MapInitState(7);
g_shouldSetState = false;
}
}
static bool isLoading = false;
if (isLoading)
{
if (*g_initState == 0)
{
OnGameFinalizeLoad();
isLoading = false;
}
}
else
{
if (*g_initState != 0)
{
isLoading = true;
}
}
});
OnGameRequestLoad();
// stuff
if (*g_initState == MapInitState(6))
{
*g_initState = MapInitState(7);
}
else
{
if (*g_initState == MapInitState(20))
{
*g_initState = MapInitState(11);
}
g_shouldSetState = true;
}
}
void FiveGameInit::ReloadGame()
{
OnGameRequestLoad();
*g_initState = MapInitState(14);
}
static void DebugBreakDo()
{
__debugbreak();
ExitProcess(0);
}
static const char* typeMap[] = {
nullptr,
"system",
"beforeMapLoaded",
nullptr,
"afterMapLoaded",
nullptr,
nullptr,
nullptr,
"session"
};
struct InitFunctionStub : public jitasm::Frontend
{
static uintptr_t LogStub(uintptr_t stub, int type)
{
trace("Running shutdown %s function: %p\n", typeMap[type], stub);
return stub;
}
virtual void InternalMain() override
{
push(r14);
mov(rcx, qword_ptr[rax + rdx * 8 + 8]);
mov(edx, r14d);
// scratch space!
sub(rsp, 0x20);
mov(rax, (uintptr_t)LogStub);
call(rax);
mov(ecx, r14d);
call(rax);
add(rsp, 0x20);
pop(r14);
ret();
}
};
struct InitFunctionStub2 : public jitasm::Frontend
{
static uintptr_t LogStub(uintptr_t stub, int type)
{
trace("Running init %s function: %p\n", typeMap[type], stub);
return stub;
}
virtual void InternalMain() override
{
push(r14);
mov(rcx, qword_ptr[rax + rdx * 8]);
mov(edx, r14d);
// scratch space!
sub(rsp, 0x20);
mov(rax, (uintptr_t)LogStub);
call(rax);
mov(ecx, r14d);
call(rax);
add(rsp, 0x20);
pop(r14);
ret();
}
};
static hook::cdecl_stub<void(int)> initModelInfo([] ()
{
return hook::pattern("48 83 EC 20 83 F9 01 0F 85 A5 06 00 00").count(1).get(0).get<void>(-0x15);
});
static hook::cdecl_stub<void(int)> shutdownModelInfo([] ()
{
return hook::pattern("48 83 EC 20 83 F9 01 0F 85 77 01 00 00").count(1).get(0).get<void>(-0x10);
});
static hook::cdecl_stub<void()> initStreamingInterface([] ()
{
return hook::get_call(hook::pattern("41 8B CE E8 ? ? ? ? 48 8B 0D ? ? ? ? 48 8D").count(1).get(0).get<void>(3));
});
static hook::cdecl_stub<void(void*)> clearSceneLinkedList([] ()
{
return hook::pattern("48 8B F9 EB 38 48 8B 17 48 8B CB 48 8B").count(1).get(0).get<void>(-0xD);
});
static hook::cdecl_stub<void()> shutdownScene([] ()
{
return hook::pattern("BB 01 00 00 00 8B CB E8 ? ? ? ? E8").count(1).get(0).get<void>(-0x4A);
});
static hook::cdecl_stub<void()> initScene([] ()
{
return hook::pattern("BF 01 00 00 00 48 8D 0D ? ? ? ? 8B D7 E8").count(1).get(0).get<void>(-0x31);
});
static void(*g_deinitLevel)();
static void* g_sceneLinkedList;
template<typename T>
class allocWrap : public rage::sysUseAllocator
{
private:
T m_value;
public:
allocWrap()
: m_value()
{
}
allocWrap(const T& value)
: m_value(value)
{
}
inline T& Get() const
{
return m_value;
}
inline void Set(const T& value)
{
m_value = value;
}
operator T&() const
{
return m_value;
}
};
static atArray<allocWrap<uint32_t>>* g_cacheArray;
static char* g_boundsStreamingModule;
class CInteriorProxy
{
public:
virtual ~CInteriorProxy() = 0;
};
template<typename T>
struct LinkNode : public rage::sysUseAllocator
{
T* value;
LinkNode* next;
};
static void ClearInteriorProxyList(void* list)
{
auto linkedList = *(LinkNode<CInteriorProxy>**)list;
if (linkedList)
{
do
{
delete linkedList->value;
auto next = linkedList->next;
delete linkedList;
linkedList = next;
} while (linkedList);
}
*(void**)list = nullptr;
}
static hook::cdecl_stub<void(int)> initPhysics([] ()
{
return hook::pattern("83 F9 08 75 23 33 C9 E8 ? ? ? ? 48 8D 0D").count(1).get(0).get<void>(-0x12);
});
static hook::cdecl_stub<void(int)> shutdownPhysics([] ()
{
return hook::pattern("83 F9 04 75 15 48 8D 0D").count(1).get(0).get<void>(-0x12);
});
template<typename T>
class fwPool
{
private:
char* m_data;
int8_t* m_flags;
uint32_t m_count;
uint32_t m_entrySize;
public:
T* GetAt(int index) const
{
return reinterpret_cast<T*>(m_data + (index * m_entrySize));
}
void Clear()
{
for (int i = 0; i < m_count; i++)
{
if (m_flags[i] >= 0)
{
delete GetAt(i);
}
}
}
};
static fwPool<CInteriorProxy>** g_interiorProxyPool;
static bool g_inLevelFree;
static bool g_didLevelFree;
static int g_stackIdx;
static std::unordered_map<int, std::vector<uintptr_t>> g_stacks;
static atArray<CInteriorProxy*>* g_vehicleReflEntityArray;
static hook::cdecl_stub<void(void*)> extraContentMgr__doScanInt([] ()
{
return hook::get_call(hook::pattern("48 83 EC 20 80 A1 7A 01 00 00 FE 41 8A D8").count(1).get(0).get<void>(17));
});
// a3: skip mount?
static hook::cdecl_stub<void(void*, bool, bool)> extraContentMgr__doScanPost([] ()
{
//return hook::pattern("48 83 EC 20 80 A1 7A 01 00 00 FE 41 8A D8").count(1).get(0).get<void>(-0x6);
return hook::get_call(hook::pattern("48 83 EC 20 80 A1 7A 01 00 00 FE 41 8A D8").count(1).get(0).get<void>(30));
});
static void** g_extraContentMgr;
static void DeinitLevel()
{
static bool initedLateHook = false;
if (!initedLateHook)
{
// late hook to prevent scenario manager from reinitializing on map load - it messes things up, a lot, and I doubt custom maps use scenarios anyway. :)
hook::put<uint16_t>(hook::pattern("83 F9 04 0F 85 F9 00 00 00").count(1).get(0).get<void>(3), 0xE990); // shutdown
hook::put<uint16_t>(hook::pattern("83 F9 02 0F 85 C6 01 00 00").count(1).get(0).get<void>(3), 0xE990); // init
// don't load mounted ped (personality) metadata anymore (temp dbg-y?)
hook::nop(hook::pattern("48 8B DA 83 E9 14 74 5B").count(1).get(0).get<void>(0x72 - 12), 5);
initedLateHook = true;
}
// stuff
g_inLevelFree = true;
g_deinitLevel();
shutdownModelInfo(1);
initModelInfo(1);
initStreamingInterface();
// extra content manager shutdown session removes these, and we want these before init session, so we scan them right here, right now.
extraContentMgr__doScanInt(*g_extraContentMgr);
extraContentMgr__doScanPost(*g_extraContentMgr, false, false);
//shutdownPhysics(1);
//initPhysics(1);
// unknown value in the bounds streaming module, doesn't get cleared on 'after map loaded' shutdown
*(uint32_t*)(g_boundsStreamingModule + 5664) = 0;
// bounds streaming module, 'has preloading bounds completed' value
*(uint8_t*)(g_boundsStreamingModule + 255) = 0;
// clear the 'loaded cache hashes' list
*g_cacheArray = atArray<allocWrap<uint32_t>>(16);
// free one CScene list of all the bad influences from the last session
ClearInteriorProxyList(g_sceneLinkedList);
// also clear the interior proxy pool out, as it might contain garbage references to static bounds, still
(*g_interiorProxyPool)->Clear();
// and some global vehicle audio entity also houses... interior proxies.
*g_vehicleReflEntityArray = atArray<CInteriorProxy*>();
g_inLevelFree = false;
if (!g_didLevelFree)
{
for (auto& stack : g_stacks)
{
FILE* f = fopen(va("D:\\dev\\stacks\\%p.txt", ((stack.first / 256) * 256)), "a");
if (f)
{
fprintf(f, "--- %p ---\n", stack.first);
for (auto& entry : stack.second)
{
fprintf(f, "%p\n", entry);
}
fprintf(f, "--- --- ---\n");
fclose(f);
}
}
g_stackIdx = 0;
g_stacks.clear();
g_didLevelFree = true;
}
}
namespace rage
{
class fwArchetype
{
public:
virtual ~fwArchetype() = 0;
virtual void m1() = 0;
virtual void m2() = 0;
virtual void m3() = 0;
virtual void m4() = 0;
virtual void m5() = 0;
virtual void m6() = 0;
virtual void m7() = 0;
virtual void m8() = 0;
virtual void _CleanUp() = 0;
};
}
static void DestructMI(rage::fwArchetype* archetype)
{
archetype->_CleanUp();
archetype->~fwArchetype(); // note: we can't delete this; that'll cause a double-free later on
}
static void(*g_origFreeMapTypes)(void* store, void* entry, void* a3, bool a4);
void DoFreeMapTypes(void* store, void* entry, void* a3, bool a4)
{
if ((uintptr_t)entry != 16)
{
g_origFreeMapTypes(store, entry, a3, a4);
}
}
static intptr_t(*g_origMemFree)(void*, void*);
static void** g_unsafePointerLoc;
#include <unordered_map>
#include <mutex>
static std::unordered_map<uintptr_t, size_t> g_allocData;
static std::mutex g_allocMutex;
static CRITICAL_SECTION g_allocCS;
static std::vector<uintptr_t> g_unsafeStack;
intptr_t CustomMemFree(void* allocator, void* pointer)
{
intptr_t retval = g_origMemFree(allocator, pointer);
/*if (pointer != nullptr && *g_unsafePointerLoc)
{
size_t allocSize = 0;
if (g_unsafeStack.size() == 0)
{
{
std::unique_lock<std::mutex> lock(g_allocMutex);
auto it = g_allocData.find(pointer);
if (it != g_allocData.end())
{
allocSize = it->second;
g_allocData.erase(it);
}
}
if (**(void***)g_unsafePointerLoc >= pointer && **(void***)g_unsafePointerLoc < ((char*)pointer + allocSize))
{
std::vector<uintptr_t> stackList(96);
uintptr_t* stack = (uintptr_t*)_AddressOfReturnAddress();
for (int i = 0; i < stackList.size(); i++)
{
stackList[i] = stack[i];
}
g_unsafeStack = stackList;
}
}
}*/
if (/*!g_didLevelFree && */pointer != nullptr)
{
//std::unique_lock<std::mutex> lock(g_allocMutex);
EnterCriticalSection(&g_allocCS);
uintptr_t ptr = (uintptr_t)pointer;
auto it = g_allocData.find(ptr);
if (it != g_allocData.end())
{
size_t allocSize = it->second;
static char* location = hook::pattern("4C 8D 0D ? ? ? ? 48 89 01 4C 89 81 80 00 00").count(1).get(0).get<char>(3);
static char** g_collectionRoot = (char**)(location + *(int32_t*)location + 4);
for (int i = 0; i < 0x950; i++)
{
if (g_collectionRoot[i])
{
void* baad = *(void**)(g_collectionRoot[i] + 32);
if (baad >= pointer && baad < ((char*)pointer + allocSize))
{
atArray<char>* array = (atArray<char>*)(g_collectionRoot[i] + 128);
trace("freed collection %s (%p-%p)\n", &array->Get(0), pointer, allocSize + (char*)pointer);
uintptr_t* stack = (uintptr_t*)_AddressOfReturnAddress();
stack += (32 / 8);
for (int i = 0; i < 16; i++)
{
trace("stack: %p\n", stack[i]);
}
}
}
}
/*if (g_inLevelFree)
{
if (allocSize != -1)
{
int stackIdx = g_stackIdx++;
std::vector<uintptr_t> stackList(96);
uintptr_t* stack = (uintptr_t*)_AddressOfReturnAddress();
for (int i = 0; i < stackList.size(); i++)
{
stackList[i] = stack[i];
}
g_stacks[stackIdx] = stackList;
trace("level free: %p-%p - stack idx: %d\n", pointer, (char*)pointer + allocSize, stackIdx);
}
}*/
g_allocData.erase(it);
}
LeaveCriticalSection(&g_allocCS);
}
return retval;
}
static void*(*g_origMemAlloc)(void*, intptr_t size, intptr_t align, int subAlloc);
void* CustomMemAlloc(void* allocator, intptr_t size, intptr_t align, int subAlloc)
{
void* ptr = g_origMemAlloc(allocator, size, align, subAlloc);
/*if (*g_unsafePointerLoc >= ptr && *g_unsafePointerLoc < ((char*)ptr + size))
{
#ifdef _DEBUG
__debugbreak();
#endif
assert(!"Tried to allocate over unsafe pointer!");
}
if (*g_unsafePointerLoc)
{
void*** unsafePtrLoc = (void***)g_unsafePointerLoc;
if (**unsafePtrLoc >= ptr && **unsafePtrLoc < ((char*)ptr + size))
{
#ifdef _DEBUG
__debugbreak();
#endif
assert(!"Tried to allocate over unsafe pointer!");
}
}*/
//memset(ptr, 0, size);
if (subAlloc == 0)
{
uintptr_t ptr_ = (uintptr_t)ptr;
//std::unique_lock<std::mutex> lock(g_allocMutex);
EnterCriticalSection(&g_allocCS);
g_allocData[ptr_] = size;
LeaveCriticalSection(&g_allocCS);
}
return ptr;
}
template<int Value>
static int ReturnInt()
{
return Value;
}
static void(*g_origError)(uint32_t, void*);
static void ErrorDo(uint32_t error)
{
trace("error function called from %p for code 0x%08x\n", _ReturnAddress(), error);
g_origError(error, 0);
}
static void(*g_runInitFunctions)(void*, int);
static void(*g_lookAlive)();
static void RunInitFunctionsWrap(void* skel, int type)
{
if (g_callBeforeLoad)
{
while (!g_callBeforeLoad())
{
g_lookAlive();
OnGameFrame();
}
}
g_runInitFunctions(skel, type);
}
static HookFunction hookFunction([] ()
{
InitializeCriticalSectionAndSpinCount(&g_allocCS, 1000);
// NOP out any code that sets the 'entering state 2' (2, 0) FSM internal state to '7' (which is 'load game'), UNLESS it's digital distribution with standalone auth...
char* p = hook::pattern("BA 07 00 00 00 8D 41 FC 83 F8 01").count(1).get(0).get<char>(14);
char* varPtr = p + 2;
g_initState = (int*)(varPtr + *(int32_t*)varPtr + 4);
// check the pointer to see if it's digital distribution
g_isDigitalDistrib = (p[-26] == 3);
// this is also a comparison point to find digital distribution type... this function will also set '3' if it's digital distrib with standalone auth
// and if this *is* digital distribution, we want to find a completely different place that sets the value to 8 (i.e. BA 08 ...)
if (g_isDigitalDistrib)
{
p = hook::pattern("BA 08 00 00 00 8D 41 FC 83 F8 01").count(1).get(0).get<char>(14);
}
// nop the right pointer
hook::nop(p, 6);
// and call our little internal loop function from there
hook::call(p, WaitForInitLoop);
// also add a silly loop to state 6 ('wait for landing page'?)
p = hook::pattern("C7 05 ? ? ? ? 06 00 00 00 EB 3F").count(1).get(0).get<char>(0);
hook::nop(p, 10);
hook::call(p, WaitForInitLoopWrap);
// for now, always reload the level in 'reload game' state, even if the current level did not change
auto matches = hook::pattern("75 0F E8 ? ? ? ? 8B 0D ? ? ? ? 3B C8 74").count(2);
for (int i = 0; i < matches.size(); i++)
{
if (i == 0)
{
void* call = matches.get(i).get<void>(17);
hook::set_call(&g_deinitLevel, call);
hook::call(call, DeinitLevel);
}
hook::nop(matches.get(i).get<void>(15), 2);
}
// fwmaptypesstore shutdown in CScene type 1 shutdown
//hook::nop(hook::pattern("BB 01 00 00 00 8B CB E8 ? ? ? ? E8").count(1).get(0).get<void>(-0x5), 5);
// redundant(?) path server init
//hook::nop(hook::pattern("33 C9 E8 ? ? ? ? EB 02 32 DB 8A C3 48").count(1).get(0).get<void>(2), 5);
// skip CModelInfo type 4 shutdown as the structure only gets initialized by core init
//hook::put<uint16_t>(hook::pattern("83 F9 04 0F 85 ? 01 00 00 48 8D 1D").count(1).get(0).get<void>(3), 0xE990);
// similar, fwmaptypesstore
//hook::return_function(hook::pattern("FF 90 00 01 00 00 85 C0 7E 72 8B D7").count(1).get(0).get<void>(-0x12));
// CModelInfo shutdown: also call destructor on said archetypes (as that's what those little bitches are in the end)
char* miPtr = hook::pattern("83 F9 04 0F 85 ? 01 00 00 48 8D 1D").count(1).get(0).get<char>(12);
*(int32_t*)miPtr = (int32_t)((char*)hook::AllocateFunctionStub(DestructMI) - miPtr - 4);
// CVehicleRecording streaming module 'freeing' in shutdown 4
hook::nop(hook::pattern("48 83 EC 20 83 F9 04 75 11 48 8D 0D").count(1).get(0).get<void>(0x10), 5);
// scene linked list
char* loc = hook::pattern("41 D2 E0 41 F6 D9 48 8D 0D").count(1).get(0).get<char>(9);
g_sceneLinkedList = (void*)(loc + *(int32_t*)loc + 4);
// temp dbg: don't scan for platform dlc packs... it's mean.
//hook::nop(hook::pattern("7C B4 48 8B CF E8").count(1).get(0).get<void>(5), 5);
//hook::return_function(hook::pattern("7C B4 48 8B CF E8").count(1).get(0).get<void>(-0xA8));
//hook::call(hook::pattern("B9 CD 36 41 A8 E8").count(1).get(0).get<void>(5), DebugBreakDo);
//hook::jump(hook::get_call(hook::pattern("B9 CD 36 41 A8 E8").count(1).get(0).get<void>(5)), DebugBreakDo);
char* errorFunc = reinterpret_cast<char*>(hook::get_call(hook::pattern("B9 CD 36 41 A8 E8").count(1).get(0).get<void>(5)));
hook::set_call(&g_origError, errorFunc + 6);
hook::jump(errorFunc, ErrorDo);
hook::nop(hook::pattern("B9 CD 36 41 A8 E8").count(1).get(0).get<void>(0x14), 5);
hook::nop(hook::pattern("B9 CD 36 41 A8 E8").count(1).get(0).get<void>(5), 5);
// init function bit #1
static InitFunctionStub initFunctionStub;
initFunctionStub.Assemble();
p = hook::pattern("41 8B CE FF 54 D0 08").count(1).get(0).get<char>(0);
hook::nop(p, 7);
hook::call_rcx(p, initFunctionStub.GetCode());
// init function bit #2
static InitFunctionStub2 initFunctionStub2;
initFunctionStub2.Assemble();
p = hook::pattern("41 8B CE FF 14 D0").count(1).get(0).get<char>(0);
hook::nop(p, 6);
hook::call_rcx(p, initFunctionStub2.GetCode());
char* location = hook::pattern("40 32 FF 45 84 C9 40 88 3D").count(1).get(0).get<char>(0x20);
g_cacheArray = (atArray<allocWrap<uint32_t>>*)(location + *(int32_t*)location + 4);
// bounds streaming module
location = hook::pattern("83 F9 04 75 15 48 8D 0D").count(1).get(0).get<char>(8);
g_boundsStreamingModule = (char*)(location + *(int32_t*)location + 4);
// interior proxy pool
location = hook::pattern("BA A1 85 94 52 41 B8 01").count(1).get(0).get<char>(0x34);
g_interiorProxyPool = (decltype(g_interiorProxyPool))(location + *(int32_t*)location + 4);
// unverified 'fix' for data pointer in fwMapTypesStore entries pointing to whatever structure being null upon free, however pool flags not having been nulled themselves
void* freeMapTypes = hook::pattern("45 8A CE 4C 8B 01 48 83 C2 10").count(1).get(0).get<void>(10);
hook::set_call(&g_origFreeMapTypes, freeMapTypes);
hook::call(freeMapTypes, DoFreeMapTypes);
// OF NOTE:
// -> CBaseModelInfo + 0x70 (instance?) being a weird FF-style pointer on deletion
// -> ??_7audVehicleReflectionsEntity@@6B@ + 800 (atArray of unk) being set to a freed pointer although capacity > 0 (destructor called somehow?)
// attempted fix for item #1
static struct : jitasm::Frontend
{
void InternalMain() override
{
mov(qword_ptr[rcx + 0x70], r9);
// original code
mov(qword_ptr[rcx + 0xA8], r9);
ret();
}
} miStub;
hook::jump(hook::pattern("4C 89 89 A8 00 00 00 C3").count(1).get(0).get<void>(), miStub.GetCode());
// attempted 'fix' for item #2 (also: logging when the destructor gets called)
// 505 changed the jump address; so it's a pattern now
location = hook::pattern("1C F6 83 A2 00 00 00 40 74 ? 48 8D 0D").count(1).get(0).get<char>(13);
g_vehicleReflEntityArray = (decltype(g_vehicleReflEntityArray))(location + *(int32_t*)location + 4 + 800);
g_unsafePointerLoc = (void**)((location + *(int32_t*)location + 4) + 800);
// dlc get
void* extraDataGetty = hook::pattern("45 33 F6 48 8B D8 48 85 C0 74 48").count(1).get(0).get<void>(0);
printf("");
location = hook::pattern("75 34 48 85 DB 75 34 B9 B0 09 00 00").count(1).get(0).get<char>(-9);
g_extraContentMgr = (void**)(location + *(int32_t*)location + 4);
// loading screen frame limit
location = hook::pattern("0F 2F 05 ? ? ? ? 0F 82 E6 02 00 00").count(1).get(0).get<char>(3);
hook::put<float>(location + *(int32_t*)location + 4, 1000.0f / 60.0f);
// bypass the state 20 calibration screen loop (which might be wrong; it doesn't seem to exist in my IDA dumps of 323/331 Steam)
matches = hook::pattern("E8 ? ? ? ? 8A D8 84 C0 74 0E C6 05");
assert(matches.size() <= 1);
for (int i = 0; i < matches.size(); i++)
{
hook::call(matches.get(i).get<void>(), ReturnInt<1>);
}
// kill GROUP_EARLY_ON DLC - this seems to make it unmount in a really weird way, and this was (as of 350) only ever used to mount platform:/patch_1/, a change
// R* reverted through dlc_patches; yet the template setup2.xml was copied pretty much everywhere by then...
//hook::put<uint32_t>(hook::pattern("41 B8 08 D4 8B 6F").count(1).get(0).get<void>(2), HashString("GROUP_REALLY_EARLY_ON"));
// similar to above, except it's actually isLevelPack which matters - get rid of those, as these packs don't even add any 'levels'...
//const uint8_t killInst[] = { 0x44, 0x88, 0xB6, 0xB0, 0x00, 0x00, 0x00 }; // mov byte ptr [rsi+0xb0], r15b
//memcpy(hook::pattern("44 38 B6 B0 00 00 00 74 07").count(1).get(0).get<void>(9), killInst, sizeof(killInst));
// mount dlc even if allegedly already mounted - bad bad idea
//hook::nop(hook::pattern("84 C0 75 7A 48 8D 4C 24 20").count(1).get(0).get<void>(2), 2);
// debug info for item #2 (generic free hook; might be useful elsewhere)
location = hook::pattern("48 89 01 83 61 48 00 48 8B C1 C3").count(1).get(0).get<char>(-4);
void** vt = (void**)(location + *(int32_t*)location + 4);
//g_origMemAlloc = (decltype(g_origMemAlloc))vt[2];
//vt[2] = CustomMemAlloc;
//g_origMemFree = (decltype(g_origMemFree))vt[4];
//vt[4] = CustomMemFree;
// block loading until conditions succeed
char* loadStarter = hook::pattern("BA 02 00 00 00 E8 ? ? ? ? E8 ? ? ? ? 8B").count(1).get(0).get<char>(5);
hook::set_call(&g_runInitFunctions, loadStarter);
hook::set_call(&g_lookAlive, loadStarter + 5);
hook::call(loadStarter, RunInitFunctionsWrap);
/*
void* setCache = hook::pattern("40 32 FF 45 84 C9 40 88 3D").count(1).get(0).get<void>(3);
printf("");
*/
// second entry, in a single obfuscated stub
/*auto obfEntries = hook::pattern("C7 05 ? ? ? ? 07 00 00 00 E9");
for (int i = 0; i < obfEntries.size(); i++)
{
char* ptr = obfEntries.get(i).get<char>();
int32_t relValue = *(int32_t*)(ptr + 2);
// obfuscated functions are AFTER .data/.rdata, so this will usually be the case for this single stub
if (relValue < 0)
{
hook::nop(ptr, 9);
}
}*/
});
// C7 05 ? ? ? ? 07 00 00 00 E9 | 25.889366 | 171 | 0.636062 | [
"vector",
"3d"
] |
a712f64410ea58a534295a51fd0751289aa4bc9e | 3,216 | cpp | C++ | practicals/chapter3/main_3_3_1.cpp | rasmunk/set10108 | 563bb339ecea28de80fffd11b5866be4fc25344d | [
"MIT"
] | null | null | null | practicals/chapter3/main_3_3_1.cpp | rasmunk/set10108 | 563bb339ecea28de80fffd11b5866be4fc25344d | [
"MIT"
] | null | null | null | practicals/chapter3/main_3_3_1.cpp | rasmunk/set10108 | 563bb339ecea28de80fffd11b5866be4fc25344d | [
"MIT"
] | null | null | null | // 3.3.1 & 3.4
#include <vector>
#include <chrono>
#include <random>
#include <iostream>
#include <fstream>
#include <thread>
#include <omp.h>
using namespace std;
using namespace std::chrono;
vector<unsigned int> generate_values(unsigned int size) {
//random engine
auto millis = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
default_random_engine e(static_cast<unsigned int>(millis.count()));
vector<unsigned int> data;
for (unsigned int i = 0; i < size; i++) {
data.push_back(e());
}
return data;
}
// 3.4 function
void parallel_sort(vector<unsigned int> &values) {
// Get the number of threads
auto num_threads = thread::hardware_concurrency();
// Get the number of elements in the vector
auto n = values.size();
// Declare the valies used in the loop
int i, tmp, phase;
// Declare parallel section
#pragma omp parallel num_threads(num_threads) default(none) shared(values, n) private(i, tmp, phase)
for (phase = 0; phase < n; ++phase) {
// Determine which phase of the sort we are in
if (phase % 2 == 0) {
// Parallel for loop. Each thread jumps forward 2 so no conflict
#pragma omp for
for (i = 1; i < n; i += 2) {
//Check if we should swap values
if (values[i - 1] > values[i]) {
tmp = values[i - 1];
values[i - 1] = values[i];
values[i] = tmp;
}
}
} else {
// Parallel for loop. Each thread jumps forward 2 so no conflict
#pragma omp for
for (i = 1; i < n; i += 2) {
// CHeck if we should swap values
if (values[i] > values[i + 1]) {
tmp = values[i + 1];
values[i + 1] = values[i];
values[i] = tmp;
}
}
}
}
}
// 3.3.1 function
void bubble_sort(vector<unsigned int> &data) {
for (vector<unsigned int>::size_type i = 0; i != data.size(); i++) {
for (vector<unsigned int>::size_type j = 0; j != data.size(); j++) {
if (data[j] > data[j + 1]) {
auto tmp = data[j];
data[j] = data[j + 1];
data[j + 1] = tmp;
}
}
}
}
int main() {
ofstream results("parallel_bubble_sort.csv", ofstream::out);
for (unsigned int size = 8; size <= 16; ++size) {
results << pow(2, size) << ", ";
for (unsigned int i = 0; i < 100; i++) {
cout << "Generating " << i << " for " << pow(2, size) << " values" << endl;
auto data = generate_values(static_cast<unsigned int>(pow(2, size)));
cout << "Sorting" << endl;
auto start = system_clock::now();
parallel_sort(data);
auto stop = system_clock::now();
auto total = duration_cast<milliseconds>(stop - start).count();
// Output Time
results << total << ",";
}
results << endl;
}
results.close();
return 0;
}
| 31.529412 | 101 | 0.502177 | [
"vector"
] |
a7189d1c8b3070f95dd6248a16b67d182342d3ac | 11,224 | cc | C++ | src/rocksdb2/utilities/cassandra/format.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | 5 | 2019-01-23T04:36:03.000Z | 2020-02-04T07:10:39.000Z | src/rocksdb2/utilities/cassandra/format.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | null | null | null | src/rocksdb2/utilities/cassandra/format.cc | yinchengtsinghua/RippleCPPChinese | a32a38a374547bdc5eb0fddcd657f45048aaad6a | [
"BSL-1.0"
] | 2 | 2019-05-14T07:26:59.000Z | 2020-06-15T07:25:01.000Z |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有(c)2017至今,Facebook,Inc.保留所有权利。
//此源代码在两个gplv2下都获得了许可(在
//复制根目录中的文件)和Apache2.0许可证
//(在根目录的license.apache文件中找到)。
#include "format.h"
#include <algorithm>
#include <map>
#include <memory>
#include "utilities/cassandra/serialize.h"
namespace rocksdb {
namespace cassandra {
namespace {
const int32_t kDefaultLocalDeletionTime =
std::numeric_limits<int32_t>::max();
const int64_t kDefaultMarkedForDeleteAt =
std::numeric_limits<int64_t>::min();
}
ColumnBase::ColumnBase(int8_t mask, int8_t index)
: mask_(mask), index_(index) {}
std::size_t ColumnBase::Size() const {
return sizeof(mask_) + sizeof(index_);
}
int8_t ColumnBase::Mask() const {
return mask_;
}
int8_t ColumnBase::Index() const {
return index_;
}
void ColumnBase::Serialize(std::string* dest) const {
rocksdb::cassandra::Serialize<int8_t>(mask_, dest);
rocksdb::cassandra::Serialize<int8_t>(index_, dest);
}
std::shared_ptr<ColumnBase> ColumnBase::Deserialize(const char* src,
std::size_t offset) {
int8_t mask = rocksdb::cassandra::Deserialize<int8_t>(src, offset);
if ((mask & ColumnTypeMask::DELETION_MASK) != 0) {
return Tombstone::Deserialize(src, offset);
} else if ((mask & ColumnTypeMask::EXPIRATION_MASK) != 0) {
return ExpiringColumn::Deserialize(src, offset);
} else {
return Column::Deserialize(src, offset);
}
}
Column::Column(
int8_t mask,
int8_t index,
int64_t timestamp,
int32_t value_size,
const char* value
) : ColumnBase(mask, index), timestamp_(timestamp),
value_size_(value_size), value_(value) {}
int64_t Column::Timestamp() const {
return timestamp_;
}
std::size_t Column::Size() const {
return ColumnBase::Size() + sizeof(timestamp_) + sizeof(value_size_)
+ value_size_;
}
void Column::Serialize(std::string* dest) const {
ColumnBase::Serialize(dest);
rocksdb::cassandra::Serialize<int64_t>(timestamp_, dest);
rocksdb::cassandra::Serialize<int32_t>(value_size_, dest);
dest->append(value_, value_size_);
}
std::shared_ptr<Column> Column::Deserialize(const char *src,
std::size_t offset) {
int8_t mask = rocksdb::cassandra::Deserialize<int8_t>(src, offset);
offset += sizeof(mask);
int8_t index = rocksdb::cassandra::Deserialize<int8_t>(src, offset);
offset += sizeof(index);
int64_t timestamp = rocksdb::cassandra::Deserialize<int64_t>(src, offset);
offset += sizeof(timestamp);
int32_t value_size = rocksdb::cassandra::Deserialize<int32_t>(src, offset);
offset += sizeof(value_size);
return std::make_shared<Column>(
mask, index, timestamp, value_size, src + offset);
}
ExpiringColumn::ExpiringColumn(
int8_t mask,
int8_t index,
int64_t timestamp,
int32_t value_size,
const char* value,
int32_t ttl
) : Column(mask, index, timestamp, value_size, value),
ttl_(ttl) {}
std::size_t ExpiringColumn::Size() const {
return Column::Size() + sizeof(ttl_);
}
void ExpiringColumn::Serialize(std::string* dest) const {
Column::Serialize(dest);
rocksdb::cassandra::Serialize<int32_t>(ttl_, dest);
}
std::chrono::time_point<std::chrono::system_clock> ExpiringColumn::TimePoint() const {
return std::chrono::time_point<std::chrono::system_clock>(std::chrono::microseconds(Timestamp()));
}
std::chrono::seconds ExpiringColumn::Ttl() const {
return std::chrono::seconds(ttl_);
}
bool ExpiringColumn::Expired() const {
return TimePoint() + Ttl() < std::chrono::system_clock::now();
}
std::shared_ptr<Tombstone> ExpiringColumn::ToTombstone() const {
auto expired_at = (TimePoint() + Ttl()).time_since_epoch();
int32_t local_deletion_time = static_cast<int32_t>(
std::chrono::duration_cast<std::chrono::seconds>(expired_at).count());
int64_t marked_for_delete_at =
std::chrono::duration_cast<std::chrono::microseconds>(expired_at).count();
return std::make_shared<Tombstone>(
ColumnTypeMask::DELETION_MASK,
Index(),
local_deletion_time,
marked_for_delete_at);
}
std::shared_ptr<ExpiringColumn> ExpiringColumn::Deserialize(
const char *src,
std::size_t offset) {
int8_t mask = rocksdb::cassandra::Deserialize<int8_t>(src, offset);
offset += sizeof(mask);
int8_t index = rocksdb::cassandra::Deserialize<int8_t>(src, offset);
offset += sizeof(index);
int64_t timestamp = rocksdb::cassandra::Deserialize<int64_t>(src, offset);
offset += sizeof(timestamp);
int32_t value_size = rocksdb::cassandra::Deserialize<int32_t>(src, offset);
offset += sizeof(value_size);
const char* value = src + offset;
offset += value_size;
int32_t ttl = rocksdb::cassandra::Deserialize<int32_t>(src, offset);
return std::make_shared<ExpiringColumn>(
mask, index, timestamp, value_size, value, ttl);
}
Tombstone::Tombstone(
int8_t mask,
int8_t index,
int32_t local_deletion_time,
int64_t marked_for_delete_at
) : ColumnBase(mask, index), local_deletion_time_(local_deletion_time),
marked_for_delete_at_(marked_for_delete_at) {}
int64_t Tombstone::Timestamp() const {
return marked_for_delete_at_;
}
std::size_t Tombstone::Size() const {
return ColumnBase::Size() + sizeof(local_deletion_time_)
+ sizeof(marked_for_delete_at_);
}
void Tombstone::Serialize(std::string* dest) const {
ColumnBase::Serialize(dest);
rocksdb::cassandra::Serialize<int32_t>(local_deletion_time_, dest);
rocksdb::cassandra::Serialize<int64_t>(marked_for_delete_at_, dest);
}
std::shared_ptr<Tombstone> Tombstone::Deserialize(const char *src,
std::size_t offset) {
int8_t mask = rocksdb::cassandra::Deserialize<int8_t>(src, offset);
offset += sizeof(mask);
int8_t index = rocksdb::cassandra::Deserialize<int8_t>(src, offset);
offset += sizeof(index);
int32_t local_deletion_time =
rocksdb::cassandra::Deserialize<int32_t>(src, offset);
offset += sizeof(int32_t);
int64_t marked_for_delete_at =
rocksdb::cassandra::Deserialize<int64_t>(src, offset);
return std::make_shared<Tombstone>(
mask, index, local_deletion_time, marked_for_delete_at);
}
RowValue::RowValue(int32_t local_deletion_time, int64_t marked_for_delete_at)
: local_deletion_time_(local_deletion_time),
marked_for_delete_at_(marked_for_delete_at), columns_(),
last_modified_time_(0) {}
RowValue::RowValue(Columns columns,
int64_t last_modified_time)
: local_deletion_time_(kDefaultLocalDeletionTime),
marked_for_delete_at_(kDefaultMarkedForDeleteAt),
columns_(std::move(columns)), last_modified_time_(last_modified_time) {}
std::size_t RowValue::Size() const {
std::size_t size = sizeof(local_deletion_time_)
+ sizeof(marked_for_delete_at_);
for (const auto& column : columns_) {
size += column -> Size();
}
return size;
}
int64_t RowValue::LastModifiedTime() const {
if (IsTombstone()) {
return marked_for_delete_at_;
} else {
return last_modified_time_;
}
}
bool RowValue::IsTombstone() const {
return marked_for_delete_at_ > kDefaultMarkedForDeleteAt;
}
void RowValue::Serialize(std::string* dest) const {
rocksdb::cassandra::Serialize<int32_t>(local_deletion_time_, dest);
rocksdb::cassandra::Serialize<int64_t>(marked_for_delete_at_, dest);
for (const auto& column : columns_) {
column -> Serialize(dest);
}
}
RowValue RowValue::PurgeTtl(bool* changed) const {
*changed = false;
Columns new_columns;
for (auto& column : columns_) {
if(column->Mask() == ColumnTypeMask::EXPIRATION_MASK) {
std::shared_ptr<ExpiringColumn> expiring_column =
std::static_pointer_cast<ExpiringColumn>(column);
if(expiring_column->Expired()){
*changed = true;
continue;
}
}
new_columns.push_back(column);
}
return RowValue(std::move(new_columns), last_modified_time_);
}
RowValue RowValue::ExpireTtl(bool* changed) const {
*changed = false;
Columns new_columns;
for (auto& column : columns_) {
if(column->Mask() == ColumnTypeMask::EXPIRATION_MASK) {
std::shared_ptr<ExpiringColumn> expiring_column =
std::static_pointer_cast<ExpiringColumn>(column);
if(expiring_column->Expired()) {
shared_ptr<Tombstone> tombstone = expiring_column->ToTombstone();
new_columns.push_back(tombstone);
*changed = true;
continue;
}
}
new_columns.push_back(column);
}
return RowValue(std::move(new_columns), last_modified_time_);
}
bool RowValue::Empty() const {
return columns_.empty();
}
RowValue RowValue::Deserialize(const char *src, std::size_t size) {
std::size_t offset = 0;
assert(size >= sizeof(local_deletion_time_) + sizeof(marked_for_delete_at_));
int32_t local_deletion_time =
rocksdb::cassandra::Deserialize<int32_t>(src, offset);
offset += sizeof(int32_t);
int64_t marked_for_delete_at =
rocksdb::cassandra::Deserialize<int64_t>(src, offset);
offset += sizeof(int64_t);
if (offset == size) {
return RowValue(local_deletion_time, marked_for_delete_at);
}
assert(local_deletion_time == kDefaultLocalDeletionTime);
assert(marked_for_delete_at == kDefaultMarkedForDeleteAt);
Columns columns;
int64_t last_modified_time = 0;
while (offset < size) {
auto c = ColumnBase::Deserialize(src, offset);
offset += c -> Size();
assert(offset <= size);
last_modified_time = std::max(last_modified_time, c -> Timestamp());
columns.push_back(std::move(c));
}
return RowValue(std::move(columns), last_modified_time);
}
//将多个行值合并为一个。
//对于具有相同索引的行中的每一列,我们选择最新的
//时间戳。我们还考虑了行墓碑,通过迭代
//每行的时间戳顺序都是相反的,当我们到达第一行时停止
//行墓碑。
RowValue RowValue::Merge(std::vector<RowValue>&& values) {
assert(values.size() > 0);
if (values.size() == 1) {
return std::move(values[0]);
}
//按上次修改的时间合并列,并在单击后跳过
//一排墓碑。
std::sort(values.begin(), values.end(),
[](const RowValue& r1, const RowValue& r2) {
return r1.LastModifiedTime() > r2.LastModifiedTime();
});
std::map<int8_t, std::shared_ptr<ColumnBase>> merged_columns;
int64_t tombstone_timestamp = 0;
for (auto& value : values) {
if (value.IsTombstone()) {
if (merged_columns.size() == 0) {
return std::move(value);
}
tombstone_timestamp = value.LastModifiedTime();
break;
}
for (auto& column : value.columns_) {
int8_t index = column->Index();
if (merged_columns.find(index) == merged_columns.end()) {
merged_columns[index] = column;
} else {
if (column->Timestamp() > merged_columns[index]->Timestamp()) {
merged_columns[index] = column;
}
}
}
}
int64_t last_modified_time = 0;
Columns columns;
for (auto& pair: merged_columns) {
//对于某些行,它的最后一个“修改时间>行逻辑删除时间戳”,但是
//它可能有时间戳比逻辑删除更有效的行,所以我们
//Ned过滤这些行。
if (pair.second->Timestamp() <= tombstone_timestamp) {
continue;
}
last_modified_time = std::max(last_modified_time, pair.second->Timestamp());
columns.push_back(std::move(pair.second));
}
return RowValue(std::move(columns), last_modified_time);
}
} //名字卡桑德达
} //命名空间rocksdb
| 30.253369 | 100 | 0.705007 | [
"vector"
] |
a71c0465fb58e64a23642bd3ef11f026ebe61db5 | 5,620 | hpp | C++ | include/liblas/variablerecord.hpp | sebastic/libLAS | 59709b36d80bf48c5463c009e9c5ff251f398e33 | [
"BSD-3-Clause"
] | null | null | null | include/liblas/variablerecord.hpp | sebastic/libLAS | 59709b36d80bf48c5463c009e9c5ff251f398e33 | [
"BSD-3-Clause"
] | null | null | null | include/liblas/variablerecord.hpp | sebastic/libLAS | 59709b36d80bf48c5463c009e9c5ff251f398e33 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* $Id: lasvariablerecord.hpp 889 2008-09-28 04:17:22Z hobu $
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: LAS record header class
* Author: Phil Vachon, philippe@cowpig.ca
*
******************************************************************************
* Copyright (c) 2008, Phil Vachon
* Copyright (c) 2008, Howard Butler
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Martin Isenburg or Iowa Department
* of Natural Resources 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.
****************************************************************************/
#ifndef LIBLAS_LASVARIABLERECORD_HPP_INCLUDED
#define LIBLAS_LASVARIABLERECORD_HPP_INCLUDED
#include <liblas/detail/private_utility.hpp>
#include <liblas/external/property_tree/ptree.hpp>
#include <liblas/export.hpp>
// boost
#include <boost/array.hpp>
#include <boost/cstdint.hpp>
// std
#include <string>
#include <vector>
#include <iostream>
namespace liblas {
/// Representation of variable-length record data.
class LAS_DLL VariableRecord
{
public:
/// Default constructor.
/// Zero-initialization of record data.
/// \exception No throw
VariableRecord();
/// Copy constructor.
/// Construction of new record object as a copy of existing one.
/// \exception No throw
VariableRecord(VariableRecord const& other);
~VariableRecord();
/// Assignment operator.
/// Construction and initializition of record object by
/// assignment of another one.
/// \exception No throw
VariableRecord& operator=(VariableRecord const& rhs);
/// Get record signature (LAS 1.0) or reserved bytes (LAS 1.1).
/// \exception No throw
boost::uint16_t GetReserved() const;
void SetReserved(boost::uint16_t data);
/// Get identifier of user which created the record.
/// The character data is up to 16 bytes long.
/// \exception No throw
std::string GetUserId(bool pad /*= false*/) const;
void SetUserId(std::string const& id);
/// Get identifier of record.
/// The record ID is closely related to the user ID.
/// \exception No throw
boost::uint16_t GetRecordId() const;
void SetRecordId(boost::uint16_t id);
/// Get record length after the header.
/// \exception No throw
boost::uint16_t GetRecordLength() const;
void SetRecordLength(boost::uint16_t length);
/// Get text description of data in the record.
/// The character data is up to 32 bytes long.
/// \exception No throw
std::string GetDescription(bool pad /*= false*/) const;
void SetDescription(std::string const& text);
/// Get the data for this VLR
std::vector<boost::uint8_t> const& GetData() const;
void SetData(std::vector<boost::uint8_t> const& data);
/// Compare actual header object against the other.
/// \exception No throw
bool equal(VariableRecord const& other) const;
/// Get the total size of the VLR in bytes
std::size_t GetTotalSize() const;
liblas::property_tree::ptree GetPTree() const;
enum
{
eUserIdSize = 16,
eDescriptionSize = 32
};
private:
std::vector<boost::uint8_t> m_data;
boost::array<char, 32> m_description;
boost::array<char, 16> m_user_id;
boost::uint16_t m_reserved;
boost::uint16_t m_record_id;
boost::uint16_t m_record_size; // length after header
};
/// Equality operator.
/// Implemented in terms of VariableRecord::equal member function.
/// \exception No throw
inline bool operator==(VariableRecord const& lhs, VariableRecord const& rhs)
{
return lhs.equal(rhs);
}
/// Inequality operator.
/// Implemented in terms of LASRecordHeader::equal member function.
/// \exception No throw
inline bool operator!=(VariableRecord const& lhs, VariableRecord const& rhs)
{
return (!(lhs == rhs));
}
LAS_DLL std::ostream& operator<<(std::ostream& os, liblas::VariableRecord const&);
} // namespace liblas
#endif // LIBLAS_LASVARIABLERECORD_HPP_INCLUDED
| 33.652695 | 82 | 0.670641 | [
"object",
"vector"
] |
a7217ad623cd78eeae1a1bf22532c8c1d4d9a206 | 29,400 | cpp | C++ | VTIL-SymEx/simplifier/simplifier.cpp | fengjixuchui/VTIL-Core | 5533e1122b3091daddbf7a82f8bb421dc2a097ea | [
"BSD-3-Clause"
] | 1 | 2021-05-16T16:50:15.000Z | 2021-05-16T16:50:15.000Z | VTIL-SymEx/simplifier/simplifier.cpp | fengjixuchui/VTIL-Core | 5533e1122b3091daddbf7a82f8bb421dc2a097ea | [
"BSD-3-Clause"
] | null | null | null | VTIL-SymEx/simplifier/simplifier.cpp | fengjixuchui/VTIL-Core | 5533e1122b3091daddbf7a82f8bb421dc2a097ea | [
"BSD-3-Clause"
] | 1 | 2020-12-10T17:56:42.000Z | 2020-12-10T17:56:42.000Z | // Copyright (c) 2020 Can Boluk and contributors of the VTIL Project
// 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.
// 3. Neither the name of VTIL Project 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 "simplifier.hpp"
#include "directives.hpp"
#include "boolean_directives.hpp"
#include "../expressions/expression.hpp"
#include "../directives/transformer.hpp"
#include <vtil/io>
#include <vtil/utility>
// [Configuration]
// Determine the depth limit after which we start self generated signature matching and
// the properties of the LRU cache.
//
#ifndef VTIL_SYMEX_SELFGEN_SIGMATCH_DEPTH_LIM
#define VTIL_SYMEX_SELFGEN_SIGMATCH_DEPTH_LIM 3
#endif
#ifndef VTIL_SYMEX_LRU_CACHE_SIZE
#define VTIL_SYMEX_LRU_CACHE_SIZE 0x10000
#endif
#ifndef VTIL_SYMEX_LRU_PRUNE_COEFF
#define VTIL_SYMEX_LRU_PRUNE_COEFF 0.35
#endif
namespace vtil::symbolic
{
struct join_depth_exception : std::exception
{
const char* what() const throw()
{
return "Reached the maximum join depth limit.";
}
};
// Implement lookup-table based dynamic tables.
//
using static_directive_table_entry = std::pair<directive::instance, directive::instance>;
using dynamic_directive_table_entry = std::pair<const directive::instance*, const directive::instance*>;
using dynamic_directive_table = std::vector<dynamic_directive_table_entry>;
using organized_directive_table = std::array<dynamic_directive_table, ( size_t ) math::operator_id::max>;
template<typename T>
static organized_directive_table build_dynamic_table( const T& container )
{
organized_directive_table table;
for ( auto [table, op] : zip( table, iindices ) )
for( auto& directive : container )
if ( directive.first.op == ( math::operator_id ) op )
table.emplace_back( &directive.first, &directive.second );
return table;
};
static auto& get_boolean_joiners( math::operator_id op ) { static const auto tbl = build_dynamic_table( directive::boolean_joiners ); return tbl[ ( size_t ) op ]; }
static auto& get_pack_descriptors( math::operator_id op ) { static const auto tbl = build_dynamic_table( directive::pack_descriptors ); return tbl[ ( size_t ) op ]; }
static auto& get_join_descriptors( math::operator_id op ) { static const auto tbl = build_dynamic_table( directive::join_descriptors ); return tbl[ ( size_t ) op ]; }
static auto& get_unpack_descriptors( math::operator_id op ) { static const auto tbl = build_dynamic_table( directive::unpack_descriptors ); return tbl[ ( size_t ) op ]; }
static auto& get_boolean_simplifiers( math::operator_id op ) { static const auto tbl = build_dynamic_table( directive::build_boolean_simplifiers() ); return tbl[ ( size_t ) op ]; }
static auto& get_universal_simplifiers( math::operator_id op ) { static const auto tbl = build_dynamic_table( directive::universal_simplifiers ); return tbl[ ( size_t ) op ]; }
// Thread local simplifier state.
//
struct simplifier_state
{
static constexpr size_t max_cache_entries = VTIL_SYMEX_LRU_CACHE_SIZE;
static constexpr size_t cache_prune_count = ( size_t ) ( max_cache_entries * VTIL_SYMEX_LRU_PRUNE_COEFF );
// Declare custom hash / equivalence checks hijacking the hash map iteration.
//
struct cache_value
{
// Type of the queue key.
//
using queue_key = typename detached_queue<cache_value>::key;
// Entry itself:
//
expression::reference result = {};
bool is_simplified = false;
// Implementation details:
//
int32_t lock_count = 0;
queue_key lru_key = {};
queue_key spec_key = {};
// Stores a type erased iterator since we don't know the map type yet, only
// an issue with libstdc++ but oh well.
// - Ref: https://github.com/vtil-project/VTIL-Core/issues/41
//
std::unordered_map<uint64_t, uint64_t>::const_iterator _iterator = {};
template<typename map_type>
auto& iterator()
{
using iterator_type = typename map_type::const_iterator;
static_assert( sizeof( iterator_type ) == sizeof( _iterator ), "Iterator sizes mismatch." );
return ( iterator_type& ) _iterator;
}
template<typename map_type>
const auto& iterator() const { return make_mutable( this )->template iterator<map_type>(); }
};
struct signature_hasher
{
size_t operator()( const expression::reference& ref ) const noexcept { return ref->signature.hash(); }
};
struct cache_scanner
{
struct sigscan_result
{
const expression::reference& key;
cache_value* match = nullptr;
expression::uid_relation_table table;
int64_t diff = 0;
};
inline static thread_local sigscan_result* sigscan = nullptr;
bool operator()( const expression::reference& a, const expression::reference& b ) const noexcept
{
// If there's a signature matching request:
//
if ( sigscan )
{
// Find out which argument is "this", if failed return false.
//
auto self = &a, other = &b;
if ( a.pointer != sigscan->key.pointer )
std::swap( self, other );
// Skip if not improving the result.
//
int64_t sdiff = ( *self )->depth - ( *other )->depth;
//if ( sdiff < 0 )
if( sdiff != 0 )
return false;
if ( sigscan->match && sdiff > sigscan->diff )
return false;
// Redirect to is identical if they're the same depth:
//
if ( sdiff == 0 && a.is_identical( *b ) )
return true;
// If other's past depth limit:
//
if ( ( *other )->depth > VTIL_SYMEX_SELFGEN_SIGMATCH_DEPTH_LIM )
{
// If matching signature, save the match, steal full value from the reference to the key.
//
if ( auto vec = ( *other )->match_to( **self, /*false*/ true ) )
{
sigscan->table = std::move( *vec );
using kv_pair = std::pair<const expression::reference, cache_value>;
sigscan->match = &( ( kv_pair* ) other )->second;
sigscan->diff = sdiff;
sigscan = nullptr;
}
}
return false;
}
// If not sigscanning, check if identical.
//
else
{
return a.is_identical( *b );
}
}
};
// Cache entry and map type.
//
using cache_map = std::unordered_map<expression::reference, cache_value, signature_hasher, cache_scanner>;
// Whether we're executing speculatively or not.
//
bool is_speculative = false;
// Queue for LRU age tracking and the speculativeness.
//
detached_queue<cache_value> lru_queue;
detached_queue<cache_value> spec_queue;
// Cache map.
//
cache_map map{ max_cache_entries };
// Disallow copy.
//
simplifier_state() {}
simplifier_state( simplifier_state&& ) = default;
simplifier_state( const simplifier_state& ) = delete;
simplifier_state& operator=( simplifier_state&& ) = default;
simplifier_state& operator=( const simplifier_state& ) = delete;
// Resets the local cache.
//
void reset()
{
lru_queue.reset();
spec_queue.reset();
is_speculative = false;
map.clear();
map.reserve( max_cache_entries );
}
// Begins speculative execution.
//
void begin_speculative()
{
is_speculative = true;
}
// Ends speculative execution and marks all speculative entries valid.
//
void join_speculative()
{
for ( auto it = spec_queue.head; it; )
{
auto next = it->next;
spec_queue.erase( it );
it = next;
}
is_speculative = false;
}
// Ends speculative execution and trashes all incomplete speculative entries.
//
void trash_speculative()
{
spec_queue.pop_front( &cache_value::spec_key );
for ( auto it = spec_queue.head; it; )
{
auto next = it->next;
cache_value* value = it->get( &cache_value::spec_key );
fassert( value->lock_count <= 0 );
if ( value->is_simplified )
spec_queue.erase( it );
else
erase( value );
it = next;
}
is_speculative = false;
}
// Erases a cache entry.
//
void erase( cache_value* value )
{
fassert( value->lock_count == 0 );
lru_queue.erase( &value->lru_key );
if( value->spec_key.is_valid() )
spec_queue.erase( &value->spec_key );
map.erase( std::move( value->template iterator<cache_map>() ) );
}
// Initializes a new entry in the map.
//
void init_entry( const cache_map::iterator& entry_it )
{
// Save the iterator.
//
entry_it->second.template iterator<cache_map>() = entry_it;
// If simplifying speculatively, link to tail.
//
if ( is_speculative )
spec_queue.emplace_back( &entry_it->second.spec_key );
// If we reached max entries, prune:
//
if ( lru_queue.size() == ( max_cache_entries - 1 ) )
{
for ( auto it = lru_queue.head; it && ( lru_queue.size() + cache_prune_count ) > max_cache_entries; )
{
auto next = it->next;
// Erase if not locked:
//
cache_value* value = it->get( &cache_value::lru_key );
if ( value->lock_count <= 0 )
erase( value );
it = next;
}
}
}
// References to cache from the active scope.
//
struct scope_reference
{
using queue_key = typename detached_queue<scope_reference>::key;
detached_queue<scope_reference>& queue;
cache_value* value;
queue_key key;
scope_reference( detached_queue<scope_reference>& queue, cache_value* value )
: queue( queue ), value( value ) { ++value->lock_count; queue.emplace_back( &key ); }
~scope_reference() { queue.erase( &key ); fassert( --value->lock_count >= 0 ); }
scope_reference( scope_reference&& o ) = delete;
scope_reference( const scope_reference& o ) = delete;
scope_reference& operator=( scope_reference&& o ) = delete;
scope_reference& operator=( const scope_reference& o ) = delete;
};
detached_queue<scope_reference> scope;
// Maximum allowed depth, once reached will reset to 0 to make all calls recursively fail.
//
uint64_t max_depth = ~0;
// Looks up the cache for the expression, returns [<result>, <simplified?>, <exists?>, <entry>].
//
std::tuple<expression::reference&, bool&, bool, cache_value*> lookup( const expression::reference& exp )
{
// Signal signature matcher.
//
cache_scanner::sigscan_result sig_search = { exp };
cache_scanner::sigscan = exp->depth > VTIL_SYMEX_SELFGEN_SIGMATCH_DEPTH_LIM ? &sig_search : nullptr;
// Make sure we don't rehash and then emplace/find.
//
fassert( ( map.max_load_factor() * map.bucket_count() ) >= ( map.size() + 1 ) );
auto [it, inserted] = map.emplace( exp, make_default<cache_value>() );
cache_scanner::sigscan = nullptr;
// Speculatively lock the entry.
//
it->second.lock_count++;
// If we inserted a new entry:
//
if ( inserted )
{
// If there is a partial match:
//
if ( auto base = sig_search.match )
{
// Reset inserted flag.
//
inserted = false;
// If simplified, transform according to the UID table.
//
if ( base->is_simplified )
{
it->second.result = make_const( base->result ).transform( [ &sig_search ] ( expression::delegate& exp )
{
if ( !exp->is_variable() )
return;
for ( auto& [a, b] : sig_search.table )
{
if ( exp->is_identical( *a ) )
{
exp = b.make_shared();
break;
}
}
}, true, false );
it->second.result->simplify_hint = true;
it->second.is_simplified = true;
}
// Otherwise, declare failure.
//
else
{
it->second.is_simplified = false;
}
// Erase or at least de-prioritize the previous entry.
//
if ( base->lock_count <= 0 )
{
erase( base );
}
else
{
lru_queue.erase( &base->lru_key );
lru_queue.emplace_front( &base->lru_key );
}
}
// Initialize it.
//
init_entry( it );
}
else
{
lru_queue.erase( &it->second.lru_key );
}
// Remove speculative lock.
//
it->second.lock_count--;
// Insert into the tail of use list.
//
lru_queue.emplace_back( &it->second.lru_key );
return { it->second.result, it->second.is_simplified, !inserted, &it->second };
}
};
static task_local( simplifier_state ) local_state;
void purge_simplifier_state() { if( local_state.init ) local_state->reset(); }
simplifier_state_ptr swap_simplifier_state( simplifier_state_ptr p )
{
if ( p )
{
std::swap( *p, *local_state );
return p;
}
else if( local_state.init )
{
return { new simplifier_state( local_state.steal() ), simplifier_state_deleter{} };
}
else
{
return nullptr;
}
}
void simplifier_state_deleter::operator()( simplifier_state* p ) const noexcept { delete p; }
simplifier_state_ptr simplifier_state_allocator::operator()() const noexcept { return { new simplifier_state, simplifier_state_deleter{} }; }
// Attempts to prettify the expression given.
//
static bool prettify_expression( expression::reference& exp )
{
using namespace logger;
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
scope_padding _p( 1 );
log<CON_CYN>( "[Prettify] = %s\n", *exp );
#endif
// Prettify each operand.
//
auto pexp = +exp;
for ( auto* op_ptr : { &pexp->lhs, &pexp->rhs } )
{
if ( !op_ptr->is_valid() ) continue;
// If successful, recurse.
//
if ( prettify_expression( *op_ptr ) )
{
pexp->update( false );
simplify_expression( exp, true, false );
return true;
}
}
// Update the expression.
//
pexp->update( false );
// Enumerate each pack descriptor:
//
for ( auto [dir_src, dir_dst] : get_pack_descriptors( exp->op ) )
{
// If we can transform the expression by the directive set:
//
if ( auto exp_new = transform( exp, dir_src, dir_dst ) )
{
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_PRP>( "[Pack] %s => %s\n", *dir_src, *dir_dst );
log<CON_GRN>( "= %s\n", *exp );
#endif
exp = exp_new;
return true;
}
}
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_YLW>( "= %s\n", *exp );
#endif
return false;
}
// Checks if the expression can be interpreted as a vector-boolean expression.
//
static std::pair<bool, expression::weak_reference> match_boolean_expression( const expression::reference& exp )
{
switch ( exp->op )
{
// If constant / variable, indicate success and return self if variable:
//
case math::operator_id::invalid:
{
if ( exp->is_variable() ) return { true, exp };
else return { true, nullptr };
}
// If bitwise not, continue from rhs.
//
case math::operator_id::bitwise_not:
return match_boolean_expression( exp->rhs );
// Bitwise OR/AND/XOR match both sides, if both were succesful
// and had matching/null UIDs, indicate success.
//
case math::operator_id::bitwise_or:
case math::operator_id::bitwise_and:
case math::operator_id::bitwise_xor:
{
auto [m1, p1] = match_boolean_expression( exp->lhs );
if ( !m1 ) return { false, nullptr };
auto [m2, p2] = match_boolean_expression( exp->rhs );
if ( !m2 ) return { false, nullptr };
if ( !p2 ) return { true, p1 };
if ( !p1 ) return { true, p2 };
if ( p1->uid == p2->uid )
return { true, p1 };
else
return { false, nullptr };
}
// Illegal operation, fail.
//
default:
return { false, nullptr };
}
}
// Attempts to normalize a vector-boolean expression into a simpler format.
//
static bool simplify_boolean_expression( expression::reference& exp )
{
// If it does not match a basic boolean expression, return false.
//
auto [is_match, uid_base] = match_boolean_expression( exp );
if ( !is_match ) return false;
// Evaluate for both states.
//
auto r0 = exp->evaluate( [ & ] ( auto& uid ) { return 0ull; } );
auto r1 = exp->evaluate( [ & ] ( auto& uid ) { return ~0ull; } );
// Calculate normal form AND/OR/XOR masks.
//
uint64_t and_mask = { ~( r0.known_zero() & r1.known_zero() ) };
uint64_t or_mask = { r0.known_one() & r1.known_one() };
uint64_t xor_mask = { r0.known_one() & r1.known_zero() };
// Apply each mask if not no-op.
//
expression::reference exp_new = uid_base.make_shared();
if ( and_mask != ~0ull ) exp_new &= expression{ and_mask, exp->size() };
if ( xor_mask ) exp_new ^= expression{ xor_mask, exp->size() };
if ( or_mask ) exp_new |= expression{ or_mask, exp->size() };
// If complexity was higher or equal, fail.
//
if ( exp_new->complexity >= exp->complexity ) return false;
// Apply and return.
//
exp = std::move( exp_new );
return true;
}
// Attempts to simplify the expression given, returns whether the simplification
// succeeded or not.
//
static bool simplify_expression_i( expression::reference& exp, bool pretty, bool unpack )
{
auto& lstate = *local_state;
using namespace logger;
// If we've reached the maximum depth, recursively fail.
//
if ( lstate.scope.size() >= lstate.max_depth )
{
lstate.max_depth = 0;
return false;
}
// Clear lazy if not done.
//
if ( exp->is_lazy )
( +exp )->is_lazy = false;
// If not an expression, we cannot simplify further.
//
if ( !exp->is_expression() )
return false;
// If simplify hint is set, only call prettify if requested and return.
//
if ( exp->simplify_hint )
{
if ( pretty )
prettify_expression( exp );
return false;
}
// If expression has known value, return as is.
//
if ( exp->value.is_known() )
{
*+exp = expression{ exp->value.known_one(), exp->value.size() };
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_CYN>( "= %s [By evaluation]\n", *exp );
#endif
return true;
}
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
// Log the input.
//
scope_padding _p( 1 );
if ( !state::get()->padding ) log( "\n" );
log( "[Input] = %s ", *exp );
log( "(Hash: %s)\n", exp->hash() );
#endif
// Lookup the expression in the cache.
//
auto [cache_entry, success_flag, found, entry] = lstate.lookup( exp );
simplifier_state::scope_reference _g{ lstate.scope, entry };
// If we resolved a valid cache entry:
//
if ( found )
{
// Replace with the cached entry if simplifies.
//
if ( cache_entry && success_flag )
{
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_YLW>( "= %s (From cache, Success: %d)\n", *cache_entry, success_flag );
#endif
exp = cache_entry;
return true;
}
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_RED>( "Failed as directed by cache...\n" );
#endif
return false;
}
// If trying to simplify resizing:
//
if ( exp->op == math::operator_id::ucast ||
exp->op == math::operator_id::cast )
{
// Simplify left hand side with the exact same arguments.
//
expression::reference exp_new = exp->lhs;
bool simplified = simplify_expression( exp_new, pretty, unpack );
bitcnt_t new_size = math::narrow_cast<bitcnt_t>( *exp->rhs->get() );
// Invoke resize with failure on explicit cast:
//
exp_new.resize( new_size, exp->op == math::operator_id::cast, true );
// If implicit resize failed:
//
if ( exp_new->size() != new_size )
{
// If operand was simplified, indicate success.
//
if ( simplified )
{
( +exp )->lhs = exp_new;
( +exp )->update( false );
success_flag = true;
}
}
else
{
// If operand was simplified or if the complexity reduced, indicate success.
//
if ( simplified || exp_new->complexity < exp->complexity )
{
exp = exp_new;
success_flag = true;
}
}
exp->simplify_hint = true;
cache_entry = exp;
return success_flag;
}
// If expression matches a basic boolean expression, simplify through that first:
//
if ( simplify_boolean_expression( exp ) )
{
// Recurse, and indicate success.
//
simplify_expression( exp, pretty );
exp->simplify_hint = true;
cache_entry = exp;
success_flag = true;
return true;
}
// Simplify operands first if not done already.
//
for ( auto* op_ptr : { &exp->lhs, &exp->rhs } )
{
// If invalid or is simplified, skip.
//
if ( !op_ptr->is_valid() || op_ptr->get()->simplify_hint )
continue;
// If we could simplify the operand:
//
expression::reference op_ref = *op_ptr;
if ( simplify_expression( op_ref, false ) )
{
// Own the reference and relocate the pointer.
//
auto [exp_new, op_new] = exp.own( op_ptr );
// Update the expression.
//
*op_new = op_ref;
exp_new->update( false );
// Recurse, and indicate success.
//
simplify_expression( exp, pretty );
exp->simplify_hint = true;
cache_entry = exp;
success_flag = true;
return true;
}
}
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
// Log the bit states.
//
log( "[Vector] = %s\n", exp->value );
#endif
// If reduced to a constant, replace it.
//
if ( exp->value.is_known() )
{
cache_entry = expression{ exp->value.known_one(), exp->value.size() };
success_flag = true;
exp = cache_entry;
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_CYN>( "= %s [By evaluation]\n", *exp );
#endif
return success_flag;
}
// Enumerate each universal simplifier:
//
for ( auto& [dir_src, dir_dst] : get_universal_simplifiers( exp->op ) )
{
// If we can transform the expression by the directive set:
//
if ( auto exp_new = transform( exp, dir_src, dir_dst ) )
{
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_GRN>( "[Simplify] %s => %s\n", *dir_src, *dir_dst );
log<CON_GRN>( "= %s [By simplify directive]\n", *exp_new );
#endif
// Recurse, set the hint and return the simplified instance.
//
simplify_expression( exp_new, pretty );
exp_new->simplify_hint = true;
cache_entry = exp_new;
if( success_flag = !exp->is_identical( *exp_new ) )
exp = exp_new;
return success_flag;
}
}
// If it is a boolean expression:
//
if ( exp->size() == 1 )
{
// Enumerate each universal simplifier:
//
for ( auto& [dir_src, dir_dst] : get_boolean_simplifiers( exp->op ) )
{
// If we can transform the expression by the directive set:
//
if ( auto exp_new = transform( exp, dir_src, dir_dst ) )
{
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_GRN>( "[Simplify] %s => %s\n", *dir_src, *dir_dst );
log<CON_GRN>( "= %s [By simplify directive]\n", *exp_new );
#endif
// Recurse, set the hint and return the simplified instance.
//
simplify_expression( exp_new, pretty );
exp_new->simplify_hint = true;
cache_entry = exp_new;
if ( success_flag = !exp->is_identical( *exp_new ) )
exp = exp_new;
return success_flag;
}
}
}
// Declare the filter.
//
auto filter = [ & ] ( auto& exp_new )
{
if ( !lstate.is_speculative )
{
// If complexity was reduced already, pass.
//
if ( exp_new->complexity < exp->complexity )
return true;
// Try simplifying with maximum depth set as expression's
// depth times two and pass if complexity was reduced.
//
auto pscope = lstate.scope;
lstate.max_depth = pscope.size() + exp_new->depth * 2;
lstate.begin_speculative();
simplify_expression( exp_new, false );
// If maximum depth was reached, revert any changes to the cache
// and fail the join directive.
//
if ( lstate.max_depth == 0 )
{
lstate.trash_speculative();
lstate.scope = pscope;
lstate.scope.tail->next = nullptr;
lstate.max_depth = ~0;
return false;
}
else
{
lstate.join_speculative();
lstate.max_depth = ~0;
return exp_new->complexity < exp->complexity;
}
}
else
{
// If complexity was reduced already, pass.
//
if ( exp_new->complexity < exp->complexity )
return true;
// Attempt simplifying with maximum depth decremented by one,
// fail if complexity was not reduced.
//
simplify_expression( exp_new, false );
return exp_new->complexity < exp->complexity;
}
};
// Enumerate each join descriptor:
//
for ( auto& [dir_src, dir_dst] : get_join_descriptors( exp->op ) )
{
// If we can transform the expression by the directive set:
//
if ( auto exp_new = transform( exp, dir_src, dir_dst, filter ) )
{
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_GRN>( "[Join] %s => %s\n", *dir_src, *dir_dst );
log<CON_GRN>( "= %s [By join directive]\n", *exp_new );
log<CON_YLW>( "Complexity: %lf => %lf\n", exp->complexity, exp_new->complexity );
#endif
// Recurse, set the hint and return the simplified instance.
//
simplify_expression( exp_new, pretty );
exp_new->simplify_hint = true;
cache_entry = exp_new;
if ( success_flag = !exp->is_identical( *exp_new ) )
exp = exp_new;
return success_flag;
}
}
// If it is a boolean expression:
//
if ( exp->size() == 1 )
{
// Enumerate each join descriptor:
//
for ( auto& [dir_src, dir_dst] : get_boolean_joiners( exp->op ) )
{
// If we can transform the expression by the directive set:
//
if ( auto exp_new = transform( exp, dir_src, dir_dst, filter ) )
{
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_GRN>( "[Join] %s => %s\n", *dir_src, *dir_dst );
log<CON_GRN>( "= %s [By join directive]\n", *exp_new );
log<CON_YLW>( "Complexity: %lf => %lf\n", exp->complexity, exp_new->complexity );
#endif
// Recurse, set the hint and return the simplified instance.
//
simplify_expression( exp_new, pretty );
exp_new->simplify_hint = true;
cache_entry = exp_new;
if ( success_flag = !exp->is_identical( *exp_new ) )
exp = exp_new;
return success_flag;
}
}
}
// Unpack the expression if requested:
//
if ( unpack )
{
// Enumerate each unpack descriptor:
//
for ( auto& [dir_src, dir_dst] : get_unpack_descriptors( exp->op ) )
{
// If we can transform the expression by the directive set:
//
if ( auto exp_new = transform( exp, dir_src, dir_dst,
[ & ] ( auto& exp_new ) { simplify_expression( exp_new, true ); return exp_new->complexity < exp->complexity; } ) )
{
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
log<CON_YLW>( "[Unpack] %s => %s\n", *dir_src, *dir_dst );
log<CON_GRN>( "= %s [By unpack directive]\n", *exp_new );
#endif
// Set the hint and return the simplified instance.
//
exp_new->simplify_hint = true;
cache_entry = exp_new;
if ( success_flag = !exp->is_identical( *exp_new ) )
exp = exp_new;
return success_flag;
}
}
}
// Prettify the expression if requested.
//
if ( pretty )
prettify_expression( exp );
#if VTIL_SYMEX_SIMPLIFY_VERBOSE
// Log the output.
//
log( "= %s\n\n", *exp );
#endif
return false;
}
// Simple routine wrapping real simplification to instrument it for any reason when needed.
//
bool simplify_expression( expression::reference& exp, bool pretty, bool unpack )
{
return simplify_expression_i( exp, pretty, unpack );
}
}; | 29.847716 | 184 | 0.620884 | [
"vector",
"transform"
] |
a723d54d5550b385f9036406e87055143a1970b6 | 9,696 | cpp | C++ | Userland/Libraries/LibTLS/Exchange.cpp | Szune/serenity | 7b7cbcecdf34e926068ab1ee59cb3ec0e40e6b9d | [
"BSD-2-Clause"
] | 1 | 2021-06-11T14:38:19.000Z | 2021-06-11T14:38:19.000Z | Userland/Libraries/LibTLS/Exchange.cpp | Szune/serenity | 7b7cbcecdf34e926068ab1ee59cb3ec0e40e6b9d | [
"BSD-2-Clause"
] | null | null | null | Userland/Libraries/LibTLS/Exchange.cpp | Szune/serenity | 7b7cbcecdf34e926068ab1ee59cb3ec0e40e6b9d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2020, Ali Mohammad Pur <ali.mpfard@gmail.com>
* 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <AK/Debug.h>
#include <LibCrypto/ASN1/DER.h>
#include <LibCrypto/PK/Code/EMSA_PSS.h>
#include <LibTLS/TLSv12.h>
namespace TLS {
bool TLSv12::expand_key()
{
u8 key[192]; // soooooooo many constants
auto key_buffer = Bytes { key, sizeof(key) };
auto is_aead = this->is_aead();
if (m_context.master_key.size() == 0) {
dbgln("expand_key() with empty master key");
return false;
}
auto key_size = key_length();
auto mac_size = mac_length();
auto iv_size = iv_length();
pseudorandom_function(
key_buffer,
m_context.master_key,
(const u8*)"key expansion", 13,
ReadonlyBytes { m_context.remote_random, sizeof(m_context.remote_random) },
ReadonlyBytes { m_context.local_random, sizeof(m_context.local_random) });
size_t offset = 0;
if (is_aead) {
iv_size = 4; // Explicit IV size.
} else {
memcpy(m_context.crypto.local_mac, key + offset, mac_size);
offset += mac_size;
memcpy(m_context.crypto.remote_mac, key + offset, mac_size);
offset += mac_size;
}
auto client_key = key + offset;
offset += key_size;
auto server_key = key + offset;
offset += key_size;
auto client_iv = key + offset;
offset += iv_size;
auto server_iv = key + offset;
offset += iv_size;
#if TLS_DEBUG
dbgln("client key");
print_buffer(client_key, key_size);
dbgln("server key");
print_buffer(server_key, key_size);
dbgln("client iv");
print_buffer(client_iv, iv_size);
dbgln("server iv");
print_buffer(server_iv, iv_size);
if (!is_aead) {
dbgln("client mac key");
print_buffer(m_context.crypto.local_mac, mac_size);
dbgln("server mac key");
print_buffer(m_context.crypto.remote_mac, mac_size);
}
#endif
if (is_aead) {
memcpy(m_context.crypto.local_aead_iv, client_iv, iv_size);
memcpy(m_context.crypto.remote_aead_iv, server_iv, iv_size);
m_aes_local.gcm = make<Crypto::Cipher::AESCipher::GCMMode>(ReadonlyBytes { client_key, key_size }, key_size * 8, Crypto::Cipher::Intent::Encryption, Crypto::Cipher::PaddingMode::RFC5246);
m_aes_remote.gcm = make<Crypto::Cipher::AESCipher::GCMMode>(ReadonlyBytes { server_key, key_size }, key_size * 8, Crypto::Cipher::Intent::Decryption, Crypto::Cipher::PaddingMode::RFC5246);
} else {
memcpy(m_context.crypto.local_iv, client_iv, iv_size);
memcpy(m_context.crypto.remote_iv, server_iv, iv_size);
m_aes_local.cbc = make<Crypto::Cipher::AESCipher::CBCMode>(ReadonlyBytes { client_key, key_size }, key_size * 8, Crypto::Cipher::Intent::Encryption, Crypto::Cipher::PaddingMode::RFC5246);
m_aes_remote.cbc = make<Crypto::Cipher::AESCipher::CBCMode>(ReadonlyBytes { server_key, key_size }, key_size * 8, Crypto::Cipher::Intent::Decryption, Crypto::Cipher::PaddingMode::RFC5246);
}
m_context.crypto.created = 1;
return true;
}
void TLSv12::pseudorandom_function(Bytes output, ReadonlyBytes secret, const u8* label, size_t label_length, ReadonlyBytes seed, ReadonlyBytes seed_b)
{
if (!secret.size()) {
dbgln("null secret");
return;
}
// RFC 5246: "In this section, we define one PRF, based on HMAC. This PRF with the
// SHA-256 hash function is used for all cipher suites defined in this
// document and in TLS documents published prior to this document when
// TLS 1.2 is negotiated."
// Apparently this PRF _always_ uses SHA256
Crypto::Authentication::HMAC<Crypto::Hash::SHA256> hmac(secret);
auto l_seed_size = label_length + seed.size() + seed_b.size();
u8 l_seed[l_seed_size];
auto label_seed_buffer = Bytes { l_seed, l_seed_size };
label_seed_buffer.overwrite(0, label, label_length);
label_seed_buffer.overwrite(label_length, seed.data(), seed.size());
if (seed_b.size() > 0)
label_seed_buffer.overwrite(label_length + seed.size(), seed_b.data(), seed_b.size());
auto digest_size = hmac.digest_size();
u8 digest[digest_size];
auto digest_0 = Bytes { digest, digest_size };
digest_0.overwrite(0, hmac.process(label_seed_buffer).immutable_data(), digest_size);
size_t index = 0;
while (index < output.size()) {
hmac.update(digest_0);
hmac.update(label_seed_buffer);
auto digest_1 = hmac.digest();
auto copy_size = min(digest_size, output.size() - index);
output.overwrite(index, digest_1.immutable_data(), copy_size);
index += copy_size;
digest_0.overwrite(0, hmac.process(digest_0).immutable_data(), digest_size);
}
}
bool TLSv12::compute_master_secret(size_t length)
{
if (m_context.premaster_key.size() == 0 || length < 48) {
dbgln("there's no way I can make a master secret like this");
dbgln("I'd like to talk to your manager about this length of {}", length);
return false;
}
m_context.master_key.clear();
m_context.master_key.grow(length);
pseudorandom_function(
m_context.master_key,
m_context.premaster_key,
(const u8*)"master secret", 13,
ReadonlyBytes { m_context.local_random, sizeof(m_context.local_random) },
ReadonlyBytes { m_context.remote_random, sizeof(m_context.remote_random) });
m_context.premaster_key.clear();
#if TLS_DEBUG
dbgln("master key:");
print_buffer(m_context.master_key);
#endif
expand_key();
return true;
}
ByteBuffer TLSv12::build_certificate()
{
PacketBuilder builder { MessageType::Handshake, m_context.options.version };
Vector<const Certificate*> certificates;
Vector<Certificate>* local_certificates = nullptr;
if (m_context.is_server) {
dbgln("Unsupported: Server mode");
VERIFY_NOT_REACHED();
} else {
local_certificates = &m_context.client_certificates;
}
constexpr size_t der_length_delta = 3;
constexpr size_t certificate_vector_header_size = 3;
size_t total_certificate_size = 0;
for (size_t i = 0; i < local_certificates->size(); ++i) {
auto& certificate = local_certificates->at(i);
if (!certificate.der.is_empty()) {
total_certificate_size += certificate.der.size() + der_length_delta;
// FIXME: Check for and respond with only the requested certificate types.
if (true) {
certificates.append(&certificate);
}
}
}
builder.append((u8)HandshakeType::CertificateMessage);
if (!total_certificate_size) {
#if TLS_DEBUG
dbgln("No certificates, sending empty certificate message");
#endif
builder.append_u24(certificate_vector_header_size);
builder.append_u24(total_certificate_size);
} else {
builder.append_u24(total_certificate_size + certificate_vector_header_size); // 3 bytes for header
builder.append_u24(total_certificate_size);
for (auto& certificate : certificates) {
if (!certificate->der.is_empty()) {
builder.append_u24(certificate->der.size());
builder.append(certificate->der.bytes());
}
}
}
auto packet = builder.build();
update_packet(packet);
return packet;
}
ByteBuffer TLSv12::build_change_cipher_spec()
{
PacketBuilder builder { MessageType::ChangeCipher, m_context.options.version, 64 };
builder.append((u8)1);
auto packet = builder.build();
update_packet(packet);
m_context.local_sequence_number = 0;
return packet;
}
ByteBuffer TLSv12::build_server_key_exchange()
{
dbgln("FIXME: build_server_key_exchange");
return {};
}
ByteBuffer TLSv12::build_client_key_exchange()
{
PacketBuilder builder { MessageType::Handshake, m_context.options.version };
builder.append((u8)HandshakeType::ClientKeyExchange);
build_random(builder);
m_context.connection_status = ConnectionStatus::KeyExchange;
auto packet = builder.build();
update_packet(packet);
return packet;
}
ssize_t TLSv12::handle_server_key_exchange(ReadonlyBytes)
{
dbgln("FIXME: parse_server_key_exchange");
return 0;
}
ssize_t TLSv12::handle_verify(ReadonlyBytes)
{
dbgln("FIXME: parse_verify");
return 0;
}
}
| 34.261484 | 196 | 0.684715 | [
"vector"
] |
a724104234d3ea333072a9eb95e282c657ae7745 | 5,187 | hpp | C++ | common/Geometry2d/TransformMatrix.hpp | AniruddhaG123/robocup-software | 0eb3b3957428894f2f39341594800be803665f44 | [
"Apache-2.0"
] | 1 | 2019-09-24T22:59:25.000Z | 2019-09-24T22:59:25.000Z | common/Geometry2d/TransformMatrix.hpp | ananth-kumar01/robocup-software | 4043a7f9590d02f617d8e9a762697e4aaa27f1a6 | [
"Apache-2.0"
] | null | null | null | common/Geometry2d/TransformMatrix.hpp | ananth-kumar01/robocup-software | 4043a7f9590d02f617d8e9a762697e4aaa27f1a6 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <Eigen/Dense>
#include "Point.hpp"
namespace Geometry2d {
// A 2x3 transformation matrix.
//
// This is the 2D equivalent of the usual 3D tranformation matrix with the
// bottom row omitted because the bottom (third) element of a 2D point is always
// 1. The third row of the matrix is understood to be [0 0 1].
class TransformMatrix {
public:
TransformMatrix() {
_m[0] = 1;
_m[1] = 0;
_m[2] = 0;
_m[3] = 0;
_m[4] = 1;
_m[5] = 0;
}
TransformMatrix(float a, float b, float c, float d, float e, float f) {
_m[0] = a;
_m[1] = b;
_m[2] = c;
_m[3] = d;
_m[4] = e;
_m[5] = f;
}
TransformMatrix(Geometry2d::Point origin, float rotation = 0,
bool mirror = false, float scale = 1);
TransformMatrix(const Eigen::Matrix<double, 3, 3>& other) {
_m[0] = other(0, 0);
_m[1] = other(0, 1);
_m[2] = other(0, 2);
_m[3] = other(1, 0);
_m[4] = other(1, 1);
_m[5] = other(1, 2);
}
TransformMatrix operator*(const TransformMatrix& other) const {
float a = _m[0] * other._m[0] + _m[1] * other._m[3];
float b = _m[0] * other._m[1] + _m[1] * other._m[4];
float c = _m[0] * other._m[2] + _m[1] * other._m[5] + _m[2];
float d = _m[3] * other._m[0] + _m[4] * other._m[3];
float e = _m[3] * other._m[1] + _m[4] * other._m[4];
float f = _m[3] * other._m[2] + _m[4] * other._m[5] + _m[5];
return TransformMatrix(a, b, c, d, e, f);
}
TransformMatrix& operator*=(const TransformMatrix& other) {
float a = _m[0] * other._m[0] + _m[1] * other._m[3];
float b = _m[0] * other._m[1] + _m[1] * other._m[4];
float c = _m[0] * other._m[2] + _m[1] * other._m[5] + _m[2];
float d = _m[3] * other._m[0] + _m[4] * other._m[3];
float e = _m[3] * other._m[1] + _m[4] * other._m[4];
float f = _m[3] * other._m[2] + _m[4] * other._m[5] + _m[5];
_m[0] = a;
_m[1] = b;
_m[2] = c;
_m[3] = d;
_m[4] = e;
_m[5] = f;
return *this;
}
operator Eigen::Matrix<double, 3, 3>() const {
Eigen::Matrix<double, 3, 3> result;
result << _m[0], _m[1], _m[2], _m[3], _m[4], _m[5], 0, 0, 1;
return result;
}
Point operator*(const Point& pt) const {
return Point(pt.x() * _m[0] + pt.y() * _m[1] + _m[2],
pt.x() * _m[3] + pt.y() * _m[4] + _m[5]);
}
// Transforms a direction vector (3rd element is zero)
Point transformDirection(const Point& dir) const {
return Point(dir.x() * _m[0] + dir.y() * _m[1],
dir.x() * _m[3] + dir.y() * _m[4]);
}
// Transforms the given angle in radians
float transformAngle(float angle) const;
// Returns the vector that represents the direction of the transformed
// X-axis.
Point x() const { return Point(_m[0], _m[3]); }
// Returns the vector that represents the direction of the transformed
// Y-axis.
Point y() const { return Point(_m[1], _m[4]); }
// Returns the origin of the transformed coordinate system
Point origin() const { return Point(_m[2], _m[5]); }
// Returns the scaling along the transformed X-axis.
float xScale() const { return x().mag(); }
// Returns the scaling along the transformed Y-axis.
float yScale() const { return y().mag(); }
// Returns the clockwise angle from the transformed Y axis to the original Y
// axis. This is not affected by horizontal reflection.
float rotation() const;
// Returns true if the coordinate system has been mirrored (i.e. is now
// left-handed).
bool mirrored() const;
const float* m() const { return _m; }
////////////////
// Functions to build common transformations:
// Translation
static TransformMatrix translate(const Point& delta) {
return TransformMatrix(1, 0, delta.x(), 0, 1, delta.y());
}
static TransformMatrix translate(float x, float y) {
return translate(Point(x, y));
}
// Rotation in radians around origin
static TransformMatrix rotate(float angle) {
float c = cos(angle);
float s = sin(angle);
return TransformMatrix(c, -s, 0, s, c, 0);
}
// Uniform scale
static TransformMatrix scale(float s) {
return TransformMatrix(s, 0, 0, 0, s, 0);
}
// Non-uniform scale
static TransformMatrix scale(float x, float y) {
return TransformMatrix(x, 0, 0, 0, y, 0);
}
// Returns a matrix to rotate <angle> radians CCW around <center>.
static TransformMatrix rotateAroundPoint(const Point& center, float angle);
// Returns a matrix to reflect along the line parallel to the Y-axis
// containing <center>.
static TransformMatrix mirrorAroundPoint(const Point& center);
static const TransformMatrix identity;
static const TransformMatrix mirrorX;
protected:
// Matrix values in row-major order.
//
// Indices:
// [0 1 2
// 3 4 5]
float _m[6];
};
} // namespace Geometry2d
| 30.511765 | 80 | 0.559476 | [
"vector",
"3d"
] |
a724986fece1adb57ee3b07595106ad0b7be8f9b | 53,528 | cpp | C++ | platform/shared/stlport/test/unit/mvctor_test.cpp | mensfeld/rhodes | 2962610a314ed563a0b7c83fcae6136913a1b033 | [
"MIT"
] | 173 | 2015-01-02T11:14:08.000Z | 2022-03-05T09:54:54.000Z | platform/shared/stlport/test/unit/mvctor_test.cpp | sdwood/rhodes | 8228aa40708dcbcc1d3967a479d1d84364022255 | [
"MIT"
] | 263 | 2015-01-05T04:35:22.000Z | 2021-09-07T06:00:02.000Z | platform/shared/stlport/test/unit/mvctor_test.cpp | sdwood/rhodes | 8228aa40708dcbcc1d3967a479d1d84364022255 | [
"MIT"
] | 77 | 2015-01-12T20:57:18.000Z | 2022-02-17T15:15:14.000Z | #include <vector>
#include <algorithm>
#include <vector>
#include <string>
#if defined (STLPORT) && !defined (_STLP_NO_EXTENSIONS)
# include <rope>
#endif
#if defined (STLPORT) && !defined (_STLP_NO_EXTENSIONS)
# include <slist>
#endif
#include <list>
#include <deque>
#include <set>
#include <map>
#if defined (STLPORT)
# include <unordered_set>
# include <unordered_map>
#endif
#if defined (STLPORT) && !defined (_STLP_NO_EXTENSIONS)
# include <hash_set>
# include <hash_map>
#endif
#include <queue>
#include <stack>
//#include <iostream>
#include "cppunit/cppunit_proxy.h"
#if !defined (STLPORT) || defined(_STLP_USE_NAMESPACES)
using namespace std;
#endif
//
// TestCase class
//
class MoveConstructorTest : public CPPUNIT_NS::TestCase
{
CPPUNIT_TEST_SUITE(MoveConstructorTest);
CPPUNIT_TEST(move_construct_test);
CPPUNIT_TEST(deque_test);
#if defined (__DMC__)
CPPUNIT_IGNORE;
#endif
CPPUNIT_TEST(vector_test);
CPPUNIT_STOP_IGNORE;
CPPUNIT_TEST(move_traits);
#if !defined (STLPORT) || defined (_STLP_NO_MOVE_SEMANTIC) || \
defined (_STLP_DONT_SIMULATE_PARTIAL_SPEC_FOR_TYPE_TRAITS) || \
defined (__BORLANDC__) || defined (__DMC__)
CPPUNIT_IGNORE;
# endif
CPPUNIT_TEST(movable_declaration)
#if defined (__BORLANDC__)
CPPUNIT_STOP_IGNORE;
CPPUNIT_TEST(nb_destructor_calls);
#endif
CPPUNIT_TEST_SUITE_END();
protected:
void move_construct_test();
void deque_test();
void vector_test();
void move_traits();
void movable_declaration();
void nb_destructor_calls();
/*
template <class _Container>
void standard_test1(_Container const& ref_cont) {
vector<_Container> vec_cont(1, ref_cont);
typedef typename _Container::value_type value_type;
value_type *pvalue = &(*vec_cont.front().begin());
size_t cur_capacity= vec_cont.capacity();
//force reallocation
while (cur_capacity == vec_cont.capacity()) {
vec_cont.push_back(ref_cont);
}
bool b=( (pvalue==(&(*vec_cont.front().begin()))) );
CPPUNIT_ASSERT(b);
}
*/
};
CPPUNIT_TEST_SUITE_REGISTRATION(MoveConstructorTest);
//
// tests implementation
//
void MoveConstructorTest::move_construct_test()
{
//cout << "vector<vector<int>>";
vector<int> const ref_vec(10, 0);
vector<vector<int> > v_v_ints(1, ref_vec);
int *pint = &(v_v_ints.front().front());
size_t cur_capacity = v_v_ints.capacity();
while (v_v_ints.capacity() <= cur_capacity) {
v_v_ints.push_back(ref_vec);
}
//v_v_ints has been resized
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT((pint == &v_v_ints.front().front()));
#endif
//cout << "vector<vector<int>>::erase";
//We need at least 3 elements:
while (v_v_ints.size() < 3) {
v_v_ints.push_back(ref_vec);
}
//We erase the 2nd
pint = &v_v_ints[2].front();
v_v_ints.erase(v_v_ints.begin() + 1);
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT((pint == &v_v_ints[1].front()));
#endif
//cout << "vector<string>";
string const ref_str("ref string, big enough to be a dynamic one");
vector<string> vec_strs(1, ref_str);
char const* pstr = vec_strs.front().c_str();
cur_capacity = vec_strs.capacity();
while (vec_strs.capacity() <= cur_capacity) {
vec_strs.push_back(ref_str);
}
//vec_str has been resized
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT((pstr == vec_strs.front().c_str()));
#endif
//cout << "vector<string>::erase";
//We need at least 3 elements:
while (vec_strs.size() < 3) {
vec_strs.push_back(ref_str);
}
//We erase the 2nd
pstr = vec_strs[2].c_str();
vec_strs.erase(vec_strs.begin() + 1);
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT((pstr == vec_strs[1].c_str()));
#endif
//cout << "swap(vector<int>, vector<int>)";
vector<int> elem1(10, 0), elem2(10, 0);
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
int *p1 = &elem1.front();
int *p2 = &elem2.front();
#endif
swap(elem1, elem2);
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT(((p1 == &elem2.front()) && (p2 == &elem1.front())));
#endif
{
vector<bool> bit_vec(5, true);
bit_vec.insert(bit_vec.end(), 5, false);
vector<vector<bool> > v_v_bits(1, bit_vec);
/*
* This is a STLport specific test as we are using internal implementation
* details to check that the move has been correctly handled. For other
* STL implementation it is only a compile check.
*/
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
# if defined (_STLP_DEBUG)
unsigned int *punit = v_v_bits.front().begin()._M_iterator._M_p;
# else
unsigned int *punit = v_v_bits.front().begin()._M_p;
# endif
#endif
cur_capacity = v_v_bits.capacity();
while (v_v_bits.capacity() <= cur_capacity) {
v_v_bits.push_back(bit_vec);
}
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
//v_v_bits has been resized
# if defined (_STLP_DEBUG)
CPPUNIT_ASSERT( punit == v_v_bits.front().begin()._M_iterator._M_p );
# else
CPPUNIT_ASSERT( punit == v_v_bits.front().begin()._M_p );
# endif
#endif
}
// zero: don't like this kind of tests
// because of template test function
// we should find another way to provide
// move constructor testing...
/*
standard_test1(list<int>(10));
standard_test1(slist<int>(10));
standard_test1(deque<int>(10));
*/
/*
int int_values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
set<int> int_set(int_values, int_values + sizeof(in_values) / sizeof(int));
standard_test1(int_set);
multiset<int> int_multiset(int_values, int_values + sizeof(in_values) / sizeof(int));
standard_test1(int_multiset);
*/
/*
CheckFullMoveSupport(string());
CheckFullMoveSupport(vector<int>());
CheckFullMoveSupport(deque<int>());
CheckFullMoveSupport(list<int>());
CheckFullMoveSupport(slist<int>());
*/
}
void MoveConstructorTest::deque_test()
{
//Check the insert range method.
//To the front:
{
# if !defined (STLPORT) || !defined (_STLP_DEBUG) || !defined (_STLP_NO_MEMBER_TEMPLATES)
deque<vector<int> > vect_deque;
vector<int*> bufs;
vect_deque.assign(3, vector<int>(10));
bufs.push_back(&vect_deque[0].front());
bufs.push_back(&vect_deque[1].front());
bufs.push_back(&vect_deque[2].front());
int nb_insert = 5;
//Initialize to 1 to generate a front insertion:
int pos = 1;
while (nb_insert--) {
vector<vector<int> > vect_vect(2, vector<int>(10));
vect_deque.insert(vect_deque.begin() + pos, vect_vect.begin(), vect_vect.end());
bufs.insert(bufs.begin() + pos, &vect_deque[pos].front());
bufs.insert(bufs.begin() + pos + 1, &vect_deque[pos + 1].front());
++pos;
}
CPPUNIT_ASSERT( vect_deque.size() == 13 );
# if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (int i = 0; i < 5; ++i) {
CPPUNIT_ASSERT( bufs[i] == &vect_deque[i].front() );
CPPUNIT_ASSERT( bufs[11 - i] == &vect_deque[11 - i].front() );
}
# endif
# endif
}
//To the back
{
# if !defined (STLPORT) || !defined (_STLP_DEBUG) || !defined (_STLP_NO_MEMBER_TEMPLATES)
deque<vector<int> > vect_deque;
vector<int*> bufs;
vect_deque.assign(3, vector<int>(10));
bufs.push_back(&vect_deque[0].front());
bufs.push_back(&vect_deque[1].front());
bufs.push_back(&vect_deque[2].front());
int nb_insert = 5;
//Initialize to 2 to generate a back insertion:
int pos = 2;
while (nb_insert--) {
vector<vector<int> > vect_vect(2, vector<int>(10));
vect_deque.insert(vect_deque.begin() + pos, vect_vect.begin(), vect_vect.end());
bufs.insert(bufs.begin() + pos, &vect_deque[pos].front());
bufs.insert(bufs.begin() + pos + 1, &vect_deque[pos + 1].front());
++pos;
}
CPPUNIT_ASSERT( vect_deque.size() == 13 );
# if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (int i = 0; i < 5; ++i) {
CPPUNIT_ASSERT( bufs[i + 1] == &vect_deque[i + 1].front() );
CPPUNIT_ASSERT( bufs[12 - i] == &vect_deque[12 - i].front() );
}
# endif
# endif
}
//Check the different erase methods.
{
deque<vector<int> > vect_deque;
vect_deque.assign(20, vector<int>(10));
deque<vector<int> >::iterator vdit(vect_deque.begin()), vditEnd(vect_deque.end());
vector<int*> bufs;
for (; vdit != vditEnd; ++vdit) {
bufs.push_back(&vdit->front());
}
{
// This check, repeated after each operation, check the deque consistency:
deque<vector<int> >::iterator it = vect_deque.end() - 5;
int nb_incr = 0;
for (; it != vect_deque.end() && nb_incr <= 6; ++nb_incr, ++it) {}
CPPUNIT_ASSERT( nb_incr == 5 );
}
{
//erase in front:
vect_deque.erase(vect_deque.begin() + 2);
bufs.erase(bufs.begin() + 2);
CPPUNIT_ASSERT( vect_deque.size() == 19 );
deque<vector<int> >::iterator dit(vect_deque.begin()), ditEnd(vect_deque.end());
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
deque<vector<int> >::iterator it = vect_deque.end() - 5;
int nb_incr = 0;
for (; it != vect_deque.end() && nb_incr <= 6; ++nb_incr, ++it) {}
CPPUNIT_ASSERT( nb_incr == 5 );
}
{
//erase in the back:
vect_deque.erase(vect_deque.end() - 2);
bufs.erase(bufs.end() - 2);
CPPUNIT_ASSERT( vect_deque.size() == 18 );
deque<vector<int> >::iterator dit(vect_deque.begin()), ditEnd(vect_deque.end());
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
deque<vector<int> >::iterator it = vect_deque.end() - 5;
int nb_incr = 0;
for (; it != vect_deque.end() && nb_incr < 6; ++nb_incr, ++it) {}
CPPUNIT_ASSERT( nb_incr == 5 );
}
{
//range erase in front
vect_deque.erase(vect_deque.begin() + 3, vect_deque.begin() + 5);
bufs.erase(bufs.begin() + 3, bufs.begin() + 5);
CPPUNIT_ASSERT( vect_deque.size() == 16 );
deque<vector<int> >::iterator dit(vect_deque.begin()), ditEnd(vect_deque.end());
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
deque<vector<int> >::iterator it = vect_deque.end() - 5;
int nb_incr = 0;
for (; it != vect_deque.end() && nb_incr <= 6; ++nb_incr, ++it) {}
CPPUNIT_ASSERT( nb_incr == 5 );
}
{
//range erase in back
vect_deque.erase(vect_deque.end() - 5, vect_deque.end() - 3);
bufs.erase(bufs.end() - 5, bufs.end() - 3);
CPPUNIT_ASSERT( vect_deque.size() == 14 );
deque<vector<int> >::iterator dit(vect_deque.begin()), ditEnd(vect_deque.end());
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
}
//Check the insert value(s)
{
deque<vector<int> > vect_deque;
vect_deque.assign(20, vector<int>(10));
deque<vector<int> >::iterator vdit(vect_deque.begin()), vditEnd(vect_deque.end());
vector<int*> bufs;
for (; vdit != vditEnd; ++vdit) {
bufs.push_back(&vdit->front());
}
{
//2 values in front:
vect_deque.insert(vect_deque.begin() + 2, 2, vector<int>(10));
bufs.insert(bufs.begin() + 2, &vect_deque[2].front());
bufs.insert(bufs.begin() + 3, &vect_deque[3].front());
CPPUNIT_ASSERT( vect_deque.size() == 22 );
deque<vector<int> >::iterator dit(vect_deque.begin()), ditEnd(vect_deque.end());
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
//2 values in back:
vect_deque.insert(vect_deque.end() - 2, 2, vector<int>(10));
bufs.insert(bufs.end() - 2, &vect_deque[20].front());
bufs.insert(bufs.end() - 2, &vect_deque[21].front());
CPPUNIT_ASSERT( vect_deque.size() == 24 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
deque<vector<int> >::iterator dit(vect_deque.begin()), ditEnd(vect_deque.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
//1 value in front:
deque<vector<int> >::iterator ret;
ret = vect_deque.insert(vect_deque.begin() + 2, vector<int>(10));
bufs.insert(bufs.begin() + 2, &vect_deque[2].front());
CPPUNIT_ASSERT( vect_deque.size() == 25 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( &ret->front() == bufs[2] );
deque<vector<int> >::iterator dit(vect_deque.begin()), ditEnd(vect_deque.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
//1 value in back:
deque<vector<int> >::iterator ret;
ret = vect_deque.insert(vect_deque.end() - 2, vector<int>(10));
bufs.insert(bufs.end() - 2, &vect_deque[23].front());
CPPUNIT_ASSERT( vect_deque.size() == 26 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( &ret->front() == bufs[23] );
deque<vector<int> >::iterator dit(vect_deque.begin()), ditEnd(vect_deque.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
}
}
void MoveConstructorTest::vector_test()
{
#if !defined (__DMC__)
//Check the insert range method.
//To the front:
{
vector<vector<int> > vect_vector;
vector<int*> bufs;
vect_vector.assign(3, vector<int>(10));
bufs.push_back(&vect_vector[0].front());
bufs.push_back(&vect_vector[1].front());
bufs.push_back(&vect_vector[2].front());
int nb_insert = 5;
int pos = 1;
while (nb_insert--) {
vector<vector<int> > vect_vect(2, vector<int>(10));
vect_vector.insert(vect_vector.begin() + pos, vect_vect.begin(), vect_vect.end());
bufs.insert(bufs.begin() + pos, &vect_vector[pos].front());
bufs.insert(bufs.begin() + pos + 1, &vect_vector[pos + 1].front());
++pos;
}
CPPUNIT_ASSERT( vect_vector.size() == 13 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (int i = 0; i < 5; ++i) {
CPPUNIT_ASSERT( bufs[i] == &vect_vector[i].front() );
CPPUNIT_ASSERT( bufs[11 - i] == &vect_vector[11 - i].front() );
}
#endif
}
//To the back
{
vector<vector<int> > vect_vector;
vector<int*> bufs;
vect_vector.assign(3, vector<int>(10));
bufs.push_back(&vect_vector[0].front());
bufs.push_back(&vect_vector[1].front());
bufs.push_back(&vect_vector[2].front());
int nb_insert = 5;
//Initialize to 2 to generate a back insertion:
int pos = 2;
while (nb_insert--) {
vector<vector<int> > vect_vect(2, vector<int>(10));
vect_vector.insert(vect_vector.begin() + pos, vect_vect.begin(), vect_vect.end());
bufs.insert(bufs.begin() + pos, &vect_vector[pos].front());
bufs.insert(bufs.begin() + pos + 1, &vect_vector[pos + 1].front());
++pos;
}
CPPUNIT_ASSERT( vect_vector.size() == 13 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
for (int i = 0; i < 5; ++i) {
CPPUNIT_ASSERT( bufs[i + 1] == &vect_vector[i + 1].front() );
CPPUNIT_ASSERT( bufs[12 - i] == &vect_vector[12 - i].front() );
}
#endif
}
//Check the different erase methods.
{
vector<vector<int> > vect_vector;
vect_vector.assign(20, vector<int>(10));
vector<vector<int> >::iterator vdit(vect_vector.begin()), vditEnd(vect_vector.end());
vector<int*> bufs;
for (; vdit != vditEnd; ++vdit) {
bufs.push_back(&vdit->front());
}
{
// This check, repeated after each operation, check the vector consistency:
vector<vector<int> >::iterator it = vect_vector.end() - 5;
int nb_incr = 0;
for (; it != vect_vector.end() && nb_incr <= 6; ++nb_incr, ++it) {}
CPPUNIT_ASSERT( nb_incr == 5 );
}
{
//erase in front:
vect_vector.erase(vect_vector.begin() + 2);
bufs.erase(bufs.begin() + 2);
CPPUNIT_ASSERT( vect_vector.size() == 19 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
vector<vector<int> >::iterator dit(vect_vector.begin()), ditEnd(vect_vector.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
vector<vector<int> >::iterator it = vect_vector.end() - 5;
int nb_incr = 0;
for (; it != vect_vector.end() && nb_incr <= 6; ++nb_incr, ++it) {}
CPPUNIT_ASSERT( nb_incr == 5 );
}
{
//erase in the back:
vect_vector.erase(vect_vector.end() - 2);
bufs.erase(bufs.end() - 2);
CPPUNIT_ASSERT( vect_vector.size() == 18 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
vector<vector<int> >::iterator dit(vect_vector.begin()), ditEnd(vect_vector.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
vector<vector<int> >::iterator it = vect_vector.end() - 5;
int nb_incr = 0;
for (; it != vect_vector.end() && nb_incr < 6; ++nb_incr, ++it) {}
CPPUNIT_ASSERT( nb_incr == 5 );
}
{
//range erase in front
vect_vector.erase(vect_vector.begin() + 3, vect_vector.begin() + 5);
bufs.erase(bufs.begin() + 3, bufs.begin() + 5);
CPPUNIT_ASSERT( vect_vector.size() == 16 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
vector<vector<int> >::iterator dit(vect_vector.begin()), ditEnd(vect_vector.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
vector<vector<int> >::iterator it = vect_vector.end() - 5;
int nb_incr = 0;
for (; it != vect_vector.end() && nb_incr <= 6; ++nb_incr, ++it) {}
CPPUNIT_ASSERT( nb_incr == 5 );
}
{
//range erase in back
vect_vector.erase(vect_vector.end() - 5, vect_vector.end() - 3);
bufs.erase(bufs.end() - 5, bufs.end() - 3);
CPPUNIT_ASSERT( vect_vector.size() == 14 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
vector<vector<int> >::iterator dit(vect_vector.begin()), ditEnd(vect_vector.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
}
//Check the insert value(s)
{
vector<vector<int> > vect_vector;
vect_vector.assign(20, vector<int>(10));
vector<vector<int> >::iterator vdit(vect_vector.begin()), vditEnd(vect_vector.end());
vector<int*> bufs;
for (; vdit != vditEnd; ++vdit) {
bufs.push_back(&vdit->front());
}
{
//2 values in front:
vect_vector.insert(vect_vector.begin() + 2, 2, vector<int>(10));
bufs.insert(bufs.begin() + 2, &vect_vector[2].front());
bufs.insert(bufs.begin() + 3, &vect_vector[3].front());
CPPUNIT_ASSERT( vect_vector.size() == 22 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
vector<vector<int> >::iterator dit(vect_vector.begin()), ditEnd(vect_vector.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
//2 values in back:
vect_vector.insert(vect_vector.end() - 2, 2, vector<int>(10));
bufs.insert(bufs.end() - 2, &vect_vector[20].front());
bufs.insert(bufs.end() - 2, &vect_vector[21].front());
CPPUNIT_ASSERT( vect_vector.size() == 24 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
vector<vector<int> >::iterator dit(vect_vector.begin()), ditEnd(vect_vector.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
//1 value in front:
vector<vector<int> >::iterator ret;
ret = vect_vector.insert(vect_vector.begin() + 2, vector<int>(10));
bufs.insert(bufs.begin() + 2, &vect_vector[2].front());
CPPUNIT_ASSERT( vect_vector.size() == 25 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( &ret->front() == bufs[2] );
vector<vector<int> >::iterator dit(vect_vector.begin()), ditEnd(vect_vector.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
{
//1 value in back:
vector<vector<int> >::iterator ret;
ret = vect_vector.insert(vect_vector.end() - 2, vector<int>(10));
bufs.insert(bufs.end() - 2, &vect_vector[23].front());
CPPUNIT_ASSERT( vect_vector.size() == 26 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( &ret->front() == bufs[23] );
vector<vector<int> >::iterator dit(vect_vector.begin()), ditEnd(vect_vector.end());
for (size_t i = 0; dit != ditEnd; ++dit, ++i) {
CPPUNIT_ASSERT( bufs[i] == &dit->front() );
}
#endif
}
}
//The following tests are checking move contructor implementations:
const string long_str("long enough string to force dynamic allocation");
{
//vector move contructor:
vector<vector<string> > vect(10, vector<string>(10, long_str));
vector<string> strs;
size_t index = 0;
while (true) {
vector<vector<string> >::iterator it(vect.begin());
advance(it, index % vect.size());
strs.push_back(it->front());
it->erase(it->begin());
if (it->empty()) {
vect.erase(it);
if (vect.empty())
break;
}
index += 3;
}
CPPUNIT_ASSERT( strs.size() == 10 * 10 );
vector<string>::iterator it(strs.begin()), itEnd(strs.end());
for (; it != itEnd; ++it) {
CPPUNIT_ASSERT( *it == long_str );
}
}
{
//deque move contructor:
vector<deque<string> > vect(10, deque<string>(10, long_str));
vector<string> strs;
size_t index = 0;
while (true) {
vector<deque<string> >::iterator it(vect.begin());
advance(it, index % vect.size());
strs.push_back(it->front());
it->pop_front();
if (it->empty()) {
vect.erase(it);
if (vect.empty())
break;
}
index += 3;
}
CPPUNIT_ASSERT( strs.size() == 10 * 10 );
vector<string>::iterator it(strs.begin()), itEnd(strs.end());
for (; it != itEnd; ++it) {
CPPUNIT_ASSERT( *it == long_str );
}
}
{
//list move contructor:
vector<list<string> > vect(10, list<string>(10, long_str));
vector<string> strs;
size_t index = 0;
while (true) {
vector<list<string> >::iterator it(vect.begin());
advance(it, index % vect.size());
strs.push_back(it->front());
it->pop_front();
if (it->empty()) {
vect.erase(it);
if (vect.empty())
break;
}
index += 3;
}
CPPUNIT_ASSERT( strs.size() == 10 * 10 );
vector<string>::iterator it(strs.begin()), itEnd(strs.end());
for (; it != itEnd; ++it) {
CPPUNIT_ASSERT( *it == long_str );
}
}
#if defined (STLPORT) && !defined (_STLP_NO_EXTENSIONS)
{
//slist move contructor:
vector<slist<string> > vect(10, slist<string>(10, long_str));
vector<string> strs;
size_t index = 0;
while (true) {
vector<slist<string> >::iterator it(vect.begin());
advance(it, index % vect.size());
strs.push_back(it->front());
it->pop_front();
if (it->empty()) {
vect.erase(it);
if (vect.empty())
break;
}
index += 3;
}
CPPUNIT_ASSERT( strs.size() == 10 * 10 );
vector<string>::iterator it(strs.begin()), itEnd(strs.end());
for (; it != itEnd; ++it) {
CPPUNIT_ASSERT( *it == long_str );
}
}
#endif
{
//binary tree move contructor:
multiset<string> ref;
for (size_t i = 0; i < 10; ++i) {
ref.insert(long_str);
}
vector<multiset<string> > vect(10, ref);
vector<string> strs;
size_t index = 0;
while (true) {
vector<multiset<string> >::iterator it(vect.begin());
advance(it, index % vect.size());
strs.push_back(*it->begin());
it->erase(it->begin());
if (it->empty()) {
vect.erase(it);
if (vect.empty())
break;
}
index += 3;
}
CPPUNIT_ASSERT( strs.size() == 10 * 10 );
vector<string>::iterator it(strs.begin()), itEnd(strs.end());
for (; it != itEnd; ++it) {
CPPUNIT_ASSERT( *it == long_str );
}
}
# endif /* __DMC__ */
#if defined (STLPORT)
# if !defined (__BORLANDC__) && !defined (__DMC__)
{
//hash container move contructor:
unordered_multiset<string> ref;
for (size_t i = 0; i < 10; ++i) {
ref.insert(long_str);
}
vector<unordered_multiset<string> > vect(10, ref);
vector<string> strs;
size_t index = 0;
while (true) {
vector<unordered_multiset<string> >::iterator it(vect.begin());
advance(it, index % vect.size());
strs.push_back(*it->begin());
it->erase(it->begin());
if (it->empty()) {
vect.erase(it);
if (vect.empty())
break;
}
index += 3;
}
CPPUNIT_ASSERT( strs.size() == 10 * 10 );
vector<string>::iterator it(strs.begin()), itEnd(strs.end());
for (; it != itEnd; ++it) {
CPPUNIT_ASSERT( *it == long_str );
}
}
# endif
#endif
}
struct MovableStruct {
MovableStruct() { ++nb_dft_construct_call; }
MovableStruct(MovableStruct const&) { ++nb_cpy_construct_call; }
# if defined (STLPORT)
MovableStruct(__move_source<MovableStruct>) { ++nb_mv_construct_call; }
# endif
~MovableStruct() { ++nb_destruct_call; }
MovableStruct& operator = (const MovableStruct&) {
++nb_assignment_call;
return *this;
}
static void reset() {
nb_dft_construct_call = nb_cpy_construct_call = nb_mv_construct_call = 0;
nb_assignment_call = 0;
nb_destruct_call = 0;
}
static size_t nb_dft_construct_call;
static size_t nb_cpy_construct_call;
static size_t nb_mv_construct_call;
static size_t nb_assignment_call;
static size_t nb_destruct_call;
//Dummy data just to control struct sizeof
//As node allocator implementation align memory blocks on 2 * sizeof(void*)
//we give MovableStruct the same size in order to have expected allocation
//and not more
void* dummy_data[2];
};
size_t MovableStruct::nb_dft_construct_call = 0;
size_t MovableStruct::nb_cpy_construct_call = 0;
size_t MovableStruct::nb_mv_construct_call = 0;
size_t MovableStruct::nb_assignment_call = 0;
size_t MovableStruct::nb_destruct_call = 0;
# if defined (STLPORT)
namespace std {
_STLP_TEMPLATE_NULL
struct __move_traits<MovableStruct> {
typedef __true_type implemented;
typedef __false_type complete;
};
}
# endif
struct CompleteMovableStruct {
CompleteMovableStruct() { ++nb_dft_construct_call; }
CompleteMovableStruct(CompleteMovableStruct const&) { ++nb_cpy_construct_call; }
# if defined (STLPORT)
CompleteMovableStruct(__move_source<CompleteMovableStruct>) { ++nb_mv_construct_call; }
# endif
~CompleteMovableStruct() { ++nb_destruct_call; }
CompleteMovableStruct& operator = (const CompleteMovableStruct&) {
++nb_assignment_call;
return *this;
}
static void reset() {
nb_dft_construct_call = nb_cpy_construct_call = nb_mv_construct_call = 0;
nb_assignment_call = 0;
nb_destruct_call = 0;
}
static size_t nb_dft_construct_call;
static size_t nb_cpy_construct_call;
static size_t nb_mv_construct_call;
static size_t nb_assignment_call;
static size_t nb_destruct_call;
//See MovableStruct
void* dummy_data[2];
};
size_t CompleteMovableStruct::nb_dft_construct_call = 0;
size_t CompleteMovableStruct::nb_cpy_construct_call = 0;
size_t CompleteMovableStruct::nb_mv_construct_call = 0;
size_t CompleteMovableStruct::nb_assignment_call = 0;
size_t CompleteMovableStruct::nb_destruct_call = 0;
# if defined (STLPORT)
namespace std {
_STLP_TEMPLATE_NULL
struct __move_traits<CompleteMovableStruct> {
typedef __true_type implemented;
typedef __true_type complete;
};
}
# endif
void MoveConstructorTest::move_traits()
{
{
{
vector<MovableStruct> vect;
vect.push_back(MovableStruct());
vect.push_back(MovableStruct());
vect.push_back(MovableStruct());
vect.push_back(MovableStruct());
// vect contains 4 elements
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 4 );
#if defined (STLPORT)
# if !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 3 );
# else
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 7 );
# endif
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 7 );
#elif !defined (_MSC_VER)
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 7 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 7 );
#else
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 14 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 14 );
#endif
CPPUNIT_ASSERT( MovableStruct::nb_assignment_call == 0 );
// Following test violate requirements to sequiences (23.1.1 Table 67)
/*
vect.insert(vect.begin() + 2, vect.begin(), vect.end());
// vect contains 8 elements
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 4 );
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 8 );
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 7 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 11 );
*/
MovableStruct::reset();
vector<MovableStruct> v2 = vect;
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_assignment_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 0 );
MovableStruct::reset();
vect.insert(vect.begin() + 2, v2.begin(), v2.end() );
// vect contains 8 elements
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 0 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 4 );
#else
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 8 );
#endif
CPPUNIT_ASSERT( MovableStruct::nb_assignment_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 4 );
MovableStruct::reset();
vect.erase(vect.begin(), vect.begin() + 2 );
// vect contains 6 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 6 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 8 );
#else
CPPUNIT_ASSERT_EQUAL( MovableStruct::nb_assignment_call, 6 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 2 );
#endif
MovableStruct::reset();
vect.erase(vect.end() - 2, vect.end());
// vect contains 4 elements
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 2 );
MovableStruct::reset();
vect.erase(vect.begin());
// vect contains 3 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 3 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 4 );
#else
CPPUNIT_ASSERT( MovableStruct::nb_assignment_call == 3 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 1 );
#endif
MovableStruct::reset();
}
//vect with 3 elements and v2 with 4 elements are now out of scope
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 3 + 4 );
}
{
{
vector<CompleteMovableStruct> vect;
vect.push_back(CompleteMovableStruct());
vect.push_back(CompleteMovableStruct());
vect.push_back(CompleteMovableStruct());
vect.push_back(CompleteMovableStruct());
// vect contains 4 elements
CPPUNIT_ASSERT( CompleteMovableStruct::nb_dft_construct_call == 4 );
#if defined (STLPORT)
# if !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 3 );
# else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 7 );
# endif
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 4 );
#elif !defined (_MSC_VER)
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 7 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 7 );
#else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 14 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 14 );
#endif
// Following test violate requirements to sequiences (23.1.1 Table 67)
/*
vect.insert(vect.begin() + 2, vect.begin(), vect.end());
// vect contains 8 elements
CPPUNIT_ASSERT( CompleteMovableStruct::nb_dft_construct_call == 4 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 8 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 7 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 4 );
*/
CompleteMovableStruct::reset();
vector<CompleteMovableStruct> v2 = vect;
CPPUNIT_ASSERT( CompleteMovableStruct::nb_dft_construct_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 0 );
CompleteMovableStruct::reset();
vect.insert(vect.begin() + 2, v2.begin(), v2.end());
// vect contains 8 elements
CPPUNIT_ASSERT( CompleteMovableStruct::nb_dft_construct_call == 0 );
#if defined (STLPORT)
# if !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 4 );
# else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 8 );
# endif
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 0 );
#else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 8 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 4 );
#endif
CompleteMovableStruct::reset();
vect.erase(vect.begin(), vect.begin() + 2);
// vect contains 6 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 6 );
#else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_assignment_call == 6 );
#endif
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 2 );
CompleteMovableStruct::reset();
vect.erase(vect.end() - 2, vect.end());
// vect contains 4 elements
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 2 );
CompleteMovableStruct::reset();
vect.erase(vect.begin());
// vect contains 3 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 3 );
#else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_assignment_call == 3 );
#endif
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 1 );
CompleteMovableStruct::reset();
}
//vect with 3 elements and v2 with 4 elements are now out of scope
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 3 + 4 );
}
{
MovableStruct::reset();
{
deque<MovableStruct> deq;
deq.push_back(MovableStruct());
deq.push_back(MovableStruct());
deq.push_back(MovableStruct());
deq.push_back(MovableStruct());
// deq contains 4 elements
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 4 );
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 4 );
// Following test violate requirements to sequiences (23.1.1 Table 67)
/*
deq.insert(deq.begin() + 2, deq.begin(), deq.end());
// deq contains 8 elements
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 4 );
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 8 );
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 7 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 11 );
*/
MovableStruct::reset();
deque<MovableStruct> d2 = deq;
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 0 );
MovableStruct::reset();
deq.insert(deq.begin() + 2, d2.begin(), d2.end() );
// deq contains 8 elements
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 0 );
CPPUNIT_ASSERT( MovableStruct::nb_cpy_construct_call == 4 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 2 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 2 );
#else
CPPUNIT_ASSERT( MovableStruct::nb_assignment_call == 2 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 0 );
#endif
MovableStruct::reset();
deq.erase(deq.begin() + 1, deq.begin() + 3 );
// deq contains 6 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 1 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 3 );
#else
//Following check is highly deque implementation dependant so
//it might not always work...
CPPUNIT_ASSERT( MovableStruct::nb_assignment_call == 1 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 2 );
#endif
MovableStruct::reset();
deq.erase(deq.end() - 3, deq.end() - 1);
// deq contains 4 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 1 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 3 );
#else
CPPUNIT_ASSERT( MovableStruct::nb_assignment_call == 1 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 2 );
#endif
MovableStruct::reset();
deq.erase(deq.begin());
// deq contains 3 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( MovableStruct::nb_mv_construct_call == 0 );
#else
CPPUNIT_ASSERT( MovableStruct::nb_assignment_call == 0 );
#endif
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 1 );
MovableStruct::reset();
}
//deq with 3 elements and d2 with 4 elements are now out of scope
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 3 + 4 );
}
{
CompleteMovableStruct::reset();
{
deque<CompleteMovableStruct> deq;
deq.push_back(CompleteMovableStruct());
deq.push_back(CompleteMovableStruct());
deq.push_back(CompleteMovableStruct());
deq.push_back(CompleteMovableStruct());
// deq contains 4 elements
CPPUNIT_ASSERT( CompleteMovableStruct::nb_dft_construct_call == 4 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 4 );
// Following test violate requirements to sequiences (23.1.1 Table 67)
/*
deq.insert(deq.begin() + 2, deq.begin(), deq.end());
// deq contains 8 elements
CPPUNIT_ASSERT( CompleteMovableStruct::nb_dft_construct_call == 4 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 8 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 7 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 4 );
*/
CompleteMovableStruct::reset();
deque<CompleteMovableStruct> d2 = deq;
CPPUNIT_ASSERT( CompleteMovableStruct::nb_dft_construct_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 4 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 0 );
CompleteMovableStruct::reset();
deq.insert(deq.begin() + 2, d2.begin(), d2.end());
// deq contains 8 elements
CPPUNIT_ASSERT( CompleteMovableStruct::nb_dft_construct_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_cpy_construct_call == 4 );
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 2 );
#else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_assignment_call == 2 );
#endif
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 0 );
CompleteMovableStruct::reset();
deq.erase(deq.begin() + 1, deq.begin() + 3);
// deq contains 6 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 1 );
#else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_assignment_call == 1 );
#endif
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 2 );
CompleteMovableStruct::reset();
deq.erase(deq.end() - 3, deq.end() - 1);
// deq contains 4 elements
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 1 );
#else
CPPUNIT_ASSERT( CompleteMovableStruct::nb_assignment_call == 1 );
#endif
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 2 );
CompleteMovableStruct::reset();
deq.erase(deq.begin());
// deq contains 3 elements
CPPUNIT_ASSERT( CompleteMovableStruct::nb_mv_construct_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_assignment_call == 0 );
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 1 );
CompleteMovableStruct::reset();
}
//deq with 3 elements and v2 with 4 elements are now out of scope
CPPUNIT_ASSERT( CompleteMovableStruct::nb_destruct_call == 3 + 4 );
}
}
#if defined (STLPORT) && !defined (_STLP_NO_MOVE_SEMANTIC)
# if defined (__GNUC__) && defined (_STLP_USE_NAMESPACES)
// libstdc++ sometimes exposed its own __true_type in
// global namespace resulting in an ambiguity.
# define __true_type std::__true_type
# define __false_type std::__false_type
# endif
static bool type_to_bool(__true_type)
{ return true; }
static bool type_to_bool(__false_type)
{ return false; }
template <class _Tp>
static bool is_movable(const _Tp&) {
#if defined (__BORLANDC__)
return __type2bool<typename __move_traits<_Tp>::implemented>::_Ret != 0;
#else
typedef typename __move_traits<_Tp>::implemented _MovableTp;
return type_to_bool(_MovableTp());
#endif
}
template <class _Tp>
static bool is_move_complete(const _Tp&) {
typedef __move_traits<_Tp> _TpMoveTraits;
#if defined (__BORLANDC__)
return type_to_bool(_TpMoveTraits::complete());
#else
typedef typename _TpMoveTraits::complete _TpMoveComplete;
return type_to_bool(_TpMoveComplete());
#endif
}
struct specially_allocated_struct {
bool operator < (specially_allocated_struct) const;
};
struct struct_with_specialized_less {};
namespace std
{
_STLP_TEMPLATE_NULL
class allocator<specially_allocated_struct>
{
//This allocator just represent what a STLport could do and in this
//case the STL containers implemented with it should still be movable
//but not completely as we cannot do any hypothesis on what is in this
//allocator.
public:
typedef specially_allocated_struct value_type;
typedef value_type * pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
#if defined (_STLP_MEMBER_TEMPLATE_CLASSES)
template <class _Tp1> struct rebind {
typedef allocator<_Tp1> other;
};
#endif
allocator() _STLP_NOTHROW {}
#if defined (_STLP_MEMBER_TEMPLATES)
template <class _Tp1> allocator(const allocator<_Tp1>&) _STLP_NOTHROW {}
#endif
allocator(const allocator&) _STLP_NOTHROW {}
~allocator() _STLP_NOTHROW {}
pointer address(reference __x) const { return &__x; }
const_pointer address(const_reference __x) const { return &__x; }
pointer allocate(size_type, const void* = 0) { return 0; }
void deallocate(pointer, size_type) {}
size_type max_size() const _STLP_NOTHROW { return 0; }
void construct(pointer, const_reference) {}
void destroy(pointer) {}
};
_STLP_TEMPLATE_NULL
struct less<struct_with_specialized_less> {
bool operator() (struct_with_specialized_less const&,
struct_with_specialized_less const&) const;
};
}
#endif
void MoveConstructorTest::movable_declaration()
{
#if defined (STLPORT) && !defined (_STLP_DONT_SIMULATE_PARTIAL_SPEC_FOR_TYPE_TRAITS) && \
!defined (_STLP_NO_MOVE_SEMANTIC) && \
!defined (__DMC__)
//This test purpose is to check correct detection of the STL movable
//traits declaration
{
//string, wstring:
CPPUNIT_ASSERT( is_movable(string()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(string()) );
# else
CPPUNIT_ASSERT( !is_move_complete(string()) );
# endif
# if defined (_STLP_HAS_WCHAR_T)
CPPUNIT_ASSERT( is_movable(wstring()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(wstring()) );
# else
CPPUNIT_ASSERT( !is_move_complete(wstring()) );
# endif
# endif
}
# if defined (STLPORT) && !defined (_STLP_NO_EXTENSIONS)
{
//crope, wrope:
CPPUNIT_ASSERT( is_movable(crope()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(crope()) );
# else
CPPUNIT_ASSERT( !is_move_complete(crope()) );
# endif
# if defined (_STLP_HAS_WCHAR_T)
CPPUNIT_ASSERT( is_movable(wrope()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(wrope()) );
# else
CPPUNIT_ASSERT( !is_move_complete(wrope()) );
# endif
# endif
}
# endif
{
//vector:
CPPUNIT_ASSERT( is_movable(vector<char>()) );
CPPUNIT_ASSERT( is_movable(vector<specially_allocated_struct>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(vector<char>()) );
CPPUNIT_ASSERT( !is_move_complete(vector<specially_allocated_struct>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(vector<char>()) );
# endif
}
{
//deque:
CPPUNIT_ASSERT( is_movable(deque<char>()) );
CPPUNIT_ASSERT( is_movable(deque<specially_allocated_struct>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(deque<char>()) );
CPPUNIT_ASSERT( !is_move_complete(deque<specially_allocated_struct>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(deque<char>()) );
# endif
}
{
//list:
CPPUNIT_ASSERT( is_movable(list<char>()) );
CPPUNIT_ASSERT( is_movable(list<specially_allocated_struct>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(list<char>()) );
CPPUNIT_ASSERT( !is_move_complete(list<specially_allocated_struct>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(list<char>()) );
# endif
}
#if defined (STLPORT) && !defined (_STLP_NO_EXTENSIONS)
{
//slist:
CPPUNIT_ASSERT( is_movable(slist<char>()) );
CPPUNIT_ASSERT( is_movable(slist<specially_allocated_struct>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(slist<char>()) );
CPPUNIT_ASSERT( !is_move_complete(slist<specially_allocated_struct>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(slist<char>()) );
# endif
}
#endif
{
//queue:
CPPUNIT_ASSERT( is_movable(queue<char>()) );
CPPUNIT_ASSERT( is_movable(queue<specially_allocated_struct>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(queue<char>()) );
CPPUNIT_ASSERT( !is_move_complete(queue<specially_allocated_struct>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(queue<char>()) );
# endif
}
{
//stack:
CPPUNIT_ASSERT( is_movable(stack<char>()) );
CPPUNIT_ASSERT( is_movable(stack<specially_allocated_struct>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(stack<char>()) );
CPPUNIT_ASSERT( !is_move_complete(stack<specially_allocated_struct>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(stack<char>()) );
# endif
}
{
//associative containers, set multiset, map, multimap:
//For associative containers it is important that less is correctly recognize as
//the STLport less or a user specialized less:
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(less<char>()) );
# endif
CPPUNIT_ASSERT( !is_move_complete(less<struct_with_specialized_less>()) );
//set
CPPUNIT_ASSERT( is_movable(set<char>()) );
CPPUNIT_ASSERT( is_movable(set<specially_allocated_struct>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(set<char>()) );
CPPUNIT_ASSERT( !is_move_complete(set<specially_allocated_struct>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(set<char>()) );
# endif
//multiset
CPPUNIT_ASSERT( is_movable(multiset<char>()) );
CPPUNIT_ASSERT( is_movable(multiset<specially_allocated_struct>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(multiset<char>()) );
CPPUNIT_ASSERT( !is_move_complete(multiset<specially_allocated_struct>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(multiset<char>()) );
# endif
//map
CPPUNIT_ASSERT( is_movable(map<char, char>()) );
CPPUNIT_ASSERT( is_movable(map<specially_allocated_struct, char>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(map<char, char>()) );
//Here even if allocator has been specialized for specially_allocated_struct
//this pecialization won't be used in default map instanciation as the default
//allocator is allocator<pair<specially_allocated_struct, char> >
CPPUNIT_ASSERT( is_move_complete(map<specially_allocated_struct, char>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(map<char, char>()) );
# endif
//multimap
CPPUNIT_ASSERT( is_movable(multimap<char, char>()) );
CPPUNIT_ASSERT( is_movable(multimap<specially_allocated_struct, char>()) );
# if defined (_STLP_CLASS_PARTIAL_SPECIALIZATION)
CPPUNIT_ASSERT( is_move_complete(multimap<char, char>()) );
//Idem map remark
CPPUNIT_ASSERT( is_move_complete(multimap<specially_allocated_struct, char>()) );
# else
CPPUNIT_ASSERT( !is_move_complete(multimap<char, char>()) );
# endif
}
# if defined (STLPORT)
{
//hashed containers, unordered_set unordered_multiset, unordered_map, unordered_multimap,
// hash_set, hash_multiset, hash_map, hash_multimap:
//We only check that they are movable, completness is not yet supported
CPPUNIT_ASSERT( is_movable(unordered_set<char>()) );
CPPUNIT_ASSERT( is_movable(unordered_multiset<char>()) );
CPPUNIT_ASSERT( is_movable(unordered_map<char, char>()) );
CPPUNIT_ASSERT( is_movable(unordered_multimap<char, char>()) );
# if defined (STLPORT) && !defined (_STLP_NO_EXTENSIONS)
CPPUNIT_ASSERT( is_movable(hash_set<char>()) );
CPPUNIT_ASSERT( is_movable(hash_multiset<char>()) );
CPPUNIT_ASSERT( is_movable(hash_map<char, char>()) );
CPPUNIT_ASSERT( is_movable(hash_multimap<char, char>()) );
# endif
}
# endif
# endif
}
#if defined (__BORLANDC__)
/* Specific Borland test case to show a really weird compiler behavior.
*/
class Standalone
{
public:
//Uncomment following to pass the test
//Standalone() {}
~Standalone() {}
MovableStruct movableStruct;
vector<int> intVector;
};
void MoveConstructorTest::nb_destructor_calls()
{
MovableStruct::reset();
try
{
Standalone standalone;
throw "some exception";
MovableStruct movableStruct;
}
catch (const char*)
{
CPPUNIT_ASSERT( MovableStruct::nb_dft_construct_call == 1 );
CPPUNIT_ASSERT( MovableStruct::nb_destruct_call == 1 );
}
}
#endif
| 33.330012 | 93 | 0.657917 | [
"vector"
] |
a724a9e3299c6cf9ca03fd999474c9b799e97f26 | 4,521 | cpp | C++ | metadata.cpp | ek0/binaryninja-api | d9661f34eec6855d495a10eaafc2a8e2679756a7 | [
"MIT"
] | 589 | 2016-04-11T11:32:33.000Z | 2022-03-30T09:49:37.000Z | metadata.cpp | ek0/binaryninja-api | d9661f34eec6855d495a10eaafc2a8e2679756a7 | [
"MIT"
] | 2,744 | 2016-04-11T02:47:37.000Z | 2022-03-31T21:05:09.000Z | metadata.cpp | ek0/binaryninja-api | d9661f34eec6855d495a10eaafc2a8e2679756a7 | [
"MIT"
] | 178 | 2016-04-15T00:47:05.000Z | 2022-03-24T10:42:54.000Z | #include "binaryninjaapi.h"
using namespace std;
using namespace BinaryNinja;
Metadata::Metadata(BNMetadata* metadata)
{
m_object = metadata;
}
Metadata::Metadata(bool data)
{
m_object = BNCreateMetadataBooleanData(data);
}
Metadata::Metadata(const string& data)
{
m_object = BNCreateMetadataStringData(data.c_str());
}
Metadata::Metadata(uint64_t data)
{
m_object = BNCreateMetadataUnsignedIntegerData(data);
}
Metadata::Metadata(int64_t data)
{
m_object = BNCreateMetadataSignedIntegerData(data);
}
Metadata::Metadata(double data)
{
m_object = BNCreateMetadataDoubleData(data);
}
Metadata::Metadata(MetadataType type)
{
m_object = BNCreateMetadataOfType(type);
}
Metadata::Metadata(const vector<uint8_t>& data)
{
auto input = new uint8_t[data.size()];
for (size_t i = 0; i < data.size(); i++)
input[i] = data[i];
m_object = BNCreateMetadataRawData(input, data.size());
delete[] input;
}
Metadata::Metadata(const std::vector<Ref<Metadata>>& data)
{
BNMetadata** dataList = new BNMetadata*[data.size()];
for (size_t i = 0; i < data.size(); i++)
dataList[i] = data[i]->m_object;
m_object = BNCreateMetadataArray(dataList, data.size());
}
Metadata::Metadata(const std::map<std::string, Ref<Metadata>>& data)
{
char** keys = new char*[data.size()];
BNMetadata** values = new BNMetadata*[data.size()];
size_t i = 0;
for (auto &elm : data)
{
keys[i] = BNAllocString(elm.first.c_str());
values[i++] = elm.second->m_object;
}
m_object = BNCreateMetadataValueStore((const char**)keys, values, data.size());
for (size_t j = 0; j < data.size(); j++)
BNFreeString(keys[j]);
delete[] keys;
delete[] values;
}
bool Metadata::operator==(const Metadata& rhs)
{
return BNMetadataIsEqual(m_object, rhs.m_object);
}
Ref<Metadata> Metadata::operator[](const std::string& key)
{
return new Metadata(BNMetadataGetForKey(m_object, key.c_str()));
}
Ref<Metadata> Metadata::operator[](size_t idx)
{
return new Metadata(BNMetadataGetForIndex(m_object, idx));
}
bool Metadata::SetValueForKey(const string& key, Ref<Metadata> data)
{
return BNMetadataSetValueForKey(m_object, key.c_str(), data->m_object);
}
void Metadata::RemoveKey(const string& key)
{
return BNMetadataRemoveKey(m_object, key.c_str());
}
MetadataType Metadata::GetType() const
{
return BNMetadataGetType(m_object);
}
bool Metadata::GetBoolean() const
{
return BNMetadataGetBoolean(m_object);
}
string Metadata::GetString() const
{
char* str = BNMetadataGetString(m_object);
string result = string(str);
BNFreeString(str);
return result;
}
uint64_t Metadata::GetUnsignedInteger() const
{
return BNMetadataGetUnsignedInteger(m_object);
}
int64_t Metadata::GetSignedInteger() const
{
return BNMetadataGetSignedInteger(m_object);
}
double Metadata::GetDouble() const
{
return BNMetadataGetDouble(m_object);
}
vector<uint8_t> Metadata::GetRaw() const
{
size_t outSize;
uint8_t* outList = BNMetadataGetRaw(m_object, &outSize);
vector<uint8_t> result(outList, outList + outSize);
BNFreeMetadataRaw(outList);
return result;
}
vector<Ref<Metadata>> Metadata::GetArray()
{
size_t size = 0;
BNMetadata** data = BNMetadataGetArray(m_object, &size);
vector<Ref<Metadata>> result;
result.reserve(size);
for (size_t i = 0; i < size; i++)
result.push_back(new Metadata(data[i]));
BNFreeMetadataArray(data);
return result;
}
map<string, Ref<Metadata>> Metadata::GetKeyValueStore()
{
BNMetadataValueStore* data = BNMetadataGetValueStore(m_object);
map<string, Ref<Metadata>> result;
for (size_t i = 0; i < data->size; i++)
{
result[data->keys[i]] = new Metadata(data->values[i]);
}
return result;
}
bool Metadata::Append(Ref<Metadata> data)
{
return BNMetadataArrayAppend(m_object, data->m_object);
}
void Metadata::RemoveIndex(size_t index)
{
BNMetadataRemoveIndex(m_object, index);
}
size_t Metadata::Size() const
{
return BNMetadataSize(m_object);
}
bool Metadata::IsBoolean() const
{
return BNMetadataIsBoolean(m_object);
}
bool Metadata::IsString() const
{
return BNMetadataIsString(m_object);
}
bool Metadata::IsUnsignedInteger() const
{
return BNMetadataIsUnsignedInteger(m_object);
}
bool Metadata::IsSignedInteger() const
{
return BNMetadataIsSignedInteger(m_object);
}
bool Metadata::IsDouble() const
{
return BNMetadataIsDouble(m_object);
}
bool Metadata::IsRaw() const
{
return BNMetadataIsRaw(m_object);
}
bool Metadata::IsArray() const
{
return BNMetadataIsArray(m_object);
}
bool Metadata::IsKeyValueStore() const
{
return BNMetadataIsKeyValueStore(m_object);
}
| 20.364865 | 80 | 0.73612 | [
"vector"
] |
a731bedc81bc19a6c2c023d4c77a29f37edd5caf | 3,465 | cpp | C++ | CepsyGLFramework/CepsyGLFramework/src/Application/Application.cpp | cepsylon/CepsyGLFramework | 72cf710c892ff34aeac5ed47b0b7799756a04032 | [
"MIT"
] | null | null | null | CepsyGLFramework/CepsyGLFramework/src/Application/Application.cpp | cepsylon/CepsyGLFramework | 72cf710c892ff34aeac5ed47b0b7799756a04032 | [
"MIT"
] | null | null | null | CepsyGLFramework/CepsyGLFramework/src/Application/Application.cpp | cepsylon/CepsyGLFramework | 72cf710c892ff34aeac5ed47b0b7799756a04032 | [
"MIT"
] | null | null | null | #include "Application.h"
#include <imgui/imgui.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
Application application;
namespace
{
LRESULT CALLBACK message_handler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
ImGuiIO& io = ImGui::GetIO();
switch (message)
{
case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
{
int button = 0;
if (message == WM_LBUTTONDOWN || message == WM_LBUTTONDBLCLK) button = 0;
if (message == WM_RBUTTONDOWN || message == WM_RBUTTONDBLCLK) button = 1;
if (message == WM_MBUTTONDOWN || message == WM_MBUTTONDBLCLK) button = 2;
if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
::SetCapture(hWnd);
io.MouseDown[button] = true;
return 0;
}
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
{
int button = 0;
if (message == WM_LBUTTONUP) button = 0;
if (message == WM_RBUTTONUP) button = 1;
if (message == WM_MBUTTONUP) button = 2;
io.MouseDown[button] = false;
if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hWnd)
::ReleaseCapture();
return 0;
}
case WM_MOUSEWHEEL:
io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
return 0;
case WM_MOUSEHWHEEL:
io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
return 0;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (wParam < 256)
io.KeysDown[wParam] = 1;
return 0;
case WM_KEYUP:
case WM_SYSKEYUP:
if (wParam < 256)
io.KeysDown[wParam] = 0;
return 0;
case WM_CHAR:
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
if (wParam > 0 && wParam < 0x10000)
io.AddInputCharacter((unsigned short)wParam);
return 0;
case WM_DESTROY:
application.set_is(false);
PostQuitMessage(0);
return 0;
// Window resizing
case WM_SIZE:
{
int width = LOWORD(lParam), height = HIWORD(lParam);
application.window().set_client_size(width, height);
if (application.graphics().is_dimension_client_size())
application.graphics().set_dimension(glm::ivec2{ width, height });
return 0;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
}
void Application::initialize(HINSTANCE__ * instance, int show)
{
mRunning = true;
mWindow.initialize(instance, show, &message_handler);
mGraphics.initialize();
mResources.initialize();
mGUI.initialize();
mScene.initialize();
}
void Application::run()
{
while (mRunning)
{
// Update everything
mWindow.update();
mGraphics.update();
mGUI.update();
mScene.update();
// Here goes gui
mScene.to_gui();
// Render
mGraphics.render();
mGUI.render();
mGraphics.present();
}
}
void Application::shutdown()
{
mScene.shutdown();
mGUI.shutdown();
mResources.shutdown();
mGraphics.shutdown();
mWindow.shutdown();
}
void Application::set_is(bool is) { mRunning = is; }
const Window & Application::window() const { return mWindow; }
Window & Application::window() { return mWindow; }
const Graphics & Application::graphics() const { return mGraphics; }
Graphics & Application::graphics() { return mGraphics; }
const Scene & Application::scene() const { return mScene; }
Scene & Application::scene() { return mScene; }
const Resources & Application::resources() const { return mResources; }
Resources & Application::resources() { return mResources; }
| 25.858209 | 88 | 0.694084 | [
"render"
] |
a732d375eee7a20f2be9bb8f107d51b30cbe44e8 | 5,570 | cc | C++ | src/network/client.cc | lorenzo-stoakes/janus | 88cb536d569edf15af112230b02ea946c828cc12 | [
"MIT"
] | 1 | 2022-02-16T11:23:47.000Z | 2022-02-16T11:23:47.000Z | src/network/client.cc | lorenzo-stoakes/janus | 88cb536d569edf15af112230b02ea946c828cc12 | [
"MIT"
] | null | null | null | src/network/client.cc | lorenzo-stoakes/janus | 88cb536d569edf15af112230b02ea946c828cc12 | [
"MIT"
] | null | null | null | #include "janus.hh"
namespace janus::tls
{
client::client(const char* host, const char* port, certs& certs, rng& rng, uint32_t timeout_ms)
: _host{host},
_port{port},
_timeout_ms{timeout_ms},
_certs{certs},
_rng{rng},
_connected{false},
_invalid{false},
_moved{false},
_server_fd{},
_ssl{},
_conf{}
{
init();
}
client::~client()
{
destroy();
}
client::client(client&& that) noexcept
: _host{that._host},
_port{that._port},
_timeout_ms{that._timeout_ms},
_certs{that._certs},
_rng{that._rng},
_connected{that._connected},
_invalid{that._invalid},
_moved{false},
_server_fd{that._server_fd},
_ssl{that._ssl},
_conf{that._conf}
{
that._moved = true;
}
void client::connect()
{
check_valid();
if (_connected)
return;
config();
// Connect via TCP/IP.
int err_num =
internal::mbedtls_net_connect(&_server_fd, _host, _port, MBEDTLS_NET_PROTO_TCP);
if (err_num != 0)
throw gen_conn_err("Client", err_num);
// Configure I/O.
internal::mbedtls_ssl_set_bio(&_ssl, &_server_fd, internal::mbedtls_net_send,
internal::mbedtls_net_recv,
internal::mbedtls_net_recv_timeout);
// TLS handshake.
do {
err_num = internal::mbedtls_ssl_handshake(&_ssl);
} while (should_try_again(err_num));
if (err_num != 0)
throw gen_conn_err("Handshake", err_num);
_connected = true;
}
void client::disconnect()
{
if (!_connected || _invalid)
return;
_connected = false;
_invalid = true;
internal::mbedtls_ssl_close_notify(&_ssl);
}
auto client::read(char* buf, int size, bool& disconnected) -> int
{
check_valid();
check_connected("read");
auto* ubuf = reinterpret_cast<unsigned char*>(buf);
int err_num = internal::mbedtls_ssl_read(&_ssl, ubuf, size);
if (should_try_again(err_num))
return 0;
if (err_num == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY || err_num == 0) {
_invalid = true;
_connected = false;
disconnected = true;
return 0;
}
if (err_num < 0)
throw gen_conn_err("Read", err_num);
disconnected = false;
int bytes_read = err_num;
return bytes_read;
}
void client::write(const char* buf, int size)
{
check_valid();
check_connected("write");
int offset = 0;
const auto* ubuf = reinterpret_cast<const unsigned char*>(buf);
while (offset < size) {
int err_num = internal::mbedtls_ssl_write(&_ssl, &ubuf[offset], size - offset);
if (should_try_again(err_num))
continue;
if (err_num < 0)
throw gen_conn_err("Write", err_num);
int bytes_written = err_num;
offset += bytes_written;
}
}
void client::init()
{
internal::mbedtls_net_init(&_server_fd);
internal::mbedtls_ssl_init(&_ssl);
internal::mbedtls_ssl_config_init(&_conf);
}
void client::destroy()
{
if (_moved)
return;
// We disconnect on destroy.
disconnect();
internal::mbedtls_net_free(&_server_fd);
internal::mbedtls_ssl_free(&_ssl);
internal::mbedtls_ssl_config_free(&_conf);
}
void client::check_valid()
{
if (_invalid)
throw std::runtime_error("Attempt to use invalid client.");
}
void client::check_connected(const char* op)
{
if (!_connected)
throw std::runtime_error(std::string("Attempt to ") + op +
" on disconnected client.");
}
auto client::gen_conn_err(const std::string& prefix, int err_code) -> network_error
{
// If we're generating a connection error then our underlying
// mbedtls state is invalid.
_invalid = true;
std::string conn_prefix = std::string(_host) + ":" + _port + ": ";
return internal::gen_err(conn_prefix + prefix, err_code);
}
auto client::should_try_again(int err_num) -> bool
{
switch (err_num) {
case MBEDTLS_ERR_SSL_WANT_READ:
case MBEDTLS_ERR_SSL_WANT_WRITE:
case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS:
return true;
default:
return false;
}
}
void client::config()
{
int err_num = internal::mbedtls_ssl_config_defaults(&_conf, MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
if (err_num != 0)
throw gen_conn_err("Initialising SSL config", err_num);
// Set timeout.
internal::mbedtls_ssl_conf_read_timeout(&_conf, _timeout_ms);
// Set RNG.
if (!_rng.seeded())
throw std::runtime_error("RNG not seeded on connect");
internal::mbedtls_ssl_conf_rng(&_conf, internal::mbedtls_ctr_drbg_random, &_rng.drbg());
// Configure certificates.
if (!_certs.loaded())
throw std::runtime_error("Certificates not loaded on connect");
if (_certs.self_signed()) {
_certs.self_sign(_conf);
// If we self-sign we don't need to verify the certificate.
internal::mbedtls_ssl_conf_authmode(&_conf, MBEDTLS_SSL_VERIFY_NONE);
} else {
internal::mbedtls_ssl_conf_authmode(&_conf, MBEDTLS_SSL_VERIFY_REQUIRED);
}
internal::mbedtls_ssl_conf_ca_chain(&_conf, &_certs.chain(), nullptr);
// Configure SSL object.
err_num = internal::mbedtls_ssl_setup(&_ssl, &_conf);
if (err_num != 0)
throw gen_conn_err("SSL setup", err_num);
err_num = internal::mbedtls_ssl_set_hostname(&_ssl, _host);
if (err_num != 0)
throw gen_conn_err("Set hostname", err_num);
}
auto client::read_until_newline(char* buf, int size) -> int
{
bool disconnected = false;
int offset = 0;
do {
offset += read(&buf[offset], size, disconnected);
} while (!disconnected && offset < size && buf[offset - 1] != '\n');
if (disconnected)
throw std::runtime_error("Unexpected disconnection");
// Leave an extra character for the null terminator.
if (offset >= size)
throw std::runtime_error("Read until newline exceeded buffer size?!");
buf[offset] = '\0';
return offset;
}
} // namespace janus::tls
| 22.827869 | 95 | 0.706643 | [
"object"
] |
a734d5e492e650c9438fcf5b0f26b1c5d24e2799 | 4,425 | cpp | C++ | tdutils/test/heap.cpp | luckydonald-backup/td | 71d03f39c364367a8a7c51f783a41099297de826 | [
"BSL-1.0"
] | 1 | 2021-04-18T08:59:02.000Z | 2021-04-18T08:59:02.000Z | tdutils/test/heap.cpp | devitsyn/td | 71d03f39c364367a8a7c51f783a41099297de826 | [
"BSL-1.0"
] | null | null | null | tdutils/test/heap.cpp | devitsyn/td | 71d03f39c364367a8a7c51f783a41099297de826 | [
"BSL-1.0"
] | null | null | null | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2017
//
// 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)
//
#include "td/utils/tests.h"
#include "td/utils/common.h"
#include "td/utils/Heap.h"
#include "td/utils/logging.h"
#include "td/utils/Random.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <set>
#include <utility>
REGISTER_TESTS(heap)
using namespace td;
TEST(Heap, sort_random_perm) {
int n = 1000000;
std::vector<int> v(n);
for (int i = 0; i < n; i++) {
v[i] = i;
}
std::srand(123);
std::random_shuffle(v.begin(), v.end());
std::vector<HeapNode> nodes(n);
KHeap<int> kheap;
for (int i = 0; i < n; i++) {
kheap.insert(v[i], &nodes[i]);
}
for (int i = 0; i < n; i++) {
ASSERT_EQ(i, kheap.top_key());
kheap.pop();
}
};
class CheckedHeap {
public:
void set_max_size(int max_size) {
nodes.resize(max_size);
free_ids.resize(max_size);
rev_ids.resize(max_size);
for (int i = 0; i < max_size; i++) {
free_ids[i] = max_size - i - 1;
nodes[i].value = i;
}
}
static void xx(int key, const HeapNode *heap_node) {
const Node *node = static_cast<const Node *>(heap_node);
std::fprintf(stderr, "(%d;%d)", node->key, node->value);
}
void check() const {
for (auto p : set_heap) {
std::fprintf(stderr, "(%d;%d)", p.first, p.second);
}
std::fprintf(stderr, "\n");
kheap.for_each(xx);
std::fprintf(stderr, "\n");
kheap.check();
}
int random_id() const {
CHECK(!empty());
return ids[Random::fast(0, static_cast<int>(ids.size() - 1))];
}
size_t size() const {
return ids.size();
}
bool empty() const {
return ids.empty();
}
int top_key() const {
CHECK(!empty());
int res = set_heap.begin()->first;
ASSERT_EQ(set_heap.size(), kheap.size());
ASSERT_EQ(res, kheap.top_key());
return res;
}
int insert(int key) {
// std::fprintf(stderr, "insert %d\n", key);
int id;
if (free_ids.empty()) {
UNREACHABLE();
id = static_cast<int>(nodes.size());
nodes.emplace_back(key, id);
rev_ids.push_back(-1);
} else {
id = free_ids.back();
free_ids.pop_back();
nodes[id].key = key;
}
rev_ids[id] = static_cast<int>(ids.size());
ids.push_back(id);
kheap.insert(key, &nodes[id]);
set_heap.emplace(key, id);
return id;
}
void fix_key(int new_key, int id) {
// std::fprintf(stderr, "fix key %d %d (old_key = %d)\n", new_key, id, nodes[id].key);
set_heap.erase(std::make_pair(nodes[id].key, id));
nodes[id].key = new_key;
kheap.fix(new_key, &nodes[id]);
set_heap.emplace(new_key, id);
}
void erase(int id) {
// std::fprintf(stderr, "erase %d\n", id);
int pos = rev_ids[id];
CHECK(pos != -1);
ids[pos] = ids.back();
rev_ids[ids[pos]] = pos;
ids.pop_back();
rev_ids[id] = -1;
free_ids.push_back(id);
kheap.erase(&nodes[id]);
set_heap.erase(std::make_pair(nodes[id].key, id));
}
void pop() {
// std::fprintf(stderr, "pop\n");
CHECK(!empty());
Node *node = static_cast<Node *>(kheap.pop());
int id = node->value;
ASSERT_EQ(node->key, set_heap.begin()->first);
int pos = rev_ids[id];
CHECK(pos != -1);
ids[pos] = ids.back();
rev_ids[ids[pos]] = pos;
ids.pop_back();
rev_ids[id] = -1;
free_ids.push_back(id);
set_heap.erase(std::make_pair(nodes[id].key, id));
}
private:
struct Node : public HeapNode {
Node() = default;
Node(int key, int value) : key(key), value(value) {
}
int key = 0;
int value = 0;
};
vector<int> ids;
vector<int> rev_ids;
vector<int> free_ids;
vector<Node> nodes;
std::set<std::pair<int, int>> set_heap;
KHeap<int> kheap;
};
TEST(Heap, random_events) {
CheckedHeap heap;
heap.set_max_size(1000);
for (int i = 0; i < 300000; i++) {
if (!heap.empty()) {
heap.top_key();
}
int x = Random::fast(0, 4);
if (heap.empty() || (x < 2 && heap.size() < 1000)) {
heap.insert(Random::fast(0, 99));
} else if (x < 3) {
heap.fix_key(Random::fast(0, 99), heap.random_id());
} else if (x < 4) {
heap.erase(heap.random_id());
} else if (x < 5) {
heap.pop();
}
// heap.check();
}
}
| 24.72067 | 96 | 0.581921 | [
"vector"
] |
a7369978f606c0679b85708354ec1f2b1b6ae290 | 15,947 | cpp | C++ | src/tetgen_plug/tetgenmeshplug.cpp | master-clown/ofeata | 306cbc3a402551fb62b3925d23a2d4f63f60d525 | [
"MIT"
] | 1 | 2021-08-30T13:51:42.000Z | 2021-08-30T13:51:42.000Z | src/tetgen_plug/tetgenmeshplug.cpp | master-clown/ofeata | 306cbc3a402551fb62b3925d23a2d4f63f60d525 | [
"MIT"
] | null | null | null | src/tetgen_plug/tetgenmeshplug.cpp | master-clown/ofeata | 306cbc3a402551fb62b3925d23a2d4f63f60d525 | [
"MIT"
] | 1 | 2021-08-30T13:51:35.000Z | 2021-08-30T13:51:35.000Z | #include "tetgenmeshplug.hpp"
#include <cstdarg>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <tetgen.h>
#define PLUGIN_NAME "TetGen 1.5.1 Meshing Plugin"
#define PLUGIN_SETS_FILE "tetgen_plugin_sets.json"
#define LOG_FILE "tetgen_plugin_tmp_log.log"
#define TO_WIDE_HELPER(str) L ## str
#define TO_WIDE(str) TO_WIDE_HELPER(str)
struct MeshParams
{
double MaxRadEdgeRatio;
double MaxElemVol;
std::map<int, double> MaxBoundElemFaceArea;
bool FromString(std::string& emsg, char* max_radedge,
char* max_vol,
char* max_area_lst_str);
bool IsValid(std::string& error_msg);
std::string ToString() const;
};
static void ConvertToTetgen(const MeshParams& params, const MeshInfo& in, tetgenio& out);
static void ConvertFromTetgen(const tetgenio& in, MeshInfo& out);
static std::string gStatsBuf;
static std::string gSetsStr;
#define SETTING_COUNT 3
static const std::string gMaxElemVolumeParamName = "max_elem_volume";
static const std::string gMaxRadEdgeRatParamName = "max_rad_edge_ratio";
static const std::string gMaxBoundFaceAreaParamName = "max_bound_face_elem_area";
static std::wstring GetLibDir();
TetgenMeshPlug::TetgenMeshPlug()
{}
TetgenMeshPlug::~TetgenMeshPlug()
{
const std::string msg = "Plugin '" PLUGIN_NAME "' has been unloaded.";
CallService("log", msg.c_str(), msg.size());
}
int TetgenMeshPlug::Init(const ServiceInfo service_lst[],
const unsigned int service_num)
{
serv_lst_ = service_lst;
serv_num_ = service_num;
std::string msg;
const auto file_name = GetLibDir() + TO_WIDE(PLUGIN_SETS_FILE);
std::ifstream ifs(file_name);
if(!ifs.is_open())
{
msg = PLUGIN_NAME ": cannot open settings file '" PLUGIN_SETS_FILE "'.";
CallService("loge", msg.c_str(), msg.size());
return 1;
}
gSetsStr = static_cast<const std::stringstream&>(std::stringstream() << ifs.rdbuf()).str();
msg = "Plugin '" PLUGIN_NAME "' has been initilized";
CallService("log", msg.c_str(), msg.size());
status_.store(MESHING_STATUS_NOT_STARTED);
return 0;
}
void TetgenMeshPlug::Mesh()
{
tetgenio tet_in;
tetgenio tet_out;
MeshParams params;
std::string log_msg;
char* param_maxvol_str = nullptr,
* param_maxradedge_str = nullptr,
* param_maxfacelst_str = nullptr;
unsigned int param_maxvol_size,
param_maxradedge_size,
param_maxfacelst_size;
status_.store(MESHING_STATUS_IN_PROGRESS);
int stcode[4];
stcode[0] = CallService("get_setting_value",
&gMaxElemVolumeParamName[0], gMaxElemVolumeParamName.size(),
¶m_maxvol_str, ¶m_maxvol_size);
stcode[1] = CallService("get_setting_value",
&gMaxRadEdgeRatParamName[0], gMaxRadEdgeRatParamName.size(),
¶m_maxradedge_str, ¶m_maxradedge_size);
stcode[2] = CallService("get_setting_value",
&gMaxBoundFaceAreaParamName[0], gMaxBoundFaceAreaParamName.size(),
¶m_maxfacelst_str, ¶m_maxfacelst_size);
for(int i = 0 ; i < SETTING_COUNT; ++i)
if(stcode[i])
{
log_msg = PLUGIN_NAME ": cannot get " + std::to_string(i) +
"th setting. Error code " + std::to_string(stcode[i]);
CallService("loge", &log_msg[0], log_msg.size());
status_.store(MESHING_STATUS_ERROR);
goto lbl_free_mem;
}
if(!params.FromString(log_msg, param_maxradedge_str, param_maxvol_str, param_maxfacelst_str) ||
!params.IsValid(log_msg))
{
log_msg = PLUGIN_NAME ": mesh parameters error: " + log_msg;
CallService("loge", &log_msg[0], log_msg.size());
status_.store(MESHING_STATUS_ERROR);
goto lbl_free_mem;
}
ConvertToTetgen(params, *mesh_in, tet_in);
gStatsBuf.clear();
try
{
std::string params_str = "pAV" + params.ToString() + "\0";
tetrahedralize(¶ms_str[0], &tet_in, &tet_out);
}
catch(const int code)
{
gStatsBuf += TetGenErrorCodeToString((TetGenErrorCode)code);
CallService("loge", &gStatsBuf[0], gStatsBuf.size());
status_.store(MESHING_STATUS_ERROR);
goto lbl_free_mem;
}
ConvertFromTetgen(tet_out, *mesh_out);
status_.store(MESHING_STATUS_FINISHED);
lbl_free_mem:
if(param_maxvol_str) CallService("free_output_data", param_maxvol_str);
if(param_maxradedge_str) CallService("free_output_data", param_maxradedge_str);
if(param_maxfacelst_str) CallService("free_output_data", param_maxfacelst_str);
}
void TetgenMeshPlug::CancelMeshing()
{
return;
}
void TetgenMeshPlug::SetInputMeshInfo(const MeshInfo& in)
{ mesh_in = ∈ }
void TetgenMeshPlug::SetOutputMeshInfo(MeshInfo& out)
{ mesh_out = &out; }
void TetgenMeshPlug::FreeOutputMeshInfo(MeshInfo& out)
{ out.Dealloc(); out.Nullify(); }
MeshingStatus TetgenMeshPlug::GetMeshingStatus() const
{
return status_.load();
}
const char* TetgenMeshPlug::GetMeshStats() const
{
if(status_.load() != MESHING_STATUS_FINISHED)
return nullptr;
return gStatsBuf.c_str();
}
const char* TetgenMeshPlug::GetMesherLog() const
{
const auto s = status_.load();
if(s != MESHING_STATUS_ERROR &&
s != MESHING_STATUS_FINISHED)
return nullptr;
return gStatsBuf.c_str();
}
const char* TetgenMeshPlug::ListRequiredSettings() const
{
return gSetsStr.c_str();
}
bool TetgenMeshPlug::IsCancelPossible() const { return false; }
int TetgenMeshPlug::CallService(const char* service_name,
const char* service_args,
const unsigned int arg_size,
char** result,
unsigned int* res_size)
{
unsigned int i_serv = 0;
for(; i_serv < serv_num_; ++i_serv)
if(!strcmp(serv_lst_[i_serv].Name, service_name))
break;
if(i_serv >= serv_num_ || !serv_lst_[i_serv].Callback)
return -1;
return serv_lst_[i_serv].Callback(service_args, arg_size, result, res_size);
}
DEF_CREATE_FREE_PLUG_ROUTINES(TetgenMeshPlug)
void ConvertToTetgen(const MeshParams& params, const MeshInfo& in, tetgenio& out)
{
out.deinitialize();
out.firstnumber = 1;
out.mesh_dim = 3;
out.numberofcorners = in.NumNodePerElem;
out.pointlist = new double[3*(out.numberofpoints = in.NodeNum)];
for(int i = 0; i < 3*out.numberofpoints; ++i)
out.pointlist[i] = in.NodeLst[i];
// out.pointmarkerlist = new int[out.numberofpoints]();
// for(unsigned int i = 0; i < in.NodeMarkerLstSize; ++i)
// out.pointmarkerlist[in.NodeMarkerLst[i].TargetObjIdx] = in.NodeMarkerLst[i].Marker;
// out.holelist = in.HoleNum ? new double[3*(out.numberofholes = in.HoleNum)] : nullptr;
// for(int i = 0; i < 3*out.numberofholes; ++i)
// out.holelist[i] = in.HoleLst[i];
out.facetconstraintlist = !params.MaxBoundElemFaceArea.empty() ? new double
[2*(out.numberoffacetconstraints
= params.MaxBoundElemFaceArea.size())] : nullptr;
int i_fconstr = 0;
for(const auto& p: params.MaxBoundElemFaceArea)
{
out.facetconstraintlist[i_fconstr + 0] = p.first + 1;
out.facetconstraintlist[i_fconstr + 1] = p.second;
i_fconstr += 2;
}
// out.edgemarkerlist = new int[out.numberofpoints]();
// for(unsigned int i = 0; i < in.NodeMarkerLstSize; ++i)
// out.pointmarkerlist[in.NodeMarkerLst[i].TargetObjIdx] = in.NodeMarkerLst[i].Marker;
out.facetlist = new tetgenio::facet[out.numberoffacets = in.FacetNum];
out.facetmarkerlist = new int[out.numberoffacets];
for(int i = 0; i < out.numberoffacets; ++i)
{
const auto num_poly = out.facetlist[i].numberofpolygons
= in.FacetLst[i].PolyNum;
const auto num_hole = out.facetlist[i].numberofholes
= in.FacetLst[i].HoleNum;
out.facetlist[i].polygonlist = new tetgenio::polygon[num_poly];
out.facetlist[i].holelist = num_hole ? new double[3*num_hole] : nullptr;
for(int i_poly = 0; i_poly < num_poly; ++i_poly)
{
const auto ptr = &out.facetlist[i].polygonlist[i_poly];
ptr->numberofvertices = in.FacetLst[i].PolyLst[i_poly].VertexNum;
ptr->vertexlist = new int[ptr->numberofvertices];
for(int i_v = 0; i_v < ptr->numberofvertices; ++i_v)
ptr->vertexlist[i_v] = in.FacetLst[i].PolyLst[i_poly].VertexLst[i_v];
}
for(int i_hc = 0; i_hc < 3*num_hole; ++i_hc)
{
out.facetlist[i].holelist[i_hc] = in.FacetLst[i].HoleLst[i_hc];
}
out.facetmarkerlist[i] = in.FacetMarkerLst[i] + 1; // offset
}
out.regionlist = new double[5*(out.numberofregions = in.RegionNum)]; // { 0.5, 0.5, 0.5, 1.0, 0.1 };
for(int i = 0; i < 5*out.numberofregions; ++i)
out.regionlist[i] = in.RegionLst[i];
}
void ConvertFromTetgen(const tetgenio& in, MeshInfo& out)
{
using siz_t = MeshInfo::siz_t;
out.Dealloc();
out.Nullify();
out.NumNodePerElem = in.numberofcorners;
out.VertexLocalIdxLst = new MeshInfo::id_t
[out.VertexLocalIdxLstSize = 4]
{ 0, 1, 2, 3 };
out.ElemFaceVertexCountLst = new MeshInfo::siz_t[out.NumFacePerElem = 4]
{ 3, 3, 3, 3 };
out.ElemFaceVertexLocalIdxLst = new MeshInfo::id_t[12]
{ 0, 2, 1, 1, 2, 3, 0, 3, 2, 0, 1, 3 };
out.NodeLst = new MeshInfo::num_t[3*(out.NodeNum = in.numberofpoints)];
for(siz_t i = 0; i < 3*out.NodeNum; ++i)
out.NodeLst[i] = in.pointlist[i];
out.ElemLst = new MeshInfo::id_t
[out.NumNodePerElem*(out.ElemNum = in.numberoftetrahedra)];
for(siz_t i = 0; i < out.NumNodePerElem*out.ElemNum; ++i)
out.ElemLst[i] = in.tetrahedronlist[i];
out.ElemAttribPerObj = in.numberoftetrahedronattributes - 1;
out.ElemAttribLst = out.ElemAttribPerObj ? new MeshInfo::num_t
[out.ElemAttribPerObj*out.ElemNum] : nullptr;
out.ElemRegionLst = new MeshInfo::id_t[out.ElemNum];
for(siz_t i = 0; i < out.ElemNum; i += out.ElemAttribPerObj + 1)
{
if(out.ElemAttribLst)
for(siz_t j = 0; j < out.ElemAttribPerObj; ++j)
out.ElemAttribLst[i*out.ElemAttribPerObj + j]
= in.tetrahedronattributelist[i*(out.ElemAttribPerObj+1) + j];
out.ElemRegionLst[i]
= (MeshInfo::id_t)in.tetrahedronattributelist[i*(out.ElemAttribPerObj+1) + out.ElemAttribPerObj];
}
const auto vert_per_face = 3;
out.ElemFaceLst = new MeshInfo::id_t[vert_per_face*(out.ElemFaceNum = in.numberoftrifaces)];
out.ElemFaceMarkerLst = new MeshInfo::mrk_t[out.ElemFaceNum];
for(siz_t i = 0; i < out.ElemFaceNum; ++i)
{
for(siz_t j = 0; j < vert_per_face; ++j)
out.ElemFaceLst[i*vert_per_face + j] = in.trifacelist[i*vert_per_face + j];
out.ElemFaceMarkerLst[i] = in.trifacemarkerlist[i] - 1;
}
out.EdgeLst = new MeshInfo::id_t[2*(out.EdgeNum = in.numberofedges)];
for(siz_t i = 0; i < 2*out.EdgeNum; ++i)
{
out.EdgeLst[i] = in.edgelist[i];
// look for edge marker list
}
}
bool MeshParams::FromString(std::string& emsg,
char* max_radedge,
char* max_vol,
char* max_area_lst_str)
{
MaxRadEdgeRatio = atof(max_radedge);
MaxElemVol = atof(max_vol);
if(MaxRadEdgeRatio < DBL_EPSILON || // negative too
MaxElemVol < DBL_EPSILON)
{
emsg = "invalid values for numeric parameters. They must be positive.";
return false;
}
MaxBoundElemFaceArea.clear();
if(int maxarea_strsize = strlen(max_area_lst_str))
{
const auto semicln_ptr = strchr(max_area_lst_str, '~');
if(!maxarea_strsize || !semicln_ptr)
{
emsg = "invalid string of maximum element boundary faces area.";
return false;
}
char* maxarea_str = new char[maxarea_strsize + 1];
strcpy_s(maxarea_str, maxarea_strsize + 1, semicln_ptr+1);
char* ptr_tmp;
char* p_str = strtok_s(maxarea_str, "$", &ptr_tmp);
while(p_str)
{
char* ptr_tmp2;
char* num_str = strtok_s(p_str, "@", &ptr_tmp2);
int id = atoi(num_str);
num_str = strtok_s(nullptr, "@", &ptr_tmp2);
double num;
if(!num_str || (num = atof(num_str)) < DBL_EPSILON)
{
emsg = "area for face '" + std::to_string(id) + "' is not positive or not specified.";
delete[] maxarea_str;
return false;
}
MaxBoundElemFaceArea[id] = num;
p_str = strtok_s(nullptr, "$", &ptr_tmp);
}
delete[] maxarea_str;
}
return true;
}
bool MeshParams::IsValid(std::string& error_msg)
{
error_msg = "";
if(MaxElemVol < 0.0)
error_msg += "Maximal element volume is negative;\n";
if(MaxRadEdgeRatio < 0.0)
error_msg += "Maximal radius-edge ratio is negative;\n";
for(const auto& p: MaxBoundElemFaceArea)
if(p.second <= 0.0)
error_msg += "Max area of boundary face of elements on shape's face '"
+ std::to_string(p.first) + "' is negative;\n";
return error_msg.empty();
}
std::string MeshParams::ToString() const
{
return "q" + std::to_string(MaxRadEdgeRatio) +
"a" + std::to_string(MaxElemVol) + (MaxBoundElemFaceArea.empty() ? "" : "a");
}
const char* TetGenErrorCodeToString(const TetGenErrorCode code)
{
switch(code)
{
case TET_GEN_ECODE_OUT_OF_MEMORY:
return "Out of memory";
case TET_GEN_ECODE_INTERNAL_ERROR:
return PLUGIN_NAME " internal error";
case TET_GEN_ECODE_SELF_INTERSECT:
return "Geometry self-intersection detected";
case TET_GEN_ECODE_BAD_GEOM_PRECISION:
return "Geometry features are too small for current tolerance";
case TET_GEN_ECODE_CLOSE_FACETS:
return "Some facets are too close to each other";
case TET_GEN_ECODE_INPUT_ERROR:
return "Plugin input error";
}
return nullptr;
}
extern "C" int printf_modified(const char *fmt, ...)
{
va_list argp;
va_start(argp, fmt);
int ret = vsnprintf(nullptr, 0, fmt, argp);
if(ret <= 0)
return ret;
va_end(argp);
va_start(argp, fmt);
std::string buf(ret+1, '\0');
ret = vsnprintf(&buf[0], ret+1, fmt, argp);
gStatsBuf += buf.c_str();
return ret;
}
#ifdef _WIN32
#include <Windows.h>
static HINSTANCE gDllHandle = nullptr;
std::wstring GetLibDir()
{
wchar_t buffer[MAX_PATH];
GetModuleFileName(gDllHandle, buffer, MAX_PATH);
const auto pos = std::wstring(buffer).find_last_of(L"\\/");
return pos == std::wstring::npos ? L"" : std::wstring(buffer).substr(0, pos+1);
}
BOOL WINAPI DllMain(_In_ HINSTANCE hinstDLL, _In_ DWORD, _In_ LPVOID)
{
gDllHandle = hinstDLL;
return TRUE;
}
#endif
| 32.812757 | 114 | 0.604126 | [
"mesh",
"geometry",
"shape",
"vector"
] |
a739148f5463f6419614346a712b52f0974ae017 | 64,863 | cpp | C++ | Engine/source/afx/afxConstraint.cpp | vbillet/Torque3D | ece8823599424ea675e5f79d9bcb44e42cba8cae | [
"MIT"
] | 2,113 | 2015-01-01T11:23:01.000Z | 2022-03-28T04:51:46.000Z | Engine/source/afx/afxConstraint.cpp | vbillet/Torque3D | ece8823599424ea675e5f79d9bcb44e42cba8cae | [
"MIT"
] | 948 | 2015-01-02T01:50:00.000Z | 2022-02-27T05:56:40.000Z | Engine/source/afx/afxConstraint.cpp | vbillet/Torque3D | ece8823599424ea675e5f79d9bcb44e42cba8cae | [
"MIT"
] | 944 | 2015-01-01T09:33:53.000Z | 2022-03-15T22:23:03.000Z |
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
// Copyright (C) 2015 Faust Logic, Inc.
//
// 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 "arcaneFX.h"
#include "T3D/aiPlayer.h"
#include "T3D/tsStatic.h"
#include "sim/netConnection.h"
#include "ts/tsShapeInstance.h"
#include "afxConstraint.h"
#include "afxChoreographer.h"
#include "afxEffectWrapper.h"
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxConstraintDef
// static
StringTableEntry afxConstraintDef::SCENE_CONS_KEY;
StringTableEntry afxConstraintDef::EFFECT_CONS_KEY;
StringTableEntry afxConstraintDef::GHOST_CONS_KEY;
afxConstraintDef::afxConstraintDef()
{
if (SCENE_CONS_KEY == 0)
{
SCENE_CONS_KEY = StringTable->insert("#scene");
EFFECT_CONS_KEY = StringTable->insert("#effect");
GHOST_CONS_KEY = StringTable->insert("#ghost");
}
reset();
}
bool afxConstraintDef::isDefined()
{
return (mDef_type != CONS_UNDEFINED);
}
bool afxConstraintDef::isArbitraryObject()
{
return ((mCons_src_name != ST_NULLSTRING) && (mDef_type == CONS_SCENE));
}
void afxConstraintDef::reset()
{
mCons_src_name = ST_NULLSTRING;
mCons_node_name = ST_NULLSTRING;
mDef_type = CONS_UNDEFINED;
mHistory_time = 0;
mSample_rate = 30;
mRuns_on_server = false;
mRuns_on_client = false;
mPos_at_box_center = false;
mTreat_as_camera = false;
}
bool afxConstraintDef::parseSpec(const char* spec, bool runs_on_server,
bool runs_on_client)
{
reset();
if (spec == 0 || spec[0] == '\0')
return false;
mHistory_time = 0.0f;
mSample_rate = 30;
mRuns_on_server = runs_on_server;
mRuns_on_client = runs_on_client;
// spec should be in one of these forms:
// CONSTRAINT_NAME (only)
// CONSTRAINT_NAME.NODE (shapeBase objects only)
// CONSTRAINT_NAME.#center
// object.OBJECT_NAME
// object.OBJECT_NAME.NODE (shapeBase objects only)
// object.OBJECT_NAME.#center
// effect.EFFECT_NAME
// effect.EFFECT_NAME.NODE
// effect.EFFECT_NAME.#center
// #ghost.EFFECT_NAME
// #ghost.EFFECT_NAME.NODE
// #ghost.EFFECT_NAME.#center
//
// create scratch buffer by duplicating spec.
char special = '\b';
char* buffer = dStrdup(spec);
// substitute a dots not inside parens with special character
S32 n_nested = 0;
for (char* b = buffer; (*b) != '\0'; b++)
{
if ((*b) == '(')
n_nested++;
else if ((*b) == ')')
n_nested--;
else if ((*b) == '.' && n_nested == 0)
(*b) = special;
}
// divide name into '.' separated tokens (up to 8)
char* words[8] = {0, 0, 0, 0, 0, 0, 0, 0};
char* dot = buffer;
int wdx = 0;
while (wdx < 8)
{
words[wdx] = dot;
dot = dStrchr(words[wdx++], special);
if (!dot)
break;
*(dot++) = '\0';
if ((*dot) == '\0')
break;
}
int n_words = wdx;
// at this point the spec has been split into words.
// n_words indicates how many words we have.
// no words found (must have been all whitespace)
if (n_words < 1)
{
dFree(buffer);
return false;
}
char* hist_spec = 0;
char* words2[8] = {0, 0, 0, 0, 0, 0, 0, 0};
int n_words2 = 0;
// move words to words2 while extracting #center and #history
for (S32 i = 0; i < n_words; i++)
{
if (dStrcmp(words[i], "#center") == 0)
mPos_at_box_center = true;
else if (dStrncmp(words[i], "#history(", 9) == 0)
hist_spec = words[i];
else
words2[n_words2++] = words[i];
}
// words2[] now contains just the constraint part
// no words found (must have been all #center and #history)
if (n_words2 < 1)
{
dFree(buffer);
return false;
}
if (hist_spec)
{
char* open_paren = dStrchr(hist_spec, '(');
if (open_paren)
{
hist_spec = open_paren+1;
if ((*hist_spec) != '\0')
{
char* close_paren = dStrchr(hist_spec, ')');
if (close_paren)
(*close_paren) = '\0';
char* slash = dStrchr(hist_spec, '/');
if (slash)
(*slash) = ' ';
F32 hist_age = 0.0;
U32 hist_rate = 30;
S32 args = dSscanf(hist_spec,"%g %d", &hist_age, &hist_rate);
if (args > 0)
mHistory_time = hist_age;
if (args > 1)
mSample_rate = hist_rate;
}
}
}
StringTableEntry cons_name_key = StringTable->insert(words2[0]);
// must be in CONSTRAINT_NAME (only) form
if (n_words2 == 1)
{
// arbitrary object/effect constraints must have a name
if (cons_name_key == SCENE_CONS_KEY || cons_name_key == EFFECT_CONS_KEY)
{
dFree(buffer);
return false;
}
mCons_src_name = cons_name_key;
mDef_type = CONS_PREDEFINED;
dFree(buffer);
return true;
}
// "#scene.NAME" or "#scene.NAME.NODE""
if (cons_name_key == SCENE_CONS_KEY)
{
mCons_src_name = StringTable->insert(words2[1]);
if (n_words2 > 2)
mCons_node_name = StringTable->insert(words2[2]);
mDef_type = CONS_SCENE;
dFree(buffer);
return true;
}
// "#effect.NAME" or "#effect.NAME.NODE"
if (cons_name_key == EFFECT_CONS_KEY)
{
mCons_src_name = StringTable->insert(words2[1]);
if (n_words2 > 2)
mCons_node_name = StringTable->insert(words2[2]);
mDef_type = CONS_EFFECT;
dFree(buffer);
return true;
}
// "#ghost.NAME" or "#ghost.NAME.NODE"
if (cons_name_key == GHOST_CONS_KEY)
{
if (runs_on_server)
{
dFree(buffer);
return false;
}
mCons_src_name = StringTable->insert(words2[1]);
if (n_words2 > 2)
mCons_node_name = StringTable->insert(words2[2]);
mDef_type = CONS_GHOST;
dFree(buffer);
return true;
}
// "CONSTRAINT_NAME.NODE"
if (n_words2 == 2)
{
mCons_src_name = cons_name_key;
mCons_node_name = StringTable->insert(words2[1]);
mDef_type = CONS_PREDEFINED;
dFree(buffer);
return true;
}
// must be in unsupported form
dFree(buffer);
return false;
}
void afxConstraintDef::gather_cons_defs(Vector<afxConstraintDef>& defs, afxEffectList& fx)
{
for (S32 i = 0; i < fx.size(); i++)
{
if (fx[i])
fx[i]->gather_cons_defs(defs);
}
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxConstraint
afxConstraint::afxConstraint(afxConstraintMgr* mgr)
{
mMgr = mgr;
mIs_defined = false;
mIs_valid = false;
mLast_pos.zero();
mLast_xfm.identity();
mHistory_time = 0.0f;
mIs_alive = true;
mGone_missing = false;
mChange_code = 0;
}
afxConstraint::~afxConstraint()
{
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
inline afxPointConstraint* newPointCons(afxConstraintMgr* mgr, bool hist)
{
return (hist) ? new afxPointHistConstraint(mgr) : new afxPointConstraint(mgr);
}
inline afxTransformConstraint* newTransformCons(afxConstraintMgr* mgr, bool hist)
{
return (hist) ? new afxTransformHistConstraint(mgr) : new afxTransformConstraint(mgr);
}
inline afxShapeConstraint* newShapeCons(afxConstraintMgr* mgr, bool hist)
{
return (hist) ? new afxShapeHistConstraint(mgr) : new afxShapeConstraint(mgr);
}
inline afxShapeConstraint* newShapeCons(afxConstraintMgr* mgr, StringTableEntry name, bool hist)
{
return (hist) ? new afxShapeHistConstraint(mgr, name) : new afxShapeConstraint(mgr, name);
}
inline afxShapeNodeConstraint* newShapeNodeCons(afxConstraintMgr* mgr, StringTableEntry name, StringTableEntry node, bool hist)
{
return (hist) ? new afxShapeNodeHistConstraint(mgr, name, node) : new afxShapeNodeConstraint(mgr, name, node);
}
inline afxObjectConstraint* newObjectCons(afxConstraintMgr* mgr, bool hist)
{
return (hist) ? new afxObjectHistConstraint(mgr) : new afxObjectConstraint(mgr);
}
inline afxObjectConstraint* newObjectCons(afxConstraintMgr* mgr, StringTableEntry name, bool hist)
{
return (hist) ? new afxObjectHistConstraint(mgr, name) : new afxObjectConstraint(mgr, name);
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxConstraintMgr
#define CONS_BY_ID(id) ((*mConstraints_v[(id).index])[(id).sub_index])
#define CONS_BY_IJ(i,j) ((*mConstraints_v[(i)])[(j)])
afxConstraintMgr::afxConstraintMgr()
{
mStartTime = 0;
mOn_server = false;
mInitialized = false;
mScoping_dist_sq = 1000.0f*1000.0f;
missing_objs = &missing_objs_a;
missing_objs2 = &missing_objs_b;
}
afxConstraintMgr::~afxConstraintMgr()
{
for (S32 i = 0; i < mConstraints_v.size(); i++)
{
for (S32 j = 0; j < (*mConstraints_v[i]).size(); j++)
delete CONS_BY_IJ(i,j);
delete mConstraints_v[i];
}
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
S32 afxConstraintMgr::find_cons_idx_from_name(StringTableEntry which)
{
for (S32 i = 0; i < mConstraints_v.size(); i++)
{
afxConstraint* cons = CONS_BY_IJ(i,0);
if (cons && afxConstraintDef::CONS_EFFECT != cons->mCons_def.mDef_type &&
which == cons->mCons_def.mCons_src_name)
{
return i;
}
}
return -1;
}
S32 afxConstraintMgr::find_effect_cons_idx_from_name(StringTableEntry which)
{
for (S32 i = 0; i < mConstraints_v.size(); i++)
{
afxConstraint* cons = CONS_BY_IJ(i,0);
if (cons && afxConstraintDef::CONS_EFFECT == cons->mCons_def.mDef_type &&
which == cons->mCons_def.mCons_src_name)
{
return i;
}
}
return -1;
}
// Defines a predefined constraint with given name and type
void afxConstraintMgr::defineConstraint(U32 type, StringTableEntry name)
{
preDef predef = { name, type };
mPredefs.push_back(predef);
}
afxConstraintID afxConstraintMgr::setReferencePoint(StringTableEntry which, Point3F point,
Point3F vector)
{
S32 idx = find_cons_idx_from_name(which);
if (idx < 0)
return afxConstraintID();
afxConstraintID id = afxConstraintID(idx);
setReferencePoint(id, point, vector);
return id;
}
afxConstraintID afxConstraintMgr::setReferenceTransform(StringTableEntry which, MatrixF& xfm)
{
S32 idx = find_cons_idx_from_name(which);
if (idx < 0)
return afxConstraintID();
afxConstraintID id = afxConstraintID(idx);
setReferenceTransform(id, xfm);
return id;
}
// Assigns an existing scene-object to the named constraint
afxConstraintID afxConstraintMgr::setReferenceObject(StringTableEntry which, SceneObject* obj)
{
S32 idx = find_cons_idx_from_name(which);
if (idx < 0)
return afxConstraintID();
afxConstraintID id = afxConstraintID(idx);
setReferenceObject(id, obj);
return id;
}
// Assigns an un-scoped scene-object by scope_id to the named constraint
afxConstraintID afxConstraintMgr::setReferenceObjectByScopeId(StringTableEntry which, U16 scope_id, bool is_shape)
{
S32 idx = find_cons_idx_from_name(which);
if (idx < 0)
return afxConstraintID();
afxConstraintID id = afxConstraintID(idx);
setReferenceObjectByScopeId(id, scope_id, is_shape);
return id;
}
afxConstraintID afxConstraintMgr::setReferenceEffect(StringTableEntry which, afxEffectWrapper* ew)
{
S32 idx = find_effect_cons_idx_from_name(which);
if (idx < 0)
return afxConstraintID();
afxConstraintID id = afxConstraintID(idx);
setReferenceEffect(id, ew);
return id;
}
afxConstraintID afxConstraintMgr::createReferenceEffect(StringTableEntry which, afxEffectWrapper* ew)
{
afxEffectConstraint* cons = new afxEffectConstraint(this, which);
//cons->cons_def = def;
cons->mCons_def.mDef_type = afxConstraintDef::CONS_EFFECT;
cons->mCons_def.mCons_src_name = which;
afxConstraintList* list = new afxConstraintList();
list->push_back(cons);
mConstraints_v.push_back(list);
return setReferenceEffect(which, ew);
}
void afxConstraintMgr::setReferencePoint(afxConstraintID id, Point3F point, Point3F vector)
{
afxPointConstraint* pt_cons = dynamic_cast<afxPointConstraint*>(CONS_BY_ID(id));
// need to change type
if (!pt_cons)
{
afxConstraint* cons = CONS_BY_ID(id);
pt_cons = newPointCons(this, cons->mCons_def.mHistory_time > 0.0f);
pt_cons->mCons_def = cons->mCons_def;
CONS_BY_ID(id) = pt_cons;
delete cons;
}
pt_cons->set(point, vector);
// nullify all subnodes
for (S32 j = 1; j < (*mConstraints_v[id.index]).size(); j++)
{
afxConstraint* cons = CONS_BY_IJ(id.index,j);
if (cons)
cons->unset();
}
}
void afxConstraintMgr::setReferenceTransform(afxConstraintID id, MatrixF& xfm)
{
afxTransformConstraint* xfm_cons = dynamic_cast<afxTransformConstraint*>(CONS_BY_ID(id));
// need to change type
if (!xfm_cons)
{
afxConstraint* cons = CONS_BY_ID(id);
xfm_cons = newTransformCons(this, cons->mCons_def.mHistory_time > 0.0f);
xfm_cons->mCons_def = cons->mCons_def;
CONS_BY_ID(id) = xfm_cons;
delete cons;
}
xfm_cons->set(xfm);
// nullify all subnodes
for (S32 j = 1; j < (*mConstraints_v[id.index]).size(); j++)
{
afxConstraint* cons = CONS_BY_IJ(id.index,j);
if (cons)
cons->unset();
}
}
void afxConstraintMgr::set_ref_shape(afxConstraintID id, ShapeBase* shape)
{
id.sub_index = 0;
afxShapeConstraint* shape_cons = dynamic_cast<afxShapeConstraint*>(CONS_BY_ID(id));
// need to change type
if (!shape_cons)
{
afxConstraint* cons = CONS_BY_ID(id);
shape_cons = newShapeCons(this, cons->mCons_def.mHistory_time > 0.0f);
shape_cons->mCons_def = cons->mCons_def;
CONS_BY_ID(id) = shape_cons;
delete cons;
}
// set new shape on root
shape_cons->set(shape);
// update all subnodes
for (S32 j = 1; j < (*mConstraints_v[id.index]).size(); j++)
{
afxConstraint* cons = CONS_BY_IJ(id.index,j);
if (cons)
{
if (dynamic_cast<afxShapeNodeConstraint*>(cons))
((afxShapeNodeConstraint*)cons)->set(shape);
else if (dynamic_cast<afxShapeConstraint*>(cons))
((afxShapeConstraint*)cons)->set(shape);
else if (dynamic_cast<afxObjectConstraint*>(cons))
((afxObjectConstraint*)cons)->set(shape);
else
cons->unset();
}
}
}
void afxConstraintMgr::set_ref_shape(afxConstraintID id, U16 scope_id)
{
id.sub_index = 0;
afxShapeConstraint* shape_cons = dynamic_cast<afxShapeConstraint*>(CONS_BY_ID(id));
// need to change type
if (!shape_cons)
{
afxConstraint* cons = CONS_BY_ID(id);
shape_cons = newShapeCons(this, cons->mCons_def.mHistory_time > 0.0f);
shape_cons->mCons_def = cons->mCons_def;
CONS_BY_ID(id) = shape_cons;
delete cons;
}
// set new shape on root
shape_cons->set_scope_id(scope_id);
// update all subnodes
for (S32 j = 1; j < (*mConstraints_v[id.index]).size(); j++)
{
afxConstraint* cons = CONS_BY_IJ(id.index,j);
if (cons)
cons->set_scope_id(scope_id);
}
}
// Assigns an existing scene-object to the constraint matching the given constraint-id.
void afxConstraintMgr::setReferenceObject(afxConstraintID id, SceneObject* obj)
{
if (!mInitialized)
Con::errorf("afxConstraintMgr::setReferenceObject() -- constraint manager not initialized");
if (!CONS_BY_ID(id)->mCons_def.mTreat_as_camera)
{
ShapeBase* shape = dynamic_cast<ShapeBase*>(obj);
if (shape)
{
set_ref_shape(id, shape);
return;
}
}
afxObjectConstraint* obj_cons = dynamic_cast<afxObjectConstraint*>(CONS_BY_ID(id));
// need to change type
if (!obj_cons)
{
afxConstraint* cons = CONS_BY_ID(id);
obj_cons = newObjectCons(this, cons->mCons_def.mHistory_time > 0.0f);
obj_cons->mCons_def = cons->mCons_def;
CONS_BY_ID(id) = obj_cons;
delete cons;
}
obj_cons->set(obj);
// update all subnodes
for (S32 j = 1; j < (*mConstraints_v[id.index]).size(); j++)
{
afxConstraint* cons = CONS_BY_IJ(id.index,j);
if (cons)
{
if (dynamic_cast<afxObjectConstraint*>(cons))
((afxObjectConstraint*)cons)->set(obj);
else
cons->unset();
}
}
}
// Assigns an un-scoped scene-object by scope_id to the constraint matching the
// given constraint-id.
void afxConstraintMgr::setReferenceObjectByScopeId(afxConstraintID id, U16 scope_id, bool is_shape)
{
if (!mInitialized)
Con::errorf("afxConstraintMgr::setReferenceObject() -- constraint manager not initialized");
if (is_shape)
{
set_ref_shape(id, scope_id);
return;
}
afxObjectConstraint* obj_cons = dynamic_cast<afxObjectConstraint*>(CONS_BY_ID(id));
// need to change type
if (!obj_cons)
{
afxConstraint* cons = CONS_BY_ID(id);
obj_cons = newObjectCons(this, cons->mCons_def.mHistory_time > 0.0f);
obj_cons->mCons_def = cons->mCons_def;
CONS_BY_ID(id) = obj_cons;
delete cons;
}
obj_cons->set_scope_id(scope_id);
// update all subnodes
for (S32 j = 1; j < (*mConstraints_v[id.index]).size(); j++)
{
afxConstraint* cons = CONS_BY_IJ(id.index,j);
if (cons)
cons->set_scope_id(scope_id);
}
}
void afxConstraintMgr::setReferenceEffect(afxConstraintID id, afxEffectWrapper* ew)
{
afxEffectConstraint* eff_cons = dynamic_cast<afxEffectConstraint*>(CONS_BY_ID(id));
if (!eff_cons)
return;
eff_cons->set(ew);
// update all subnodes
for (S32 j = 1; j < (*mConstraints_v[id.index]).size(); j++)
{
afxConstraint* cons = CONS_BY_IJ(id.index,j);
if (cons)
{
if (dynamic_cast<afxEffectNodeConstraint*>(cons))
((afxEffectNodeConstraint*)cons)->set(ew);
else if (dynamic_cast<afxEffectConstraint*>(cons))
((afxEffectConstraint*)cons)->set(ew);
else
cons->unset();
}
}
}
void afxConstraintMgr::invalidateReference(afxConstraintID id)
{
afxConstraint* cons = CONS_BY_ID(id);
if (cons)
cons->mIs_valid = false;
}
void afxConstraintMgr::create_constraint(const afxConstraintDef& def)
{
if (def.mDef_type == afxConstraintDef::CONS_UNDEFINED)
return;
//Con::printf("CON - %s [%s] [%s] h=%g", def.cons_type_name, def.cons_src_name, def.cons_node_name, def.history_time);
bool want_history = (def.mHistory_time > 0.0f);
// constraint is an arbitrary named scene object
//
if (def.mDef_type == afxConstraintDef::CONS_SCENE)
{
if (def.mCons_src_name == ST_NULLSTRING)
return;
// find the arbitrary object by name
SceneObject* arb_obj;
if (mOn_server)
{
arb_obj = dynamic_cast<SceneObject*>(Sim::findObject(def.mCons_src_name));
if (!arb_obj)
Con::errorf("afxConstraintMgr -- failed to find scene constraint source, \"%s\" on server.",
def.mCons_src_name);
}
else
{
arb_obj = find_object_from_name(def.mCons_src_name);
if (!arb_obj)
Con::errorf("afxConstraintMgr -- failed to find scene constraint source, \"%s\" on client.",
def.mCons_src_name);
}
// if it's a shapeBase object, create a Shape or ShapeNode constraint
if (dynamic_cast<ShapeBase*>(arb_obj))
{
if (def.mCons_node_name == ST_NULLSTRING && !def.mPos_at_box_center)
{
afxShapeConstraint* cons = newShapeCons(this, def.mCons_src_name, want_history);
cons->mCons_def = def;
cons->set((ShapeBase*)arb_obj);
afxConstraintList* list = new afxConstraintList();
list->push_back(cons);
mConstraints_v.push_back(list);
}
else if (def.mPos_at_box_center)
{
afxShapeConstraint* cons = newShapeCons(this, def.mCons_src_name, want_history);
cons->mCons_def = def;
cons->set((ShapeBase*)arb_obj);
afxConstraintList* list = mConstraints_v[mConstraints_v.size()-1]; // SHAPE-NODE CONS-LIST (#scene)(#center)
if (list && (*list)[0])
list->push_back(cons);
}
else
{
afxShapeNodeConstraint* sub = newShapeNodeCons(this, def.mCons_src_name, def.mCons_node_name, want_history);
sub->mCons_def = def;
sub->set((ShapeBase*)arb_obj);
afxConstraintList* list = mConstraints_v[mConstraints_v.size()-1];
if (list && (*list)[0])
list->push_back(sub);
}
}
// if it's not a shapeBase object, create an Object constraint
else if (arb_obj)
{
if (!def.mPos_at_box_center)
{
afxObjectConstraint* cons = newObjectCons(this, def.mCons_src_name, want_history);
cons->mCons_def = def;
cons->set(arb_obj);
afxConstraintList* list = new afxConstraintList(); // OBJECT CONS-LIST (#scene)
list->push_back(cons);
mConstraints_v.push_back(list);
}
else // if (def.pos_at_box_center)
{
afxObjectConstraint* cons = newObjectCons(this, def.mCons_src_name, want_history);
cons->mCons_def = def;
cons->set(arb_obj);
afxConstraintList* list = mConstraints_v[mConstraints_v.size()-1]; // OBJECT CONS-LIST (#scene)(#center)
if (list && (*list)[0])
list->push_back(cons);
}
}
}
// constraint is an arbitrary named effect
//
else if (def.mDef_type == afxConstraintDef::CONS_EFFECT)
{
if (def.mCons_src_name == ST_NULLSTRING)
return;
// create an Effect constraint
if (def.mCons_node_name == ST_NULLSTRING && !def.mPos_at_box_center)
{
afxEffectConstraint* cons = new afxEffectConstraint(this, def.mCons_src_name);
cons->mCons_def = def;
afxConstraintList* list = new afxConstraintList();
list->push_back(cons);
mConstraints_v.push_back(list);
}
// create an Effect #center constraint
else if (def.mPos_at_box_center)
{
afxEffectConstraint* cons = new afxEffectConstraint(this, def.mCons_src_name);
cons->mCons_def = def;
afxConstraintList* list = mConstraints_v[mConstraints_v.size()-1]; // EFFECT-NODE CONS-LIST (#effect)
if (list && (*list)[0])
list->push_back(cons);
}
// create an EffectNode constraint
else
{
afxEffectNodeConstraint* sub = new afxEffectNodeConstraint(this, def.mCons_src_name, def.mCons_node_name);
sub->mCons_def = def;
afxConstraintList* list = mConstraints_v[mConstraints_v.size()-1];
if (list && (*list)[0])
list->push_back(sub);
}
}
// constraint is a predefined constraint
//
else
{
afxConstraint* cons = 0;
afxConstraint* cons_ctr = 0;
afxConstraint* sub = 0;
if (def.mDef_type == afxConstraintDef::CONS_GHOST)
{
for (S32 i = 0; i < mPredefs.size(); i++)
{
if (mPredefs[i].name == def.mCons_src_name)
{
if (def.mCons_node_name == ST_NULLSTRING && !def.mPos_at_box_center)
{
cons = newShapeCons(this, want_history);
cons->mCons_def = def;
}
else if (def.mPos_at_box_center)
{
cons_ctr = newShapeCons(this, want_history);
cons_ctr->mCons_def = def;
}
else
{
sub = newShapeNodeCons(this, ST_NULLSTRING, def.mCons_node_name, want_history);
sub->mCons_def = def;
}
break;
}
}
}
else
{
for (S32 i = 0; i < mPredefs.size(); i++)
{
if (mPredefs[i].name == def.mCons_src_name)
{
switch (mPredefs[i].type)
{
case POINT_CONSTRAINT:
cons = newPointCons(this, want_history);
cons->mCons_def = def;
break;
case TRANSFORM_CONSTRAINT:
cons = newTransformCons(this, want_history);
cons->mCons_def = def;
break;
case OBJECT_CONSTRAINT:
if (def.mCons_node_name == ST_NULLSTRING && !def.mPos_at_box_center)
{
cons = newShapeCons(this, want_history);
cons->mCons_def = def;
}
else if (def.mPos_at_box_center)
{
cons_ctr = newShapeCons(this, want_history);
cons_ctr->mCons_def = def;
}
else
{
sub = newShapeNodeCons(this, ST_NULLSTRING, def.mCons_node_name, want_history);
sub->mCons_def = def;
}
break;
case CAMERA_CONSTRAINT:
cons = newObjectCons(this, want_history);
cons->mCons_def = def;
cons->mCons_def.mTreat_as_camera = true;
break;
}
break;
}
}
}
if (cons)
{
afxConstraintList* list = new afxConstraintList();
list->push_back(cons);
mConstraints_v.push_back(list);
}
else if (cons_ctr && mConstraints_v.size() > 0)
{
afxConstraintList* list = mConstraints_v[mConstraints_v.size()-1]; // PREDEF-NODE CONS-LIST
if (list && (*list)[0])
list->push_back(cons_ctr);
}
else if (sub && mConstraints_v.size() > 0)
{
afxConstraintList* list = mConstraints_v[mConstraints_v.size()-1];
if (list && (*list)[0])
list->push_back(sub);
}
else
Con::printf("predef not found %s", def.mCons_src_name);
}
}
afxConstraintID afxConstraintMgr::getConstraintId(const afxConstraintDef& def)
{
if (def.mDef_type == afxConstraintDef::CONS_UNDEFINED)
return afxConstraintID();
if (def.mCons_src_name != ST_NULLSTRING)
{
for (S32 i = 0; i < mConstraints_v.size(); i++)
{
afxConstraintList* list = mConstraints_v[i];
afxConstraint* cons = (*list)[0];
if (def.mCons_src_name == cons->mCons_def.mCons_src_name)
{
for (S32 j = 0; j < list->size(); j++)
{
afxConstraint* sub = (*list)[j];
if (def.mCons_node_name == sub->mCons_def.mCons_node_name &&
def.mPos_at_box_center == sub->mCons_def.mPos_at_box_center &&
def.mCons_src_name == sub->mCons_def.mCons_src_name)
{
return afxConstraintID(i, j);
}
}
// if we're here, it means the root object name matched but the node name
// did not.
if (def.mDef_type == afxConstraintDef::CONS_PREDEFINED && !def.mPos_at_box_center)
{
afxShapeConstraint* shape_cons = dynamic_cast<afxShapeConstraint*>(cons);
if (shape_cons)
{
//Con::errorf("Append a Node constraint [%s.%s] [%d,%d]", def.cons_src_name, def.cons_node_name, i, list->size());
bool want_history = (def.mHistory_time > 0.0f);
afxConstraint* sub = newShapeNodeCons(this, ST_NULLSTRING, def.mCons_node_name, want_history);
sub->mCons_def = def;
((afxShapeConstraint*)sub)->set(shape_cons->mShape);
list->push_back(sub);
return afxConstraintID(i, list->size()-1);
}
}
break;
}
}
}
return afxConstraintID();
}
afxConstraint* afxConstraintMgr::getConstraint(afxConstraintID id)
{
if (id.undefined())
return 0;
afxConstraint* cons = CONS_BY_IJ(id.index,id.sub_index);
if (cons && !cons->isDefined())
return NULL;
return cons;
}
void afxConstraintMgr::sample(F32 dt, U32 now, const Point3F* cam_pos)
{
U32 elapsed = now - mStartTime;
for (S32 i = 0; i < mConstraints_v.size(); i++)
{
afxConstraintList* list = mConstraints_v[i];
for (S32 j = 0; j < list->size(); j++)
(*list)[j]->sample(dt, elapsed, cam_pos);
}
}
S32 QSORT_CALLBACK cmp_cons_defs(const void* a, const void* b)
{
afxConstraintDef* def_a = (afxConstraintDef*) a;
afxConstraintDef* def_b = (afxConstraintDef*) b;
if (def_a->mDef_type == def_b->mDef_type)
{
if (def_a->mCons_src_name == def_b->mCons_src_name)
{
if (def_a->mPos_at_box_center == def_b->mPos_at_box_center)
return (def_a->mCons_node_name - def_b->mCons_node_name);
else
return (def_a->mPos_at_box_center) ? 1 : -1;
}
return (def_a->mCons_src_name - def_b->mCons_src_name);
}
return (def_a->mDef_type - def_b->mDef_type);
}
void afxConstraintMgr::initConstraintDefs(Vector<afxConstraintDef>& all_defs, bool on_server, F32 scoping_dist)
{
mInitialized = true;
mOn_server = on_server;
if (scoping_dist > 0.0)
mScoping_dist_sq = scoping_dist*scoping_dist;
else
{
SceneManager* sg = (on_server) ? gServerSceneGraph : gClientSceneGraph;
F32 vis_dist = (sg) ? sg->getVisibleDistance() : 1000.0f;
mScoping_dist_sq = vis_dist*vis_dist;
}
if (all_defs.size() < 1)
return;
// find effect ghost constraints
if (!on_server)
{
Vector<afxConstraintDef> ghost_defs;
for (S32 i = 0; i < all_defs.size(); i++)
if (all_defs[i].mDef_type == afxConstraintDef::CONS_GHOST && all_defs[i].mCons_src_name != ST_NULLSTRING)
ghost_defs.push_back(all_defs[i]);
if (ghost_defs.size() > 0)
{
// sort the defs
if (ghost_defs.size() > 1)
dQsort(ghost_defs.address(), ghost_defs.size(), sizeof(afxConstraintDef), cmp_cons_defs);
S32 last = 0;
defineConstraint(OBJECT_CONSTRAINT, ghost_defs[0].mCons_src_name);
for (S32 i = 1; i < ghost_defs.size(); i++)
{
if (ghost_defs[last].mCons_src_name != ghost_defs[i].mCons_src_name)
{
defineConstraint(OBJECT_CONSTRAINT, ghost_defs[i].mCons_src_name);
last++;
}
}
}
}
Vector<afxConstraintDef> defs;
// collect defs that run here (server or client)
if (on_server)
{
for (S32 i = 0; i < all_defs.size(); i++)
if (all_defs[i].mRuns_on_server)
defs.push_back(all_defs[i]);
}
else
{
for (S32 i = 0; i < all_defs.size(); i++)
if (all_defs[i].mRuns_on_client)
defs.push_back(all_defs[i]);
}
// create unique set of constraints.
//
if (defs.size() > 0)
{
// sort the defs
if (defs.size() > 1)
dQsort(defs.address(), defs.size(), sizeof(afxConstraintDef), cmp_cons_defs);
Vector<afxConstraintDef> unique_defs;
S32 last = 0;
// manufacture root-object def if absent
if (defs[0].mCons_node_name != ST_NULLSTRING)
{
afxConstraintDef root_def = defs[0];
root_def.mCons_node_name = ST_NULLSTRING;
unique_defs.push_back(root_def);
last++;
}
else if (defs[0].mPos_at_box_center)
{
afxConstraintDef root_def = defs[0];
root_def.mPos_at_box_center = false;
unique_defs.push_back(root_def);
last++;
}
unique_defs.push_back(defs[0]);
for (S32 i = 1; i < defs.size(); i++)
{
if (unique_defs[last].mCons_node_name != defs[i].mCons_node_name ||
unique_defs[last].mCons_src_name != defs[i].mCons_src_name ||
unique_defs[last].mPos_at_box_center != defs[i].mPos_at_box_center ||
unique_defs[last].mDef_type != defs[i].mDef_type)
{
// manufacture root-object def if absent
if (defs[i].mCons_src_name != ST_NULLSTRING && unique_defs[last].mCons_src_name != defs[i].mCons_src_name)
{
if (defs[i].mCons_node_name != ST_NULLSTRING || defs[i].mPos_at_box_center)
{
afxConstraintDef root_def = defs[i];
root_def.mCons_node_name = ST_NULLSTRING;
root_def.mPos_at_box_center = false;
unique_defs.push_back(root_def);
last++;
}
}
unique_defs.push_back(defs[i]);
last++;
}
else
{
if (defs[i].mHistory_time > unique_defs[last].mHistory_time)
unique_defs[last].mHistory_time = defs[i].mHistory_time;
if (defs[i].mSample_rate > unique_defs[last].mSample_rate)
unique_defs[last].mSample_rate = defs[i].mSample_rate;
}
}
//Con::printf("\nConstraints on %s", (on_server) ? "server" : "client");
for (S32 i = 0; i < unique_defs.size(); i++)
create_constraint(unique_defs[i]);
}
// collect the names of all the arbitrary object constraints
// that run on clients and store in names_on_server array.
//
if (on_server)
{
mNames_on_server.clear();
defs.clear();
for (S32 i = 0; i < all_defs.size(); i++)
if (all_defs[i].mRuns_on_client && all_defs[i].isArbitraryObject())
defs.push_back(all_defs[i]);
if (defs.size() < 1)
return;
// sort the defs
if (defs.size() > 1)
dQsort(defs.address(), defs.size(), sizeof(afxConstraintDef), cmp_cons_defs);
S32 last = 0;
mNames_on_server.push_back(defs[0].mCons_src_name);
for (S32 i = 1; i < defs.size(); i++)
{
if (mNames_on_server[last] != defs[i].mCons_src_name)
{
mNames_on_server.push_back(defs[i].mCons_src_name);
last++;
}
}
}
}
void afxConstraintMgr::packConstraintNames(NetConnection* conn, BitStream* stream)
{
// pack any named constraint names and ghost indices
if (stream->writeFlag(mNames_on_server.size() > 0)) //-- ANY NAMED CONS_BY_ID?
{
stream->write(mNames_on_server.size());
for (S32 i = 0; i < mNames_on_server.size(); i++)
{
stream->writeString(mNames_on_server[i]);
NetObject* obj = dynamic_cast<NetObject*>(Sim::findObject(mNames_on_server[i]));
if (!obj)
{
//Con::printf("CONSTRAINT-OBJECT %s does not exist.", names_on_server[i]);
stream->write((S32)-1);
}
else
{
S32 ghost_id = conn->getGhostIndex(obj);
/*
if (ghost_id == -1)
Con::printf("CONSTRAINT-OBJECT %s does not have a ghost.", names_on_server[i]);
else
Con::printf("CONSTRAINT-OBJECT %s name to server.", names_on_server[i]);
*/
stream->write(ghost_id);
}
}
}
}
void afxConstraintMgr::unpackConstraintNames(BitStream* stream)
{
if (stream->readFlag()) //-- ANY NAMED CONS_BY_ID?
{
mNames_on_server.clear();
S32 sz; stream->read(&sz);
for (S32 i = 0; i < sz; i++)
{
mNames_on_server.push_back(stream->readSTString());
S32 ghost_id; stream->read(&ghost_id);
mGhost_ids.push_back(ghost_id);
}
}
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//
SceneObject* afxConstraintMgr::find_object_from_name(StringTableEntry name)
{
if (mNames_on_server.size() > 0)
{
for (S32 i = 0; i < mNames_on_server.size(); i++)
if (mNames_on_server[i] == name)
{
if (mGhost_ids[i] == -1)
return 0;
NetConnection* conn = NetConnection::getConnectionToServer();
if (!conn)
return 0;
return dynamic_cast<SceneObject*>(conn->resolveGhost(mGhost_ids[i]));
}
}
return dynamic_cast<SceneObject*>(Sim::findObject(name));
}
void afxConstraintMgr::addScopeableObject(SceneObject* object)
{
for (S32 i = 0; i < scopeable_objs.size(); i++)
{
if (scopeable_objs[i] == object)
return;
}
object->addScopeRef();
scopeable_objs.push_back(object);
}
void afxConstraintMgr::removeScopeableObject(SceneObject* object)
{
for (S32 i = 0; i < scopeable_objs.size(); i++)
if (scopeable_objs[i] == object)
{
object->removeScopeRef();
scopeable_objs.erase_fast(i);
return;
}
}
void afxConstraintMgr::clearAllScopeableObjs()
{
for (S32 i = 0; i < scopeable_objs.size(); i++)
scopeable_objs[i]->removeScopeRef();
scopeable_objs.clear();
}
void afxConstraintMgr::postMissingConstraintObject(afxConstraint* cons, bool is_deleting)
{
if (cons->mGone_missing)
return;
if (!is_deleting)
{
SceneObject* obj = arcaneFX::findScopedObject(cons->getScopeId());
if (obj)
{
cons->restoreObject(obj);
return;
}
}
cons->mGone_missing = true;
missing_objs->push_back(cons);
}
void afxConstraintMgr::restoreScopedObject(SceneObject* obj, afxChoreographer* ch)
{
for (S32 i = 0; i < missing_objs->size(); i++)
{
if ((*missing_objs)[i]->getScopeId() == obj->getScopeId())
{
(*missing_objs)[i]->mGone_missing = false;
(*missing_objs)[i]->restoreObject(obj);
if (ch)
ch->restoreObject(obj);
}
else
missing_objs2->push_back((*missing_objs)[i]);
}
Vector<afxConstraint*>* tmp = missing_objs;
missing_objs = missing_objs2;
missing_objs2 = tmp;
missing_objs2->clear();
}
void afxConstraintMgr::adjustProcessOrdering(afxChoreographer* ch)
{
Vector<ProcessObject*> cons_sources;
// add choreographer to the list
cons_sources.push_back(ch);
// collect all the ProcessObject related constraint sources
for (S32 i = 0; i < mConstraints_v.size(); i++)
{
afxConstraintList* list = mConstraints_v[i];
afxConstraint* cons = (*list)[0];
if (cons)
{
ProcessObject* pobj = dynamic_cast<ProcessObject*>(cons->getSceneObject());
if (pobj)
cons_sources.push_back(pobj);
}
}
ProcessList* proc_list;
if (ch->isServerObject())
proc_list = ServerProcessList::get();
else
proc_list = ClientProcessList::get();
if (!proc_list)
return;
GameBase* nearest_to_end = dynamic_cast<GameBase*>(proc_list->findNearestToEnd(cons_sources));
GameBase* chor = (GameBase*) ch;
// choreographer needs to be processed after the latest process object
if (chor != nearest_to_end && nearest_to_end != 0)
{
//Con::printf("Choreographer processing BEFORE some of its constraints... fixing. [%s] -- %s",
// (ch->isServerObject()) ? "S" : "C", nearest_to_end->getClassName());
if (chor->isProperlyAdded())
ch->processAfter(nearest_to_end);
else
ch->postProcessAfterObject(nearest_to_end);
}
else
{
//Con::printf("Choreographer processing AFTER its constraints... fine. [%s]",
// (ch->isServerObject()) ? "S" : "C");
}
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxPointConstraint
afxPointConstraint::afxPointConstraint(afxConstraintMgr* mgr)
: afxConstraint(mgr)
{
mPoint.zero();
mVector.set(0,0,1);
}
afxPointConstraint::~afxPointConstraint()
{
}
void afxPointConstraint::set(Point3F point, Point3F vector)
{
mPoint = point;
mVector = vector;
mIs_defined = true;
mIs_valid = true;
mChange_code++;
sample(0.0f, 0, 0);
}
void afxPointConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
if (cam_pos)
{
Point3F dir = (*cam_pos) - mPoint;
F32 dist_sq = dir.lenSquared();
if (dist_sq > mMgr->getScopingDistanceSquared())
{
mIs_valid = false;
return;
}
mIs_valid = true;
}
mLast_pos = mPoint;
mLast_xfm.identity();
mLast_xfm.setPosition(mPoint);
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxTransformConstraint
afxTransformConstraint::afxTransformConstraint(afxConstraintMgr* mgr)
: afxConstraint(mgr)
{
mXfm.identity();
}
afxTransformConstraint::~afxTransformConstraint()
{
}
void afxTransformConstraint::set(const MatrixF& xfm)
{
mXfm = xfm;
mIs_defined = true;
mIs_valid = true;
mChange_code++;
sample(0.0f, 0, 0);
}
void afxTransformConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
if (cam_pos)
{
Point3F dir = (*cam_pos) - mXfm.getPosition();
F32 dist_sq = dir.lenSquared();
if (dist_sq > mMgr->getScopingDistanceSquared())
{
mIs_valid = false;
return;
}
mIs_valid = true;
}
mLast_xfm = mXfm;
mLast_pos = mXfm.getPosition();
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxShapeConstraint
afxShapeConstraint::afxShapeConstraint(afxConstraintMgr* mgr)
: afxConstraint(mgr)
{
mArb_name = ST_NULLSTRING;
mShape = 0;
mScope_id = 0;
mClip_tag = 0;
mLock_tag = 0;
}
afxShapeConstraint::afxShapeConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name)
: afxConstraint(mgr)
{
mArb_name = arb_name;
mShape = 0;
mScope_id = 0;
mClip_tag = 0;
mLock_tag = 0;
}
afxShapeConstraint::~afxShapeConstraint()
{
if (mShape)
clearNotify(mShape);
}
void afxShapeConstraint::set(ShapeBase* shape)
{
if (mShape)
{
mScope_id = 0;
clearNotify(mShape);
if (mClip_tag > 0)
remapAnimation(mClip_tag, shape);
if (mLock_tag > 0)
unlockAnimation(mLock_tag);
}
mShape = shape;
if (mShape)
{
deleteNotify(mShape);
mScope_id = mShape->getScopeId();
}
if (mShape != NULL)
{
mIs_defined = true;
mIs_valid = true;
mChange_code++;
sample(0.0f, 0, 0);
}
else
mIs_valid = false;
}
void afxShapeConstraint::set_scope_id(U16 scope_id)
{
if (mShape)
clearNotify(mShape);
mShape = 0;
mScope_id = scope_id;
mIs_defined = (mScope_id > 0);
mIs_valid = false;
mMgr->postMissingConstraintObject(this);
}
void afxShapeConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
if (mGone_missing)
return;
if (mShape)
{
mLast_xfm = mShape->getRenderTransform();
if (mCons_def.mPos_at_box_center)
mLast_pos = mShape->getBoxCenter();
else
mLast_pos = mShape->getRenderPosition();
}
}
void afxShapeConstraint::restoreObject(SceneObject* obj)
{
if (mShape)
{
mScope_id = 0;
clearNotify(mShape);
}
mShape = (ShapeBase* )obj;
if (mShape)
{
deleteNotify(mShape);
mScope_id = mShape->getScopeId();
}
mIs_valid = (mShape != NULL);
}
void afxShapeConstraint::onDeleteNotify(SimObject* obj)
{
if (mShape == dynamic_cast<ShapeBase*>(obj))
{
mShape = 0;
mIs_valid = false;
if (mScope_id > 0)
mMgr->postMissingConstraintObject(this, true);
}
Parent::onDeleteNotify(obj);
}
U32 afxShapeConstraint::setAnimClip(const char* clip, F32 pos, F32 rate, F32 trans, bool is_death_anim)
{
if (!mShape)
return 0;
if (mShape->isServerObject())
{
AIPlayer* ai_player = dynamic_cast<AIPlayer*>(mShape);
if (ai_player && !ai_player->isBlendAnimation(clip))
{
ai_player->saveMoveState();
ai_player->stopMove();
}
}
mClip_tag = mShape->playAnimation(clip, pos, rate, trans, false/*hold*/, true/*wait*/, is_death_anim);
return mClip_tag;
}
void afxShapeConstraint::remapAnimation(U32 tag, ShapeBase* other_shape)
{
if (mClip_tag == 0)
return;
if (!mShape)
return;
if (!other_shape)
{
resetAnimation(tag);
return;
}
Con::errorf("remapAnimation -- Clip name, %s.", mShape->getLastClipName(tag));
if (mShape->isClientObject())
{
mShape->restoreAnimation(tag);
}
else
{
AIPlayer* ai_player = dynamic_cast<AIPlayer*>(mShape);
if (ai_player)
ai_player->restartMove(tag);
else
mShape->restoreAnimation(tag);
}
mClip_tag = 0;
}
void afxShapeConstraint::resetAnimation(U32 tag)
{
if (mClip_tag == 0)
return;
if (!mShape)
return;
if (mShape->isClientObject())
{
mShape->restoreAnimation(tag);
}
else
{
AIPlayer* ai_player = dynamic_cast<AIPlayer*>(mShape);
if (ai_player)
ai_player->restartMove(tag);
else
mShape->restoreAnimation(tag);
}
if ((tag & 0x80000000) == 0 && tag == mClip_tag)
mClip_tag = 0;
}
U32 afxShapeConstraint::lockAnimation()
{
if (!mShape)
return 0;
mLock_tag = mShape->lockAnimation();
return mLock_tag;
}
void afxShapeConstraint::unlockAnimation(U32 tag)
{
if (mLock_tag == 0)
return;
if (!mShape)
return;
mShape->unlockAnimation(tag);
mLock_tag = 0;
}
F32 afxShapeConstraint::getAnimClipDuration(const char* clip)
{
return (mShape) ? mShape->getAnimationDuration(clip) : 0.0f;
}
S32 afxShapeConstraint::getDamageState()
{
return (mShape) ? mShape->getDamageState() : -1;
}
U32 afxShapeConstraint::getTriggers()
{
return (mShape) ? mShape->getShapeInstance()->getTriggerStateMask() : 0;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxShapeNodeConstraint
afxShapeNodeConstraint::afxShapeNodeConstraint(afxConstraintMgr* mgr)
: afxShapeConstraint(mgr)
{
mArb_node = ST_NULLSTRING;
mShape_node_ID = -1;
}
afxShapeNodeConstraint::afxShapeNodeConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name, StringTableEntry arb_node)
: afxShapeConstraint(mgr, arb_name)
{
mArb_node = arb_node;
mShape_node_ID = -1;
}
void afxShapeNodeConstraint::set(ShapeBase* shape)
{
if (shape)
{
mShape_node_ID = shape->getShape()->findNode(mArb_node);
if (mShape_node_ID == -1)
Con::errorf("Failed to find node [%s]", mArb_node);
}
else
mShape_node_ID = -1;
Parent::set(shape);
}
void afxShapeNodeConstraint::set_scope_id(U16 scope_id)
{
mShape_node_ID = -1;
Parent::set_scope_id(scope_id);
}
void afxShapeNodeConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
if (mShape && mShape_node_ID != -1)
{
mLast_xfm = mShape->getRenderTransform();
mLast_xfm.scale(mShape->getScale());
mLast_xfm.mul(mShape->getShapeInstance()->mNodeTransforms[mShape_node_ID]);
mLast_pos = mLast_xfm.getPosition();
}
}
void afxShapeNodeConstraint::restoreObject(SceneObject* obj)
{
ShapeBase* shape = dynamic_cast<ShapeBase*>(obj);
if (shape)
{
mShape_node_ID = shape->getShape()->findNode(mArb_node);
if (mShape_node_ID == -1)
Con::errorf("Failed to find node [%s]", mArb_node);
}
else
mShape_node_ID = -1;
Parent::restoreObject(obj);
}
void afxShapeNodeConstraint::onDeleteNotify(SimObject* obj)
{
Parent::onDeleteNotify(obj);
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxObjectConstraint
afxObjectConstraint::afxObjectConstraint(afxConstraintMgr* mgr)
: afxConstraint(mgr)
{
mArb_name = ST_NULLSTRING;
mObj = 0;
mScope_id = 0;
mIs_camera = false;
}
afxObjectConstraint::afxObjectConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name)
: afxConstraint(mgr)
{
mArb_name = arb_name;
mObj = 0;
mScope_id = 0;
mIs_camera = false;
}
afxObjectConstraint::~afxObjectConstraint()
{
if (mObj)
clearNotify(mObj);
}
void afxObjectConstraint::set(SceneObject* obj)
{
if (mObj)
{
mScope_id = 0;
clearNotify(mObj);
}
mObj = obj;
if (mObj)
{
deleteNotify(mObj);
mScope_id = mObj->getScopeId();
}
if (mObj != NULL)
{
mIs_camera = mObj->isCamera();
mIs_defined = true;
mIs_valid = true;
mChange_code++;
sample(0.0f, 0, 0);
}
else
mIs_valid = false;
}
void afxObjectConstraint::set_scope_id(U16 scope_id)
{
if (mObj)
clearNotify(mObj);
mObj = 0;
mScope_id = scope_id;
mIs_defined = (scope_id > 0);
mIs_valid = false;
mMgr->postMissingConstraintObject(this);
}
void afxObjectConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
if (mGone_missing)
return;
if (mObj)
{
if (!mIs_camera && mCons_def.mTreat_as_camera && dynamic_cast<ShapeBase*>(mObj))
{
ShapeBase* cam_obj = (ShapeBase*) mObj;
F32 pov = 1.0f;
cam_obj->getCameraTransform(&pov, &mLast_xfm);
mLast_xfm.getColumn(3, &mLast_pos);
}
else
{
mLast_xfm = mObj->getRenderTransform();
if (mCons_def.mPos_at_box_center)
mLast_pos = mObj->getBoxCenter();
else
mLast_pos = mObj->getRenderPosition();
}
}
}
void afxObjectConstraint::restoreObject(SceneObject* obj)
{
if (mObj)
{
mScope_id = 0;
clearNotify(mObj);
}
mObj = obj;
if (mObj)
{
deleteNotify(mObj);
mScope_id = mObj->getScopeId();
}
mIs_valid = (mObj != NULL);
}
void afxObjectConstraint::onDeleteNotify(SimObject* obj)
{
if (mObj == dynamic_cast<SceneObject*>(obj))
{
mObj = 0;
mIs_valid = false;
if (mScope_id > 0)
mMgr->postMissingConstraintObject(this, true);
}
Parent::onDeleteNotify(obj);
}
U32 afxObjectConstraint::getTriggers()
{
TSStatic* ts_static = dynamic_cast<TSStatic*>(mObj);
if (ts_static)
{
TSShapeInstance* obj_inst = ts_static->getShapeInstance();
return (obj_inst) ? obj_inst->getTriggerStateMask() : 0;
}
ShapeBase* shape_base = dynamic_cast<ShapeBase*>(mObj);
if (shape_base)
{
TSShapeInstance* obj_inst = shape_base->getShapeInstance();
return (obj_inst) ? obj_inst->getTriggerStateMask() : 0;
}
return 0;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxEffectConstraint
afxEffectConstraint::afxEffectConstraint(afxConstraintMgr* mgr)
: afxConstraint(mgr)
{
mEffect_name = ST_NULLSTRING;
mEffect = 0;
}
afxEffectConstraint::afxEffectConstraint(afxConstraintMgr* mgr, StringTableEntry effect_name)
: afxConstraint(mgr)
{
mEffect_name = effect_name;
mEffect = 0;
}
afxEffectConstraint::~afxEffectConstraint()
{
}
bool afxEffectConstraint::getPosition(Point3F& pos, F32 hist)
{
if (!mEffect || !mEffect->inScope())
return false;
if (mCons_def.mPos_at_box_center)
mEffect->getUpdatedBoxCenter(pos);
else
mEffect->getUpdatedPosition(pos);
return true;
}
bool afxEffectConstraint::getTransform(MatrixF& xfm, F32 hist)
{
if (!mEffect || !mEffect->inScope())
return false;
mEffect->getUpdatedTransform(xfm);
return true;
}
bool afxEffectConstraint::getAltitudes(F32& terrain_alt, F32& interior_alt)
{
if (!mEffect)
return false;
mEffect->getAltitudes(terrain_alt, interior_alt);
return true;
}
void afxEffectConstraint::set(afxEffectWrapper* effect)
{
mEffect = effect;
if (mEffect != NULL)
{
mIs_defined = true;
mIs_valid = true;
mChange_code++;
}
else
mIs_valid = false;
}
U32 afxEffectConstraint::setAnimClip(const char* clip, F32 pos, F32 rate, F32 trans, bool is_death_anim)
{
return (mEffect) ? mEffect->setAnimClip(clip, pos, rate, trans) : 0;
}
void afxEffectConstraint::resetAnimation(U32 tag)
{
if (mEffect)
mEffect->resetAnimation(tag);
}
F32 afxEffectConstraint::getAnimClipDuration(const char* clip)
{
return (mEffect) ? getAnimClipDuration(clip) : 0;
}
U32 afxEffectConstraint::getTriggers()
{
return (mEffect) ? mEffect->getTriggers() : 0;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxEffectNodeConstraint
afxEffectNodeConstraint::afxEffectNodeConstraint(afxConstraintMgr* mgr)
: afxEffectConstraint(mgr)
{
mEffect_node = ST_NULLSTRING;
mEffect_node_ID = -1;
}
afxEffectNodeConstraint::afxEffectNodeConstraint(afxConstraintMgr* mgr, StringTableEntry name, StringTableEntry node)
: afxEffectConstraint(mgr, name)
{
mEffect_node = node;
mEffect_node_ID = -1;
}
bool afxEffectNodeConstraint::getPosition(Point3F& pos, F32 hist)
{
if (!mEffect || !mEffect->inScope())
return false;
TSShapeInstance* ts_shape_inst = mEffect->getTSShapeInstance();
if (!ts_shape_inst)
return false;
if (mEffect_node_ID == -1)
{
TSShape* ts_shape = mEffect->getTSShape();
mEffect_node_ID = (ts_shape) ? ts_shape->findNode(mEffect_node) : -1;
}
if (mEffect_node_ID == -1)
return false;
mEffect->getUpdatedTransform(mLast_xfm);
Point3F scale;
mEffect->getUpdatedScale(scale);
MatrixF gag = ts_shape_inst->mNodeTransforms[mEffect_node_ID];
gag.setPosition( gag.getPosition()*scale );
MatrixF xfm;
xfm.mul(mLast_xfm, gag);
//
pos = xfm.getPosition();
return true;
}
bool afxEffectNodeConstraint::getTransform(MatrixF& xfm, F32 hist)
{
if (!mEffect || !mEffect->inScope())
return false;
TSShapeInstance* ts_shape_inst = mEffect->getTSShapeInstance();
if (!ts_shape_inst)
return false;
if (mEffect_node_ID == -1)
{
TSShape* ts_shape = mEffect->getTSShape();
mEffect_node_ID = (ts_shape) ? ts_shape->findNode(mEffect_node) : -1;
}
if (mEffect_node_ID == -1)
return false;
mEffect->getUpdatedTransform(mLast_xfm);
Point3F scale;
mEffect->getUpdatedScale(scale);
MatrixF gag = ts_shape_inst->mNodeTransforms[mEffect_node_ID];
gag.setPosition( gag.getPosition()*scale );
xfm.mul(mLast_xfm, gag);
return true;
}
void afxEffectNodeConstraint::set(afxEffectWrapper* effect)
{
if (effect)
{
TSShape* ts_shape = effect->getTSShape();
mEffect_node_ID = (ts_shape) ? ts_shape->findNode(mEffect_node) : -1;
}
else
mEffect_node_ID = -1;
Parent::set(effect);
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxSampleBuffer
afxSampleBuffer::afxSampleBuffer()
{
mBuffer_sz = 0;
mBuffer_ms = 0;
mMS_per_sample = 33;
mElapsed_ms = 0;
mLast_sample_ms = 0;
mNext_sample_num = 0;
mNum_samples = 0;
}
afxSampleBuffer::~afxSampleBuffer()
{
}
void afxSampleBuffer::configHistory(F32 hist_len, U8 sample_rate)
{
mBuffer_sz = mCeil(hist_len*sample_rate) + 1;
mMS_per_sample = mCeil(1000.0f/sample_rate);
mBuffer_ms = mBuffer_sz*mMS_per_sample;
}
void afxSampleBuffer::recordSample(F32 dt, U32 elapsed_ms, void* data)
{
mElapsed_ms = elapsed_ms;
if (!data)
return;
U32 now_sample_num = elapsed_ms/mMS_per_sample;
if (mNext_sample_num <= now_sample_num)
{
mLast_sample_ms = elapsed_ms;
while (mNext_sample_num <= now_sample_num)
{
recSample(mNext_sample_num % mBuffer_sz, data);
mNext_sample_num++;
mNum_samples++;
}
}
}
inline bool afxSampleBuffer::compute_idx_from_lag(F32 lag, U32& idx)
{
bool in_bounds = true;
U32 lag_ms = lag*1000.0f;
U32 rec_ms = (mElapsed_ms < mBuffer_ms) ? mElapsed_ms : mBuffer_ms;
if (lag_ms > rec_ms)
{
// hasn't produced enough history
lag_ms = rec_ms;
in_bounds = false;
}
U32 latest_sample_num = mLast_sample_ms/mMS_per_sample;
U32 then_sample_num = (mElapsed_ms - lag_ms)/mMS_per_sample;
if (then_sample_num > latest_sample_num)
{
// latest sample is older than lag
then_sample_num = latest_sample_num;
in_bounds = false;
}
idx = then_sample_num % mBuffer_sz;
return in_bounds;
}
inline bool afxSampleBuffer::compute_idx_from_lag(F32 lag, U32& idx1, U32& idx2, F32& t)
{
bool in_bounds = true;
F32 lag_ms = lag*1000.0f;
F32 rec_ms = (mElapsed_ms < mBuffer_ms) ? mElapsed_ms : mBuffer_ms;
if (lag_ms > rec_ms)
{
// hasn't produced enough history
lag_ms = rec_ms;
in_bounds = false;
}
F32 per_samp = mMS_per_sample;
F32 latest_sample_num = mLast_sample_ms/per_samp;
F32 then_sample_num = (mElapsed_ms - lag_ms)/per_samp;
U32 latest_sample_num_i = latest_sample_num;
U32 then_sample_num_i = then_sample_num;
if (then_sample_num_i >= latest_sample_num_i)
{
if (latest_sample_num_i < then_sample_num_i)
in_bounds = false;
t = 0.0;
idx1 = then_sample_num_i % mBuffer_sz;
idx2 = idx1;
}
else
{
t = then_sample_num - then_sample_num_i;
idx1 = then_sample_num_i % mBuffer_sz;
idx2 = (then_sample_num_i+1) % mBuffer_sz;
}
return in_bounds;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxSampleXfmBuffer
afxSampleXfmBuffer::afxSampleXfmBuffer()
{
mXfm_buffer = 0;
}
afxSampleXfmBuffer::~afxSampleXfmBuffer()
{
delete [] mXfm_buffer;
}
void afxSampleXfmBuffer::configHistory(F32 hist_len, U8 sample_rate)
{
if (!mXfm_buffer)
{
afxSampleBuffer::configHistory(hist_len, sample_rate);
if (mBuffer_sz > 0)
mXfm_buffer = new MatrixF[mBuffer_sz];
}
}
void afxSampleXfmBuffer::recSample(U32 idx, void* data)
{
mXfm_buffer[idx] = *((MatrixF*)data);
}
void afxSampleXfmBuffer::getSample(F32 lag, void* data, bool& in_bounds)
{
U32 idx1, idx2;
F32 t;
in_bounds = compute_idx_from_lag(lag, idx1, idx2, t);
if (idx1 == idx2)
{
MatrixF* m1 = &mXfm_buffer[idx1];
*((MatrixF*)data) = *m1;
}
else
{
MatrixF* m1 = &mXfm_buffer[idx1];
MatrixF* m2 = &mXfm_buffer[idx2];
Point3F p1 = m1->getPosition();
Point3F p2 = m2->getPosition();
Point3F p; p.interpolate(p1, p2, t);
if (t < 0.5f)
*((MatrixF*)data) = *m1;
else
*((MatrixF*)data) = *m2;
((MatrixF*)data)->setPosition(p);
}
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxPointHistConstraint
afxPointHistConstraint::afxPointHistConstraint(afxConstraintMgr* mgr)
: afxPointConstraint(mgr)
{
mSamples = 0;
}
afxPointHistConstraint::~afxPointHistConstraint()
{
delete mSamples;
}
void afxPointHistConstraint::set(Point3F point, Point3F vector)
{
if (!mSamples)
{
mSamples = new afxSampleXfmBuffer;
mSamples->configHistory(mCons_def.mHistory_time, mCons_def.mSample_rate);
}
Parent::set(point, vector);
}
void afxPointHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
Parent::sample(dt, elapsed_ms, cam_pos);
if (isDefined())
{
if (isValid())
mSamples->recordSample(dt, elapsed_ms, &mLast_xfm);
else
mSamples->recordSample(dt, elapsed_ms, 0);
}
}
bool afxPointHistConstraint::getPosition(Point3F& pos, F32 hist)
{
bool in_bounds;
MatrixF xfm;
mSamples->getSample(hist, &xfm, in_bounds);
pos = xfm.getPosition();
return in_bounds;
}
bool afxPointHistConstraint::getTransform(MatrixF& xfm, F32 hist)
{
bool in_bounds;
mSamples->getSample(hist, &xfm, in_bounds);
return in_bounds;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxPointHistConstraint
afxTransformHistConstraint::afxTransformHistConstraint(afxConstraintMgr* mgr)
: afxTransformConstraint(mgr)
{
mSamples = 0;
}
afxTransformHistConstraint::~afxTransformHistConstraint()
{
delete mSamples;
}
void afxTransformHistConstraint::set(const MatrixF& xfm)
{
if (!mSamples)
{
mSamples = new afxSampleXfmBuffer;
mSamples->configHistory(mCons_def.mHistory_time, mCons_def.mSample_rate);
}
Parent::set(xfm);
}
void afxTransformHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
Parent::sample(dt, elapsed_ms, cam_pos);
if (isDefined())
{
if (isValid())
mSamples->recordSample(dt, elapsed_ms, &mLast_xfm);
else
mSamples->recordSample(dt, elapsed_ms, 0);
}
}
bool afxTransformHistConstraint::getPosition(Point3F& pos, F32 hist)
{
bool in_bounds;
MatrixF xfm;
mSamples->getSample(hist, &xfm, in_bounds);
pos = xfm.getPosition();
return in_bounds;
}
bool afxTransformHistConstraint::getTransform(MatrixF& xfm, F32 hist)
{
bool in_bounds;
mSamples->getSample(hist, &xfm, in_bounds);
return in_bounds;
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxShapeHistConstraint
afxShapeHistConstraint::afxShapeHistConstraint(afxConstraintMgr* mgr)
: afxShapeConstraint(mgr)
{
mSamples = 0;
}
afxShapeHistConstraint::afxShapeHistConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name)
: afxShapeConstraint(mgr, arb_name)
{
mSamples = 0;
}
afxShapeHistConstraint::~afxShapeHistConstraint()
{
delete mSamples;
}
void afxShapeHistConstraint::set(ShapeBase* shape)
{
if (shape && !mSamples)
{
mSamples = new afxSampleXfmBuffer;
mSamples->configHistory(mCons_def.mHistory_time, mCons_def.mSample_rate);
}
Parent::set(shape);
}
void afxShapeHistConstraint::set_scope_id(U16 scope_id)
{
if (scope_id > 0 && !mSamples)
{
mSamples = new afxSampleXfmBuffer;
mSamples->configHistory(mCons_def.mHistory_time, mCons_def.mSample_rate);
}
Parent::set_scope_id(scope_id);
}
void afxShapeHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
Parent::sample(dt, elapsed_ms, cam_pos);
if (isDefined())
{
if (isValid())
mSamples->recordSample(dt, elapsed_ms, &mLast_xfm);
else
mSamples->recordSample(dt, elapsed_ms, 0);
}
}
bool afxShapeHistConstraint::getPosition(Point3F& pos, F32 hist)
{
bool in_bounds;
MatrixF xfm;
mSamples->getSample(hist, &xfm, in_bounds);
pos = xfm.getPosition();
return in_bounds;
}
bool afxShapeHistConstraint::getTransform(MatrixF& xfm, F32 hist)
{
bool in_bounds;
mSamples->getSample(hist, &xfm, in_bounds);
return in_bounds;
}
void afxShapeHistConstraint::onDeleteNotify(SimObject* obj)
{
Parent::onDeleteNotify(obj);
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxShapeNodeHistConstraint
afxShapeNodeHistConstraint::afxShapeNodeHistConstraint(afxConstraintMgr* mgr)
: afxShapeNodeConstraint(mgr)
{
mSamples = 0;
}
afxShapeNodeHistConstraint::afxShapeNodeHistConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name,
StringTableEntry arb_node)
: afxShapeNodeConstraint(mgr, arb_name, arb_node)
{
mSamples = 0;
}
afxShapeNodeHistConstraint::~afxShapeNodeHistConstraint()
{
delete mSamples;
}
void afxShapeNodeHistConstraint::set(ShapeBase* shape)
{
if (shape && !mSamples)
{
mSamples = new afxSampleXfmBuffer;
mSamples->configHistory(mCons_def.mHistory_time, mCons_def.mSample_rate);
}
Parent::set(shape);
}
void afxShapeNodeHistConstraint::set_scope_id(U16 scope_id)
{
if (scope_id > 0 && !mSamples)
{
mSamples = new afxSampleXfmBuffer;
mSamples->configHistory(mCons_def.mHistory_time, mCons_def.mSample_rate);
}
Parent::set_scope_id(scope_id);
}
void afxShapeNodeHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
Parent::sample(dt, elapsed_ms, cam_pos);
if (isDefined())
{
if (isValid())
mSamples->recordSample(dt, elapsed_ms, &mLast_xfm);
else
mSamples->recordSample(dt, elapsed_ms, 0);
}
}
bool afxShapeNodeHistConstraint::getPosition(Point3F& pos, F32 hist)
{
bool in_bounds;
MatrixF xfm;
mSamples->getSample(hist, &xfm, in_bounds);
pos = xfm.getPosition();
return in_bounds;
}
bool afxShapeNodeHistConstraint::getTransform(MatrixF& xfm, F32 hist)
{
bool in_bounds;
mSamples->getSample(hist, &xfm, in_bounds);
return in_bounds;
}
void afxShapeNodeHistConstraint::onDeleteNotify(SimObject* obj)
{
Parent::onDeleteNotify(obj);
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// afxObjectHistConstraint
afxObjectHistConstraint::afxObjectHistConstraint(afxConstraintMgr* mgr)
: afxObjectConstraint(mgr)
{
mSamples = 0;
}
afxObjectHistConstraint::afxObjectHistConstraint(afxConstraintMgr* mgr, StringTableEntry arb_name)
: afxObjectConstraint(mgr, arb_name)
{
mSamples = 0;
}
afxObjectHistConstraint::~afxObjectHistConstraint()
{
delete mSamples;
}
void afxObjectHistConstraint::set(SceneObject* obj)
{
if (obj && !mSamples)
{
mSamples = new afxSampleXfmBuffer;
mSamples->configHistory(mCons_def.mHistory_time, mCons_def.mSample_rate);
}
Parent::set(obj);
}
void afxObjectHistConstraint::set_scope_id(U16 scope_id)
{
if (scope_id > 0 && !mSamples)
{
mSamples = new afxSampleXfmBuffer;
mSamples->configHistory(mCons_def.mHistory_time, mCons_def.mSample_rate);
}
Parent::set_scope_id(scope_id);
}
void afxObjectHistConstraint::sample(F32 dt, U32 elapsed_ms, const Point3F* cam_pos)
{
Parent::sample(dt, elapsed_ms, cam_pos);
if (isDefined())
{
if (isValid())
mSamples->recordSample(dt, elapsed_ms, &mLast_xfm);
else
mSamples->recordSample(dt, elapsed_ms, 0);
}
}
bool afxObjectHistConstraint::getPosition(Point3F& pos, F32 hist)
{
bool in_bounds;
MatrixF xfm;
mSamples->getSample(hist, &xfm, in_bounds);
pos = xfm.getPosition();
return in_bounds;
}
bool afxObjectHistConstraint::getTransform(MatrixF& xfm, F32 hist)
{
bool in_bounds;
mSamples->getSample(hist, &xfm, in_bounds);
return in_bounds;
}
void afxObjectHistConstraint::onDeleteNotify(SimObject* obj)
{
Parent::onDeleteNotify(obj);
}
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
| 24.813695 | 127 | 0.642184 | [
"object",
"shape",
"vector",
"3d"
] |
a73b3a3132d82fd6741bb59c5bebad490f21c98b | 7,068 | cc | C++ | onnxruntime/test/ir/schema_registry_manager_test.cc | codemzs/onnxruntime | c69194ec4c8c9674368113aa6044d0db708cd813 | [
"MIT"
] | 4 | 2019-06-06T23:48:57.000Z | 2021-06-03T11:51:45.000Z | onnxruntime/test/ir/schema_registry_manager_test.cc | Montaer/onnxruntime | 6dc25a60f8b058a556964801d99d5508641dcf69 | [
"MIT"
] | 17 | 2020-07-21T11:13:27.000Z | 2022-03-27T02:37:05.000Z | onnxruntime/test/ir/schema_registry_manager_test.cc | Surfndez/onnxruntime | 9d748afff19e9604a00632d66b97159b917dabb2 | [
"MIT"
] | 3 | 2019-05-07T01:29:04.000Z | 2020-08-09T08:36:12.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <core/graph/schema_registry.h>
#include "test/providers/provider_test_utils.h" //For ASSERT_STATUS_OK
#include "gtest/gtest.h"
ONNX_NAMESPACE::OpSchema CreateTestSchema(const char* name, const char* domain, int sinceVersion) {
return ONNX_NAMESPACE::OpSchema().SetName(name).SinceVersion(sinceVersion).SetDomain(domain).Output(0, "output_1", "docstr for output", "tensor(int32)");
}
using namespace onnxruntime;
TEST(SchemaRegistryManager, search_onnx_op) {
SchemaRegistryManager manager;
ASSERT_NE(manager.GetSchema("Gemm", 10, ""), nullptr);
}
TEST(SchemaRegistryManager, search_memcpy_op) {
SchemaRegistryManager manager;
ASSERT_NE(manager.GetSchema("MemcpyToHost", 1, ""), nullptr);
}
TEST(SchemaRegistryManager, search_memcpy_op_wrong_version) {
SchemaRegistryManager manager;
ASSERT_EQ(manager.GetSchema("MemcpyToHost", 9999, ""), nullptr);
}
TEST(SchemaRegistryManager, search_onnxml_op) {
SchemaRegistryManager manager;
ASSERT_NE(manager.GetSchema("ArrayFeatureExtractor", 1, "ai.onnx.ml"), nullptr);
}
TEST(SchemaRegistryManager, search_onnxml_op_wrong_opset_version) {
SchemaRegistryManager manager;
ASSERT_EQ(manager.GetSchema("ArrayFeatureExtractor", 99, "ai.onnx.ml"), nullptr);
}
TEST(SchemaRegistryManager, search_custom_op_wrong_opset_version) {
SchemaRegistryManager manager;
std::shared_ptr<onnxruntime::OnnxRuntimeOpSchemaRegistry> registry = std::make_shared<OnnxRuntimeOpSchemaRegistry>();
std::vector<ONNX_NAMESPACE::OpSchema> schema = {CreateTestSchema("Op1", "Domain1", 1)};
ASSERT_EQ(manager.GetSchema("Op1", 99, "Domain1"), nullptr);
}
TEST(SchemaRegistryManager, OpsetRegTest) {
std::shared_ptr<onnxruntime::OnnxRuntimeOpSchemaRegistry> registry = std::make_shared<OnnxRuntimeOpSchemaRegistry>();
// Register op-set version 1 with baseline version 0
std::vector<ONNX_NAMESPACE::OpSchema> schema = {CreateTestSchema("Op1", "Domain1", 1), CreateTestSchema("Op2", "Domain1", 1)};
ASSERT_STATUS_OK(registry->RegisterOpSet(schema, "Domain1", 0, 1));
// Get the schema
ASSERT_TRUE(registry->GetSchema("Op1", 1, "Domain1")->Name() == "Op1");
ASSERT_TRUE(registry->GetSchema("Op2", 1, "Domain1")->Name() == "Op2");
// Getting schema with wrong name, domain, and version will fail
ASSERT_TRUE(registry->GetSchema("Op1", 1, "WrongDomain") == nullptr);
ASSERT_TRUE(registry->GetSchema("WrongOp", 1, "Domain1") == nullptr);
// Fail because this registry doesn't have information for opset2.
ASSERT_TRUE(registry->GetSchema("Op1", 2, "Domain1") == nullptr);
ASSERT_TRUE(registry->GetSchema("Op1", 0, "Domain1") == nullptr);
// Registering a new op-set in the same domain will fail. This (currently) requires the caller to
// use multiple registry instances and a registry manager.
std::vector<ONNX_NAMESPACE::OpSchema> schemaV2 = {CreateTestSchema("Op1", "Domain1", 2)};
ASSERT_FALSE(registry->RegisterOpSet(schemaV2, "Domain1", 1, 2).IsOK());
// Registering a second op-set in a different domain should succeed
std::vector<ONNX_NAMESPACE::OpSchema> schemaDomain2 = {CreateTestSchema("Op2", "Domain2", 1)};
ASSERT_STATUS_OK(registry->RegisterOpSet(schemaDomain2, "Domain2", 0, 1));
ASSERT_TRUE(registry->GetSchema("Op1", 1, "Domain1")->Name() == "Op1");
ASSERT_TRUE(registry->GetSchema("Op2", 1, "Domain2")->Name() == "Op2");
// Overriding existing op-set schema will fail
std::vector<ONNX_NAMESPACE::OpSchema> schemaOverride = {CreateTestSchema("Op1", "Domain1", 1)};
ASSERT_FALSE(registry->RegisterOpSet(schema, "Domain1", 0, 1).IsOK());
// Create a second registry, combined with the first through a manager
std::shared_ptr<onnxruntime::OnnxRuntimeOpSchemaRegistry> registry2 = std::make_shared<OnnxRuntimeOpSchemaRegistry>();
SchemaRegistryManager manager;
manager.RegisterRegistry(registry);
manager.RegisterRegistry(registry2);
// Register the second version of the same op-set on the second registry, overriding one operator
ASSERT_STATUS_OK(registry2->RegisterOpSet(schemaV2, "Domain1", 1, 2));
//Now the registry1 has: (op1,domain1,version1), (op2,domain1,version1), (op2,domain2,version1)
//registry2 has:(op1,domain1,version2)
ASSERT_TRUE(registry2->GetSchema("Op1", 1, "Domain1") == nullptr);
ASSERT_TRUE(registry2->GetSchema("Op1", 2, "Domain1") != nullptr);
//Fail because this registery doesn't have the information of opset3
ASSERT_TRUE(registry2->GetSchema("Op1", 3, "Domain1") == nullptr);
std::shared_ptr<onnxruntime::OnnxRuntimeOpSchemaRegistry> registry3 = std::make_shared<OnnxRuntimeOpSchemaRegistry>();
ASSERT_STATUS_OK(registry3->RegisterOpSet(schemaV2, "Domain1", 1, 3));
//Now it's ok.
ASSERT_TRUE(registry3->GetSchema("Op1", 3, "Domain1") != nullptr);
ASSERT_TRUE(manager.GetSchema("Op1", 1, "Domain1")->since_version() == 1);
ASSERT_TRUE(manager.GetSchema("Op1", 2, "Domain1")->since_version() == 2);
ASSERT_TRUE(manager.GetSchema("Op2", 1, "Domain1")->since_version() == 1);
ASSERT_TRUE(manager.GetSchema("Op2", 2, "Domain1")->since_version() == 1);
// Add a new operator set which is verion 5, with a baseline of version 4, meaning that
// there is a gap at version 3.
std::shared_ptr<onnxruntime::OnnxRuntimeOpSchemaRegistry> registryV5 = std::make_shared<OnnxRuntimeOpSchemaRegistry>();
manager.RegisterRegistry(registryV5);
std::vector<ONNX_NAMESPACE::OpSchema> schemaV5 = {
CreateTestSchema("Op3", "Domain1", 4),
CreateTestSchema("Op4", "Domain1", 5),
CreateTestSchema("Op5", "Domain1", 1)};
ASSERT_STATUS_OK(registryV5->RegisterOpSet(schemaV5, "Domain1", 4, 5));
// Query the new version 5 op. This will be missing for earlier versions
ASSERT_TRUE(manager.GetSchema("Op4", 5, "Domain1")->since_version() == 5);
ASSERT_TRUE(manager.GetSchema("Op4", 4, "Domain1") == nullptr);
// The only schema with SinceVersion < 3 which can be queried as version 5 are those which are registered on
// the v5 registry itself. Those schema may be queried for any version between their sinceVersion and the
// opset's version.
ASSERT_TRUE(manager.GetSchema("Op1", 5, "Domain1") == nullptr);
ASSERT_TRUE(manager.GetSchema("Op3", 5, "Domain1")->since_version() == 4);
ASSERT_TRUE(manager.GetSchema("Op3", 4, "Domain1")->since_version() == 4);
// Note that "Op5" has SinceVersion equal to 1, but a V1 operator set was already registered
// without this operator. This would normally be invalid, and the registry with the missing
// operator could trigger the operator lookup to fail. Version 1 is a special case to allow
// for experimental operators, and is accomplished by not reducing the targetted version to
// zero in OnnxRuntimeOpSchemaRegistry::GetSchemaAndHistory.
// TODO - Consider making the registration algorithm robust to this invalid usage in general
ASSERT_TRUE(manager.GetSchema("Op5", 5, "Domain1")->since_version() == 1);
ASSERT_TRUE(manager.GetSchema("Op5", 1, "Domain1")->since_version() == 1);
} | 53.545455 | 155 | 0.74137 | [
"vector"
] |
a742bc62abfc163661f75ceff085b775248467b7 | 4,579 | cpp | C++ | OOP/Mathematic Relations/Mathematic Relations/Source.cpp | mitaka00/Sofia-University | 46e7153e9302428bbe14beec5a353f7a378ba912 | [
"MIT"
] | 3 | 2020-02-22T17:22:08.000Z | 2020-07-08T12:05:48.000Z | OOP/Mathematic Relations/Mathematic Relations/Source.cpp | mitaka00/Sofia-University | 46e7153e9302428bbe14beec5a353f7a378ba912 | [
"MIT"
] | null | null | null | OOP/Mathematic Relations/Mathematic Relations/Source.cpp | mitaka00/Sofia-University | 46e7153e9302428bbe14beec5a353f7a378ba912 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <tuple>
#include "BinaryRelation.h"
#include "KnowledgeBase.h"
using std::cout;
int main() {
//BinaryRelation examples
BinaryRelation<int,const char*> test1;
test1.addRelation(5, "five");
test1.addRelation(5, "funf");
test1.addRelation(6, "six");
test1.addRelation(7, "seven");
test1.addRelation(8, "eight");
test1.addRelation(9, "nine");
test1.addRelation(10, "ten");
BinaryRelation<int, const char*> test2;
test2.addRelation(15, "fifteen");
test2.addRelation(5, "five");
BinaryRelation<const char*, const char*> test3;
test3.addRelation("five", "pet");
test3.addRelation("funf", "pett");
test3.addRelation("six", "6");
test3.addRelation("two", "dve");
test3.addRelation("three", "tri");
cout << "test1= " << test1; //print test1
cout << "test2= " << test2; //print test2
cout << "test3= " << test3; //print test3
cout << "test1+test= " << test1 + test2; // print test1 + test2
cout << "test1^test2= " << (test1 ^ test2); // print test1 ^ test2
cout << "test1*test3= " << test1 * test3; // print test1 * test3
cout << "test1= " << test1; // print test1
cout << "!test1= " << !test1; //print !test1
if (test1(5, "five")) {
cout << "test1 relation contain (5,\"five\")\n"; //check ()operator
}
if (!test1(17, "seventeen")) {
cout << "test1 relation doesn't contain (17,\"seventeen\")\n"; //check ()operator
}
//check injection method
if (test1.injection()) {
cout << "test1 is injectable function\n";
}
else {
cout << "test1 is not an injectable function\n";
}
//check function method
if (test1.function()) {
cout << "test1 is a partial function\n";
}
else {
cout << "test1 is not a partial function\n";
}
std::vector<int> firstParamArray;
std::vector<const char*> secondParamArray;
firstParamArray = test1.dom();
secondParamArray = test1.ran();
//Show .dom() functionality
cout << "test1.dom()=";
for (int i = 0; i < firstParamArray.size(); i++)
{
cout << firstParamArray[i] << " ";
}
cout << std::endl;
//Show .ran() functionality
cout << "test1.ran()=";
for (int i = 0; i < secondParamArray.size(); i++)
{
cout << secondParamArray[i] << " ";
}
cout << std::endl;
//Show (U u) functionality
firstParamArray = test1("five");
cout << "test1(\"five\")=";
for (int i = 0; i < firstParamArray.size(); i++)
{
cout << firstParamArray[i] << " ";
}
cout << std::endl;
//Show [T t] functionality
secondParamArray = test1[5];
cout << "test1[5]=";
for (int i = 0; i < secondParamArray.size(); i++)
{
cout << secondParamArray[i] << " ";
}
cout << std::endl;
cout << std::endl;
//Show KnowledgeBase logic
BinaryRelation<int, const char*> test4;
test4.addRelation(10, "ten");
test4.addRelation(16, "sixteen");
KnowledgeBase<int, const char*> knowledge1;
knowledge1.addMember("firstMember", test1);
knowledge1.addMember("secondMember", BinaryRelation<int, const char*>());
test4.addRelation(5, "five");
KnowledgeBase<int, const char*> knowledge2;
knowledge2.addMember("firstMember", test2);
knowledge2.addMember("secondMember", test4);
knowledge2.addMember("thirdMember", BinaryRelation<int, const char*>());
cout << "knowledge1:\n" << knowledge1;
cout << "knowledge2:\n" << knowledge2;
cout << std::endl;
cout << "knowledge2.addRelation(20 ,\"twenty\")\n";
knowledge2.addRelation(20, "twenty");
cout << "knowledge2:\n" << knowledge2;
cout << std::endl;
cout << "knowledge1+knowledge2:\n" << knowledge1+knowledge2 << std::endl;
cout << "knowledge1^knowledge2:\n" << (knowledge1 ^ knowledge2) << std::endl;
cout << "knowledge1:\n" << knowledge1 << std::endl;
cout << "!knowledge1:\n" << !knowledge1;
cout << std::endl;
BinaryRelation<int, const char*> test5;
test5 = knowledge1.kb("firstMember");
cout << "Print relation with name: firstMember in knowledge1:\n" << test5;
test5 = knowledge1.kb("fifthMember");
cout << "Print relation with name: fifthMember in knowledge1:\n" << test5;
cout << std::endl;
cout << "knowledge1.injection():\n";
knowledge1.injection();
cout << "knowledge1.function():\n";
knowledge1.function();
cout << std::endl;
//Show (U u) functionality
firstParamArray = knowledge1("five");
cout << "knowledge1(\"five\")=";
for (int i = 0; i < firstParamArray.size(); i++)
{
cout << firstParamArray[i] << " ";
}
cout << std::endl;
//Show [T t] functionality
secondParamArray = knowledge1[5];
cout << "knowledge1[5]=";
for (int i = 0; i < secondParamArray.size(); i++)
{
cout << secondParamArray[i] << " ";
}
cout << std::endl;
return 0;
} | 27.094675 | 83 | 0.64228 | [
"vector"
] |
a751fc23f054fa538e2ebb3faf9cf749357b3a0d | 642 | cpp | C++ | CODEFORCES/Meximization.cpp | HassanRahim26/COMPETITIVE-PROGRAMMING | a2d13fd27cc5e3e78612a5be500ccbe57f9201b8 | [
"MIT"
] | 2 | 2021-07-31T15:40:56.000Z | 2021-08-25T10:04:00.000Z | CODEFORCES/Meximization.cpp | HassanRahim26/COMPETITIVE-PROGRAMMING | a2d13fd27cc5e3e78612a5be500ccbe57f9201b8 | [
"MIT"
] | null | null | null | CODEFORCES/Meximization.cpp | HassanRahim26/COMPETITIVE-PROGRAMMING | a2d13fd27cc5e3e78612a5be500ccbe57f9201b8 | [
"MIT"
] | null | null | null | /*
PROBLEM LINK:- https://codeforces.com/problemset/problem/1497/A
*/
#include<bits/stdc++.h>
#define ll long long
#define mod 1000000007
#define test ll t; cin >> t; while(t--)
#define FOR for(ll i = 0; i < n; i++)
#define vi vector<int>
#define nn "\n"
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
test
{
ll n, i;
cin >> n;
vi v(n);
FOR cin >> v[i];
sort(v.begin(), v.end());
for (i = 0; i < n; i++)
if (i == 0 || v[i] != v[i - 1])
cout << v[i] << ' ';
for (i = 0; i < n; i++)
if (i > 0 && v[i] == v[i - 1])
cout << v[i] << ' ';
cout << nn;
}
return 0;
}
| 16.461538 | 63 | 0.512461 | [
"vector"
] |
a754aad141ebc454de0ff95e4d6e3f0229cb22d3 | 320 | cpp | C++ | CodeChef/Practice/HS08TEST.cpp | builes/Challenges | b49c91957bcd6efc691ba36093bd53e50023110b | [
"MIT"
] | 1 | 2018-06-03T22:09:17.000Z | 2018-06-03T22:09:17.000Z | CodeChef/Practice/HS08TEST.cpp | builes/Challenges | b49c91957bcd6efc691ba36093bd53e50023110b | [
"MIT"
] | null | null | null | CodeChef/Practice/HS08TEST.cpp | builes/Challenges | b49c91957bcd6efc691ba36093bd53e50023110b | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <iomanip>
using namespace std;
int main(){
//Read()
int x;
double y;
cin >> x >> y;
//Code()
if(y > 0 && y - x - 0.50 >= 0){
if(x % 5 == 0){
y = y - x - 0.50;
}
}
cout<<fixed<<setprecision(2)<<y;
return 0;
}
| 11.428571 | 33 | 0.525 | [
"vector"
] |
a756ca96256fd7edf2ea899f29fe845c1b3a7205 | 1,855 | cpp | C++ | nets/Examples/Marsili_opt.cpp | CxAalto/lcelib | dceea76e3f18696a2fa7c8287e1a537fbf493474 | [
"0BSD"
] | 1 | 2017-01-24T01:35:43.000Z | 2017-01-24T01:35:43.000Z | nets/Examples/Marsili_opt.cpp | CxAalto/lcelib | dceea76e3f18696a2fa7c8287e1a537fbf493474 | [
"0BSD"
] | null | null | null | nets/Examples/Marsili_opt.cpp | CxAalto/lcelib | dceea76e3f18696a2fa7c8287e1a537fbf493474 | [
"0BSD"
] | null | null | null | /* Marsili_opt
2007 May 22
Author: Lauri Kovanen
Function for the optimization of Marsili et al. model. Generates a
Marsili network with given parameters and returns a line containing
[mean_degree clustering_coeff pearson_corr_coeff]
To compile: g++ -O -Wall Marsili_opt.cpp -o Marsili_opt
To run: ./Marsili_opt [params]
Example: ./Marsili_opt 8003 0.01 0.003 0.05 3892672 1400
[params] = N lambda eta xi randseed [maxiter]
(maxiter is an optional parameter. If not given,
the number of iterations will be determined dynamically.)
*/
//#define DEBUG // for debugging code to be run
#define NDEBUG // to turn assertions off
#include "../models/Marsili.H"
#include "../NetExtras.H"
#include "../NetExtrasB.H"
#include <time.h>
//typedef float EdgeData;
//typedef SymmNet<EdgeData> NetType;
typedef SymmNet<float, ValueTable, ExplSumTreeTable> _NetType;
int main(int argc, char* argv[]) {
struct MarsiliArgs args;
readMarsiliArgs(args, argc, argv);
RandNumGen<> generator(args.randseed);
_NetType net(args.netSize);
//time_t starttime = time(NULL);
// Generate the network
Marsili(net, args, generator);
//time_t endtime = time(NULL);
//std::cerr << "Time taken by generation: " << difftime(endtime, starttime) << " s\n";
std::auto_ptr<_NetType> netPointer2(findLargestComponent<_NetType>(net));
_NetType& net2 = *netPointer2; // Create a reference for easier handling of net.
double avg_clust = 0;
for (size_t i = 0; i < net2.size(); i++)
avg_clust += clusteringCoefficient(net2, i);
size_t edges = numberOfEdges(net2);
std::cout << net2.size() << " " << (double)2*edges/net2.size() << " " << avg_clust/net2.size() << " " << pearsonCoeff2(net2) << "\n";
}
| 30.409836 | 135 | 0.651752 | [
"model"
] |
a7571e2d47b03b8de0ebd2ed5df123d4c4402977 | 3,007 | cc | C++ | open_spiel/games/connect_four_test.cc | badlogicmanpreet/open_spiel | b1b321a57754df76309ed9d7ac3c9b449ed34901 | [
"Apache-2.0"
] | null | null | null | open_spiel/games/connect_four_test.cc | badlogicmanpreet/open_spiel | b1b321a57754df76309ed9d7ac3c9b449ed34901 | [
"Apache-2.0"
] | null | null | null | open_spiel/games/connect_four_test.cc | badlogicmanpreet/open_spiel | b1b321a57754df76309ed9d7ac3c9b449ed34901 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/games/connect_four.h"
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_utils.h"
#include "open_spiel/tests/basic_tests.h"
namespace open_spiel {
namespace connect_four {
namespace {
namespace testing = open_spiel::testing;
void BasicConnectFourTests() {
testing::LoadGameTest("connect_four");
testing::NoChanceOutcomesTest(*LoadGame("connect_four"));
testing::RandomSimTest(*LoadGame("connect_four"), 100);
}
void FastLoss() {
std::shared_ptr<const Game> game = LoadGame("connect_four");
auto state = game->NewInitialState();
state->ApplyAction(3);
state->ApplyAction(3);
state->ApplyAction(4);
state->ApplyAction(4);
state->ApplyAction(2);
state->ApplyAction(2);
SPIEL_CHECK_FALSE(state->IsTerminal());
state->ApplyAction(1);
SPIEL_CHECK_TRUE(state->IsTerminal());
SPIEL_CHECK_EQ(state->Returns(), (std::vector<double>{1.0, -1.0}));
SPIEL_CHECK_EQ(state->ToString(),
".......\n"
".......\n"
".......\n"
".......\n"
"..ooo..\n"
".xxxx..\n");
}
void BasicSerializationTest() {
std::shared_ptr<const Game> game = LoadGame("connect_four");
std::unique_ptr<State> state = game->NewInitialState();
std::unique_ptr<State> state2 = game->DeserializeState(state->Serialize());
SPIEL_CHECK_EQ(state->ToString(), state2->ToString());
}
void DeserializeDraw() {
std::shared_ptr<const Game> game = LoadGame("connect_four");
auto state = game->DeserializeState(
"ooxxxoo\n"
"xxoooxx\n"
"ooxxxoo\n"
"xxoooxx\n"
"ooxxxoo\n"
"xxoooxx\n");
SPIEL_CHECK_EQ(state->ToString(),
"ooxxxoo\n"
"xxoooxx\n"
"ooxxxoo\n"
"xxoooxx\n"
"ooxxxoo\n"
"xxoooxx\n");
SPIEL_CHECK_TRUE(state->IsTerminal());
SPIEL_CHECK_EQ(state->Returns(), (std::vector<double>{0, 0}));
}
void Benchmark() {
testing::RandomSimBenchmark("connect_four", 10000);
}
} // namespace
} // namespace connect_four
} // namespace open_spiel
int main(int argc, char **argv) {
open_spiel::connect_four::BasicConnectFourTests();
open_spiel::connect_four::FastLoss();
open_spiel::connect_four::BasicSerializationTest();
open_spiel::connect_four::DeserializeDraw();
open_spiel::connect_four::Benchmark();
}
| 31 | 77 | 0.660459 | [
"vector"
] |
a75dddc851661add1fcb0dc08fda8fa080c610d1 | 9,363 | cc | C++ | tools/src/vcf2genomicsdb.cc | GenomicsDB/GenomicsDB | 6069e4a2f31823af48d845b384fb3d0a9f5fa941 | [
"Intel",
"MIT"
] | 72 | 2018-11-23T13:08:39.000Z | 2022-03-20T10:07:17.000Z | tools/src/vcf2genomicsdb.cc | GenomicsDB/GenomicsDB | 6069e4a2f31823af48d845b384fb3d0a9f5fa941 | [
"Intel",
"MIT"
] | 182 | 2018-08-24T22:07:37.000Z | 2022-03-13T07:38:01.000Z | tools/src/vcf2genomicsdb.cc | GenomicsDB/GenomicsDB | 6069e4a2f31823af48d845b384fb3d0a9f5fa941 | [
"Intel",
"MIT"
] | 17 | 2019-01-14T08:19:06.000Z | 2021-09-15T02:42:59.000Z | /**
* The MIT License (MIT)
* Copyright (c) 2016-2017 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "vcf2binary.h"
#include "tiledb_loader.h"
#include <mpi.h>
#include <getopt.h>
#ifdef USE_GPERFTOOLS
#include "gperftools/profiler.h"
#endif
extern bool g_show_import_progress;
extern int g_progress_interval;
static Logger g_logger(Logger::get_logger("vcf2genomicsdb"));
enum VCF2TileDBArgsEnum {
VCF2TILEDB_ARG_SPLIT_FILES_IDX=1000,
VCF2TILEDB_ARG_SPLIT_FILES_PRODUCE_ALL_PARTITIONS_IDX,
VCF2TILEDB_ARG_SPLIT_FILES_RESULTS_DIRECTORY_IDX,
VCF2TILEDB_ARG_SPLIT_FILES_SPLIT_OUTPUT_FILENAME_IDX,
VCF2TILEDB_ARG_SPLIT_FILES_SPLIT_CALLSET_MAPPING_IDX,
VCF2TILEDB_ARG_VERSION
};
void print_usage(){
std::cerr << "Usage vcf2genomicsdb [options] <loader_json_config_file>\n"
<< "where options include:\n"
<< "\t--help, -h\n"
<< "\t--version\n"
<< "\t--progress, -p Show import progress\n"
<< "\t\tspecify minimum amount of time between progress messages with --progress=<interval> or -p<interval>\n"
<< "\t\twhere <interval> is a floating point number. Default units are seconds, explicitly specify seconds, minutes, or hours by appending s, m, or h to the end of the number\n"
<< "\t--tmp-directory, -T Specify temporary directory (stores some temporary files during the import process, default is " << g_tmp_scratch_dir << ")\n"
<< "\t--rank, -r Manually assign MPI rank of process, determines on which partition the process will operate\n"
<< "\t--split-files Split the files specified by the callset mapping JSON file according to the column partitions in the loader JSON\n"
<< "\t\tresulting files will be placed in the same directory as the originals\n"
<< "\t\tdefault behavior is to generate split files only for the partition corresponding to the rank\n"
<< "\tModifiers to --split-files:\n"
<< "\t\t--split-all-partitions Overrides --split-files default behavior and instead creates split files for all partitions\n"
<< "\t\t--split-files-results-directory Specify where to place split files, overrides default behavior of placing them in the same directory as originals\n"
<< "\t\t--split-output-filename Create a split file for one column partition and one VCF\n"
<< "\t\t\te.g. vcf2genomicsdb <loader.json> --rank=<rank> --split-files --split-output-filename=<output_path> <input.vcf.gz>\n"
<< "\t\t--split-callset-mapping-file Create callset mapping files containing the paths to the generated split files, one callset per partition\n" << std::endl;
}
int main(int argc, char** argv) {
#ifdef DEBUG
spdlog::set_level(spdlog::level::debug);
#endif
g_show_import_progress = false;
//Initialize MPI environment
auto rc = MPI_Init(0, 0);
if (rc != MPI_SUCCESS) {
printf ("Error starting MPI program. Terminating.\n");
MPI_Abort(MPI_COMM_WORLD, rc);
}
//Get my world rank
int my_world_mpi_rank = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &my_world_mpi_rank);
// Define long options
static struct option long_options[] = {
{"tmp-directory",1,0,'T'},
{"rank",1,0,'r'},
{"help",0,0,'h'},
{"progress",2,0,'p'},
{"split-files",0,0,VCF2TILEDB_ARG_SPLIT_FILES_IDX},
{"split-all-partitions",0,0,VCF2TILEDB_ARG_SPLIT_FILES_PRODUCE_ALL_PARTITIONS_IDX},
{"split-files-results-directory",1,0,VCF2TILEDB_ARG_SPLIT_FILES_RESULTS_DIRECTORY_IDX},
{"split-output-filename",1,0,VCF2TILEDB_ARG_SPLIT_FILES_SPLIT_OUTPUT_FILENAME_IDX},
{"split-callset-mapping-file",0,0,VCF2TILEDB_ARG_SPLIT_FILES_SPLIT_CALLSET_MAPPING_IDX},
{"version",0,0,VCF2TILEDB_ARG_VERSION},
{0,0,0,0},
};
int c;
auto split_files = false;
auto produce_all_partitions = false;
std::string results_directory;
std::string split_output_filename;
auto split_callset_mapping_file = false;
auto print_version_only = false;
while ((c=getopt_long(argc, argv, "T:r:hp::", long_options, NULL)) >= 0) {
switch (c) {
case 'T':
g_tmp_scratch_dir = optarg;
break;
case 'r':
my_world_mpi_rank = strtol(optarg, 0, 10);
break;
case 'h':
print_usage();
exit(0);
case 'p':
if (optarg) {
try {
int unit_multiplier = 1;
std::string optstring(optarg);
switch(optstring.back()){
case 's': optstring.pop_back(); break;
case 'm': unit_multiplier=60; optstring.pop_back(); break;
case 'h': unit_multiplier=3600; optstring.pop_back(); break;
}
g_progress_interval = (int)(std::stod(std::string(optarg)) * 1000 * unit_multiplier);
}
catch ( std::exception& e ) {
g_progress_interval = 5000;
}
}
else {
g_progress_interval = 5000;
}
g_show_import_progress = true;
break;
case VCF2TILEDB_ARG_SPLIT_FILES_IDX:
split_files = true;
break;
case VCF2TILEDB_ARG_SPLIT_FILES_PRODUCE_ALL_PARTITIONS_IDX:
produce_all_partitions = true;
break;
case VCF2TILEDB_ARG_SPLIT_FILES_RESULTS_DIRECTORY_IDX:
results_directory = optarg;
break;
case VCF2TILEDB_ARG_SPLIT_FILES_SPLIT_OUTPUT_FILENAME_IDX:
split_output_filename = optarg;
break;
case VCF2TILEDB_ARG_SPLIT_FILES_SPLIT_CALLSET_MAPPING_IDX:
split_callset_mapping_file = true;
break;
case VCF2TILEDB_ARG_VERSION:
std::cout << GENOMICSDB_VERSION <<"\n";
print_version_only = true;
break;
default:
std::cerr << "Unknown parameter "<< argv[optind] << "\n";
print_usage();
exit(-1);
}
}
if (!print_version_only) {
if (optind+1 > argc) {
print_usage();
exit(-1);
}
auto loader_json_config_file = std::move(std::string(argv[optind]));
#ifdef USE_GPERFTOOLS
ProfilerStart("gprofile.log");
#endif
//Split files as per the partitions defined - don't load data
if (split_files) {
std::cout << "Split files" << std::endl;
GenomicsDBImportConfig loader_config;
loader_config.read_from_file(loader_json_config_file, my_world_mpi_rank);
if (loader_config.is_partitioned_by_row()) {
std::cerr << "Splitting is available for column partitioning, row partitioning should be trivial if samples are scattered across files. See wiki page https://github.com/Intel-HLS/GenomicsDB/wiki/Dealing-with-multiple-GenomicsDB-partitions for more information\n";
return 0;
}
VidMapper id_mapper = loader_config.get_vid_mapper(); //copy
//Might specify more VCF files from the command line
for (auto i=optind+1; i<argc; ++i)
id_mapper.get_or_append_global_file_idx(argv[i]);
//Single split output
if (!produce_all_partitions && id_mapper.get_num_files() == 1u && !split_output_filename.empty())
id_mapper.set_single_split_file_path(0u, split_output_filename);
std::vector<std::vector<uint8_t>> empty_buffers;
std::vector<LoaderConverterMessageExchange> empty_exchange;
const auto& column_partitions = loader_config.get_sorted_column_partitions();
auto loop_bound = (produce_all_partitions ? column_partitions.size() : 1u);
for (auto i=0ull; i<loop_bound; ++i) {
int rank = produce_all_partitions ? i : my_world_mpi_rank;
VCF2TileDBConverter converter(loader_config, rank,
&empty_buffers, &empty_exchange);
converter.print_all_partitions(results_directory, "", rank);
if (split_callset_mapping_file)
id_mapper.write_partition_callsets_json_file(loader_config.get_callset_mapping_file(), results_directory, rank);
}
if (split_callset_mapping_file)
id_mapper.write_partition_loader_json_file(loader_json_config_file, loader_config.get_callset_mapping_file(),
results_directory, (produce_all_partitions ? column_partitions.size() : 1u), my_world_mpi_rank);
} else {
//Loader object
VCF2TileDBLoader loader(loader_json_config_file, my_world_mpi_rank);
loader.read_all();
}
#ifdef USE_GPERFTOOLS
ProfilerStop();
#endif
}
//finalize
MPI_Finalize();
return 0;
}
| 43.752336 | 271 | 0.691765 | [
"object",
"vector"
] |
a75f75dab0e24e494392fb96883142063038a77e | 3,428 | cpp | C++ | tf2_src/game/server/tf2/order_repair.cpp | IamIndeedGamingAsHardAsICan03489/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 4 | 2021-10-03T05:16:55.000Z | 2021-12-28T16:49:27.000Z | tf2_src/game/server/tf2/order_repair.cpp | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | null | null | null | tf2_src/game/server/tf2/order_repair.cpp | Counter2828/TeamFortress2 | 1b81dded673d49adebf4d0958e52236ecc28a956 | [
"MIT"
] | 3 | 2022-02-02T18:09:58.000Z | 2022-03-06T18:54:39.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "order_repair.h"
#include "tf_team.h"
#include "tf_class_defender.h"
#include "order_helpers.h"
#include "tf_obj.h"
IMPLEMENT_SERVERCLASS_ST( COrderRepair, DT_OrderRepair )
END_SEND_TABLE()
static int SortFn_Defender( void *pUserData, int a, int b )
{
CSortBase *p = (CSortBase*)pUserData;
const Vector &vOrigin1 = p->m_pPlayer->GetTFTeam()->GetObject( a )->GetAbsOrigin();
const Vector &vOrigin2 = p->m_pPlayer->GetTFTeam()->GetObject( b )->GetAbsOrigin();
return p->m_pPlayer->GetAbsOrigin().DistTo( vOrigin1 ) < p->m_pPlayer->GetAbsOrigin().DistTo( vOrigin2 );
}
static bool IsValidFn_RepairFriendlyObjects( void *pUserData, int a )
{
// Only pick objects that are damaged.
CSortBase *p = (CSortBase*)pUserData;
CBaseObject *pObj = p->m_pPlayer->GetTFTeam()->GetObject( a );
// Skip objects under construction
if ( pObj->IsBuilding() )
return false;
return ( pObj->m_iHealth < pObj->m_iMaxHealth );
}
static bool IsValidFn_RepairOwnObjects( void *pUserData, int a )
{
// Only pick objects that are damaged.
CSortBase *pSortBase = (CSortBase*)pUserData;
CBaseObject *pObj = pSortBase->m_pPlayer->GetObject(a);
// Skip objects under construction
if ( !pObj || pObj->IsBuilding() )
return false;
return pObj->m_iHealth < pObj->m_iMaxHealth;
}
bool COrderRepair::CreateOrder_RepairFriendlyObjects( CPlayerClassDefender *pClass )
{
if( !pClass->CanBuildSentryGun() )
return false;
CBaseTFPlayer *pPlayer = pClass->GetPlayer();
CTFTeam *pTeam = pClass->GetTeam();
// Sort the list and filter out fully healed objects..
CSortBase info;
info.m_pPlayer = pPlayer;
int sorted[MAX_TEAM_OBJECTS];
int nSorted = BuildSortedActiveList(
sorted,
MAX_TEAM_OBJECTS,
SortFn_Defender,
IsValidFn_RepairFriendlyObjects,
&info,
pTeam->GetNumObjects() );
// If the player is close enough to the closest damaged object, issue an order.
if( nSorted )
{
CBaseObject *pObjToHeal = pTeam->GetObject( sorted[0] );
static float flClosestDist = 1024;
if( pPlayer->GetAbsOrigin().DistTo( pObjToHeal->GetAbsOrigin() ) < flClosestDist )
{
COrder *pOrder = new COrderRepair;
pTeam->AddOrder(
ORDER_REPAIR,
pObjToHeal,
pPlayer,
1e24,
60,
pOrder
);
return true;
}
}
return false;
}
bool COrderRepair::CreateOrder_RepairOwnObjects( CPlayerClass *pClass )
{
CSortBase info;
info.m_pPlayer = pClass->GetPlayer();
int sorted[16];
int nSorted = BuildSortedActiveList(
sorted,
sizeof( sorted ) / sizeof( sorted[0] ),
SortFn_PlayerObjectsByDistance,
IsValidFn_RepairOwnObjects,
&info,
info.m_pPlayer->GetObjectCount() );
if( nSorted )
{
// Make an order to repair the closest damaged object.
CBaseObject *pObj = info.m_pPlayer->GetObject( sorted[0] );
if (!pObj)
return false;
COrderRepair *pOrder = new COrderRepair;
info.m_pPlayer->GetTFTeam()->AddOrder(
ORDER_REPAIR,
pObj,
info.m_pPlayer,
1e24,
60,
pOrder
);
return true;
}
else
{
return false;
}
}
bool COrderRepair::Update()
{
CBaseEntity *pEnt = GetTargetEntity();
if( !pEnt )
return true;
// Kill the order when the object is repaired.
return pEnt->m_iHealth >= pEnt->m_iMaxHealth;
}
| 21.696203 | 106 | 0.683489 | [
"object",
"vector"
] |
a75fd4c0daaa77313237f9f68fa13e3b746b573c | 9,173 | cpp | C++ | LocalizationNotes/MarkovLocalizationIntro.cpp | ahtchow/CarND-ParticleFilters-P5 | afb0616926dcb313e6371fdf41f5cae03c86d02b | [
"MIT"
] | null | null | null | LocalizationNotes/MarkovLocalizationIntro.cpp | ahtchow/CarND-ParticleFilters-P5 | afb0616926dcb313e6371fdf41f5cae03c86d02b | [
"MIT"
] | null | null | null | LocalizationNotes/MarkovLocalizationIntro.cpp | ahtchow/CarND-ParticleFilters-P5 | afb0616926dcb313e6371fdf41f5cae03c86d02b | [
"MIT"
] | null | null | null | /**
* @file MarkovLocalization.cpp
* @author Adrian Chow
* @brief Markov Localization
* @version 0.1
* @date 2020-03-12
*
* @copyright Copyright (c) 2020
*
*/
/**
* @brief Formal Definition of Variables
* Known:
* @param z(1:t) represents the observation vector from time 0 to t
* (range measurements, bearing, images, etc.).
* @param u(1:t) represents the control vector from time 0 to t
* (yaw/pitch/roll rates and velocities).
* @param m represents the map (grid maps, feature maps, landmarks)
*
* Unknown:
* @param x(t) represents the pose (position (x,y) + orientation \thetaθ)
*
* Localization is all about estimating the pose of car (x(t)) based on
* previous measurements from 0 to t
*
* Thus we use the Posterior Distribution:
* bel(x(t)) = p( Xt | z(1:t), u(1:t))
*
* We will solve the mapping issue and localization issue:
*
* m -> Mapping feauture map (1-D)
* 0m - Pole (9m) - Pole(15m) - Tree(25m) - Tree(31m)
* m = [0,9,15,25,31]
*
* z(1:t) -> Observation List (Assume can see distance)
* z(1:t) = {zt.....,z1} - A list of timestamps
* zt = [zt1,...,ztk] - A vector of distnaces
*
* u(1:t) -> Control Vector
* u(1:t) = [ut,...,u1] - A vector of distances traveled between timestamps
* t-1 -------- 2m ---------> t
*
* OVERALL: belief(xt) = [belief(xt = 0) ,......, belief(xt = 99)]
*
*/
/**
* @brief BAYES RULE
*
* Bayes' Rule enables us to determine the conditional probability
* of a state given evidence P(a|b) by relating it to the
* conditional probability of the evidence given the state
* P(b|a) in the form of:
*
* P(a\b) = (P(b|a) * P(a)) / P(b)
*
* P(B|A) => P(B|A) * P(A)
* P(A)<
* P(B|!A) => P(B|!A) * P(A)
* P <
* P(A|B) => P(A|B) * P(B)
* P(B)<
* P(A|!B) => P(A|!B) * P(B)
*
* We can apply Bayes' Rule to vehicle localization by passing
* variables through Bayes' Rule for each time step, as our
* vehicle moves.
*
* For: P(a\b) = (P(b|a) * P(a)) / P(b)
*
* 1. P(location∣ observation):
* This is P(a|b), the normalized probability
* of a position given an observation (posterior).
*
* 2. P(observation∣location):
* This is P(b|a), the probability of an
* observation given a position (likelihood).
*
* 3. P(location):
* This is P(a), the prior probability of a position
*
* 4. P(observation):
* This is P(b), the probability of an observation
*
* P(location) is determined by the motion model. The probability
* returned by the motion model is the product of the transition
* model probability (the probability of moving from
* x(t−1) --> x(t) and the probability of the state x(t−1).
*
* As a result:
* P(location|observation) = P(observation|location)* P(location)/ P(observation)
*
*/
/**
* @brief BAYES FILTER
*
* To build a bayes filter you must:
* 1. Compute Bayes’ rule
* 2. Calculate Bayes' posterior for localization
* 3. Initialize a prior belief state
* 4. Create a function to initialize a prior belief state
* given landmarks and assumptions
*
* P(location|observation) = P(observation|location)* P(location)/ P(observation)
*
* P(obs|loc) => P(obs|loc) * P(loc)
* P(loc)<s
* P(obs|!loc) => P(obs|!loc) * P(loc)
* P <
* P(loc|obs) => P(loc|obs) * P(obs)
* P(obs)<
* P(loc|!obs) => P(loc|!obs) * P(obs)
*
* Raw P(Posterior) = P(loc|obs) * P(obs)
* Normalized P(Posterior) = P(loc|obs)
*
* @brief Initialize Belief State
* what values should our initial belief state take for each possible position?
* Let's say we have a 1D map extending from 0 to 25 meters.
*
* Landmarks @ 5.0 , 10.0 & 20.0 with S.D of 1 meters
*
* thus we have chances to be at:
* [4,5,6,9,10,11,19,20,21] out of [1-25] or 1/11
*
* {0, 0, 0, 1.11E-01, 1.11E-01, 1.11E-01, 0, 0, 1.11E-01, 1.11E-01,
* 1.11E-01, 0, 0, 0, 0, 0, 0, 0, 1.11E-01, 1.11E-01, 1.11E-01, 0, 0, 0, 0}
*
*
*/
/***************************************************************************
* CODE TIME
* *************************************************************************/
/**
* @brief We will create a function that initializes priors (initial belief for each
* position on the map) given a standard deviation of +/- 1 and the assumption that
* our car is parked next to a landmark
*
* We input a control of moving 1 step but our actual movement could be in the range
* of 1 +/- control standard deviation. The position SD is a spread of actual position.
*
* For example, we may believe start at a particular location, but we could be anywhere
* in that location +/- our position standard deviation.
*
*/
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
// initialize priors assuming vehicle at landmark +/- 1.0 meters position stdev
vector<float> initialize_priors(int map_size, vector<float> landmark_positions,
float position_stdev);
int main() {
// set standard deviation of position
float position_stdev = 1.0f;
// set map horizon distance in meters
int map_size = 25;
// initialize landmarks
vector<float> landmark_positions {5, 10, 20};
// initialize priors
vector<float> priors = initialize_priors(map_size, landmark_positions,
position_stdev);
// print values to stdout
for (int p = 0; p < priors.size(); ++p) {
std::cout << priors[p] << std::endl;
}
return 0;
}
// TODO: Complete the initialize_priors function
vector<float> initialize_priors(int map_size, vector<float> landmark_positions,
float position_stdev) {
// initialize priors assuming vehicle at landmark +/- 1.0 meters position stdev
// set all priors to 0.0
vector<float> priors(map_size, 0.0);
float denom = float(landmark_positions.size() * (1+position_stdev*2));
float probability = 1/denom;
int length = 0;
for(int i = 0; i < map_size; i++){
if(i == landmark_positions[length]){
priors[i] += probability;
priors[i-1] += probability;
priors[i+1] += probability;
length++;
}
return priors;
}
/**
* @brief How much data does Z(1:t) contain?
* - w/ each refresh rate LiDAR sends 100,000 data points
* - each data point has 5 data pieces (id, range, 2 angles, reflectivity)
* - each data piece is 4 bytes.
* - Update at 10Hz per second
*
* 6 hours(10Hz/s) can generate 432 GB of data.
*
* Two problems if we want to estimate bel(x(t)) directly
* 1. A lot of data
* 2. Amount of data increases over time
*/
/**
* @brief Definition fo Localization Posterior: P(loc|observation)
*
* bel(x(t)) = p( x(t) | z(1:t), u(1:t), m)
*
* We do not want to store all observations, but rather update the
* state estimator recursively w/ new observation.
*
* WE CALL THIS; MARKOV LOCALIZATION
* achieved using:
* 1. Bayes Rule
* 2. Law of Total Probability
* 3. Markov Assumption
*
* Also we must split z(1:t) to z(t), z(1:t-1) as current obs and prev obs
* in bel(x(t)) = p( x(t) | z(t), z(1:t-1), u(1:t) , m)
*
* BAYES RULE:
* bel(x(t)|z(t)) = p( z(t) | x(t), z(1:t-1), u(1:t) , m) *
* p( x(t) | z(1:t-1), u(1:t) , m) /
* p( z(t) | z(1:t-1), u(1:t) , m)
*
* P(loc) = P(x(t)) , P(obs) = P(z(t))
*
* LAW OF TOTAL PROBABILITY: P(A) = ∑ P(B|A) * P(B)
*
* p( x(t) | z(1:t-1), u(1:t) , m)
* = ∑ p( x(t) | x(t-1), z(1:t-1), u(1:t) , m) *
* p( x(t-1) | z(1:t-1), u(1:t) , m)
*
*
* MARKOV ASSUMPTION:
* 1. Since we (hypothetically) know in which state the system is at time step t-1,
* the past observations z_{1:t-1} and controls u{1:t-1} would not provide new info.
*
* Thus p( x(t) | x(t-1), z(1:t-1), u(1:t) , m) can be simplified to
* p( x(t) | x(t-1), u(t), m) (TRANSITION/SYSTEM MODEL)
*
* or simply: P(x(t)|x(1:t-1)) = P(x(t)|x(t-1))
*
* 2. Since u(t) is “in the future” with reference to x{t-1}, u(t)
* does not tell us much about x{t-1}.
*
* Thus p (x(t-1)| z(1:t-1) , u(1:t), m ) can be simplified to
* p (x(t-1)| z(1:t-1) , u(1:t-1), m )
*
* OVERALL:
* P(x(t)|z(1:t-1), u(1:t), m) =
* ∫ p( x(t) | x(t-1), u(t), m) * p (x(t-1)| z(1:t-1) , u(1:t-1), m ) dx(t-1)
* = ∫ p( x(t) | x(t-1), u(t), m) * bel(x(t-1)) dx(t-1) (Recursive Case)
* = ∑ p( x(t) | x(t-1), u(t), m) * bel(x(t-1)) (Discrete Case)
*
* After applying the Markov Assumption, the term p(x{t-1} | z{1:t-1}, u{1:t-1}, m)
* describes exactly the belief at x{t-1}. This means we achieved a
* recursive structure!
*
* The prediction of x(t) should simply reply on the previous belief
* bel(x(t-1)) , the current control state u(t) and the map m.
*
* */
| 32.528369 | 88 | 0.557833 | [
"vector",
"model"
] |
a766eed16629d3b3f616b9f9761d48419946fcd2 | 1,280 | cpp | C++ | TabGraph/src/Parser/BinaryData.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | 1 | 2020-08-28T09:35:18.000Z | 2020-08-28T09:35:18.000Z | TabGraph/src/Parser/BinaryData.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | null | null | null | TabGraph/src/Parser/BinaryData.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | 1 | 2020-10-08T11:21:13.000Z | 2020-10-08T11:21:13.000Z | /*
* @Author: gpinchon
* @Date: 2021-02-03 17:50:02
* @Last Modified by: gpinchon
* @Last Modified time: 2021-02-03 17:50:55
*/
#include "Assets/Asset.hpp"
#include "Assets/AssetsParser.hpp"
#include "Assets/BinaryData.hpp"
#include "Assets/Uri.hpp"
#include <fstream>
void ParseBinaryData(const std::shared_ptr<Asset>&);
auto bufferMime { AssetsParser::AddMimeExtension("application/octet-stream", ".bin") };
auto bufferParser { AssetsParser::Add("application/octet-stream", ParseBinaryData) };
void ParseBinaryData(const std::shared_ptr<Asset>& asset)
{
std::shared_ptr<BinaryData> binaryData;
{
auto uri { asset->GetUri() };
std::vector<std::byte> data;
if (uri.GetScheme() == "data") {
data = DataUri(uri).Decode();
} else {
auto path{ uri.DecodePath() };
auto size{ std::filesystem::file_size(path) };
data.resize(size);
std::ifstream file(path, std::ios::binary);
file.read(reinterpret_cast<char*>(data.data()), data.size());
}
binaryData = Component::Create<BinaryData>(data);
}
asset->SetComponent(binaryData);
asset->SetAssetType(BinaryData::AssetType);
asset->SetLoaded(true);
} | 32 | 88 | 0.619531 | [
"vector"
] |
a76f36a826e51010868f4f57494f40c8fdb97603 | 5,505 | cc | C++ | mindspore/ccsrc/plugin/device/ascend/optimizer/ir_fission/seed_adapter.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/ccsrc/plugin/device/ascend/optimizer/ir_fission/seed_adapter.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/plugin/device/ascend/optimizer/ir_fission/seed_adapter.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "plugin/device/ascend/optimizer/ir_fission/seed_adapter.h"
#include <string>
#include <vector>
#include <memory>
#include "backend/common/optimizer/helper.h"
#include "kernel/kernel_build_info.h"
#include "include/common/utils/utils.h"
#include "utils/trace_base.h"
#include "backend/common/session/kernel_graph.h"
#include "backend/common/session/anf_runtime_algorithm.h"
#include "include/common/utils/anfalgo.h"
#include "runtime/device/kernel_info.h"
#include "kernel/oplib/oplib.h"
namespace mindspore::opt {
namespace {
tensor::TensorPtr CreateTensor(int64_t seed) {
// 1 create seed tensor
std::vector<int64_t> indices_shape = {1};
TensorTypePtr tensor_type = std::make_shared<TensorType>(kInt64);
MS_EXCEPTION_IF_NULL(tensor_type);
tensor::DeviceInfo device_info{kOpFormat_DEFAULT, tensor_type};
tensor::TensorPtr indices_tensor = std::make_shared<tensor::Tensor>(kInt64->type_id(), indices_shape);
MS_EXCEPTION_IF_NULL(indices_tensor);
indices_tensor->set_device_info(device_info);
// 2 set value of tensor
auto data_ptr = indices_tensor->data_c();
MS_EXCEPTION_IF_NULL(data_ptr);
auto ptr = static_cast<int64_t *>(data_ptr);
*ptr = seed;
return indices_tensor;
}
ValueNodePtr CreateValueNode(int64_t seed) {
tensor::TensorPtr tensor = CreateTensor(seed);
MS_EXCEPTION_IF_NULL(tensor);
auto value_node = std::make_shared<ValueNode>(tensor);
MS_EXCEPTION_IF_NULL(value_node);
auto abstract = tensor->ToAbstract();
value_node->set_abstract(abstract);
auto indices_kernel_info = std::make_shared<device::KernelInfo>();
MS_EXCEPTION_IF_NULL(indices_kernel_info);
value_node->set_kernel_info(indices_kernel_info);
kernel::KernelBuildInfo::KernelBuildInfoBuilder builder;
builder.SetOutputsFormat({kOpFormat_DEFAULT});
builder.SetOutputsDeviceType({kNumberTypeInt64});
AnfAlgo::SetSelectKernelBuildInfo(builder.Build(), value_node.get());
return value_node;
}
std::vector<ValueNodePtr> ConvertAttrToValueNode(const std::shared_ptr<kernel::OpInfo> &op_info,
const CNodePtr &cnode) {
MS_EXCEPTION_IF_NULL(op_info);
MS_EXCEPTION_IF_NULL(cnode);
// get seed
std::vector<ValueNodePtr> ret = {};
auto attrs = op_info->attrs_ptr();
if (attrs.empty()) {
MS_LOG(EXCEPTION) << "Node(" << cnode->DebugString() << ") doesn't have any attrs."
<< trace::DumpSourceLines(cnode);
}
for (const auto &attr : attrs) {
if (!common::AnfAlgo::HasNodeAttr(attr->name(), cnode)) {
MS_LOG(EXCEPTION) << "Node(" << cnode->DebugString() << ") doesn't have attr(" << attr->name() << ")."
<< trace::DumpSourceLines(cnode);
}
auto attr_value = common::AnfAlgo::GetNodeAttr<int64_t>(cnode, attr->name());
auto value_node = CreateValueNode(attr_value);
if (value_node == nullptr) {
MS_LOG(EXCEPTION) << "Create value node error, node: " << cnode->DebugString() << ", seed value: " << attr_value
<< trace::DumpSourceLines(cnode);
}
(void)ret.emplace_back(value_node);
}
if (ret.empty()) {
MS_LOG(EXCEPTION) << "Node(" << cnode->DebugString() << ") doesn't have any matched attrs."
<< trace::DumpSourceLines(cnode);
}
return ret;
}
} // namespace
const BaseRef SeedAdapter::DefinePattern() const {
std::shared_ptr<Var> V = std::make_shared<CondVar>(UnVisited);
std::shared_ptr<Var> Xs = std::make_shared<SeqVar>();
return VectorRef({V, Xs});
}
// This pass in ordr to convert attr seed to value node
// exp: DropoutGenMask
// |input0 |input1 |input0 |input1 |s0 |s1
// DropoutGenMask(seed0/seed1) ---> DropoutGenMask(seed0/seed1)
// | |
const AnfNodePtr SeedAdapter::Process(const FuncGraphPtr &func_graph, const AnfNodePtr &node, const EquivPtr &) const {
MS_EXCEPTION_IF_NULL(func_graph);
auto kernel_graph = func_graph->cast<KernelGraphPtr>();
MS_EXCEPTION_IF_NULL(kernel_graph);
MS_EXCEPTION_IF_NULL(node);
auto cnode = node->cast<CNodePtr>();
MS_EXCEPTION_IF_NULL(cnode);
auto cnode_type = common::AnfAlgo::GetCNodeName(node);
if (kNodeWithSeedOperators.find(cnode_type) == kNodeWithSeedOperators.end()) {
return nullptr;
}
// 1. convert attr seed to value node
auto op_info = kernel::OpLib::FindOp(cnode_type, kernel::OpImplyType::kAICPU);
if (!op_info) {
MS_LOG(EXCEPTION) << "Find op info failed, node type: " << cnode_type << ", node debug: " << cnode->DebugString();
}
auto value_nodes = ConvertAttrToValueNode(op_info, cnode);
for (auto &value_node : value_nodes) {
cnode->add_input(value_node);
kernel_graph->AddValueNodeToGraph(value_node);
}
// 2. set visited
common::AnfAlgo::SetNodeAttr(kAttrVisited, MakeValue(true), node);
return node;
}
} // namespace mindspore::opt
| 40.477941 | 119 | 0.698456 | [
"vector"
] |
a76f917c8326355fc1bb3eb63427fa1001ee21ed | 2,153 | cpp | C++ | falkon/ooc_ops/multigpu/cuda_bind.cpp | gpleiss/falkon | 36aa6713aff8ee6b9ad922d48b07c994fce30559 | [
"MIT"
] | 1 | 2021-11-10T16:50:53.000Z | 2021-11-10T16:50:53.000Z | falkon/ooc_ops/multigpu/cuda_bind.cpp | gpleiss/falkon | 36aa6713aff8ee6b9ad922d48b07c994fce30559 | [
"MIT"
] | null | null | null | falkon/ooc_ops/multigpu/cuda_bind.cpp | gpleiss/falkon | 36aa6713aff8ee6b9ad922d48b07c994fce30559 | [
"MIT"
] | null | null | null | #include <vector>
#include <tuple>
#include <torch/extension.h>
#include <pybind11/stl.h>
#include <cusolverDn.h>
#include "cuda/multigpu_potrf.cuh"
#include "cuda/lauum.cuh"
static void* ctypes_void_ptr(const py::object& object) {
PyObject *p_ptr = object.ptr();
if (!PyObject_HasAttr(p_ptr, PyUnicode_FromString("value"))) {
return nullptr;
}
PyObject *ptr_as_int = PyObject_GetAttr(p_ptr, PyUnicode_FromString("value"));
if (ptr_as_int == Py_None) {
return nullptr;
}
void *ptr = PyLong_AsVoidPtr(ptr_as_int);
return ptr;
}
torch::Tensor parallel_potrf(
std::vector<std::tuple<float, py::object, int>> gpu_info,
std::vector<std::tuple<int, int, int, int, int>> allocations,
torch::Tensor A) {
std::vector<blockAlloc> out_allocs;
for (std::tuple<int, int, int, int, int> ba_tpl : allocations) {
blockAlloc ba = {
.start =std::get<0>(ba_tpl),
.end =std::get<1>(ba_tpl),
.size =std::get<2>(ba_tpl),
.device=std::get<3>(ba_tpl),
.id =std::get<4>(ba_tpl)
};
out_allocs.push_back(ba);
}
auto ctypes = py::module::import("ctypes");
std::vector<gpuInfo> out_gpu_info;
for (auto &gi_tp : gpu_info) {
// Parse the cusolver handle
py::object cus_handle_obj = std::get<1>(gi_tp);
void *cus_handle_vptr = ctypes_void_ptr(cus_handle_obj);
if (cus_handle_vptr == nullptr) {
throw std::invalid_argument("cusolver_handle");
}
gpuInfo gi = {
.free_memory = std::get<0>(gi_tp),
.cusolver_handle = (cusolverDnHandle_t)cus_handle_vptr,
.id = std::get<2>(gi_tp)
};
out_gpu_info.push_back(gi);
}
return parallel_potrf_cuda(out_gpu_info, out_allocs, A);
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("parallel_potrf", ¶llel_potrf, "GPU-Parallel Cholesky Factorization");
m.def("cuda_lauum", &lauum, "out of place LAUUM operation on CUDA matrices.",
py::arg("n"), py::arg("A"), py::arg("lda"), py::arg("B"),
py::arg("ldb"), py::arg("lower"));
}
| 32.134328 | 82 | 0.612169 | [
"object",
"vector"
] |
a772889cf8dc342208d231f4a34c582694ae6e8c | 13,156 | hxx | C++ | Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.hxx | khangthk/ITK | f3c12edaf9cef07dbc34107e1a8aec9859204116 | [
"Apache-2.0"
] | null | null | null | Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.hxx | khangthk/ITK | f3c12edaf9cef07dbc34107e1a8aec9859204116 | [
"Apache-2.0"
] | null | null | null | Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.hxx | khangthk/ITK | f3c12edaf9cef07dbc34107e1a8aec9859204116 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkScalarImageToRunLengthMatrixFilter_hxx
#define itkScalarImageToRunLengthMatrixFilter_hxx
#include "itkConstNeighborhoodIterator.h"
#include "itkNeighborhood.h"
#include "itkMath.h"
#include "itkMacro.h"
#include "itkMath.h"
namespace itk
{
namespace Statistics
{
template <typename TImageType, typename THistogramFrequencyContainer>
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::ScalarImageToRunLengthMatrixFilter()
: m_NumberOfBinsPerAxis(Self::DefaultBinsPerAxis)
, m_Min(NumericTraits<PixelType>::NonpositiveMin())
, m_Max(NumericTraits<PixelType>::max())
, m_MinDistance(NumericTraits<RealType>::ZeroValue())
, m_MaxDistance(NumericTraits<RealType>::max())
, m_InsidePixelValue(NumericTraits<PixelType>::OneValue())
{
this->SetNumberOfRequiredInputs(1);
this->SetNumberOfRequiredOutputs(1);
constexpr unsigned int measurementVectorSize = 2;
this->ProcessObject::SetNthOutput(0, this->MakeOutput(0));
auto * output = const_cast<HistogramType *>(this->GetOutput());
output->SetMeasurementVectorSize(measurementVectorSize);
this->m_LowerBound.SetSize(measurementVectorSize);
this->m_UpperBound.SetSize(measurementVectorSize);
this->m_LowerBound[0] = this->m_Min;
this->m_LowerBound[1] = this->m_MinDistance;
this->m_UpperBound[0] = this->m_Max;
this->m_UpperBound[1] = this->m_MaxDistance;
}
template <typename TImageType, typename THistogramFrequencyContainer>
void
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::SetOffset(const OffsetType offset)
{
OffsetVectorPointer offsetVector = OffsetVector::New();
offsetVector->push_back(offset);
this->SetOffsets(offsetVector);
}
template <typename TImageType, typename THistogramFrequencyContainer>
void
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::SetInput(const ImageType * image)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(0, const_cast<ImageType *>(image));
}
template <typename TImageType, typename THistogramFrequencyContainer>
void
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::SetMaskImage(const ImageType * image)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(1, const_cast<ImageType *>(image));
}
template <typename TImageType, typename THistogramFrequencyContainer>
const TImageType *
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::GetInput() const
{
if (this->GetNumberOfInputs() < 1)
{
return nullptr;
}
return static_cast<const ImageType *>(this->ProcessObject::GetInput(0));
}
template <typename TImageType, typename THistogramFrequencyContainer>
const TImageType *
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::GetMaskImage() const
{
if (this->GetNumberOfInputs() < 2)
{
return nullptr;
}
return static_cast<const ImageType *>(this->ProcessObject::GetInput(1));
}
template <typename TImageType, typename THistogramFrequencyContainer>
auto
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::GetOutput() const -> const HistogramType *
{
const auto * output = static_cast<const HistogramType *>(this->ProcessObject::GetOutput(0));
return output;
}
template <typename TImageType, typename THistogramFrequencyContainer>
typename ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::DataObjectPointer
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::MakeOutput(
DataObjectPointerArraySizeType itkNotUsed(idx))
{
return HistogramType::New().GetPointer();
}
template <typename TImageType, typename THistogramFrequencyContainer>
void
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::GenerateData()
{
auto * output = static_cast<HistogramType *>(this->ProcessObject::GetOutput(0));
const ImageType * inputImage = this->GetInput();
// First, create an appropriate histogram with the right number of bins
// and mins and maxes correct for the image type.
typename HistogramType::SizeType size(output->GetMeasurementVectorSize());
size.Fill(this->m_NumberOfBinsPerAxis);
this->m_LowerBound[0] = this->m_Min;
this->m_LowerBound[1] = this->m_MinDistance;
this->m_UpperBound[0] = this->m_Max;
this->m_UpperBound[1] = this->m_MaxDistance;
output->Initialize(size, this->m_LowerBound, this->m_UpperBound);
MeasurementVectorType run(output->GetMeasurementVectorSize());
typename HistogramType::IndexType hIndex;
// Iterate over all of those pixels and offsets, adding each
// distance/intensity pair to the histogram
using NeighborhoodIteratorType = ConstNeighborhoodIterator<ImageType>;
typename NeighborhoodIteratorType::RadiusType radius;
radius.Fill(1);
NeighborhoodIteratorType neighborIt(radius, inputImage, inputImage->GetRequestedRegion());
// this temp image has the same dimension for each offset
// moving the allocation out of loop of offsets
// while keeping FillBuffer with boolean false in each loop
using BoolImageType = Image<bool, ImageDimension>;
auto alreadyVisitedImage = BoolImageType::New();
alreadyVisitedImage->CopyInformation(inputImage);
alreadyVisitedImage->SetRegions(inputImage->GetRequestedRegion());
alreadyVisitedImage->Allocate();
typename OffsetVector::ConstIterator offsets;
for (offsets = this->GetOffsets()->Begin(); offsets != this->GetOffsets()->End(); ++offsets)
{
alreadyVisitedImage->FillBuffer(false);
neighborIt.GoToBegin();
OffsetType offset = offsets.Value();
this->NormalizeOffsetDirection(offset);
for (neighborIt.GoToBegin(); !neighborIt.IsAtEnd(); ++neighborIt)
{
const PixelType centerPixelIntensity = neighborIt.GetCenterPixel();
IndexType centerIndex = neighborIt.GetIndex();
if (centerPixelIntensity < this->m_Min || centerPixelIntensity > this->m_Max ||
alreadyVisitedImage->GetPixel(centerIndex) ||
(this->GetMaskImage() && this->GetMaskImage()->GetPixel(centerIndex) != this->m_InsidePixelValue))
{
continue; // don't put a pixel in the histogram if the value
// is out-of-bounds or is outside the mask.
}
itkDebugMacro("===> offset = " << offset << std::endl);
MeasurementType centerBinMin = this->GetOutput()->GetBinMinFromValue(0, centerPixelIntensity);
MeasurementType centerBinMax = this->GetOutput()->GetBinMaxFromValue(0, centerPixelIntensity);
MeasurementType lastBinMax = this->GetOutput()->GetDimensionMaxs(0)[this->GetOutput()->GetSize(0) - 1];
PixelType pixelIntensity(NumericTraits<PixelType>::ZeroValue());
IndexType index;
index = centerIndex + offset;
IndexType lastGoodIndex = centerIndex;
bool runLengthSegmentAlreadyVisited = false;
// Scan from the current pixel at index, following
// the direction of offset. Run length is computed as the
// length of continuous pixels whose pixel values are
// in the same bin.
while (inputImage->GetRequestedRegion().IsInside(index))
{
// For the same offset, each run length segment can
// only be visited once
if (alreadyVisitedImage->GetPixel(index))
{
runLengthSegmentAlreadyVisited = true;
break;
}
pixelIntensity = inputImage->GetPixel(index);
// Special attention paid to boundaries of bins.
// For the last bin,
// it is left close and right close (following the previous
// gerrit patch).
// For all
// other bins,
// the bin is left close and right open.
if (pixelIntensity >= centerBinMin &&
(pixelIntensity < centerBinMax ||
(Math::ExactlyEquals(pixelIntensity, centerBinMax) && Math::ExactlyEquals(centerBinMax, lastBinMax))))
{
alreadyVisitedImage->SetPixel(index, true);
lastGoodIndex = index;
index += offset;
}
else
{
break;
}
}
if (runLengthSegmentAlreadyVisited)
{
continue;
}
PointType centerPoint;
inputImage->TransformIndexToPhysicalPoint(centerIndex, centerPoint);
PointType point;
inputImage->TransformIndexToPhysicalPoint(lastGoodIndex, point);
run[0] = centerPixelIntensity;
run[1] = centerPoint.EuclideanDistanceTo(point);
if (run[1] >= this->m_MinDistance && run[1] <= this->m_MaxDistance)
{
output->GetIndex(run, hIndex);
output->IncreaseFrequencyOfIndex(hIndex, 1);
itkDebugStatement(typename HistogramType::IndexType tempMeasurementIndex);
itkDebugStatement(output->GetIndex(run, tempMeasurementIndex));
itkDebugMacro("centerIndex<->index: " << static_cast<int>(centerPixelIntensity) << "@" << centerIndex << "<->"
<< static_cast<int>(pixelIntensity) << "@" << index << ", Bin# "
<< tempMeasurementIndex << ", Measurement: (" << run[0] << ", " << run[1]
<< ")"
<< ", Center bin [" << this->GetOutput()->GetBinMinFromValue(0, run[0])
<< "," << this->GetOutput()->GetBinMaxFromValue(0, run[0]) << "]"
<< "~[" << this->GetOutput()->GetBinMinFromValue(1, run[1]) << ","
<< this->GetOutput()->GetBinMaxFromValue(1, run[1]) << "]" << std::endl);
}
}
}
}
template <typename TImageType, typename THistogramFrequencyContainer>
void
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::SetPixelValueMinMax(PixelType min,
PixelType max)
{
if (this->m_Min != min || this->m_Max != max)
{
itkDebugMacro("setting Min to " << min << "and Max to " << max);
this->m_Min = min;
this->m_Max = max;
this->Modified();
}
}
template <typename TImageType, typename THistogramFrequencyContainer>
void
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::SetDistanceValueMinMax(RealType min,
RealType max)
{
if (Math::NotExactlyEquals(this->m_MinDistance, min) || Math::NotExactlyEquals(this->m_MaxDistance, max))
{
itkDebugMacro("setting MinDistance to " << min << "and MaxDistance to " << max);
this->m_MinDistance = min;
this->m_MaxDistance = max;
this->Modified();
}
}
template <typename TImageType, typename THistogramFrequencyContainer>
void
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::PrintSelf(std::ostream & os,
Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Offsets: " << this->GetOffsets() << std::endl;
os << indent << "Min: " << this->m_Min << std::endl;
os << indent << "Max: " << this->m_Max << std::endl;
os << indent << "Min distance: " << this->m_MinDistance << std::endl;
os << indent << "Max distance: " << this->m_MaxDistance << std::endl;
os << indent << "NumberOfBinsPerAxis: " << this->m_NumberOfBinsPerAxis << std::endl;
os << indent << "InsidePixelValue: " << this->m_InsidePixelValue << std::endl;
}
template <typename TImageType, typename THistogramFrequencyContainer>
void
ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer>::NormalizeOffsetDirection(
OffsetType & offset)
{
itkDebugMacro("old offset = " << offset << std::endl);
int sign = 1;
bool metLastNonZero = false;
for (int i = offset.GetOffsetDimension() - 1; i >= 0; i--)
{
if (metLastNonZero)
{
offset[i] *= sign;
}
else if (offset[i] != 0)
{
sign = (offset[i] > 0) ? 1 : -1;
metLastNonZero = true;
offset[i] *= sign;
}
}
itkDebugMacro("new offset = " << offset << std::endl);
}
} // end of namespace Statistics
} // end of namespace itk
#endif
| 37.913545 | 120 | 0.675281 | [
"object"
] |
a77368bddc6c17a45b7ee26ed82a9b35f6239f6b | 14,049 | cpp | C++ | ROS_Eploration/nav2d_karto/OpenKarto/source/StringHelper.cpp | WarOfDevil/AGV | 3891570995f639081d7865098c19efbed27e33f9 | [
"MIT"
] | null | null | null | ROS_Eploration/nav2d_karto/OpenKarto/source/StringHelper.cpp | WarOfDevil/AGV | 3891570995f639081d7865098c19efbed27e33f9 | [
"MIT"
] | null | null | null | ROS_Eploration/nav2d_karto/OpenKarto/source/StringHelper.cpp | WarOfDevil/AGV | 3891570995f639081d7865098c19efbed27e33f9 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2006-2011, SRI International (R)
*
* 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/>.
*/
#include <algorithm>
#include <string>
#include <limits>
#include <OpenKarto/StringHelper.h>
#include <OpenKarto/Geometry.h>
namespace karto
{
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
String StringHelper::ToString(const char* value)
{
return String(value);
}
String StringHelper::ToString(kt_bool value)
{
if (value == true)
{
return String("true");
}
return String("false");
}
//String StringHelper::ToString(kt_size_t value)
//{
// std::stringstream converter;
// converter.precision(std::numeric_limits<double>::digits10);
// converter << value;
// return converter.str().c_str();
//}
String StringHelper::ToString(kt_int16u value)
{
std::stringstream converter;
converter.precision(std::numeric_limits<double>::digits10);
converter << value;
return converter.str().c_str();
}
String StringHelper::ToString(kt_int16s value)
{
std::stringstream converter;
converter.precision(std::numeric_limits<double>::digits10);
converter << value;
return converter.str().c_str();
}
String StringHelper::ToString(kt_int32u value)
{
char buffer[64];
#ifdef WIN32
sprintf_s(buffer, 64, "%u", value);
#else
sprintf(buffer, "%u", value);
#endif
return String(buffer);
}
String StringHelper::ToString(kt_int32s value)
{
char buffer[64];
#ifdef WIN32
sprintf_s(buffer, 64, "%d", value);
#else
sprintf(buffer, "%d", value);
#endif
return String(buffer);
}
String StringHelper::ToString(kt_int64u value)
{
std::stringstream converter;
converter.precision(std::numeric_limits<double>::digits10);
converter << value;
return converter.str().c_str();
}
String StringHelper::ToString(kt_int64s value)
{
std::stringstream converter;
converter.precision(std::numeric_limits<double>::digits10);
converter << value;
return converter.str().c_str();
}
#if defined(__APPLE__) && !defined(__LP64__)
String StringHelper::ToString(kt_size_t value)
{
std::stringstream converter;
converter.precision(std::numeric_limits<double>::digits10);
converter << value;
return converter.str().c_str();
}
#endif
String StringHelper::ToString(kt_float value)
{
char buffer[64];
#ifdef WIN32
sprintf_s(buffer, 64, "%.*g", 8, (double) value);
#else
sprintf(buffer, "%.*g", 8, (double) value);
#endif
return String(buffer);
}
String StringHelper::ToString(kt_double value)
{
char buffer[64];
#ifdef WIN32
sprintf_s(buffer, 64, "%.*g", 16, value);
#else
sprintf(buffer, "%.*g", 16, value);
#endif
return String(buffer);
}
String StringHelper::ToString(kt_float value, kt_int32u precision)
{
char buffer[64];
#ifdef WIN32
sprintf_s(buffer, 64, "%.*f", (kt_int32s)precision, (double)value);
#else
sprintf(buffer, "%.*f", (kt_int32s)precision, (double)value);
#endif
return String(buffer);
}
String StringHelper::ToString(kt_double value, kt_int32u precision)
{
char buffer[64];
#ifdef WIN32
sprintf_s(buffer, 64, "%.*f", (kt_int32s)precision, value);
#else
sprintf(buffer, "%.*f", (kt_int32s)precision, value);
#endif
return String(buffer);
}
karto::String StringHelper::ToString(const String& rValue)
{
return rValue;
}
karto::String StringHelper::ToString(const Quaternion& rValue)
{
return rValue.ToString();
}
karto::String StringHelper::ToString(const Color& rValue)
{
return rValue.ToString();
}
karto::String StringHelper::ToString(const Pose2& rValue)
{
return rValue.ToString();
}
karto::String StringHelper::ToString(const Pose3& rValue)
{
return rValue.ToString();
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_bool& rValue)
{
rValue = false;
if (ToLowerCase(rStringValue) == String("true"))
{
rValue = true;
}
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_int16s& rValue)
{
int precision = std::numeric_limits<double>::digits10;
std::stringstream converter;
converter.precision(precision);
converter.str(rStringValue.ToCString());
converter >> rValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_int16u& rValue)
{
int precision = std::numeric_limits<double>::digits10;
std::stringstream converter;
converter.precision(precision);
converter.str(rStringValue.ToCString());
converter >> rValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_int32s& rValue)
{
int precision = std::numeric_limits<double>::digits10;
std::stringstream converter;
converter.precision(precision);
converter.str(rStringValue.ToCString());
converter >> rValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_int32u& rValue)
{
int precision = std::numeric_limits<double>::digits10;
std::stringstream converter;
converter.precision(precision);
converter.str(rStringValue.ToCString());
converter >> rValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_int64s& rValue)
{
int precision = std::numeric_limits<double>::digits10;
std::stringstream converter;
converter.precision(precision);
converter.str(rStringValue.ToCString());
converter >> rValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_int64u& rValue)
{
int precision = std::numeric_limits<double>::digits10;
std::stringstream converter;
converter.precision(precision);
converter.str(rStringValue.ToCString());
converter >> rValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_float& rValue)
{
int precision = std::numeric_limits<double>::digits10;
std::stringstream converter;
converter.precision(precision);
converter.str(rStringValue.ToCString());
converter >> rValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, kt_double& rValue)
{
int precision = std::numeric_limits<double>::digits10;
std::stringstream converter;
converter.precision(precision);
converter.str(rStringValue.ToCString());
converter >> rValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, String& rValue)
{
rValue = rStringValue;
return true;
}
kt_bool StringHelper::FromString(const String& rStringValue, Quaternion& rValue)
{
kt_size_t index = rStringValue.FindFirstOf(" ");
if (index != -1)
{
std::stringstream converter;
converter.str(rStringValue.ToCString());
kt_double valueX = 0.0;
kt_double valueY = 0.0;
kt_double valueZ = 0.0;
kt_double valueW = 0.0;
converter >> valueX;
converter >> valueY;
converter >> valueZ;
converter >> valueW;
rValue.SetX(valueX);
rValue.SetY(valueY);
rValue.SetZ(valueZ);
rValue.SetW(valueW);
return true;
}
return false;
}
kt_bool StringHelper::FromString(const String& rStringValue, Color& rValue)
{
kt_size_t index = rStringValue.FindFirstOf(" ");
if (index != -1)
{
std::stringstream converter;
converter.str(rStringValue.ToCString());
kt_double valueRed = 0.0;
kt_double valueGreen = 0.0;
kt_double valueBlue = 0.0;
kt_double valueAlpha = 0.0;
converter >> valueRed;
converter >> valueGreen;
converter >> valueBlue;
converter >> valueAlpha;
rValue.SetRed(valueRed);
rValue.SetGreen(valueGreen);
rValue.SetBlue(valueBlue);
rValue.SetAlpha(valueAlpha);
return true;
}
return false;
}
kt_bool StringHelper::FromString(const String& rStringValue, Pose2& rValue)
{
kt_size_t index = rStringValue.FindFirstOf(" ");
if (index != -1)
{
std::stringstream converter;
converter.str(rStringValue.ToCString());
kt_double valueX = 0.0;
kt_double valueY = 0.0;
kt_double valueHeading = 0.0;
converter >> valueX;
converter >> valueY;
converter >> valueHeading;
rValue.SetX(valueX);
rValue.SetY(valueY);
rValue.SetHeading(valueHeading);
return true;
}
return false;
}
kt_bool StringHelper::FromString(const String& rStringValue, Pose3& rValue)
{
kt_size_t index = rStringValue.FindFirstOf(" ");
if (index != -1)
{
std::stringstream converter;
converter.str(rStringValue.ToCString());
kt_double valueX = 0.0;
kt_double valueY = 0.0;
kt_double valueZ = 0.0;
kt_double valueW = 0.0;
converter >> valueX;
converter >> valueY;
converter >> valueZ;
rValue.SetPosition(karto::Vector3d(valueX, valueY, valueZ));
valueX = 0.0;
valueY = 0.0;
valueZ = 0.0;
valueW = 0.0;
converter >> valueX;
converter >> valueY;
converter >> valueZ;
converter >> valueW;
rValue.SetOrientation(karto::Quaternion(valueX, valueY, valueZ, valueW));
return true;
}
return false;
}
String StringHelper::Trim(const String& rValue)
{
char const* delims = " \t\r\n";
std::string result(rValue.ToCString());
std::string::size_type index = result.find_last_not_of(delims);
if (index != std::string::npos)
result.erase(++index);
index = result.find_first_not_of(delims);
if (index != std::string::npos)
{
result.erase(0, index);
}
else
{
result.erase();
}
return String(result.c_str());
}
String StringHelper::Replace(const String& rSource, const String& rFind, const String& rReplace)
{
size_t j;
std::string retStr = rSource.ToCString();
if (rFind == rReplace)
{
return String(retStr.c_str());
}
for (; ( j = retStr.find(rFind.ToCString()) ) != std::string::npos; )
{
retStr.replace( j, rFind.Size(), rReplace.ToCString());
}
return String(retStr.c_str());
}
kt_bool StringHelper::IsLetter(char ch)
{
return isalpha(ch) != 0;
}
String StringHelper::ToLowerCase(const String &rValue)
{
std::string value = rValue.ToCString();
std::string ext = rValue.ToCString();
std::transform(value.begin(), value.end(), ext.begin(), tolower);
return String(ext.c_str());
}
String StringHelper::ToUpperCase(const String &rValue)
{
std::string value = rValue.ToCString();
std::string ext = rValue.ToCString();
std::transform(value.begin(), value.end(), ext.begin(), toupper);
return String(ext.c_str());
}
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
void StringBuilder::Clear()
{
m_String = "";
}
const String& StringBuilder::ToString() const
{
return m_String;
}
//StringBuilder& StringBuilder::operator << (char value)
//{
// m_String.Append(value);
// return *this;
//}
StringBuilder& StringBuilder::operator << (kt_int8u value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
StringBuilder& StringBuilder::operator << (kt_int16s value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
StringBuilder& StringBuilder::operator << (kt_int16u value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
StringBuilder& StringBuilder::operator << (kt_int32s value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
StringBuilder& StringBuilder::operator << (kt_int32u value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
StringBuilder& StringBuilder::operator << (kt_int64s value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
StringBuilder& StringBuilder::operator << (kt_int64u value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
#if defined(__APPLE__) && !defined(__LP64__)
StringBuilder& StringBuilder::operator << (kt_size_t value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
#endif
StringBuilder& StringBuilder::operator << (kt_float value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
StringBuilder& StringBuilder::operator << (kt_double value)
{
m_String.Append(karto::StringHelper::ToString(value));
return *this;
}
StringBuilder& StringBuilder::operator << (const String& rValue)
{
m_String.Append(rValue);
return *this;
}
StringBuilder& StringBuilder::operator << (const StringBuilder& rValue)
{
m_String.Append(rValue.ToString());
return *this;
}
} | 23.298507 | 98 | 0.635632 | [
"geometry",
"transform"
] |
a77578081bd8fcd384ec71efe1803612cfe5cf67 | 35,138 | cpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_wanphy_ui_oper.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_wanphy_ui_oper.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_wanphy_ui_oper.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XR_wanphy_ui_oper.hpp"
using namespace ydk;
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_wanphy_ui_oper {
Wanphy::Wanphy()
:
controllers(std::make_shared<Wanphy::Controllers>())
{
controllers->parent = this;
yang_name = "wanphy"; yang_parent_name = "Cisco-IOS-XR-wanphy-ui-oper"; is_top_level_class = true; has_list_ancestor = false;
}
Wanphy::~Wanphy()
{
}
bool Wanphy::has_data() const
{
if (is_presence_container) return true;
return (controllers != nullptr && controllers->has_data());
}
bool Wanphy::has_operation() const
{
return is_set(yfilter)
|| (controllers != nullptr && controllers->has_operation());
}
std::string Wanphy::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-wanphy-ui-oper:wanphy";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Wanphy::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Wanphy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "controllers")
{
if(controllers == nullptr)
{
controllers = std::make_shared<Wanphy::Controllers>();
}
return controllers;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Wanphy::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(controllers != nullptr)
{
_children["controllers"] = controllers;
}
return _children;
}
void Wanphy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Wanphy::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> Wanphy::clone_ptr() const
{
return std::make_shared<Wanphy>();
}
std::string Wanphy::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string Wanphy::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function Wanphy::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> Wanphy::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool Wanphy::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "controllers")
return true;
return false;
}
Wanphy::Controllers::Controllers()
:
controller(this, {"controller_name"})
{
yang_name = "controllers"; yang_parent_name = "wanphy"; is_top_level_class = false; has_list_ancestor = false;
}
Wanphy::Controllers::~Controllers()
{
}
bool Wanphy::Controllers::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<controller.len(); index++)
{
if(controller[index]->has_data())
return true;
}
return false;
}
bool Wanphy::Controllers::has_operation() const
{
for (std::size_t index=0; index<controller.len(); index++)
{
if(controller[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Wanphy::Controllers::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-wanphy-ui-oper:wanphy/" << get_segment_path();
return path_buffer.str();
}
std::string Wanphy::Controllers::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "controllers";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Wanphy::Controllers::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Wanphy::Controllers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "controller")
{
auto ent_ = std::make_shared<Wanphy::Controllers::Controller>();
ent_->parent = this;
controller.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Wanphy::Controllers::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : controller.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Wanphy::Controllers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Wanphy::Controllers::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Wanphy::Controllers::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "controller")
return true;
return false;
}
Wanphy::Controllers::Controller::Controller()
:
controller_name{YType::str, "controller-name"}
,
info(std::make_shared<Wanphy::Controllers::Controller::Info>())
{
info->parent = this;
yang_name = "controller"; yang_parent_name = "controllers"; is_top_level_class = false; has_list_ancestor = false;
}
Wanphy::Controllers::Controller::~Controller()
{
}
bool Wanphy::Controllers::Controller::has_data() const
{
if (is_presence_container) return true;
return controller_name.is_set
|| (info != nullptr && info->has_data());
}
bool Wanphy::Controllers::Controller::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(controller_name.yfilter)
|| (info != nullptr && info->has_operation());
}
std::string Wanphy::Controllers::Controller::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-wanphy-ui-oper:wanphy/controllers/" << get_segment_path();
return path_buffer.str();
}
std::string Wanphy::Controllers::Controller::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "controller";
ADD_KEY_TOKEN(controller_name, "controller-name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Wanphy::Controllers::Controller::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (controller_name.is_set || is_set(controller_name.yfilter)) leaf_name_data.push_back(controller_name.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Wanphy::Controllers::Controller::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "info")
{
if(info == nullptr)
{
info = std::make_shared<Wanphy::Controllers::Controller::Info>();
}
return info;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Wanphy::Controllers::Controller::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(info != nullptr)
{
_children["info"] = info;
}
return _children;
}
void Wanphy::Controllers::Controller::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "controller-name")
{
controller_name = value;
controller_name.value_namespace = name_space;
controller_name.value_namespace_prefix = name_space_prefix;
}
}
void Wanphy::Controllers::Controller::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "controller-name")
{
controller_name.yfilter = yfilter;
}
}
bool Wanphy::Controllers::Controller::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "info" || name == "controller-name")
return true;
return false;
}
Wanphy::Controllers::Controller::Info::Info()
:
admin_mode{YType::enumeration, "admin-mode"},
port_state{YType::uint32, "port-state"},
section_lof{YType::uint32, "section-lof"},
section_los{YType::uint32, "section-los"},
section_bip{YType::uint64, "section-bip"},
line_ais{YType::uint32, "line-ais"},
line_rdi{YType::uint32, "line-rdi"},
line_febe{YType::uint64, "line-febe"},
line_bip{YType::uint64, "line-bip"},
path_ais{YType::uint32, "path-ais"},
path_rdi{YType::uint32, "path-rdi"},
path_febe{YType::uint64, "path-febe"},
path_bip{YType::uint64, "path-bip"},
path_lop{YType::uint32, "path-lop"},
path_newptr{YType::uint32, "path-newptr"},
path_pse{YType::uint32, "path-pse"},
path_nse{YType::uint32, "path-nse"},
wis_alarms_ser{YType::uint32, "wis-alarms-ser"},
wis_alarms_felcdp{YType::uint32, "wis-alarms-felcdp"},
wis_alarms_feaisp{YType::uint32, "wis-alarms-feaisp"},
wis_alarms_wlos{YType::uint32, "wis-alarms-wlos"},
wis_alarms_plcd{YType::uint32, "wis-alarms-plcd"},
wis_alarms_lfebip{YType::uint64, "wis-alarms-lfebip"},
wis_alarms_pbec{YType::uint64, "wis-alarms-pbec"},
wis_alarms_plmp{YType::uint32, "wis-alarms-plmp"},
sf_ber_threshold{YType::uint32, "sf-ber-threshold"},
sd_ber_threshold{YType::uint32, "sd-ber-threshold"},
sf_ber_report{YType::enumeration, "sf-ber-report"},
sd_ber_report{YType::enumeration, "sd-ber-report"},
operational_mode{YType::enumeration, "operational-mode"},
remote_ip{YType::str, "remote-ip"},
register_p_febe{YType::uint32, "register-p-febe"},
register_l_fe_bip{YType::uint32, "register-l-fe-bip"},
register_l_bip{YType::uint32, "register-l-bip"},
register_p_bec{YType::uint32, "register-p-bec"},
register_s_bip{YType::uint32, "register-s-bip"},
register_j1_rx0{YType::uint32, "register-j1-rx0"},
register_j1_rx1{YType::uint32, "register-j1-rx1"},
register_j1_rx2{YType::uint32, "register-j1-rx2"},
register_j1_rx3{YType::uint32, "register-j1-rx3"},
register_j1_rx4{YType::uint32, "register-j1-rx4"},
register_j1_rx5{YType::uint32, "register-j1-rx5"},
register_j1_rx6{YType::uint32, "register-j1-rx6"},
register_j1_rx7{YType::uint32, "register-j1-rx7"},
wanphy_poll_timer{YType::uint32, "wanphy-poll-timer"}
{
yang_name = "info"; yang_parent_name = "controller"; is_top_level_class = false; has_list_ancestor = true;
}
Wanphy::Controllers::Controller::Info::~Info()
{
}
bool Wanphy::Controllers::Controller::Info::has_data() const
{
if (is_presence_container) return true;
return admin_mode.is_set
|| port_state.is_set
|| section_lof.is_set
|| section_los.is_set
|| section_bip.is_set
|| line_ais.is_set
|| line_rdi.is_set
|| line_febe.is_set
|| line_bip.is_set
|| path_ais.is_set
|| path_rdi.is_set
|| path_febe.is_set
|| path_bip.is_set
|| path_lop.is_set
|| path_newptr.is_set
|| path_pse.is_set
|| path_nse.is_set
|| wis_alarms_ser.is_set
|| wis_alarms_felcdp.is_set
|| wis_alarms_feaisp.is_set
|| wis_alarms_wlos.is_set
|| wis_alarms_plcd.is_set
|| wis_alarms_lfebip.is_set
|| wis_alarms_pbec.is_set
|| wis_alarms_plmp.is_set
|| sf_ber_threshold.is_set
|| sd_ber_threshold.is_set
|| sf_ber_report.is_set
|| sd_ber_report.is_set
|| operational_mode.is_set
|| remote_ip.is_set
|| register_p_febe.is_set
|| register_l_fe_bip.is_set
|| register_l_bip.is_set
|| register_p_bec.is_set
|| register_s_bip.is_set
|| register_j1_rx0.is_set
|| register_j1_rx1.is_set
|| register_j1_rx2.is_set
|| register_j1_rx3.is_set
|| register_j1_rx4.is_set
|| register_j1_rx5.is_set
|| register_j1_rx6.is_set
|| register_j1_rx7.is_set
|| wanphy_poll_timer.is_set;
}
bool Wanphy::Controllers::Controller::Info::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(admin_mode.yfilter)
|| ydk::is_set(port_state.yfilter)
|| ydk::is_set(section_lof.yfilter)
|| ydk::is_set(section_los.yfilter)
|| ydk::is_set(section_bip.yfilter)
|| ydk::is_set(line_ais.yfilter)
|| ydk::is_set(line_rdi.yfilter)
|| ydk::is_set(line_febe.yfilter)
|| ydk::is_set(line_bip.yfilter)
|| ydk::is_set(path_ais.yfilter)
|| ydk::is_set(path_rdi.yfilter)
|| ydk::is_set(path_febe.yfilter)
|| ydk::is_set(path_bip.yfilter)
|| ydk::is_set(path_lop.yfilter)
|| ydk::is_set(path_newptr.yfilter)
|| ydk::is_set(path_pse.yfilter)
|| ydk::is_set(path_nse.yfilter)
|| ydk::is_set(wis_alarms_ser.yfilter)
|| ydk::is_set(wis_alarms_felcdp.yfilter)
|| ydk::is_set(wis_alarms_feaisp.yfilter)
|| ydk::is_set(wis_alarms_wlos.yfilter)
|| ydk::is_set(wis_alarms_plcd.yfilter)
|| ydk::is_set(wis_alarms_lfebip.yfilter)
|| ydk::is_set(wis_alarms_pbec.yfilter)
|| ydk::is_set(wis_alarms_plmp.yfilter)
|| ydk::is_set(sf_ber_threshold.yfilter)
|| ydk::is_set(sd_ber_threshold.yfilter)
|| ydk::is_set(sf_ber_report.yfilter)
|| ydk::is_set(sd_ber_report.yfilter)
|| ydk::is_set(operational_mode.yfilter)
|| ydk::is_set(remote_ip.yfilter)
|| ydk::is_set(register_p_febe.yfilter)
|| ydk::is_set(register_l_fe_bip.yfilter)
|| ydk::is_set(register_l_bip.yfilter)
|| ydk::is_set(register_p_bec.yfilter)
|| ydk::is_set(register_s_bip.yfilter)
|| ydk::is_set(register_j1_rx0.yfilter)
|| ydk::is_set(register_j1_rx1.yfilter)
|| ydk::is_set(register_j1_rx2.yfilter)
|| ydk::is_set(register_j1_rx3.yfilter)
|| ydk::is_set(register_j1_rx4.yfilter)
|| ydk::is_set(register_j1_rx5.yfilter)
|| ydk::is_set(register_j1_rx6.yfilter)
|| ydk::is_set(register_j1_rx7.yfilter)
|| ydk::is_set(wanphy_poll_timer.yfilter);
}
std::string Wanphy::Controllers::Controller::Info::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "info";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Wanphy::Controllers::Controller::Info::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (admin_mode.is_set || is_set(admin_mode.yfilter)) leaf_name_data.push_back(admin_mode.get_name_leafdata());
if (port_state.is_set || is_set(port_state.yfilter)) leaf_name_data.push_back(port_state.get_name_leafdata());
if (section_lof.is_set || is_set(section_lof.yfilter)) leaf_name_data.push_back(section_lof.get_name_leafdata());
if (section_los.is_set || is_set(section_los.yfilter)) leaf_name_data.push_back(section_los.get_name_leafdata());
if (section_bip.is_set || is_set(section_bip.yfilter)) leaf_name_data.push_back(section_bip.get_name_leafdata());
if (line_ais.is_set || is_set(line_ais.yfilter)) leaf_name_data.push_back(line_ais.get_name_leafdata());
if (line_rdi.is_set || is_set(line_rdi.yfilter)) leaf_name_data.push_back(line_rdi.get_name_leafdata());
if (line_febe.is_set || is_set(line_febe.yfilter)) leaf_name_data.push_back(line_febe.get_name_leafdata());
if (line_bip.is_set || is_set(line_bip.yfilter)) leaf_name_data.push_back(line_bip.get_name_leafdata());
if (path_ais.is_set || is_set(path_ais.yfilter)) leaf_name_data.push_back(path_ais.get_name_leafdata());
if (path_rdi.is_set || is_set(path_rdi.yfilter)) leaf_name_data.push_back(path_rdi.get_name_leafdata());
if (path_febe.is_set || is_set(path_febe.yfilter)) leaf_name_data.push_back(path_febe.get_name_leafdata());
if (path_bip.is_set || is_set(path_bip.yfilter)) leaf_name_data.push_back(path_bip.get_name_leafdata());
if (path_lop.is_set || is_set(path_lop.yfilter)) leaf_name_data.push_back(path_lop.get_name_leafdata());
if (path_newptr.is_set || is_set(path_newptr.yfilter)) leaf_name_data.push_back(path_newptr.get_name_leafdata());
if (path_pse.is_set || is_set(path_pse.yfilter)) leaf_name_data.push_back(path_pse.get_name_leafdata());
if (path_nse.is_set || is_set(path_nse.yfilter)) leaf_name_data.push_back(path_nse.get_name_leafdata());
if (wis_alarms_ser.is_set || is_set(wis_alarms_ser.yfilter)) leaf_name_data.push_back(wis_alarms_ser.get_name_leafdata());
if (wis_alarms_felcdp.is_set || is_set(wis_alarms_felcdp.yfilter)) leaf_name_data.push_back(wis_alarms_felcdp.get_name_leafdata());
if (wis_alarms_feaisp.is_set || is_set(wis_alarms_feaisp.yfilter)) leaf_name_data.push_back(wis_alarms_feaisp.get_name_leafdata());
if (wis_alarms_wlos.is_set || is_set(wis_alarms_wlos.yfilter)) leaf_name_data.push_back(wis_alarms_wlos.get_name_leafdata());
if (wis_alarms_plcd.is_set || is_set(wis_alarms_plcd.yfilter)) leaf_name_data.push_back(wis_alarms_plcd.get_name_leafdata());
if (wis_alarms_lfebip.is_set || is_set(wis_alarms_lfebip.yfilter)) leaf_name_data.push_back(wis_alarms_lfebip.get_name_leafdata());
if (wis_alarms_pbec.is_set || is_set(wis_alarms_pbec.yfilter)) leaf_name_data.push_back(wis_alarms_pbec.get_name_leafdata());
if (wis_alarms_plmp.is_set || is_set(wis_alarms_plmp.yfilter)) leaf_name_data.push_back(wis_alarms_plmp.get_name_leafdata());
if (sf_ber_threshold.is_set || is_set(sf_ber_threshold.yfilter)) leaf_name_data.push_back(sf_ber_threshold.get_name_leafdata());
if (sd_ber_threshold.is_set || is_set(sd_ber_threshold.yfilter)) leaf_name_data.push_back(sd_ber_threshold.get_name_leafdata());
if (sf_ber_report.is_set || is_set(sf_ber_report.yfilter)) leaf_name_data.push_back(sf_ber_report.get_name_leafdata());
if (sd_ber_report.is_set || is_set(sd_ber_report.yfilter)) leaf_name_data.push_back(sd_ber_report.get_name_leafdata());
if (operational_mode.is_set || is_set(operational_mode.yfilter)) leaf_name_data.push_back(operational_mode.get_name_leafdata());
if (remote_ip.is_set || is_set(remote_ip.yfilter)) leaf_name_data.push_back(remote_ip.get_name_leafdata());
if (register_p_febe.is_set || is_set(register_p_febe.yfilter)) leaf_name_data.push_back(register_p_febe.get_name_leafdata());
if (register_l_fe_bip.is_set || is_set(register_l_fe_bip.yfilter)) leaf_name_data.push_back(register_l_fe_bip.get_name_leafdata());
if (register_l_bip.is_set || is_set(register_l_bip.yfilter)) leaf_name_data.push_back(register_l_bip.get_name_leafdata());
if (register_p_bec.is_set || is_set(register_p_bec.yfilter)) leaf_name_data.push_back(register_p_bec.get_name_leafdata());
if (register_s_bip.is_set || is_set(register_s_bip.yfilter)) leaf_name_data.push_back(register_s_bip.get_name_leafdata());
if (register_j1_rx0.is_set || is_set(register_j1_rx0.yfilter)) leaf_name_data.push_back(register_j1_rx0.get_name_leafdata());
if (register_j1_rx1.is_set || is_set(register_j1_rx1.yfilter)) leaf_name_data.push_back(register_j1_rx1.get_name_leafdata());
if (register_j1_rx2.is_set || is_set(register_j1_rx2.yfilter)) leaf_name_data.push_back(register_j1_rx2.get_name_leafdata());
if (register_j1_rx3.is_set || is_set(register_j1_rx3.yfilter)) leaf_name_data.push_back(register_j1_rx3.get_name_leafdata());
if (register_j1_rx4.is_set || is_set(register_j1_rx4.yfilter)) leaf_name_data.push_back(register_j1_rx4.get_name_leafdata());
if (register_j1_rx5.is_set || is_set(register_j1_rx5.yfilter)) leaf_name_data.push_back(register_j1_rx5.get_name_leafdata());
if (register_j1_rx6.is_set || is_set(register_j1_rx6.yfilter)) leaf_name_data.push_back(register_j1_rx6.get_name_leafdata());
if (register_j1_rx7.is_set || is_set(register_j1_rx7.yfilter)) leaf_name_data.push_back(register_j1_rx7.get_name_leafdata());
if (wanphy_poll_timer.is_set || is_set(wanphy_poll_timer.yfilter)) leaf_name_data.push_back(wanphy_poll_timer.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Wanphy::Controllers::Controller::Info::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Wanphy::Controllers::Controller::Info::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Wanphy::Controllers::Controller::Info::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "admin-mode")
{
admin_mode = value;
admin_mode.value_namespace = name_space;
admin_mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "port-state")
{
port_state = value;
port_state.value_namespace = name_space;
port_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "section-lof")
{
section_lof = value;
section_lof.value_namespace = name_space;
section_lof.value_namespace_prefix = name_space_prefix;
}
if(value_path == "section-los")
{
section_los = value;
section_los.value_namespace = name_space;
section_los.value_namespace_prefix = name_space_prefix;
}
if(value_path == "section-bip")
{
section_bip = value;
section_bip.value_namespace = name_space;
section_bip.value_namespace_prefix = name_space_prefix;
}
if(value_path == "line-ais")
{
line_ais = value;
line_ais.value_namespace = name_space;
line_ais.value_namespace_prefix = name_space_prefix;
}
if(value_path == "line-rdi")
{
line_rdi = value;
line_rdi.value_namespace = name_space;
line_rdi.value_namespace_prefix = name_space_prefix;
}
if(value_path == "line-febe")
{
line_febe = value;
line_febe.value_namespace = name_space;
line_febe.value_namespace_prefix = name_space_prefix;
}
if(value_path == "line-bip")
{
line_bip = value;
line_bip.value_namespace = name_space;
line_bip.value_namespace_prefix = name_space_prefix;
}
if(value_path == "path-ais")
{
path_ais = value;
path_ais.value_namespace = name_space;
path_ais.value_namespace_prefix = name_space_prefix;
}
if(value_path == "path-rdi")
{
path_rdi = value;
path_rdi.value_namespace = name_space;
path_rdi.value_namespace_prefix = name_space_prefix;
}
if(value_path == "path-febe")
{
path_febe = value;
path_febe.value_namespace = name_space;
path_febe.value_namespace_prefix = name_space_prefix;
}
if(value_path == "path-bip")
{
path_bip = value;
path_bip.value_namespace = name_space;
path_bip.value_namespace_prefix = name_space_prefix;
}
if(value_path == "path-lop")
{
path_lop = value;
path_lop.value_namespace = name_space;
path_lop.value_namespace_prefix = name_space_prefix;
}
if(value_path == "path-newptr")
{
path_newptr = value;
path_newptr.value_namespace = name_space;
path_newptr.value_namespace_prefix = name_space_prefix;
}
if(value_path == "path-pse")
{
path_pse = value;
path_pse.value_namespace = name_space;
path_pse.value_namespace_prefix = name_space_prefix;
}
if(value_path == "path-nse")
{
path_nse = value;
path_nse.value_namespace = name_space;
path_nse.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wis-alarms-ser")
{
wis_alarms_ser = value;
wis_alarms_ser.value_namespace = name_space;
wis_alarms_ser.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wis-alarms-felcdp")
{
wis_alarms_felcdp = value;
wis_alarms_felcdp.value_namespace = name_space;
wis_alarms_felcdp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wis-alarms-feaisp")
{
wis_alarms_feaisp = value;
wis_alarms_feaisp.value_namespace = name_space;
wis_alarms_feaisp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wis-alarms-wlos")
{
wis_alarms_wlos = value;
wis_alarms_wlos.value_namespace = name_space;
wis_alarms_wlos.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wis-alarms-plcd")
{
wis_alarms_plcd = value;
wis_alarms_plcd.value_namespace = name_space;
wis_alarms_plcd.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wis-alarms-lfebip")
{
wis_alarms_lfebip = value;
wis_alarms_lfebip.value_namespace = name_space;
wis_alarms_lfebip.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wis-alarms-pbec")
{
wis_alarms_pbec = value;
wis_alarms_pbec.value_namespace = name_space;
wis_alarms_pbec.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wis-alarms-plmp")
{
wis_alarms_plmp = value;
wis_alarms_plmp.value_namespace = name_space;
wis_alarms_plmp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sf-ber-threshold")
{
sf_ber_threshold = value;
sf_ber_threshold.value_namespace = name_space;
sf_ber_threshold.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sd-ber-threshold")
{
sd_ber_threshold = value;
sd_ber_threshold.value_namespace = name_space;
sd_ber_threshold.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sf-ber-report")
{
sf_ber_report = value;
sf_ber_report.value_namespace = name_space;
sf_ber_report.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sd-ber-report")
{
sd_ber_report = value;
sd_ber_report.value_namespace = name_space;
sd_ber_report.value_namespace_prefix = name_space_prefix;
}
if(value_path == "operational-mode")
{
operational_mode = value;
operational_mode.value_namespace = name_space;
operational_mode.value_namespace_prefix = name_space_prefix;
}
if(value_path == "remote-ip")
{
remote_ip = value;
remote_ip.value_namespace = name_space;
remote_ip.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-p-febe")
{
register_p_febe = value;
register_p_febe.value_namespace = name_space;
register_p_febe.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-l-fe-bip")
{
register_l_fe_bip = value;
register_l_fe_bip.value_namespace = name_space;
register_l_fe_bip.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-l-bip")
{
register_l_bip = value;
register_l_bip.value_namespace = name_space;
register_l_bip.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-p-bec")
{
register_p_bec = value;
register_p_bec.value_namespace = name_space;
register_p_bec.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-s-bip")
{
register_s_bip = value;
register_s_bip.value_namespace = name_space;
register_s_bip.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-j1-rx0")
{
register_j1_rx0 = value;
register_j1_rx0.value_namespace = name_space;
register_j1_rx0.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-j1-rx1")
{
register_j1_rx1 = value;
register_j1_rx1.value_namespace = name_space;
register_j1_rx1.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-j1-rx2")
{
register_j1_rx2 = value;
register_j1_rx2.value_namespace = name_space;
register_j1_rx2.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-j1-rx3")
{
register_j1_rx3 = value;
register_j1_rx3.value_namespace = name_space;
register_j1_rx3.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-j1-rx4")
{
register_j1_rx4 = value;
register_j1_rx4.value_namespace = name_space;
register_j1_rx4.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-j1-rx5")
{
register_j1_rx5 = value;
register_j1_rx5.value_namespace = name_space;
register_j1_rx5.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-j1-rx6")
{
register_j1_rx6 = value;
register_j1_rx6.value_namespace = name_space;
register_j1_rx6.value_namespace_prefix = name_space_prefix;
}
if(value_path == "register-j1-rx7")
{
register_j1_rx7 = value;
register_j1_rx7.value_namespace = name_space;
register_j1_rx7.value_namespace_prefix = name_space_prefix;
}
if(value_path == "wanphy-poll-timer")
{
wanphy_poll_timer = value;
wanphy_poll_timer.value_namespace = name_space;
wanphy_poll_timer.value_namespace_prefix = name_space_prefix;
}
}
void Wanphy::Controllers::Controller::Info::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "admin-mode")
{
admin_mode.yfilter = yfilter;
}
if(value_path == "port-state")
{
port_state.yfilter = yfilter;
}
if(value_path == "section-lof")
{
section_lof.yfilter = yfilter;
}
if(value_path == "section-los")
{
section_los.yfilter = yfilter;
}
if(value_path == "section-bip")
{
section_bip.yfilter = yfilter;
}
if(value_path == "line-ais")
{
line_ais.yfilter = yfilter;
}
if(value_path == "line-rdi")
{
line_rdi.yfilter = yfilter;
}
if(value_path == "line-febe")
{
line_febe.yfilter = yfilter;
}
if(value_path == "line-bip")
{
line_bip.yfilter = yfilter;
}
if(value_path == "path-ais")
{
path_ais.yfilter = yfilter;
}
if(value_path == "path-rdi")
{
path_rdi.yfilter = yfilter;
}
if(value_path == "path-febe")
{
path_febe.yfilter = yfilter;
}
if(value_path == "path-bip")
{
path_bip.yfilter = yfilter;
}
if(value_path == "path-lop")
{
path_lop.yfilter = yfilter;
}
if(value_path == "path-newptr")
{
path_newptr.yfilter = yfilter;
}
if(value_path == "path-pse")
{
path_pse.yfilter = yfilter;
}
if(value_path == "path-nse")
{
path_nse.yfilter = yfilter;
}
if(value_path == "wis-alarms-ser")
{
wis_alarms_ser.yfilter = yfilter;
}
if(value_path == "wis-alarms-felcdp")
{
wis_alarms_felcdp.yfilter = yfilter;
}
if(value_path == "wis-alarms-feaisp")
{
wis_alarms_feaisp.yfilter = yfilter;
}
if(value_path == "wis-alarms-wlos")
{
wis_alarms_wlos.yfilter = yfilter;
}
if(value_path == "wis-alarms-plcd")
{
wis_alarms_plcd.yfilter = yfilter;
}
if(value_path == "wis-alarms-lfebip")
{
wis_alarms_lfebip.yfilter = yfilter;
}
if(value_path == "wis-alarms-pbec")
{
wis_alarms_pbec.yfilter = yfilter;
}
if(value_path == "wis-alarms-plmp")
{
wis_alarms_plmp.yfilter = yfilter;
}
if(value_path == "sf-ber-threshold")
{
sf_ber_threshold.yfilter = yfilter;
}
if(value_path == "sd-ber-threshold")
{
sd_ber_threshold.yfilter = yfilter;
}
if(value_path == "sf-ber-report")
{
sf_ber_report.yfilter = yfilter;
}
if(value_path == "sd-ber-report")
{
sd_ber_report.yfilter = yfilter;
}
if(value_path == "operational-mode")
{
operational_mode.yfilter = yfilter;
}
if(value_path == "remote-ip")
{
remote_ip.yfilter = yfilter;
}
if(value_path == "register-p-febe")
{
register_p_febe.yfilter = yfilter;
}
if(value_path == "register-l-fe-bip")
{
register_l_fe_bip.yfilter = yfilter;
}
if(value_path == "register-l-bip")
{
register_l_bip.yfilter = yfilter;
}
if(value_path == "register-p-bec")
{
register_p_bec.yfilter = yfilter;
}
if(value_path == "register-s-bip")
{
register_s_bip.yfilter = yfilter;
}
if(value_path == "register-j1-rx0")
{
register_j1_rx0.yfilter = yfilter;
}
if(value_path == "register-j1-rx1")
{
register_j1_rx1.yfilter = yfilter;
}
if(value_path == "register-j1-rx2")
{
register_j1_rx2.yfilter = yfilter;
}
if(value_path == "register-j1-rx3")
{
register_j1_rx3.yfilter = yfilter;
}
if(value_path == "register-j1-rx4")
{
register_j1_rx4.yfilter = yfilter;
}
if(value_path == "register-j1-rx5")
{
register_j1_rx5.yfilter = yfilter;
}
if(value_path == "register-j1-rx6")
{
register_j1_rx6.yfilter = yfilter;
}
if(value_path == "register-j1-rx7")
{
register_j1_rx7.yfilter = yfilter;
}
if(value_path == "wanphy-poll-timer")
{
wanphy_poll_timer.yfilter = yfilter;
}
}
bool Wanphy::Controllers::Controller::Info::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "admin-mode" || name == "port-state" || name == "section-lof" || name == "section-los" || name == "section-bip" || name == "line-ais" || name == "line-rdi" || name == "line-febe" || name == "line-bip" || name == "path-ais" || name == "path-rdi" || name == "path-febe" || name == "path-bip" || name == "path-lop" || name == "path-newptr" || name == "path-pse" || name == "path-nse" || name == "wis-alarms-ser" || name == "wis-alarms-felcdp" || name == "wis-alarms-feaisp" || name == "wis-alarms-wlos" || name == "wis-alarms-plcd" || name == "wis-alarms-lfebip" || name == "wis-alarms-pbec" || name == "wis-alarms-plmp" || name == "sf-ber-threshold" || name == "sd-ber-threshold" || name == "sf-ber-report" || name == "sd-ber-report" || name == "operational-mode" || name == "remote-ip" || name == "register-p-febe" || name == "register-l-fe-bip" || name == "register-l-bip" || name == "register-p-bec" || name == "register-s-bip" || name == "register-j1-rx0" || name == "register-j1-rx1" || name == "register-j1-rx2" || name == "register-j1-rx3" || name == "register-j1-rx4" || name == "register-j1-rx5" || name == "register-j1-rx6" || name == "register-j1-rx7" || name == "wanphy-poll-timer")
return true;
return false;
}
const Enum::YLeaf WanphyAlarmRepStatus::disable {0, "disable"};
const Enum::YLeaf WanphyAlarmRepStatus::enable {1, "enable"};
const Enum::YLeaf WanphyModeInfo::lan {0, "lan"};
const Enum::YLeaf WanphyModeInfo::wan {1, "wan"};
}
}
| 34.114563 | 1,207 | 0.68581 | [
"vector"
] |
a775d9bdc2e5b6f4f7657e19b3b1e8b67e7fa35d | 13,170 | cc | C++ | gazebo/sensors/Sensor.cc | SamFerwerda/Gazebo10-commits | b33ac5982fb75cac894fa145f7268146d44e0724 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-06-19T14:52:45.000Z | 2020-11-05T10:25:10.000Z | gazebo/sensors/Sensor.cc | SamFerwerda/Gazebo10-commits | b33ac5982fb75cac894fa145f7268146d44e0724 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-06-04T10:26:04.000Z | 2020-06-04T10:26:04.000Z | gazebo/sensors/Sensor.cc | SamFerwerda/Gazebo10-commits | b33ac5982fb75cac894fa145f7268146d44e0724 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-04-25T22:05:09.000Z | 2020-03-08T08:45:12.000Z | /*
* Copyright (C) 2012 Open Source Robotics Foundation
*
* 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.
*
*/
#ifdef _WIN32
// Ensure that Winsock2.h is included before Windows.h, which can get
// pulled in by anybody (e.g., Boost).
#include <Winsock2.h>
#endif
#include "gazebo/transport/transport.hh"
#include "gazebo/physics/PhysicsIface.hh"
#include "gazebo/physics/World.hh"
#include "gazebo/common/Timer.hh"
#include "gazebo/common/Console.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/common/Plugin.hh"
#include "gazebo/rendering/Camera.hh"
#include "gazebo/rendering/Distortion.hh"
#include "gazebo/rendering/RenderingIface.hh"
#include "gazebo/rendering/Scene.hh"
#include "gazebo/sensors/CameraSensor.hh"
#include "gazebo/sensors/LogicalCameraSensor.hh"
#include "gazebo/sensors/Noise.hh"
#include "gazebo/sensors/SensorPrivate.hh"
#include "gazebo/sensors/Sensor.hh"
#include "gazebo/sensors/SensorManager.hh"
using namespace gazebo;
using namespace sensors;
sdf::ElementPtr SensorPrivate::sdfSensor;
//////////////////////////////////////////////////
Sensor::Sensor(SensorCategory _cat)
: dataPtr(new SensorPrivate)
{
if (!this->dataPtr->sdfSensor)
{
this->dataPtr->sdfSensor.reset(new sdf::Element);
sdf::initFile("sensor.sdf", this->dataPtr->sdfSensor);
}
this->dataPtr->category = _cat;
this->sdf = this->dataPtr->sdfSensor->Clone();
this->active = false;
this->node = transport::NodePtr(new transport::Node());
this->dataPtr->updateDelay = common::Time(0.0);
this->updatePeriod = common::Time(0.0);
this->dataPtr->id = physics::getUniqueId();
}
//////////////////////////////////////////////////
Sensor::~Sensor()
{
this->Fini();
}
//////////////////////////////////////////////////
void Sensor::Load(const std::string &_worldName, sdf::ElementPtr _sdf)
{
this->sdf->Copy(_sdf);
this->Load(_worldName);
}
//////////////////////////////////////////////////
void Sensor::Load(const std::string &_worldName)
{
if (this->sdf->HasElement("pose"))
{
this->pose =
this->sdf->Get<ignition::math::Pose3d>("pose");
}
if (this->sdf->Get<bool>("always_on"))
this->SetActive(true);
this->world = physics::get_world(_worldName);
if (this->dataPtr->category == IMAGE)
this->scene = rendering::get_scene(_worldName);
// loaded, but not updated
this->lastUpdateTime = common::Time(0.0);
this->node->Init(this->world->Name());
this->dataPtr->sensorPub =
this->node->Advertise<msgs::Sensor>("~/sensor");
}
//////////////////////////////////////////////////
void Sensor::Init()
{
this->SetUpdateRate(this->sdf->Get<double>("update_rate"));
// Load the plugins
if (this->sdf->HasElement("plugin"))
{
sdf::ElementPtr pluginElem = this->sdf->GetElement("plugin");
while (pluginElem)
{
this->LoadPlugin(pluginElem);
pluginElem = pluginElem->GetNextElement("plugin");
}
}
msgs::Sensor msg;
this->FillMsg(msg);
this->dataPtr->sensorPub->Publish(msg);
}
//////////////////////////////////////////////////
void Sensor::SetParent(const std::string &_name, const uint32_t _id)
{
this->parentName = _name;
this->parentId = _id;
}
//////////////////////////////////////////////////
std::string Sensor::ParentName() const
{
return this->parentName;
}
//////////////////////////////////////////////////
uint32_t Sensor::Id() const
{
return this->dataPtr->id;
}
//////////////////////////////////////////////////
uint32_t Sensor::ParentId() const
{
return this->parentId;
}
//////////////////////////////////////////////////
bool Sensor::NeedsUpdate()
{
// Adjust time-to-update period to compensate for delays caused by another
// sensor's update in the same thread.
common::Time simTime;
if (this->dataPtr->category == IMAGE && this->scene)
simTime = this->scene->SimTime();
else
simTime = this->world->SimTime();
// case when last update occurred in the future probably due to
// world reset
if (simTime <= this->lastMeasurementTime)
{
// Rendering sensors also set the lastMeasurementTime variable in Render()
// and lastUpdateTime in Sensor::Update based on Scene::SimTime() which
// could be outdated when the world is reset. In this case reset
// the variables back to 0.
this->ResetLastUpdateTime();
return false;
}
return (simTime - this->lastMeasurementTime +
this->dataPtr->updateDelay) >= this->updatePeriod;
}
//////////////////////////////////////////////////
void Sensor::Update(const bool _force)
{
if (this->IsActive() || _force)
{
common::Time simTime;
if (this->dataPtr->category == IMAGE && this->scene)
simTime = this->scene->SimTime();
else
simTime = this->world->SimTime();
{
std::lock_guard<std::mutex> lock(this->dataPtr->mutexLastUpdateTime);
if (simTime <= this->lastUpdateTime && !_force)
return;
// Adjust time-to-update period to compensate for delays caused by another
// sensor's update in the same thread.
// NOTE: If you change this equation, also change the matching equation in
// Sensor::NeedsUpdate
common::Time adjustedElapsed = simTime -
this->lastUpdateTime + this->dataPtr->updateDelay;
if (adjustedElapsed < this->updatePeriod && !_force)
return;
this->dataPtr->updateDelay = std::max(common::Time::Zero,
adjustedElapsed - this->updatePeriod);
// if delay is more than a full update period, then give up trying
// to catch up. This happens normally when the sensor just changed from
// an inactive to an active state, or the sensor just cannot hit its
// target update rate (worst case).
if (this->dataPtr->updateDelay >= this->updatePeriod)
this->dataPtr->updateDelay = common::Time::Zero;
}
if (this->UpdateImpl(_force))
{
std::lock_guard<std::mutex> lock(this->dataPtr->mutexLastUpdateTime);
this->lastUpdateTime = simTime;
this->dataPtr->updated();
}
}
}
//////////////////////////////////////////////////
void Sensor::Fini()
{
if (this->node)
this->node->Fini();
this->node.reset();
this->connections.clear();
for (auto &it : this->noises)
it.second->Fini();
this->noises.clear();
this->active = false;
this->plugins.clear();
if (this->sdf)
this->sdf->Reset();
this->sdf.reset();
this->scene.reset();
this->world.reset();
}
//////////////////////////////////////////////////
std::string Sensor::Name() const
{
if (this->sdf)
return this->sdf->Get<std::string>("name");
gzwarn << "Missing sensor SDF." << std::endl;
return "";
}
//////////////////////////////////////////////////
std::string Sensor::ScopedName() const
{
return this->world->Name() + "::" + this->parentName + "::" + this->Name();
}
//////////////////////////////////////////////////
void Sensor::LoadPlugin(sdf::ElementPtr _sdf)
{
std::string name = _sdf->Get<std::string>("name");
std::string filename = _sdf->Get<std::string>("filename");
gazebo::SensorPluginPtr plugin = gazebo::SensorPlugin::Create(filename, name);
if (plugin)
{
if (plugin->GetType() != SENSOR_PLUGIN)
{
gzerr << "Sensor[" << this->Name() << "] is attempting to load "
<< "a plugin, but detected an incorrect plugin type. "
<< "Plugin filename[" << filename << "] name[" << name << "]\n";
return;
}
SensorPtr myself = shared_from_this();
plugin->Load(myself, _sdf);
plugin->Init();
this->plugins.push_back(plugin);
}
}
//////////////////////////////////////////////////
void Sensor::SetActive(const bool _value)
{
this->active = _value;
}
//////////////////////////////////////////////////
bool Sensor::IsActive() const
{
return this->active;
}
//////////////////////////////////////////////////
ignition::math::Pose3d Sensor::Pose() const
{
return this->pose;
}
//////////////////////////////////////////////////
void Sensor::SetPose(const ignition::math::Pose3d &_pose)
{
this->pose = _pose;
// Update the visualization with the pose information.
if (this->dataPtr->sensorPub && this->Visualize())
{
msgs::Sensor msg;
msg.set_name(this->Name());
msg.set_id(this->Id());
msg.set_parent(this->ParentName());
msg.set_parent_id(this->ParentId());
msg.set_type(this->Type());
msg.set_visualize(true);
msgs::Set(msg.mutable_pose(), this->pose);
this->dataPtr->sensorPub->Publish(msg);
}
}
//////////////////////////////////////////////////
double Sensor::UpdateRate() const
{
if (this->updatePeriod.Double() > 0.0)
return 1.0/this->updatePeriod.Double();
else
return 0.0;
}
//////////////////////////////////////////////////
void Sensor::SetUpdateRate(const double _hz)
{
if (_hz > 0.0)
this->updatePeriod = 1.0/_hz;
else
this->updatePeriod = 0.0;
}
//////////////////////////////////////////////////
common::Time Sensor::LastUpdateTime() const
{
return this->lastUpdateTime;
}
//////////////////////////////////////////////////
common::Time Sensor::LastMeasurementTime() const
{
return this->lastMeasurementTime;
}
//////////////////////////////////////////////////
std::string Sensor::Type() const
{
return this->sdf->Get<std::string>("type");
}
//////////////////////////////////////////////////
bool Sensor::Visualize() const
{
return this->sdf->Get<bool>("visualize");
}
//////////////////////////////////////////////////
std::string Sensor::Topic() const
{
std::string result;
if (this->sdf->HasElement("topic") &&
this->sdf->Get<std::string>("topic") != "__default__")
result = this->sdf->Get<std::string>("topic");
return result;
}
//////////////////////////////////////////////////
void Sensor::FillMsg(msgs::Sensor &_msg)
{
_msg.set_name(this->Name());
_msg.set_id(this->Id());
_msg.set_type(this->Type());
_msg.set_parent(this->ParentName());
_msg.set_parent_id(this->ParentId());
msgs::Set(_msg.mutable_pose(), this->Pose());
_msg.set_always_on(this->IsActive());
_msg.set_topic(this->Topic());
_msg.set_update_rate(this->UpdateRate());
_msg.set_visualize(this->Visualize());
if (this->Type() == "logical_camera")
{
LogicalCameraSensor *camSensor = static_cast<LogicalCameraSensor*>(this);
msgs::LogicalCameraSensor *camMsg = _msg.mutable_logical_camera();
camMsg->set_near_clip(camSensor->Near());
camMsg->set_far_clip(camSensor->Far());
camMsg->set_horizontal_fov(camSensor->HorizontalFOV().Radian());
camMsg->set_aspect_ratio(camSensor->AspectRatio());
}
else if (this->Type() == "camera" || this->Type() == "wideanglecamera")
{
CameraSensor *camSensor = static_cast<CameraSensor*>(this);
msgs::CameraSensor *camMsg = _msg.mutable_camera();
auto cam = camSensor->Camera();
camMsg->set_horizontal_fov(cam->HFOV().Radian());
camMsg->mutable_image_size()->set_x(camSensor->ImageWidth());
camMsg->mutable_image_size()->set_y(camSensor->ImageHeight());
camMsg->set_image_format(cam->ImageFormat());
camMsg->set_near_clip(cam->NearClip());
camMsg->set_far_clip(cam->FarClip());
auto distortion = cam->LensDistortion();
if (distortion)
{
msgs::Distortion *distortionMsg = camMsg->mutable_distortion();
distortionMsg->set_k1(distortion->K1());
distortionMsg->set_k2(distortion->K2());
distortionMsg->set_k3(distortion->K3());
distortionMsg->set_p1(distortion->P1());
distortionMsg->set_p2(distortion->P2());
distortionMsg->mutable_center()->set_x(distortion->Center().X());
distortionMsg->mutable_center()->set_y(distortion->Center().Y());
}
}
}
//////////////////////////////////////////////////
std::string Sensor::WorldName() const
{
return this->world->Name();
}
//////////////////////////////////////////////////
SensorCategory Sensor::Category() const
{
return this->dataPtr->category;
}
//////////////////////////////////////////////////
NoisePtr Sensor::Noise(const SensorNoiseType _type) const
{
if (this->noises.find(_type) == this->noises.end())
{
gzerr << "Get noise index not valid" << std::endl;
return NoisePtr();
}
return this->noises.at(_type);
}
//////////////////////////////////////////////////
void Sensor::ResetLastUpdateTime()
{
std::lock_guard<std::mutex> lock(this->dataPtr->mutexLastUpdateTime);
this->lastUpdateTime = 0.0;
this->lastMeasurementTime = 0.0;
this->dataPtr->updateDelay = 0.0;
}
//////////////////////////////////////////////////
event::ConnectionPtr Sensor::ConnectUpdated(std::function<void()> _subscriber)
{
return this->dataPtr->updated.Connect(_subscriber);
}
| 27.78481 | 80 | 0.587396 | [
"render"
] |
a777d4ef00587b8f2d66ec52605527ddcd46e29d | 4,041 | cpp | C++ | JorGpi/asa/solver/solver.cpp | adujovic/JorG | 15062984e837a938819e548c83f6f5414fa47103 | [
"BSD-3-Clause"
] | 1 | 2020-07-22T11:05:03.000Z | 2020-07-22T11:05:03.000Z | JorGpi/asa/solver/solver.cpp | adujovic/JorG | 15062984e837a938819e548c83f6f5414fa47103 | [
"BSD-3-Clause"
] | 2 | 2019-06-07T11:53:48.000Z | 2019-06-24T08:20:25.000Z | JorGpi/asa/solver/solver.cpp | adujovic/JorG | 15062984e837a938819e548c83f6f5414fa47103 | [
"BSD-3-Clause"
] | 3 | 2019-07-01T12:38:06.000Z | 2022-02-01T21:38:12.000Z | #include "solver.h"
int solver(char _basis[],char _supercell[],char _flippable[], size_t reference, size_t unique_flips, size_t ansatz){
#ifndef _SITESNUMBER
#define _SITESNUMBER 64
#endif
constexpr size_t SITESNUMBER = _SITESNUMBER;
// *****************************************************************************************
// ************************************** READ *****************************************
// *****************************************************************************************
aux::System<typename ising::IsingModel<SITESNUMBER>::VectorType> system;
aux::read_basis(system.basis,_basis);
aux::read_supercell(system.supercell,_supercell);
aux::read_flippables(system.flippable,_flippable);
#ifndef _QUIET
aux::greetings();
#endif
// *****************************************************************************************
// ******************************* INITIALIZE ENGINE ***********************************
// *****************************************************************************************
std::random_device randomDevice{};
std::mt19937 generator{randomDevice()};
std::normal_distribution<> gauss{0.0,1.0};
ising::IsingModel<SITESNUMBER> model;
model.set_basis(system.basis);
model.set_supercell(system.flippable);
model.set_reference(reference);
// *****************************************************************************************
// ******************************** MAP INTERACTIONS ***********************************
// *****************************************************************************************
double decayCoeff;
aux::map_geometry(system.flippable,decayCoeff);
std::bitset<SITESNUMBER> mask(std::string(SITESNUMBER,'0'));
for (const auto& atom : system.flippable) mask.set(std::get<0>(atom));
mask.reset(reference);
// *****************************************************************************************
// ******************************** CHECK MODEL ****************************************
// *****************************************************************************************
#ifdef _VERBOSE
std::cout<<" ";
for(int i=1; i<(SITESNUMBER-reference); ++i) std::cout<<" ";
std::cout<<"| reference"<<std::endl;
std::cout<<"Mask: "<<mask<<std::endl;
#endif
#ifdef _LOWERLIMIT
size_t lowerlimit = _LOWERLIMIT;
#else
size_t lowerlimit = 0.15*mask.count(); // doesn't allow less than 15% flipps
#endif
#ifdef _UPPERLIMIT
size_t upperlimit = _UPPERLIMIT;
#else
size_t upperlimit = 0.85*mask.count(); // doesn't allow more than 85% flipps
#endif
upperlimit = upperlimit < 2U ? 2U : upperlimit;
lowerlimit = lowerlimit > upperlimit ? 1U : lowerlimit;
lowerlimit = lowerlimit < 1U ? 1U : lowerlimit;
std::unordered_set<std::bitset<SITESNUMBER>> solutions;
size_t iteration = 0U;
for(auto n = 4.0; n<1024.0; n*=2){
model.reset();
auto d = aux::get_interactions(system,n*decayCoeff,ansatz);
model.add_interaction(d);
#ifdef _VERBOSE
std::cout<<"Limits are set to be: ["<<lowerlimit<<","<<upperlimit<<']'<<std::endl;
#endif
for(unsigned m = 0; m<unique_flips; ++m){
model.randomize_state();
auto x = model.run(&mask);
if(x.count() < lowerlimit) continue;
if(x.count() > upperlimit) continue;
if(x.count() > 0.5*mask.count()) x.flip();
#ifndef _QUIET
std::cout<<"("<<iteration<<")\t"<<n*decayCoeff<<"\t";
aux::print_state(x,reference,mask);
#endif
solutions.insert(x);
++iteration;
if(solutions.size() >= unique_flips) break;
}
if(solutions.size() >= unique_flips) break;
}
std::ofstream ostrm("best.flips", std::ios::out);
for(const auto& x : solutions){
for(unsigned b=0U; b<SITESNUMBER; ++b){
ostrm<<x[b]<<" ";
}
ostrm<<std::endl;
}
return 0;
}
| 36.736364 | 116 | 0.464736 | [
"model"
] |
a777e1c6c413654a8874acfcba129863f4617bc4 | 9,578 | cpp | C++ | src/minisef/movieobjects/dmedccmakefile.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/minisef/movieobjects/dmedccmakefile.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/minisef/movieobjects/dmedccmakefile.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Describes an asset: something that is compiled from sources,
// in potentially multiple steps, to a compiled resource
//
//=============================================================================
#include "movieobjects/dmedccmakefile.h"
#include "datamodel/dmelementfactoryhelper.h"
#include "tier2/fileutils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Hook into datamodel
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeSourceDCCFile, CDmeSourceDCCFile );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CDmeSourceDCCFile::OnConstruction()
{
m_RootDCCObjects.Init( this, "rootDCCObjects" );
m_ExportType.InitAndSet( this, "exportType", 0 );
m_FrameStart.InitAndSet( this, "frameStart", 0.0f );
m_FrameEnd.InitAndSet( this, "frameEnd", 0.0f );
m_FrameIncrement.InitAndSet( this, "frameIncrement", 1.0f );
}
void CDmeSourceDCCFile::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Hook into datamodel
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeSourceMayaFile, CDmeSourceMayaFile );
IMPLEMENT_ELEMENT_FACTORY( DmeSourceMayaModelFile, CDmeSourceMayaModelFile );
IMPLEMENT_ELEMENT_FACTORY( DmeSourceMayaAnimationFile, CDmeSourceMayaAnimationFile );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CDmeSourceMayaFile::OnConstruction()
{
}
void CDmeSourceMayaFile::OnDestruction()
{
}
void CDmeSourceMayaModelFile::OnConstruction()
{
m_ExportType = 0;
}
void CDmeSourceMayaModelFile::OnDestruction()
{
}
void CDmeSourceMayaAnimationFile::OnConstruction()
{
m_ExportType = 1;
}
void CDmeSourceMayaAnimationFile::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Hook into datamodel
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeSourceXSIFile, CDmeSourceXSIFile );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CDmeSourceXSIFile::OnConstruction()
{
}
void CDmeSourceXSIFile::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Hook into datamodel
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeDCCMakefile, CDmeDCCMakefile );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CDmeDCCMakefile::OnConstruction()
{
m_bFlushFile = false;
}
void CDmeDCCMakefile::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Compile assets
//-----------------------------------------------------------------------------
void CDmeDCCMakefile::GetOutputs( CUtlVector<CUtlString> &fullPaths )
{
fullPaths.RemoveAll();
char pOutputName[MAX_PATH];
Q_FileBase( GetFileName(), pOutputName, sizeof(pOutputName) );
if ( !pOutputName[0] )
return;
// FIXME: We need to come up with an appropriate directory structure for export
char pOutputDir[MAX_PATH];
GetMakefilePath( pOutputDir, sizeof(pOutputDir) );
if ( !pOutputDir[0] )
return;
Q_StripTrailingSlash( pOutputDir );
char pFullPath[MAX_PATH];
Q_snprintf( pFullPath, sizeof(pFullPath), "%s\\%s.dmx", pOutputDir, pOutputName );
fullPaths.AddToTail( pFullPath );
}
//-----------------------------------------------------------------------------
// Creates, destroys the output element associated with this makefile
//-----------------------------------------------------------------------------
CDmElement *CDmeDCCMakefile::CreateOutputElement( )
{
if ( m_bFlushFile )
{
m_bFlushFile = false;
if ( GetFileId() != DMFILEID_INVALID )
{
// NOTE: CDmeHandles will correctly re-hook up to the new makefile after load
// If the file fails to load, we have the copy. If the file correctly has the make in it
// it will replace this copy I made
CDmeHandle< CDmeDCCMakefile > hMakefileOld;
hMakefileOld = this;
// NOTE NOTE NOTE
// UnloadFile essentially calls delete this!
// So don't refer to any state in this DmElement after that
DmFileId_t fileId = GetFileId();
g_pDataModel->UnloadFile( fileId );
CDmElement *pRoot = NULL;
if ( g_pDataModel->RestoreFromFile( g_pDataModel->GetFileName( fileId ), NULL, NULL, &pRoot, CR_DELETE_OLD ) != DMFILEID_INVALID )
{
// NOTE: Unload/restore kills the this pointer, we need to redo this
if ( hMakefileOld.Get() )
{
hMakefileOld->SetDirty( false );
return hMakefileOld->CreateOutputElement();
}
}
// NOTE: We expect file backup prior to compile to avoid really fatal errors
// This case happens if the file failed to load. In this case, we must use
// the copy of the makefile
Assert( 0 );
return NULL;
}
}
// The output element is the root element containing the makefile
return FindReferringElement< CDmElement >( this, "makefile" );
}
void CDmeDCCMakefile::DestroyOutputElement( CDmElement *pOutput )
{
m_bFlushFile = true;
}
//-----------------------------------------------------------------------------
// Hook into datamodel
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeMayaMakefile, CDmeMayaMakefile );
IMPLEMENT_ELEMENT_FACTORY( DmeMayaModelMakefile, CDmeMayaModelMakefile );
IMPLEMENT_ELEMENT_FACTORY( DmeMayaAnimationMakefile, CDmeMayaAnimationMakefile );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CDmeMayaMakefile::OnConstruction()
{
}
void CDmeMayaMakefile::OnDestruction()
{
}
void CDmeMayaModelMakefile::OnConstruction()
{
}
void CDmeMayaModelMakefile::OnDestruction()
{
}
void CDmeMayaAnimationMakefile::OnConstruction()
{
}
void CDmeMayaAnimationMakefile::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Returns source types
//-----------------------------------------------------------------------------
static DmeMakefileType_t s_pMayaModelSourceTypes[] =
{
{ "DmeSourceMayaModelFile", "Maya Model File", true, "makefiledir:../maya", "*.ma;*.mb", "Maya File (*.ma,*.mb)" },
{ NULL, NULL, false, NULL, NULL, NULL },
};
DmeMakefileType_t* CDmeMayaModelMakefile::GetSourceTypes()
{
return s_pMayaModelSourceTypes;
}
static DmeMakefileType_t s_pMayaAnimationSourceTypes[] =
{
{ "DmeSourceMayaAnimationFile", "Maya Animation File", true, "makefiledir:../maya", "*.ma;*.mb", "Maya File (*.ma,*.mb)" },
{ NULL, NULL, false, NULL, NULL, NULL },
};
DmeMakefileType_t* CDmeMayaAnimationMakefile::GetSourceTypes()
{
return s_pMayaAnimationSourceTypes;
}
//-----------------------------------------------------------------------------
// Makefile type
//-----------------------------------------------------------------------------
static DmeMakefileType_t s_MayaModelMakefileType =
{
"DmeMayaModelMakefile", "Maya Model Component", true, "contentdir:models", "*.dmx", "DMX File (*.dmx)"
};
DmeMakefileType_t *CDmeMayaModelMakefile::GetMakefileType()
{
return &s_MayaModelMakefileType;
}
static DmeMakefileType_t s_MayaAnimationMakefileType =
{
"DmeMayaAnimationMakefile", "Maya Animation Component", true, "contentdir:models", "*.dmx", "DMX File (*.dmx)"
};
DmeMakefileType_t *CDmeMayaAnimationMakefile::GetMakefileType()
{
return &s_MayaAnimationMakefileType;
}
//-----------------------------------------------------------------------------
// Hook into datamodel
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeXSIMakefile, CDmeXSIMakefile );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CDmeXSIMakefile::OnConstruction()
{
}
void CDmeXSIMakefile::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Returns source types
//-----------------------------------------------------------------------------
static DmeMakefileType_t s_pXSISourceTypes[] =
{
{ "DmeSourceXSIFile", "XSI File", true, "makefiledir:../xsi", "*.xsi", "XSI File (*.xsi)" },
{ NULL, NULL, false, NULL, NULL, NULL },
};
DmeMakefileType_t* CDmeXSIMakefile::GetSourceTypes()
{
return s_pXSISourceTypes;
}
//-----------------------------------------------------------------------------
// Makefile type
//-----------------------------------------------------------------------------
static DmeMakefileType_t s_XSIMakefileType =
{
"DmeXSIMakefile", "XSI Model Component", true, "contentdir:models", "*.dmx", "DMX File (*.dmx)",
};
DmeMakefileType_t *CDmeXSIMakefile::GetMakefileType()
{
return &s_XSIMakefileType;
}
| 29.561728 | 133 | 0.511276 | [
"model"
] |
a77a2811a5b7386964c31d357a3b92967527f178 | 27,270 | cc | C++ | src/media/audio/audio_core/mixer/point_sampler.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | src/media/audio/audio_core/mixer/point_sampler.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | src/media/audio/audio_core/mixer/point_sampler.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia 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 "src/media/audio/audio_core/mixer/point_sampler.h"
#include <algorithm>
#include <limits>
#include "src/lib/fxl/logging.h"
#include "src/media/audio/audio_core/mixer/constants.h"
#include "src/media/audio/audio_core/mixer/mixer_utils.h"
namespace media::audio::mixer {
// Point Sample Mixer implementation.
template <size_t DestChanCount, typename SrcSampleType, size_t SrcChanCount>
class PointSamplerImpl : public PointSampler {
public:
PointSamplerImpl() : PointSampler(kPositiveFilterWidth, kNegativeFilterWidth) {}
bool Mix(float* dest, uint32_t dest_frames, uint32_t* dest_offset, const void* src,
uint32_t frac_src_frames, int32_t* frac_src_offset, bool accumulate,
Bookkeeping* info) override;
private:
static constexpr uint32_t kPositiveFilterWidth = 0;
static constexpr uint32_t kNegativeFilterWidth = FRAC_ONE - 1;
template <ScalerType ScaleType, bool DoAccumulate, bool HasModulo>
static inline bool Mix(float* dest, uint32_t dest_frames, uint32_t* dest_offset, const void* src,
uint32_t frac_src_frames, int32_t* frac_src_offset, Bookkeeping* info);
};
// TODO(MTWN-75): refactor to minimize code duplication, or even better eliminate NxN
// implementations altogether, replaced by flexible rechannelization (MTWN-399).
template <typename SrcSampleType>
class NxNPointSamplerImpl : public PointSampler {
public:
NxNPointSamplerImpl(uint32_t chan_count)
: PointSampler(0, FRAC_ONE - 1), chan_count_(chan_count) {}
bool Mix(float* dest, uint32_t dest_frames, uint32_t* dest_offset, const void* src,
uint32_t frac_src_frames, int32_t* frac_src_offset, bool accumulate,
Bookkeeping* info) override;
private:
static constexpr uint32_t kPositiveFilterWidth = 0;
static constexpr uint32_t kNegativeFilterWidth = FRAC_ONE - 1;
template <ScalerType ScaleType, bool DoAccumulate, bool HasModulo>
static inline bool Mix(float* dest, uint32_t dest_frames, uint32_t* dest_offset, const void* src,
uint32_t frac_src_frames, int32_t* frac_src_offset, Bookkeeping* info,
uint32_t chan_count);
uint32_t chan_count_ = 0;
};
// If upper layers call with ScaleType MUTED, they must set DoAccumulate=TRUE.
// They guarantee new buffers are cleared before usage; we optimize accordingly.
template <size_t DestChanCount, typename SrcSampleType, size_t SrcChanCount>
template <ScalerType ScaleType, bool DoAccumulate, bool HasModulo>
inline bool PointSamplerImpl<DestChanCount, SrcSampleType, SrcChanCount>::Mix(
float* dest, uint32_t dest_frames, uint32_t* dest_offset, const void* src_void,
uint32_t frac_src_frames, int32_t* frac_src_offset, Bookkeeping* info) {
static_assert(ScaleType != ScalerType::MUTED || DoAccumulate == true,
"Mixing muted streams without accumulation is explicitly unsupported");
// We express number-of-source-frames as fixed-point 19.13 (to align with
// src_offset) but the actual number of frames provided is always an integer.
FXL_DCHECK((frac_src_frames & kPtsFractionalMask) == 0);
// Interpolation offset is int32, so even though frac_src_frames is a uint32,
// callers should not exceed int32_t::max().
FXL_DCHECK(frac_src_frames <= static_cast<uint32_t>(std::numeric_limits<int32_t>::max()));
// This method must always be provided at least one source frame.
FXL_DCHECK(frac_src_frames >= FRAC_ONE);
using DM = DestMixer<ScaleType, DoAccumulate>;
uint32_t dest_off = *dest_offset;
uint32_t dest_off_start = dest_off; // Only used when ramping.
// Location of first dest frame to produce must be within the provided buffer.
FXL_DCHECK(dest_off < dest_frames);
using SR = SrcReader<SrcSampleType, SrcChanCount, DestChanCount>;
int32_t src_off = *frac_src_offset;
const auto* src = static_cast<const SrcSampleType*>(src_void);
// "Source offset" can be negative within the bounds of pos_filter_width.
// Here, PointSampler has no memory: input frames only affect present/future
// output. That is: its "positive filter width" is zero. Thus src_off must be
// non-negative. Callers explicitly avoid calling Mix in this error case.
FXL_DCHECK(src_off >= 0) << std::hex << "src_off: 0x" << src_off;
// src_off cannot exceed our last sampleable subframe. We define this as
// "Source end": the last subframe for which this Mix call can produce output.
// Otherwise, all these src samples are in the past and irrelevant here.
auto src_end = static_cast<int32_t>(frac_src_frames - PointSamplerImpl::kPositiveFilterWidth - 1);
FXL_DCHECK(src_end >= 0);
FXL_DCHECK(src_off < static_cast<int32_t>(frac_src_frames))
<< std::hex << "src_off: 0x" << src_off << ", src_end: 0x" << src_end
<< ", frac_src_frames: 0x" << frac_src_frames;
// Cache these locally, for the HasModulo specializations that use them.
// Only src_pos_modulo must be written back before returning.
uint32_t step_size = info->step_size;
uint32_t rate_modulo, denominator, src_pos_modulo;
if constexpr (HasModulo) {
rate_modulo = info->rate_modulo;
denominator = info->denominator;
src_pos_modulo = info->src_pos_modulo;
FXL_DCHECK(denominator > 0);
FXL_DCHECK(denominator > rate_modulo);
FXL_DCHECK(denominator > src_pos_modulo);
}
if constexpr (kVerboseRampDebug) {
FXL_LOG(INFO) << "Point Ramping: " << (ScaleType == ScalerType::RAMPING)
<< ", dest_frames: " << dest_frames << ", dest_off: " << dest_off;
}
if constexpr (ScaleType == ScalerType::RAMPING) {
if (dest_frames > Bookkeeping::kScaleArrLen + dest_off) {
dest_frames = Bookkeeping::kScaleArrLen + dest_off;
}
}
// If we are not attenuated to the point of being muted, go ahead and perform
// the mix. Otherwise, just update the source and dest offsets.
if constexpr (ScaleType != ScalerType::MUTED) {
Gain::AScale amplitude_scale;
if constexpr (ScaleType != ScalerType::RAMPING) {
amplitude_scale = info->gain.GetGainScale();
}
while ((dest_off < dest_frames) && (src_off <= src_end)) {
if constexpr (ScaleType == ScalerType::RAMPING) {
amplitude_scale = info->scale_arr[dest_off - dest_off_start];
}
uint32_t src_iter = (src_off >> kPtsFractionalBits) * SrcChanCount;
float* out = dest + (dest_off * DestChanCount);
for (size_t dest_iter = 0; dest_iter < DestChanCount; ++dest_iter) {
auto src_chan_offset = dest_iter % SrcChanCount;
float sample = SR::Read(src + src_iter + src_chan_offset);
out[dest_iter] = DM::Mix(out[dest_iter], sample, amplitude_scale);
}
++dest_off;
src_off += step_size;
if constexpr (HasModulo) {
src_pos_modulo += rate_modulo;
if (src_pos_modulo >= denominator) {
++src_off;
src_pos_modulo -= denominator;
}
}
}
} else {
// We are muted. Don't mix, but figure out how many samples we WOULD have
// produced and update the src_off and dest_off values appropriately.
if ((dest_off < dest_frames) && (src_off <= src_end)) {
uint32_t src_avail = ((src_end - src_off) / step_size) + 1;
uint32_t dest_avail = dest_frames - dest_off;
uint32_t avail = std::min(dest_avail, src_avail);
src_off += (avail * step_size);
dest_off += avail;
if constexpr (HasModulo) {
uint64_t total_mod = src_pos_modulo + (avail * rate_modulo);
src_off += (total_mod / denominator);
src_pos_modulo = total_mod % denominator;
int32_t prev_src_off =
(src_pos_modulo < rate_modulo) ? (src_off - step_size - 1) : (src_off - step_size);
while (prev_src_off > src_end) {
if (src_pos_modulo < rate_modulo) {
src_pos_modulo += denominator;
}
--dest_off;
src_off = prev_src_off;
src_pos_modulo -= rate_modulo;
prev_src_off =
(src_pos_modulo < rate_modulo) ? (src_off - step_size - 1) : (src_off - step_size);
}
}
}
}
// Update all our returned in-out parameters
*dest_offset = dest_off;
*frac_src_offset = src_off;
if constexpr (HasModulo) {
info->src_pos_modulo = src_pos_modulo;
}
// If we passed the last valid source subframe, then we exhausted this source.
return (src_off > src_end);
}
template <size_t DestChanCount, typename SrcSampleType, size_t SrcChanCount>
bool PointSamplerImpl<DestChanCount, SrcSampleType, SrcChanCount>::Mix(
float* dest, uint32_t dest_frames, uint32_t* dest_offset, const void* src,
uint32_t frac_src_frames, int32_t* frac_src_offset, bool accumulate, Bookkeeping* info) {
FXL_DCHECK(info != nullptr);
bool hasModulo = (info->denominator > 0 && info->rate_modulo > 0);
if (info->gain.IsUnity()) {
return accumulate
? (hasModulo ? Mix<ScalerType::EQ_UNITY, true, true>(dest, dest_frames, dest_offset,
src, frac_src_frames,
frac_src_offset, info)
: Mix<ScalerType::EQ_UNITY, true, false>(dest, dest_frames, dest_offset,
src, frac_src_frames,
frac_src_offset, info))
: (hasModulo ? Mix<ScalerType::EQ_UNITY, false, true>(dest, dest_frames, dest_offset,
src, frac_src_frames,
frac_src_offset, info)
: Mix<ScalerType::EQ_UNITY, false, false>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info));
} else if (info->gain.IsSilent()) {
return (hasModulo
? Mix<ScalerType::MUTED, true, true>(dest, dest_frames, dest_offset, src,
frac_src_frames, frac_src_offset, info)
: Mix<ScalerType::MUTED, true, false>(dest, dest_frames, dest_offset, src,
frac_src_frames, frac_src_offset, info));
} else if (info->gain.IsRamping()) {
return accumulate
? (hasModulo
? Mix<ScalerType::RAMPING, true, true>(dest, dest_frames, dest_offset, src,
frac_src_frames, frac_src_offset, info)
: Mix<ScalerType::RAMPING, true, false>(dest, dest_frames, dest_offset, src,
frac_src_frames, frac_src_offset,
info))
: (hasModulo ? Mix<ScalerType::RAMPING, false, true>(dest, dest_frames, dest_offset,
src, frac_src_frames,
frac_src_offset, info)
: Mix<ScalerType::RAMPING, false, false>(dest, dest_frames, dest_offset,
src, frac_src_frames,
frac_src_offset, info));
} else {
return accumulate
? (hasModulo ? Mix<ScalerType::NE_UNITY, true, true>(dest, dest_frames, dest_offset,
src, frac_src_frames,
frac_src_offset, info)
: Mix<ScalerType::NE_UNITY, true, false>(dest, dest_frames, dest_offset,
src, frac_src_frames,
frac_src_offset, info))
: (hasModulo ? Mix<ScalerType::NE_UNITY, false, true>(dest, dest_frames, dest_offset,
src, frac_src_frames,
frac_src_offset, info)
: Mix<ScalerType::NE_UNITY, false, false>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info));
}
}
// If upper layers call with ScaleType MUTED, they must set DoAccumulate=TRUE.
// They guarantee new buffers are cleared before usage; we optimize accordingly.
template <typename SrcSampleType>
template <ScalerType ScaleType, bool DoAccumulate, bool HasModulo>
inline bool NxNPointSamplerImpl<SrcSampleType>::Mix(float* dest, uint32_t dest_frames,
uint32_t* dest_offset, const void* src_void,
uint32_t frac_src_frames,
int32_t* frac_src_offset, Bookkeeping* info,
uint32_t chan_count) {
static_assert(ScaleType != ScalerType::MUTED || DoAccumulate == true,
"Mixing muted streams without accumulation is explicitly unsupported");
// We express number-of-source-frames as fixed-point 19.13 (to align with
// src_offset) but the actual number of frames provided is always an integer.
FXL_DCHECK((frac_src_frames & kPtsFractionalMask) == 0);
// Interpolation offset is int32, so even though frac_src_frames is a uint32,
// callers should not exceed int32_t::max().
FXL_DCHECK(frac_src_frames <= static_cast<uint32_t>(std::numeric_limits<int32_t>::max()));
// This method must always be provided at least one source frame.
FXL_DCHECK(frac_src_frames >= FRAC_ONE);
using DM = DestMixer<ScaleType, DoAccumulate>;
uint32_t dest_off = *dest_offset;
uint32_t dest_off_start = dest_off; // Only used when ramping.
// Location of first dest frame to produce must be within the provided buffer.
FXL_DCHECK(dest_off < dest_frames);
int32_t src_off = *frac_src_offset;
const auto* src = static_cast<const SrcSampleType*>(src_void);
// "Source offset" can be negative within the bounds of pos_filter_width.
// Here, PointSampler has no memory: input frames only affect present/future
// output. That is: its "positive filter width" is zero. Thus src_off must be
// non-negative. Callers explicitly avoid calling Mix in this error case.
FXL_DCHECK(src_off + static_cast<int32_t>(NxNPointSamplerImpl::kPositiveFilterWidth) >= 0)
<< std::hex << "src_off: 0x" << src_off;
// src_off cannot exceed our last sampleable subframe. We define this as
// "Source end": the last subframe for which this Mix call can produce output.
// Otherwise, all these src samples are in the past and irrelevant here.
auto src_end =
static_cast<int32_t>(frac_src_frames - NxNPointSamplerImpl::kPositiveFilterWidth - 1);
FXL_DCHECK(src_end >= 0);
FXL_DCHECK(src_off < static_cast<int32_t>(frac_src_frames))
<< std::hex << "src_off: 0x" << src_off << ", src_end: 0x" << src_end
<< ", frac_src_frames: 0x" << frac_src_frames;
// Cache these locally, in the template specialization that uses them.
// Only src_pos_modulo needs to be written back before returning.
uint32_t step_size = info->step_size;
uint32_t rate_modulo, denominator, src_pos_modulo;
if constexpr (HasModulo) {
rate_modulo = info->rate_modulo;
denominator = info->denominator;
src_pos_modulo = info->src_pos_modulo;
FXL_DCHECK(denominator > 0);
FXL_DCHECK(denominator > rate_modulo);
FXL_DCHECK(denominator > src_pos_modulo);
}
if constexpr (kVerboseRampDebug) {
FXL_LOG(INFO) << "Point-NxN Ramping: " << (ScaleType == ScalerType::RAMPING)
<< ", dest_frames: " << dest_frames << ", dest_off: " << dest_off;
}
if constexpr (ScaleType == ScalerType::RAMPING) {
if (dest_frames > Bookkeeping::kScaleArrLen + dest_off) {
dest_frames = Bookkeeping::kScaleArrLen + dest_off;
}
}
// If we are not attenuated to the point of being muted, perform the mix.
// Otherwise, just update the source and dest offsets.
if constexpr (ScaleType != ScalerType::MUTED) {
Gain::AScale amplitude_scale;
if constexpr (ScaleType != ScalerType::RAMPING) {
amplitude_scale = info->gain.GetGainScale();
}
while ((dest_off < dest_frames) && (src_off <= src_end)) {
if constexpr (ScaleType == ScalerType::RAMPING) {
amplitude_scale = info->scale_arr[dest_off - dest_off_start];
}
uint32_t src_iter = (src_off >> kPtsFractionalBits) * chan_count;
float* out = dest + (dest_off * chan_count);
for (size_t dest_iter = 0; dest_iter < chan_count; ++dest_iter) {
float sample = SampleNormalizer<SrcSampleType>::Read(src + src_iter + dest_iter);
out[dest_iter] = DM::Mix(out[dest_iter], sample, amplitude_scale);
}
++dest_off;
src_off += step_size;
if constexpr (HasModulo) {
src_pos_modulo += rate_modulo;
if (src_pos_modulo >= denominator) {
++src_off;
src_pos_modulo -= denominator;
}
}
}
} else {
// We are muted. Don't mix, but figure out how many samples we WOULD have
// produced and update the src_off and dest_off values appropriately.
if ((dest_off < dest_frames) && (src_off <= src_end)) {
uint32_t src_avail = ((src_end - src_off) / step_size) + 1;
uint32_t dest_avail = dest_frames - dest_off;
uint32_t avail = std::min(src_avail, dest_avail);
src_off += (avail * step_size);
dest_off += avail;
if constexpr (HasModulo) {
uint64_t total_mod = src_pos_modulo + (avail * rate_modulo);
src_off += (total_mod / denominator);
src_pos_modulo = total_mod % denominator;
int32_t prev_src_off =
(src_pos_modulo < rate_modulo) ? (src_off - step_size - 1) : (src_off - step_size);
while (prev_src_off > src_end) {
if (src_pos_modulo < rate_modulo) {
src_pos_modulo += denominator;
}
--dest_off;
src_off = prev_src_off;
src_pos_modulo -= rate_modulo;
prev_src_off =
(src_pos_modulo < rate_modulo) ? (src_off - step_size - 1) : (src_off - step_size);
}
}
}
}
// Update all our returned in-out parameters
*dest_offset = dest_off;
*frac_src_offset = src_off;
if constexpr (HasModulo) {
info->src_pos_modulo = src_pos_modulo;
}
// If we passed the last valid source subframe, then we exhausted this source.
return (src_off > src_end);
}
template <typename SrcSampleType>
bool NxNPointSamplerImpl<SrcSampleType>::Mix(float* dest, uint32_t dest_frames,
uint32_t* dest_offset, const void* src,
uint32_t frac_src_frames, int32_t* frac_src_offset,
bool accumulate, Bookkeeping* info) {
FXL_DCHECK(info != nullptr);
bool hasModulo = (info->denominator > 0 && info->rate_modulo > 0);
if (info->gain.IsUnity()) {
return accumulate ? (hasModulo ? Mix<ScalerType::EQ_UNITY, true, true>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_)
: Mix<ScalerType::EQ_UNITY, true, false>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_))
: (hasModulo ? Mix<ScalerType::EQ_UNITY, false, true>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_)
: Mix<ScalerType::EQ_UNITY, false, false>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_));
} else if (info->gain.IsSilent()) {
return (hasModulo ? Mix<ScalerType::MUTED, true, true>(dest, dest_frames, dest_offset, src,
frac_src_frames, frac_src_offset, info,
chan_count_)
: Mix<ScalerType::MUTED, true, false>(dest, dest_frames, dest_offset, src,
frac_src_frames, frac_src_offset, info,
chan_count_));
} else if (info->gain.IsRamping()) {
return accumulate ? (hasModulo ? Mix<ScalerType::RAMPING, true, true>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_)
: Mix<ScalerType::RAMPING, true, false>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_))
: (hasModulo ? Mix<ScalerType::RAMPING, false, true>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_)
: Mix<ScalerType::RAMPING, false, false>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_));
} else {
return accumulate ? (hasModulo ? Mix<ScalerType::NE_UNITY, true, true>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_)
: Mix<ScalerType::NE_UNITY, true, false>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_))
: (hasModulo ? Mix<ScalerType::NE_UNITY, false, true>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_)
: Mix<ScalerType::NE_UNITY, false, false>(
dest, dest_frames, dest_offset, src, frac_src_frames,
frac_src_offset, info, chan_count_));
}
}
// Templates used to expand all of the different combinations of the possible
// PointSampler Mixer configurations.
template <size_t DestChanCount, typename SrcSampleType, size_t SrcChanCount>
static inline std::unique_ptr<Mixer> SelectPSM(const fuchsia::media::AudioStreamType& src_format,
const fuchsia::media::AudioStreamType& dest_format) {
return std::make_unique<PointSamplerImpl<DestChanCount, SrcSampleType, SrcChanCount>>();
}
template <size_t DestChanCount, typename SrcSampleType>
static inline std::unique_ptr<Mixer> SelectPSM(const fuchsia::media::AudioStreamType& src_format,
const fuchsia::media::AudioStreamType& dest_format) {
switch (src_format.channels) {
case 1:
return SelectPSM<DestChanCount, SrcSampleType, 1>(src_format, dest_format);
case 2:
return SelectPSM<DestChanCount, SrcSampleType, 2>(src_format, dest_format);
case 4:
if (dest_format.channels == 1 || dest_format.channels == 2) {
return SelectPSM<DestChanCount, SrcSampleType, 4>(src_format, dest_format);
}
return nullptr;
default:
return nullptr;
}
}
template <size_t DestChanCount>
static inline std::unique_ptr<Mixer> SelectPSM(const fuchsia::media::AudioStreamType& src_format,
const fuchsia::media::AudioStreamType& dest_format) {
switch (src_format.sample_format) {
case fuchsia::media::AudioSampleFormat::UNSIGNED_8:
return SelectPSM<DestChanCount, uint8_t>(src_format, dest_format);
case fuchsia::media::AudioSampleFormat::SIGNED_16:
return SelectPSM<DestChanCount, int16_t>(src_format, dest_format);
case fuchsia::media::AudioSampleFormat::SIGNED_24_IN_32:
return SelectPSM<DestChanCount, int32_t>(src_format, dest_format);
case fuchsia::media::AudioSampleFormat::FLOAT:
return SelectPSM<DestChanCount, float>(src_format, dest_format);
default:
return nullptr;
}
}
static inline std::unique_ptr<Mixer> SelectNxNPSM(
const fuchsia::media::AudioStreamType& src_format) {
switch (src_format.sample_format) {
case fuchsia::media::AudioSampleFormat::UNSIGNED_8:
return std::make_unique<NxNPointSamplerImpl<uint8_t>>(src_format.channels);
case fuchsia::media::AudioSampleFormat::SIGNED_16:
return std::make_unique<NxNPointSamplerImpl<int16_t>>(src_format.channels);
case fuchsia::media::AudioSampleFormat::SIGNED_24_IN_32:
return std::make_unique<NxNPointSamplerImpl<int32_t>>(src_format.channels);
case fuchsia::media::AudioSampleFormat::FLOAT:
return std::make_unique<NxNPointSamplerImpl<float>>(src_format.channels);
default:
return nullptr;
}
}
std::unique_ptr<Mixer> PointSampler::Select(const fuchsia::media::AudioStreamType& src_format,
const fuchsia::media::AudioStreamType& dest_format) {
// If num_channels for src and dest are equal and > 2, directly map these one-to-one.
// TODO(MTWN-75): eliminate the NxN mixers, replacing with flexible rechannelization (see below).
if (src_format.channels == dest_format.channels && src_format.channels > 2) {
return SelectNxNPSM(src_format);
}
switch (dest_format.channels) {
case 1:
return SelectPSM<1>(src_format, dest_format);
case 2:
return SelectPSM<2>(src_format, dest_format);
case 4:
// For now, to mix Mono and Stereo sources to 4-channel destinations, we duplicate source
// channels across multiple destinations (Stereo LR becomes LRLR, Mono M becomes MMMM). Audio
// formats do not include info needed to filter frequencies or locate channels in 3D space.
// TODO(MTWN-399): enable the mixer to rechannelize in a more sophisticated way.
// TODO(MTWN-402): account for frequency range (e.g. a "4-channel" stereo woofer+tweeter).
return SelectPSM<4>(src_format, dest_format);
default:
return nullptr;
}
return nullptr;
}
} // namespace media::audio::mixer
| 49.223827 | 100 | 0.615328 | [
"3d"
] |
a783e83d97c545c285ff91ddefa7c293e0c4656d | 9,323 | cpp | C++ | kuri_multi_agent_navigation/src/gps_waypoints_local.cpp | kucars/kuri_mbzirc_challenge_3 | 9942aae773eb4d32971b43223e4fea1554c1c8c8 | [
"BSD-3-Clause"
] | 4 | 2019-03-02T12:55:51.000Z | 2019-07-23T08:45:17.000Z | kuri_multi_agent_navigation/src/gps_waypoints_local.cpp | kucars/kuri_mbzirc_challenge_3 | 9942aae773eb4d32971b43223e4fea1554c1c8c8 | [
"BSD-3-Clause"
] | 2 | 2019-07-23T08:40:18.000Z | 2019-07-23T13:22:18.000Z | kuri_multi_agent_navigation/src/gps_waypoints_local.cpp | kucars/kuri_mbzirc_challenge_3 | 9942aae773eb4d32971b43223e4fea1554c1c8c8 | [
"BSD-3-Clause"
] | 2 | 2018-06-08T01:40:13.000Z | 2019-07-23T11:24:22.000Z | /***************************************************************************
* Copyright (C) 2017 by *
* Tarek Taha, KURI <tataha@tarektaha.com> *
* Randa Almadhoun, KURI <randa.almadhoun@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 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 General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Steet, Fifth Floor, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <mavros_msgs/CommandBool.h>
#include <mavros_msgs/SetMode.h>
#include <mavros_msgs/CommandTOL.h>
#include <mavros_msgs/State.h>
#include <mavros_msgs/PositionTarget.h>
#include <mavros_msgs/GlobalPositionTarget.h>
#include <geometry_msgs/PoseArray.h>
#include <signal.h>
#include <termios.h>
#include <iostream>
#include <queue>
#include <sstream>
#include <string>
#include <time.h>
#include <algorithm>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
#include <float.h>
#include <std_msgs/Float64.h>
#include <visualization_msgs/Marker.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/Pose.h>
#include <stdio.h>
#include <stdlib.h>
#include <boost/filesystem.hpp>
#include <ros/package.h>
#include <sensor_msgs/NavSatFix.h>
#include <geo.h>
mavros_msgs::PositionTarget p;
geometry_msgs::Pose globalPose;
std::vector<mavros_msgs::PositionTarget> localPoses;
geometry_msgs::Point real;
geometry_msgs::PoseArray waypoints;
geometry_msgs::PoseArray globalWaypoints;
geometry_msgs::PoseStamped goalPose;
mavros_msgs::State current_state;
int count = 0 ;
double tolerance = 0.4;
double errorX = 0;
double errorY = 0;
double errorZ = 0;
double lat_ref;
double lon_ref;
bool flagRef = false;
bool finished = false;
void state_cb(const mavros_msgs::State::ConstPtr& msg){
current_state = *msg;
}
void reached(geometry_msgs::Point msg)
{
float x,y,z;
//transfered to local based on the uav home position as a map reference
globallocalconverter_tolocal(msg.x,msg.y,msg.z,&y,&x,&z);
//std::cout<<"current global position: x"<<msg.x<<" y "<<msg.y<<" z "<<msg.z<<std::endl;
//check reached accroding to the home position of the uav
errorX = p.position.x - x;
errorY = p.position.y - y;
errorZ = p.position.z - z;
//std::cout<<"p: x"<<p.position.x<<" y "<<p.position.y<<" z "<<p.position.z<<std::endl;
//std::cout<<"current local position ref to the uav home position: x"<<x<<" y "<<y<<" z "<<z<<std::endl;
//std::cout<<"error: x"<<fabs(errorX)<<" y "<<fabs(errorY)<<" z "<<fabs(errorZ)<<std::endl;
if ((fabs(errorX) < tolerance) && (fabs(errorY) < tolerance))
{
count++;
if(count<waypoints.poses.size())
{
localPoses.push_back(p);
std::cout<<"**************REACHED --> next ***************"<<std::endl;
}else finished=true;
}
}
void globalPoseCallback(const sensor_msgs::NavSatFix:: ConstPtr& msg)
{
real.x=msg->latitude;
real.y=msg->longitude;
real.z=msg->altitude;
if(!flagRef)
{
if(real.x != 0 && real.y != 0)
{
lat_ref = real.x;
lon_ref = real.y;
flagRef=true;
}
}else if(!finished){
reached(real);
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "local_control");
ros::NodeHandle nh;
ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>
("/uav_2/mavros/state", 10, state_cb);
ros::Publisher local_pos_pub = nh.advertise<mavros_msgs::PositionTarget>
("/uav_2/mavros/setpoint_raw/local", 10);
ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>
("/uav_2/mavros/cmd/arming");
ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>
("/uav_2/mavros/set_mode");
ros::Subscriber globalPoseSub = nh.subscribe
("/uav_2/mavros/global_position/global", 1, globalPoseCallback);
//the setpoint publishing rate MUST be faster than 2Hz
ros::Rate rate(20.0);
// wait for FCU connection
while(ros::ok() && current_state.connected){
ros::spinOnce();
rate.sleep();
}
//read setpoints from file
std::string str1 = ros::package::getPath("kuri_system_coordinator")+"/config/exploration_waypoints_50.txt";
const char * filename1 = str1.c_str();
assert(filename1 != NULL);
filename1 = strdup(filename1);
FILE *file1 = fopen(filename1, "r");
if (!file1)
{
std::cout<<"\nCan not open File";
fclose(file1);
}
double locationx,locationy,locationz,qy;
geometry_msgs::Pose pose;
//transfer exploration generated waypoints in terms of the reference that was chosen in creating the search space ( in simulation it is the world 0,0,0 which is represented as zurich 47.3977419 , 8.5455938
// but in the real experiments it should be based on one of the corners of the arena of the challenge
double wpt_lat_ref,wpt_lon_ref;
ros::param::param("~ref_lat", wpt_lat_ref, 1.0);
ros::param::param("~ref_lon", wpt_lon_ref, 1.0);
std::cout<<" The local waypoints map reference: "<<(double)wpt_lat_ref<<" "<<(double)wpt_lon_ref<<std::endl;
map_projection_global_init(wpt_lat_ref, wpt_lon_ref,1);
while (!feof(file1))
{
fscanf(file1,"%lf %lf %lf %lf\n",&locationx,&locationy,&locationz,&qy);
pose.position.x = locationx;
pose.position.y = locationy;
pose.position.z = locationz;
pose.orientation.x = qy;
waypoints.poses.push_back(pose);
double lat;
double lon;
float alt;
globallocalconverter_toglobal(locationy,locationx,locationz,&lat,&lon,&alt);
globalPose.position.x = lat;
globalPose.position.y = lon;
globalPose.position.z = alt*-1;
//std::cout<<"global : lat "<<lat<<" lon "<<lon<<" alt "<<alt<<std::endl;
//std::cout<<"local : x "<<locationx<<" y "<<locationy<<" z "<<locationz<<std::endl;
globalWaypoints.poses.push_back(globalPose);
}
mavros_msgs::SetMode offb_set_mode;
offb_set_mode.request.custom_mode = "OFFBOARD";
mavros_msgs::CommandBool arm_cmd;
ros::Time last_request = ros::Time::now();
bool flag=false;
while(ros::ok()){
arm_cmd.request.value = true;
if( current_state.mode != "OFFBOARD" &&
(ros::Time::now() - last_request > ros::Duration(5.0))){
if( set_mode_client.call(offb_set_mode) &&
offb_set_mode.response.success){
ROS_INFO("OFFBOARD enabled");
}
last_request = ros::Time::now();
} else {
if( !current_state.armed &&
(ros::Time::now() - last_request > ros::Duration(5.0))){
if( arming_client.call(arm_cmd) &&
arm_cmd.response.success){
ROS_INFO("Vehicle armed");
}
last_request = ros::Time::now();
}
}
if(flagRef && !finished)
{
std::cout<<(double)lat_ref<<" "<<(double)lon_ref<<std::endl;
map_projection_global_init(lat_ref, lon_ref,1);
//transfer exploration global waypoints in terms of the uav gps home position
float p_x,p_y,p_z;
globallocalconverter_tolocal(globalWaypoints.poses[count].position.x,globalWaypoints.poses[count].position.y, -1*globalWaypoints.poses[count].position.z,&p_y,&p_x,&p_z);
p.position.x=p_x;
p.position.y=p_y;
p.position.z=p_z;
//std::cout<<"local waypoint based on the uav home position : x "<<p.position.x<<" y "<<p.position.y<<" z "<<p.position.z<<std::endl;
p.coordinate_frame = mavros_msgs::PositionTarget::FRAME_LOCAL_NED;
p.type_mask = (1 << 11) | (7 << 6) | (7 << 3);
local_pos_pub.publish(p);
}
else
{
local_pos_pub.publish(p);
}
ros::spinOnce();
rate.sleep();
}
return 0;
}
| 34.657993 | 209 | 0.582538 | [
"vector"
] |
a786fbf65c5dfe80d7eac38b9ec7a12c59c71d4c | 3,107 | cc | C++ | extensions/common/permissions/manifest_permission_set.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | extensions/common/permissions/manifest_permission_set.cc | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | extensions/common/permissions/manifest_permission_set.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2013 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/common/permissions/manifest_permission_set.h"
#include <stddef.h>
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handler.h"
#include "extensions/common/permissions/manifest_permission.h"
namespace {
using extensions::ErrorUtils;
using extensions::ManifestPermission;
using extensions::ManifestPermissionSet;
using extensions::ManifestHandler;
namespace errors = extensions::manifest_errors;
bool CreateManifestPermission(const std::string& permission_name,
const base::Value* permission_value,
ManifestPermissionSet* manifest_permissions,
std::u16string* error,
std::vector<std::string>* unhandled_permissions) {
std::unique_ptr<ManifestPermission> permission(
ManifestHandler::CreatePermission(permission_name));
if (!permission) {
if (unhandled_permissions)
unhandled_permissions->push_back(permission_name);
else
LOG(WARNING) << "Unknown permission[" << permission_name << "].";
return true;
}
if (!permission->FromValue(permission_value)) {
if (error) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidPermission, permission_name);
return false;
}
LOG(WARNING) << "Parse permission failed.";
return true;
} else {
manifest_permissions->insert(std::move(permission));
return true;
}
}
} // namespace
namespace extensions {
// static
bool ManifestPermissionSet::ParseFromJSON(
const base::ListValue* permissions,
ManifestPermissionSet* manifest_permissions,
std::u16string* error,
std::vector<std::string>* unhandled_permissions) {
for (size_t i = 0; i < permissions->GetList().size(); ++i) {
std::string permission_name;
const base::Value* permission_value = NULL;
if (!permissions->GetString(i, &permission_name)) {
const base::DictionaryValue* dict = NULL;
// permission should be a string or a single key dict.
if (!permissions->GetDictionary(i, &dict) || dict->DictSize() != 1) {
if (error) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidPermission, base::NumberToString(i));
return false;
}
LOG(WARNING) << "Permission is not a string or single key dict.";
continue;
}
base::DictionaryValue::Iterator it(*dict);
permission_name = it.key();
permission_value = &it.value();
}
if (!CreateManifestPermission(permission_name, permission_value,
manifest_permissions, error,
unhandled_permissions))
return false;
}
return true;
}
} // namespace extensions
| 33.053191 | 80 | 0.668812 | [
"vector"
] |
a7895beed7caa878017d762ce21eadb18d3e065c | 2,027 | cpp | C++ | CodeForces/Solutions/450E.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 5 | 2020-10-03T17:15:26.000Z | 2022-03-29T21:39:22.000Z | CodeForces/Solutions/449C.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | null | null | null | CodeForces/Solutions/449C.cpp | Shefin-CSE16/Competitive-Programming | 7c792081ae1d4b7060893165de34ffe7b9b7caed | [
"MIT"
] | 1 | 2021-03-01T12:56:50.000Z | 2021-03-01T12:56:50.000Z | // #pragma GCC optimize("Ofast,unroll-loops")
// #pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define dd double
#define ld long double
#define sl(n) scanf("%lld", &n)
#define si(n) scanf("%d", &n)
#define sd(n) scanf("%lf", &n)
#define pll pair <ll, ll>
#define pii pair <int, int>
#define mp make_pair
#define pb push_back
#define all(v) v.begin(), v.end()
#define inf (1LL << 61)
#define loop(i, start, stop, inc) for(ll i = start; i <= stop; i += inc)
#define for1(i, stop) for(ll i = 1; i <= stop; ++i)
#define for0(i, stop) for(ll i = 0; i < stop; ++i)
#define rep1(i, start) for(ll i = start; i >= 1; --i)
#define rep0(i, start) for(ll i = (start-1); i >= 0; --i)
#define ms(n, i) memset(n, i, sizeof(n))
#define casep(n) printf("Case %lld:", ++n)
#define pn printf("\n")
#define pf printf
#define EL '\n'
#define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
const ll sz = 1e5 + 10;
vector <ll> mult[sz];
bool check[sz], take[sz];
vector <pii> ans;
int main()
{
ll n;
sl(n);
for(ll i = 2; i*i <= n; i++) {
if(!check[i]) {
for(ll j = i*i; j <= n; j += i)
check[j] = 1;
}
}
for(ll i = n; i >= 2; i--) {
if(check[i]) continue;
for(ll j = i; j <= n; j += i) {
if(!take[j]) {
mult[i].pb(j);
take[j] = 1;
}
}
if(mult[i].size() <= 1) continue;
while(mult[i].size() > 3) {
pii p;
p.first = mult[i].back(), mult[i].pop_back();
p.second = mult[i].back(), mult[i].pop_back();
ans.pb(p);
}
if(mult[i].size() == 2) ans.pb(mp(mult[i][0], mult[i][1]));
else {
ans.pb(mp(mult[i][0], mult[i][2]));
take[ mult[i][1] ] = 0;
}
}
cout << ans.size() << EL;
for(pii &p : ans)
pf("%d %d\n", p.first, p.second);
return 0;
} | 23.847059 | 82 | 0.499753 | [
"vector"
] |
a78b30aa4f83471c9cab0ac3287c127b9368f170 | 1,574 | cpp | C++ | leetcode/391-perfect-rectangle.cpp | 01nomagic/Algorithms | b184aa12141f5127baa55502d3ea47ccd1f97ba8 | [
"MIT"
] | 2 | 2021-03-27T03:23:20.000Z | 2021-08-11T12:54:17.000Z | leetcode/391-perfect-rectangle.cpp | 01nomagic/Algorithms | b184aa12141f5127baa55502d3ea47ccd1f97ba8 | [
"MIT"
] | null | null | null | leetcode/391-perfect-rectangle.cpp | 01nomagic/Algorithms | b184aa12141f5127baa55502d3ea47ccd1f97ba8 | [
"MIT"
] | null | null | null | #include "./leetcode.hpp"
class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
map<pair<int, int>, int> dp;
set<pair<int, int>> points;
int minX = INT_MAX;
int maxX = INT_MIN;
int minY = INT_MAX;
int maxY = INT_MIN;
int area = 0;
for (auto rectangle : rectangles) {
minX = min(minX, rectangle[0]);
minY = min(minY, rectangle[1]);
maxX = max(maxX, rectangle[2]);
maxY = max(maxY, rectangle[3]);
area += (rectangle[2] - rectangle[0]) * (rectangle[3] - rectangle[1]);
pair<int, int> p1 = {rectangle[0], rectangle[1]};
pair<int, int> p2 = {rectangle[2], rectangle[1]};
pair<int, int> p3 = {rectangle[0], rectangle[3]};
pair<int, int> p4 = {rectangle[2], rectangle[3]};
if (points.count(p1)) {
points.erase(p1);
} else {
points.insert(p1);
}
if (points.count(p2)) {
points.erase(p2);
} else {
points.insert(p2);
}
if (points.count(p3)) {
points.erase(p3);
} else {
points.insert(p3);
}
if (points.count(p4)) {
points.erase(p4);
} else {
points.insert(p4);
}
}
if (area != (maxX - minX) * (maxY - minY) ||
points.size() != 4 ||
!(points.count({minX, minY}) && points.count({maxX, minY}) && points.count({minX, maxY}) && points.count({maxX, maxY}))) {
return false;
}
return true;
}
};
| 29.148148 | 132 | 0.494917 | [
"vector"
] |
a78e2022536c0c5fe123dee7087193c6a7048039 | 8,815 | cpp | C++ | admin/pchealth/sr/shell/frmmars.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/pchealth/sr/shell/frmmars.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/pchealth/sr/shell/frmmars.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /******************************************************************************
Copyright (c) 2000 Microsoft Corporation
Module Name:
FrmMars.cpp
Abstract:
This file contains the implementation of the CSRFrameMars class, which
implements SR UI using MARS / IE.
Revision History:
Seong Kook Khang (SKKhang) 04/04/2000
created
******************************************************************************/
#include "stdwin.h"
#include "stdatl.h"
#include <MarsHost.h>
#include "resource.h"
#include "rstrpriv.h"
#include <initguid.h>
#include "srui_htm.h"
#include "rstrmgr.h"
#include "rstrprog.h"
#include "rstrshl.h"
#include "FrmBase.h"
#include "srui_htm_i.c"
/////////////////////////////////////////////////////////////////////////////
//
// ATL Module for UI Frame
//
/////////////////////////////////////////////////////////////////////////////
CComModule _Module;
BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_RstrProgress, CRstrProgress)
//OBJECT_ENTRY(CLSID_RstrEdit, CRstrEdit)
OBJECT_ENTRY(CLSID_RestoreShellExternal, CRestoreShell)
END_OBJECT_MAP()
/////////////////////////////////////////////////////////////////////////////
//
// CSRFrameMars
//
/////////////////////////////////////////////////////////////////////////////
class CSRFrameMars : public ISRFrameBase
{
public:
CSRFrameMars();
~CSRFrameMars();
// ISRUI_Base methods
public:
DWORD RegisterServer();
DWORD UnregisterServer();
BOOL InitInstance( HINSTANCE hInst );
BOOL ExitInstance();
void Release();
int RunUI( LPCWSTR szTitle, int nStart );
// Operations
protected:
BOOL CleanUp();
DWORD InvokeMARS( LPCWSTR szTitle );
// Attributes
protected:
HWND m_hWnd;
};
/////////////////////////////////////////////////////////////////////////////
// CSRFrameMars create instance
BOOL CreateSRFrameInstance( ISRFrameBase **pUI )
{
TraceFunctEnter("CreateSRFrameInstance");
BOOL fRet = TRUE;
LPCWSTR cszErr;
*pUI = new CSRFrameMars;
if ( *pUI == NULL )
{
cszErr = ::GetSysErrStr();
ErrorTrace(TRACE_ID, "Creating SRUI Instance failed - %s", cszErr);
fRet = FALSE;
goto Exit;
}
Exit:
TraceFunctLeave();
return( fRet );
}
/////////////////////////////////////////////////////////////////////////////
// CSRFrameMars construction/destruction
CSRFrameMars::CSRFrameMars()
{
m_hWnd = NULL;
}
CSRFrameMars::~CSRFrameMars()
{
}
/////////////////////////////////////////////////////////////////////////////
// CSRFrameMars - ISRFrameBase methods
DWORD CSRFrameMars::RegisterServer()
{
TraceFunctEnter("CSRFrameMars::RegisterServer");
DWORD dwRet = 0;
HRESULT hr;
hr = _Module.UpdateRegistryFromResource(IDR_RSTRUI, TRUE);
if ( FAILED(hr) )
{
ErrorTrace(TRACE_ID, "CComModule::UpdateRegistryFromResource failed, err=%l", hr);
dwRet = hr;
goto Exit;
}
hr = _Module.RegisterServer(TRUE);
if ( FAILED(hr) )
{
ErrorTrace(TRACE_ID, "CComModule::RegisterServer failed, err=%l", hr);
dwRet = hr;
goto Exit;
}
Exit:
TraceFunctLeave();
return( dwRet );
}
DWORD CSRFrameMars::UnregisterServer()
{
TraceFunctEnter("CSRFrameMars::UnregisterServer");
DWORD dwRet = 0;
HRESULT hr;
hr = _Module.UpdateRegistryFromResource(IDR_RSTRUI, FALSE);
if ( FAILED(hr) )
{
ErrorTrace(TRACE_ID, "CComModule::UpdateRegistryFromResource failed, err=%l", hr);
dwRet = hr;
goto Exit;
}
hr = _Module.UnregisterServer(TRUE);
if ( FAILED(hr) )
{
ErrorTrace(TRACE_ID, "CComModule::UnregisterServer failed, err=%l", hr);
dwRet = hr;
goto Exit;
}
Exit:
TraceFunctLeave();
return( dwRet );
}
BOOL CSRFrameMars::InitInstance( HINSTANCE hInst )
{
TraceFunctEnter("CSRFrameMars::InitInstance");
BOOL fRet = TRUE;
HRESULT hr;
//BUGBUG - Is this necessary???
g_hInst = hInst;
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
#else
// we're using apartment threading model
hr = ::CoInitialize(NULL);
#endif
if (FAILED(hr))
{
FatalTrace(TRACE_ID, "Cannot initialize COM, hr=%l", hr);
fRet = FALSE;
goto Exit;
}
_Module.Init(ObjectMap, hInst, &LIBID_RestoreUILib);
Exit:
TraceFunctLeave();
return( fRet );
}
BOOL CSRFrameMars::ExitInstance()
{
TraceFunctEnter("CSRFrameMars::ExitInstance");
_Module.Term();
::CoUninitialize();
TraceFunctLeave();
return( TRUE );
}
void CSRFrameMars::Release()
{
TraceFunctEnter("CSRFrameMars::Release");
// clean up...
delete this;
TraceFunctLeave();
}
int CSRFrameMars::RunUI( LPCWSTR szTitle, int nStart )
{
TraceFunctEnter("CSRFrameMars::RunUI");
int nRet = 0;
HRESULT hr;
RECT rc = { 0, 0, 0, 0 };
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
hr = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER,
REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
_ASSERTE(SUCCEEDED(hRes));
hr = CoResumeClassObjects();
#else
// we're using apartment threading model
hr = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER,
REGCLS_MULTIPLEUSE);
#endif
_ASSERTE(SUCCEEDED(hr));
if ( !g_pRstrMgr->SetStartMode( nStart ) )
{
nRet = E_FAIL;
goto Exit;
}
//if ( g_cRestoreShell.Create( NULL, rc ) == NULL )
//{
// nRet = E_FAIL;
// goto Exit;
//}
nRet = InvokeMARS( szTitle );
if ( nRet != 0 )
goto Exit;
_Module.RevokeClassObjects();
Exit:
TraceFunctLeave();
return( nRet );
}
/////////////////////////////////////////////////////////////////////////////
// CSRFrameMars operations - internal
BOOL CSRFrameMars::CleanUp()
{
return( TRUE );
}
DWORD CSRFrameMars::InvokeMARS( LPCWSTR szTitle )
{
TraceFunctEnter("CSRFrameMars::InvokeMARS");
DWORD dwRet = 0;
LPCWSTR cszErr;
WCHAR szMarsPath[MAX_PATH+1];
WCHAR szSRPath[MAX_PATH+1];
HMODULE hMars;
PFNMARSTHREADPROC pfnMarsThreadProc;
MARSTHREADPARAM sMTP;
WCHAR szMainWndTitle[MAX_PATH+1];
CComBSTR bstrTitle, bstrSRPath;
CSRMarsHost_Object *pMH = NULL;
HRESULT hr;
::GetWindowsDirectory( szMarsPath, MAX_PATH );
::lstrcat( szMarsPath, L"\\pchealth\\helpctr\\binaries\\pchshell.dll" );
hMars = ::LoadLibrary( szMarsPath );
if ( hMars == NULL )
{
#ifdef DEBUG
MessageBox( NULL, szMarsPath, L"LoadLibrary failed", MB_OK );
#endif
dwRet = ::GetLastError();
cszErr = ::GetSysErrStr( dwRet );
ErrorTrace(TRACE_ID, "::LoadLibrary('marscore.dll') failed - %s", cszErr);
goto Exit;
}
pfnMarsThreadProc = (PFNMARSTHREADPROC)::GetProcAddress( hMars, (LPCSTR)MAKEINTRESOURCE(ORD_MARSTHREADPROC) );
if ( pfnMarsThreadProc == NULL )
{
#ifdef DEBUG
MessageBox( NULL, L"Unknown", L"GetProcAddress failed", MB_OK );
#endif
dwRet = ::GetLastError();
cszErr = ::GetSysErrStr( dwRet );
ErrorTrace(TRACE_ID, "::GetProcAddress failed - %s", cszErr);
goto Exit;
}
bstrTitle = szTitle;
::GetModuleFileName( NULL, szSRPath, MAX_PATH );
::PathRemoveFileSpec( szSRPath );
::PathAppend( szSRPath, L"srframe.mmf" );
bstrSRPath = szSRPath;
::ZeroMemory( &sMTP, sizeof(sMTP) );
sMTP.cbSize = sizeof(sMTP);
sMTP.hIcon = NULL;
sMTP.nCmdShow = SW_HIDE;
sMTP.dwFlags = MTF_MANAGE_WINDOW_SIZE;
sMTP.pwszTitle = bstrTitle;
sMTP.pwszPanelURL = bstrSRPath;
// Create an UI Instance.
hr = CSRMarsHost_Object::CreateInstance( &pMH );
if ( FAILED(hr) )
{
#ifdef DEBUG
MessageBox( NULL, szMarsPath, L"CreateInstance of MarsHost failed", MB_OK );
#endif
dwRet = hr;
ErrorTrace(TRACE_ID, "CHCPMarsHost_Object::CreateInstance failed, hr=%u", hr);
goto Exit;
}
//
// Add a reference count
//
pMH->AddRef();
dwRet = pfnMarsThreadProc( pMH, &sMTP );
if ( pMH )
pMH->Release();
if ( hMars )
::FreeLibrary( hMars );
Exit:
TraceFunctLeave();
return( dwRet );
}
// end of file
| 24.486111 | 115 | 0.546115 | [
"model"
] |
a7914108f942fc6692c1a65fe8dc7fb2eb00ee78 | 3,410 | hpp | C++ | ql/experimental/templatemodels/hullwhite/fixedratebondoption.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | null | null | null | ql/experimental/templatemodels/hullwhite/fixedratebondoption.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 17 | 2020-11-23T07:24:16.000Z | 2022-03-28T10:29:06.000Z | ql/experimental/templatemodels/hullwhite/fixedratebondoption.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 7 | 2017-04-24T08:28:43.000Z | 2022-03-15T08:59:54.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2010 Sebastian Schlenkrich
*/
/*! \file fixedratebondoption.hpp
\brief (Bermudan) fixed-rate bond option
*/
#ifndef quantlib_fixedratebondoption_hpp
#define quantlib_fixedratebondoption_hpp
#include <ql/instruments/bonds/fixedratebond.hpp>
#include <ql/instruments/swaption.hpp>
#include <ql/termstructures/yieldtermstructure.hpp>
#include <ql/time/date.hpp>
#include <ql/option.hpp>
namespace QuantLib {
class FixedRateBondOption : public Instrument {
protected:
Leg cashflows_;
std::vector<Date> exerciseDates_;
std::vector<Real> dirtyStrikeValues_;
Option::Type callOrPut_;
void setupArguments(PricingEngine::arguments*) const;
public:
FixedRateBondOption ( const ext::shared_ptr<FixedRateBond>& underlyingBond,
const std::vector<Date>& exerciseDates,
const std::vector<Real>& dirtyStrikeValues,
const Option::Type callOrPut )
: cashflows_(underlyingBond->cashflows()), exerciseDates_(exerciseDates),
dirtyStrikeValues_(dirtyStrikeValues), callOrPut_(callOrPut) {}
// constructor to map a swaption to bond option according to spread model
FixedRateBondOption ( const ext::shared_ptr<Swaption>& swaption,
const Handle<YieldTermStructure>& discountCurve,
bool contTenorSpread = true );
bool isExpired() const { // Instrument interface
return exerciseDates_.back()<= Settings::instance().evaluationDate();
}
// inspectors
const std::vector<Date>& exerciseDates() const { return exerciseDates_; }
const std::vector<Real>& dirtyStrikeValues() const { return dirtyStrikeValues_; }
const Option::Type callOrPut() const { return callOrPut_; }
const std::vector< QuantLib::Date > startDates();
const std::vector< QuantLib::Date > payDates();
const std::vector< QuantLib::Real > cashflowValues();
class arguments : public PricingEngine::arguments {
public:
Leg cashflows;
std::vector<Date> exerciseDates;
std::vector<Real> dirtyStrikeValues;
Option::Type callOrPut;
void validate() const {} // add some meaningfull checks here
};
class results : public Instrument::results {
public:
// value (NPV), errorEstimate, additionalResults and valuationDate
// are declared in Instrument::results
// here we may add the sensitivities
// fetchResults is inherited from Instrument and currently NOT overloaded
};
class engine : public GenericEngine<arguments,results> {};
// derived engines have to evaluate
// Real value, i.e., NPV
// Real errorEstimate, i.e., numerical vs. analytical results
// Date valuationDate, date until discounted
// std::map<std::string,boost::any> additionalResults, european reference prices
};
}
#endif /* #ifndef quantlib_fixedratebondoption_hpp */
| 41.084337 | 103 | 0.606158 | [
"vector",
"model"
] |
04297c272b1ecd936d298171240c68202a7270bd | 14,050 | cpp | C++ | src/chunk.cpp | bcfriesen/asgard | 33765e6edc2dd1ac5edc589a21bf4ba649c4fb6f | [
"MIT"
] | null | null | null | src/chunk.cpp | bcfriesen/asgard | 33765e6edc2dd1ac5edc589a21bf4ba649c4fb6f | [
"MIT"
] | null | null | null | src/chunk.cpp | bcfriesen/asgard | 33765e6edc2dd1ac5edc589a21bf4ba649c4fb6f | [
"MIT"
] | null | null | null | #include "chunk.hpp"
#include "fast_math.hpp"
int num_elements_in_chunk(element_chunk const &g)
{
int num_elems = 0;
for (auto const &[row, cols] : g)
{
ignore(row);
num_elems += cols.stop - cols.start + 1;
}
return num_elems;
}
int max_connected_in_chunk(element_chunk const &g)
{
int current_max = 0;
for (auto const &[row, cols] : g)
{
ignore(row);
current_max = std::max(current_max, cols.stop - cols.start + 1);
}
return current_max;
}
grid_limits columns_in_chunk(element_chunk const &g)
{
assert(g.size() > 0);
int const min_col =
(*std::min_element(g.begin(), g.end(),
[](auto const &a, auto const &b) {
return a.second.start < b.second.start;
}))
.second.start;
int const max_col = (*std::max_element(g.begin(), g.end(),
[](auto const &a, auto const &b) {
return a.second.stop < b.second.stop;
}))
.second.stop;
return grid_limits(min_col, max_col);
}
grid_limits rows_in_chunk(element_chunk const &g)
{
assert(g.size() > 0);
return grid_limits(g.begin()->first, g.rbegin()->first);
}
template<typename P>
rank_workspace<P>::rank_workspace(PDE<P> const &pde,
std::vector<element_chunk> const &chunks)
{
int const elem_size = element_segment_size(pde);
int const max_elems =
(*std::max_element(chunks.begin(), chunks.end(),
[](element_chunk const &a, element_chunk const &b) {
return a.size() < b.size();
}))
.size();
auto const max_col_limits = columns_in_chunk(*std::max_element(
chunks.begin(), chunks.end(),
[](element_chunk const &a, element_chunk const &b) {
auto const cols_in_a = columns_in_chunk(a);
auto const cols_in_b = columns_in_chunk(b);
auto const num_a = cols_in_a.stop - cols_in_a.start + 1;
auto const num_b = cols_in_b.stop - cols_in_b.start + 1;
return num_a < num_b;
}));
auto const max_cols = max_col_limits.stop - max_col_limits.start + 1;
int const max_total = num_elements_in_chunk(*std::max_element(
chunks.begin(), chunks.end(),
[](element_chunk const &a, element_chunk const &b) {
return num_elements_in_chunk(a) < num_elements_in_chunk(b);
}));
batch_input.resize(elem_size * max_cols);
batch_output.resize(elem_size * max_elems);
reduction_space.resize(elem_size * max_total * pde.num_terms);
// intermediate workspaces for kron product.
int const num_workspaces = std::min(pde.num_dims - 1, 2);
batch_intermediate.resize(reduction_space.size() * num_workspaces);
// unit vector for reduction
unit_vector_.resize(pde.num_terms * max_cols);
fk::vector<P, mem_type::owner, resource::host> unit_vect(unit_vector_.size());
std::fill(unit_vect.begin(), unit_vect.end(), 1.0);
unit_vector_.transfer_from(unit_vect);
}
template<typename P>
fk::vector<P, mem_type::owner, resource::device> const &
rank_workspace<P>::get_unit_vector() const
{
return unit_vector_;
}
template<typename P>
host_workspace<P>::host_workspace(PDE<P> const &pde,
element_subgrid const &grid)
{
int elem_size = element_segment_size(pde);
int64_t const col_size = elem_size * static_cast<int64_t>(grid.ncols());
int64_t const row_size = elem_size * static_cast<int64_t>(grid.nrows());
x_orig.resize(col_size);
x.resize(col_size);
fx.resize(row_size);
reduced_fx.resize(row_size);
scaled_source.resize(row_size);
result_1.resize(col_size);
result_2.resize(col_size);
result_3.resize(col_size);
}
// calculate how much workspace we need on device to compute a single connected
// element
//
// *does not include operator matrices - working for now on assumption they'll
// all be resident*
template<typename P>
static double get_element_size_MB(PDE<P> const &pde)
{
int const elem_size = element_segment_size(pde);
// number of intermediate workspaces for kron product.
// FIXME this only applies to explicit
int const num_workspaces = std::min(pde.num_dims - 1, 2);
// calc size of reduction space for a single work item
double const elem_reduction_space_MB = get_MB<P>(pde.num_terms * elem_size);
// calc size of intermediate space for a single work item
double const elem_intermediate_space_MB =
num_workspaces == 0 ? 0.0
: get_MB<P>(static_cast<double>(num_workspaces) *
pde.num_terms * elem_size);
// calc in and out vector sizes for each elem
// since we will scheme to have most elems require overlapping pieces of
// x and y, we will never need 2 addtl xy space per elem
double const elem_xy_space_MB = get_MB<P>(elem_size * 1.2);
return (elem_reduction_space_MB + elem_intermediate_space_MB +
elem_xy_space_MB);
}
// determine how many chunks will be required to solve the problem
// a chunk is a subset of the element subgrid whose total workspace requirement
// is less than the limit passed in rank_size_MB
template<typename P>
int get_num_chunks(element_subgrid const &grid, PDE<P> const &pde,
int const rank_size_MB)
{
assert(grid.size() > 0);
// determine total problem size
auto const num_elems = grid.size();
double const space_per_elem = get_element_size_MB(pde);
// make sure rank size is something reasonable
// a single element is the finest we can split the problem
// if that requires a lot of space relative to rank size,
// roundoff of elements over chunks will cause us to exceed the limit
assert(space_per_elem < (0.5 * rank_size_MB));
double const problem_size_MB = space_per_elem * num_elems;
// FIXME here we assume all coefficients are of equal size; if we shortcut
// computation for identity coefficients later, we will need to do this more
// carefully
int const coefficients_size_MB = static_cast<int>(std::ceil(
get_MB<P>(static_cast<uint64_t>(pde.get_coefficients(0, 0).size()) *
pde.num_terms * pde.num_dims)));
// make sure the coefficient matrices aren't leaving us without room
// for anything else in rank workspace
int const remaining_rank_MB = rank_size_MB - coefficients_size_MB;
assert(remaining_rank_MB > space_per_elem * 2);
// determine number of chunks
return static_cast<int>(std::ceil(problem_size_MB / remaining_rank_MB));
}
// divide the problem given the previously computed number of chunks
// this function divides via a greedy, row-major split.
// i.e., consecutive elements are taken row-wise until the end of a
// row, and continuing as needed to the next row, beginning with the first
// element of the new row (typewriter style). this is done to minimize the
// portion of the y-vector written to by each task, and ultimately the size of
// communication between ranks.
std::vector<element_chunk>
assign_elements(element_subgrid const &grid, int const num_chunks)
{
assert(num_chunks > 0);
auto const num_elems = grid.size();
int64_t const elems_left_over = num_elems % num_chunks;
int64_t const elems_per_chunk =
num_elems / num_chunks + elems_left_over / num_chunks;
int64_t const still_left_over = elems_left_over % num_chunks;
std::vector<element_chunk> chunks;
int64_t assigned = 0;
for (int i = 0; i < num_chunks; ++i)
{
std::map<int, std::vector<int>> chunk_map;
auto const insert = [&chunk_map, &grid](int const key, int const col) {
chunk_map.try_emplace(grid.to_global_row(key), std::vector<int>());
chunk_map[grid.to_global_row(key)].push_back(grid.to_global_col(col));
};
int64_t const elems_this_chunk =
i < still_left_over ? elems_per_chunk + 1 : elems_per_chunk;
int64_t const chunk_end = assigned + elems_this_chunk - 1;
int64_t const chunk_start_row = assigned / grid.ncols();
int64_t const chunk_start_col = assigned % grid.ncols();
int64_t const chunk_end_row = chunk_end / grid.ncols();
int64_t const chunk_end_col = chunk_end % grid.ncols();
assigned += elems_this_chunk;
if (chunk_end_row > chunk_start_row)
{
for (int i = chunk_start_row + 1; i < chunk_end_row; ++i)
{
for (int j = 0; j < grid.ncols(); ++j)
{
insert(i, j);
}
}
for (int j = chunk_start_col; j < grid.ncols(); ++j)
{
insert(chunk_start_row, j);
}
for (int j = 0; j <= chunk_end_col; ++j)
{
insert(chunk_end_row, j);
}
}
else
{
for (int j = chunk_start_col; j <= chunk_end_col; ++j)
{
insert(chunk_start_row, j);
}
}
element_chunk chunk;
for (auto const &[row, cols] : chunk_map)
{
chunk.insert({row, grid_limits(cols[0], cols.back())});
}
chunks.push_back(chunk);
}
return chunks;
}
template<typename P>
void copy_chunk_inputs(PDE<P> const &pde, element_subgrid const &grid,
rank_workspace<P> &rank_space,
host_workspace<P> const &host_space,
element_chunk const &chunk)
{
int const elem_size = element_segment_size(pde);
auto const x_range = columns_in_chunk(chunk);
fk::vector<P, mem_type::view> const x_view(
host_space.x, grid.to_local_col(x_range.start) * elem_size,
(grid.to_local_col(x_range.stop) + 1) * elem_size - 1);
fk::vector<P, mem_type::view, resource::device> in_view(
rank_space.batch_input, 0,
(x_range.stop - x_range.start + 1) * elem_size - 1);
in_view.transfer_from(x_view);
}
template<typename P>
void copy_chunk_outputs(PDE<P> const &pde, element_subgrid const &grid,
rank_workspace<P> &rank_space,
host_workspace<P> const &host_space,
element_chunk const &chunk)
{
int const elem_size = element_segment_size(pde);
auto const y_range = rows_in_chunk(chunk);
fk::vector<P, mem_type::view> y_view(
host_space.fx, grid.to_local_row(y_range.start) * elem_size,
(grid.to_local_row(y_range.stop) + 1) * elem_size - 1);
fk::vector<P, mem_type::view, resource::device> const out_view(
rank_space.batch_output, 0,
(y_range.stop - y_range.start + 1) * elem_size - 1);
fk::vector<P, mem_type::owner> const out_view_h(out_view.clone_onto_host());
y_view = fm::axpy(out_view_h, y_view);
}
template<typename P>
void reduce_chunk(PDE<P> const &pde, rank_workspace<P> &rank_space,
element_chunk const &chunk)
{
int const elem_size = element_segment_size(pde);
fm::scal(static_cast<P>(0.0), rank_space.batch_output);
for (auto const &[row, cols] : chunk)
{
int const prev_row_elems = [i = row, &chunk] {
if (i == chunk.begin()->first)
{
return 0;
}
int prev_elems = 0;
for (int r = chunk.begin()->first; r < i; ++r)
{
prev_elems += chunk.at(r).stop - chunk.at(r).start + 1;
}
return prev_elems;
}();
fk::matrix<P, mem_type::view, resource::device> const reduction_matrix(
rank_space.reduction_space, elem_size,
(cols.stop - cols.start + 1) * pde.num_terms,
prev_row_elems * elem_size * pde.num_terms);
int const reduction_row = row - chunk.begin()->first;
fk::vector<P, mem_type::view, resource::device> output_view(
rank_space.batch_output, reduction_row * elem_size,
((reduction_row + 1) * elem_size) - 1);
fk::vector<P, mem_type::view, resource::device> const unit_view(
rank_space.get_unit_vector(), 0,
(cols.stop - cols.start + 1) * pde.num_terms - 1);
P const alpha = 1.0;
P const beta = 1.0;
bool const transA = false;
fm::gemv(reduction_matrix, unit_view, output_view, transA, alpha, beta);
}
}
template class rank_workspace<float>;
template class rank_workspace<double>;
template class host_workspace<float>;
template class host_workspace<double>;
template int get_num_chunks(element_subgrid const &grid, PDE<float> const &pde,
int const rank_size_MB);
template int get_num_chunks(element_subgrid const &grid, PDE<double> const &pde,
int const rank_size_MB);
template void copy_chunk_inputs(PDE<float> const &pde,
element_subgrid const &grid,
rank_workspace<float> &rank_space,
host_workspace<float> const &host_space,
element_chunk const &chunk);
template void copy_chunk_inputs(PDE<double> const &pde,
element_subgrid const &grid,
rank_workspace<double> &rank_space,
host_workspace<double> const &host_space,
element_chunk const &chunk);
template void copy_chunk_outputs(PDE<float> const &pde,
element_subgrid const &grid,
rank_workspace<float> &rank_space,
host_workspace<float> const &host_space,
element_chunk const &chunk);
template void copy_chunk_outputs(PDE<double> const &pde,
element_subgrid const &grid,
rank_workspace<double> &rank_space,
host_workspace<double> const &host_space,
element_chunk const &chunk);
template void reduce_chunk(PDE<float> const &pde,
rank_workspace<float> &rank_space,
element_chunk const &chunk);
template void reduce_chunk(PDE<double> const &pde,
rank_workspace<double> &rank_space,
element_chunk const &chunk);
| 36.780105 | 80 | 0.636868 | [
"vector"
] |
042a6103a074323a68863590fbeeba87fde0491d | 63,352 | cpp | C++ | src/common/backend/utils/adt/jsonb_util.cpp | Yanci0/openGauss-server | b2ff10be1367c77f2fda396d6c12ffa3c25874c7 | [
"MulanPSL-1.0"
] | 360 | 2020-06-30T14:47:34.000Z | 2022-03-31T15:21:53.000Z | src/common/backend/utils/adt/jsonb_util.cpp | Yanci0/openGauss-server | b2ff10be1367c77f2fda396d6c12ffa3c25874c7 | [
"MulanPSL-1.0"
] | 4 | 2020-06-30T15:09:16.000Z | 2020-07-14T06:20:03.000Z | src/common/backend/utils/adt/jsonb_util.cpp | futurewei-cloud/chogori-opengauss | f43410e1643c887819e718d9baceb9e853ad9574 | [
"MulanPSL-1.0"
] | 133 | 2020-06-30T14:47:36.000Z | 2022-03-25T15:29:00.000Z | /*-------------------------------------------------------------------------
*
* jsonb_util.c
* Utilities for jsonb datatype
*
* Portions Copyright (c) 2021 Huawei Technologies Co.,Ltd.
* Copyright (c) 2014, PostgreSQL Global Development Group
*
*
* IDENTIFICATION
* src/backend/utils/adt/jsonb_util.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/hash.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/jsonb.h"
#include "utils/memutils.h"
/*
* Twice as many values may be stored within pairs (for an Object) than within
* elements (for an Array), modulo the current MaxAllocSize limitation. Note
* that JSONB_MAX_PAIRS is derived from the number of possible pairs, not
* values (as is the case for arrays and their elements), because we're
* concerned about limitations on the representation of the number of pairs.
* Over twice the memory is required to store n JsonbPairs as n JsonbValues.
* It only takes exactly twice as much disk space for storage, though. The
* JsonbPair (not an actual pair of values) representation is used here because
* that is what is subject to the MaxAllocSize restriction when building an
* object.
*/
#define JSONB_MAX_ELEMS (Min(MaxAllocSize / sizeof(JsonbValue), JENTRY_POSMASK))
#define JSONB_MAX_PAIRS (Min(MaxAllocSize / sizeof(JsonbPair), JENTRY_POSMASK))
/*
* State used while converting an arbitrary JsonbValue into a Jsonb value
* (4-byte varlena uncompressed representation of a Jsonb)
*
* ConvertLevel: Bookkeeping around particular level when converting.
*/
typedef struct convertLevel {
uint32 i; /* Iterates once per element, or once per pair */
uint32 *header; /* Pointer to current container header */
JEntry *meta; /* This level's metadata */
char *begin; /* Pointer into convertState.buffer */
} convertLevel;
/*
* convertState: Overall bookkeeping state for conversion
*/
typedef struct convertState {
/* Preallocated buffer in which to form varlena/Jsonb value */
Jsonb *buffer;
/* Pointer into buffer */
char *ptr;
/* State for */
convertLevel *allState; /* Overall state array */
convertLevel *contPtr; /* Cur container pointer (in allState) */
/* Current size of buffer containing allState array */
Size levelSz;
} convertState;
static int compareJsonbScalarValue(JsonbValue* a, JsonbValue* b);
static int lexicalCompareJsonbStringValue(const void* a, const void* b);
static Size convertJsonb(JsonbValue* val, Jsonb* buffer);
static inline short addPaddingInt(convertState* cstate);
static void walkJsonbValueConversion(JsonbValue* val, convertState* cstate, uint32 nestlevel);
static void putJsonbValueConversion(convertState* cstate, JsonbValue* val, uint32 flags, uint32 level);
static void putScalarConversion(convertState* cstate, JsonbValue* scalarVal, uint32 level, uint32 i);
static void iteratorFromContainerBuf(JsonbIterator* it, char* buffer);
static bool formIterIsContainer(JsonbIterator** it, JsonbValue* val, JEntry* ent, bool skipNested);
static JsonbIterator* freeAndGetParent(JsonbIterator* it);
static JsonbParseState* pushState(JsonbParseState** pstate);
static void appendKey(JsonbParseState* pstate, JsonbValue* scalarVal);
static void appendValue(JsonbParseState* pstate, JsonbValue* scalarVal);
static void appendElement(JsonbParseState* pstate, JsonbValue* scalarVal);
static int lengthCompareJsonbStringValue(const void* a, const void* b, void* binequal);
static int lengthCompareJsonbPair(const void* a, const void* b, void* binequal);
static void uniqueifyJsonbObject(JsonbValue* object);
static void uniqueifyJsonbArray(JsonbValue* array);
/*
* Turn an in-memory JsonbValue into a Jsonb for on-disk storage.
*
* There isn't a JsonbToJsonbValue(), because generally we find it more
* convenient to directly iterate through the Jsonb representation and only
* really convert nested scalar values. formIterIsContainer() does this, so
* that clients of the iteration code don't have to directly deal with the
* binary representation (JsonbDeepContains() is a notable exception, although
* all exceptions are internal to this module). In general, functions that
* accept a JsonbValue argument are concerned with the manipulation of scalar
* values, or simple containers of scalar values, where it would be
* inconvenient to deal with a great amount of other state.
*/
Jsonb* JsonbValueToJsonb(JsonbValue *val)
{
Jsonb *out = NULL;
Size sz;
if (IsAJsonbScalar(val)) {
/* Scalar value */
JsonbParseState *pstate = NULL;
JsonbValue *res = NULL;
JsonbValue scalarArray;
scalarArray.type = jbvArray;
scalarArray.array.rawScalar = true;
scalarArray.array.nElems = 1;
pushJsonbValue(&pstate, WJB_BEGIN_ARRAY, &scalarArray);
pushJsonbValue(&pstate, WJB_ELEM, val);
res = pushJsonbValue(&pstate, WJB_END_ARRAY, NULL);
out = (Jsonb*)palloc(VARHDRSZ + res->estSize);
sz = convertJsonb(res, out);
Assert(sz <= (uint)res->estSize);
SET_VARSIZE(out, sz + VARHDRSZ);
} else if (val->type == jbvObject || val->type == jbvArray) {
out = (Jsonb*)palloc(VARHDRSZ + val->estSize);
sz = convertJsonb(val, out);
Assert(sz <= (uint)val->estSize);
SET_VARSIZE(out, VARHDRSZ + sz);
} else {
Assert(val->type == jbvBinary);
out = (Jsonb*)palloc(VARHDRSZ + val->binary.len);
SET_VARSIZE(out, VARHDRSZ + val->binary.len);
errno_t rc = memcpy_s(VARDATA(out), VARHDRSZ + val->binary.len, val->binary.data, val->binary.len);
securec_check(rc, "\0", "\0");
}
return out;
}
/*
* BT comparator worker function. Returns an integer less than, equal to, or
* greater than zero, indicating whether a is less than, equal to, or greater
* than b. Consistent with the requirements for a B-Tree operator class
*
* Strings are compared lexically, in contrast with other places where we use a
* much simpler comparator logic for searching through Strings. Since this is
* called from B-Tree support function 1, we're careful about not leaking
* memory here.
*/
int compareJsonbSuperHeaderValue(JsonbSuperHeader a, JsonbSuperHeader b)
{
JsonbIterator *ita = NULL;
JsonbIterator *itb = NULL;
int res = 0;
ita = JsonbIteratorInit(a);
itb = JsonbIteratorInit(b);
do {
JsonbValue va,
vb;
int ra,
rb;
ra = JsonbIteratorNext(&ita, &va, false);
rb = JsonbIteratorNext(&itb, &vb, false);
/*
* To a limited extent we'll redundantly iterate over an array/object
* while re-performing the same test without any reasonable expectation
* of the same container types having differing lengths (as when we
* process a WJB_BEGIN_OBJECT, and later the corresponding
* WJB_END_OBJECT), but no matter.
*/
if (ra == rb) {
if (ra == WJB_DONE) {
/* Decisively equal */
break;
}
if (ra == WJB_END_ARRAY || ra == WJB_END_OBJECT) {
/*
* There is no array or object to compare at this stage of
* processing. jbvArray/jbvObject values are compared
* initially, at the WJB_BEGIN_ARRAY and WJB_BEGIN_OBJECT
* tokens.
*/
continue;
}
if (va.type == vb.type) {
switch (va.type) {
case jbvString:
res = lexicalCompareJsonbStringValue(&va, &vb);
break;
case jbvNull:
case jbvNumeric:
case jbvBool:
res = compareJsonbScalarValue(&va, &vb);
break;
case jbvArray:
/*
* This could be a "raw scalar" pseudo array. That's a
* special case here though, since we still want the
* general type-based comparisons to apply, and as far
* as we're concerned a pseudo array is just a scalar.
*/
if (va.array.rawScalar != vb.array.rawScalar) {
res = (va.array.rawScalar) ? -1 : 1;
} else if (va.array.nElems != vb.array.nElems) {
res = (va.array.nElems > vb.array.nElems) ? 1 : -1;
}
break;
case jbvObject:
if (va.object.nPairs != vb.object.nPairs) {
res = (va.object.nPairs > vb.object.nPairs) ? 1 : -1;
}
break;
case jbvBinary:
elog(ERROR, "unexpected jbvBinary value");
}
} else {
/* Type-defined order */
res = (va.type > vb.type) ? 1 : -1;
}
} else {
/*
* It's safe to assume that the types differed.
*
* If the two values were the same container type, then there'd
* have been a chance to observe the variation in the number of
* elements/pairs (when processing WJB_BEGIN_OBJECT, say). They
* can't be scalar types either, because then they'd have to be
* contained in containers already ruled unequal due to differing
* numbers of pairs/elements, or already directly ruled unequal
* with a call to the underlying type's comparator.
*/
Assert(ra != WJB_END_ARRAY && ra != WJB_END_OBJECT);
Assert(rb != WJB_END_ARRAY && rb != WJB_END_OBJECT);
Assert(va.type != vb.type);
Assert(va.type != jbvBinary);
Assert(vb.type != jbvBinary);
/* Type-defined order */
res = (va.type > vb.type) ? 1 : -1;
}
} while (res == 0);
while (ita != NULL) {
JsonbIterator *i = ita->parent;
pfree(ita);
ita = i;
}
while (itb != NULL) {
JsonbIterator *i = itb->parent;
pfree(itb);
itb = i;
}
return res;
}
/*
* Find value in object (i.e. the "value" part of some key/value pair in an
* object), or find a matching element if we're looking through an array. Do
* so on the basis of equality of the object keys only, or alternatively
* element values only, with a caller-supplied value "key". The "flags"
* argument allows the caller to specify which container types are of interest.
*
* This exported utility function exists to facilitate various cases concerned
* with "containment". If asked to look through an object, the caller had
* better pass a Jsonb String, because their keys can only be strings.
* Otherwise, for an array, any type of JsonbValue will do.
*
* In order to proceed with the search, it is necessary for callers to have
* both specified an interest in exactly one particular container type with an
* appropriate flag, as well as having the pointed-to Jsonb superheader be of
* one of those same container types at the top level. (Actually, we just do
* whichever makes sense to save callers the trouble of figuring it out - at
* most one can make sense, because the super header either points to an array
* (possible a "raw scalar" pseudo array) or an object.)
*
* Note that we can return a jbvBinary JsonbValue if this is called on an
* object, but we never do so on an array. If the caller asks to look through
* a container type that is not of the type pointed to by the superheader,
* immediately fall through and return NULL. If we cannot find the value,
* return NULL. Otherwise, return palloc()'d copy of value.
*
* lowbound can be NULL, but if not it's used to establish a point at which to
* start searching. If the value searched for is found, then lowbound is then
* set to an offset into the array or object. Typically, this is used to
* exploit the ordering of objects to avoid redundant work, by also sorting a
* list of items to be checked using the internal sort criteria for objects
* (object pair keys), and then, when searching for the second or subsequent
* item, picking it up where we left off knowing that the second or subsequent
* item can not be at a point below the low bound set when the first was found.
* This is only useful for objects, not arrays (which have a user-defined
* order), so array superheader Jsonbs should just pass NULL. Moreover, it's
* only useful because we only match object pairs on the basis of their key, so
* presumably anyone exploiting this is only interested in matching Object keys
* with a String. lowbound is given in units of pairs, not underlying values.
*/
JsonbValue *findJsonbValueFromSuperHeader(JsonbSuperHeader sheader, uint32 flags, uint32 *lowbound, JsonbValue *key)
{
uint32 superheader = *(uint32 *)sheader;
JEntry *array = (JEntry *)(sheader + sizeof(uint32));
uint count = (superheader & JB_CMASK);
JsonbValue *result = (JsonbValue*)palloc(sizeof(JsonbValue));
Assert((flags & ~(JB_FARRAY | JB_FOBJECT)) == 0);
if (flags & JB_FARRAY & superheader) {
char *data = (char *)(array + (superheader & JB_CMASK));
uint i;
for (i = 0; i < count; i++) {
JEntry *e = array + i;
if (JBE_ISNULL(*e) && key->type == jbvNull) {
result->type = jbvNull;
result->estSize = sizeof(JEntry);
} else if (JBE_ISSTRING(*e) && key->type == jbvString) {
result->type = jbvString;
result->string.val = data + JBE_OFF(*e);
result->string.len = JBE_LEN(*e);
result->estSize = sizeof(JEntry) + result->string.len;
} else if (JBE_ISNUMERIC(*e) && key->type == jbvNumeric) {
result->type = jbvNumeric;
result->numeric = (Numeric) (data + INTALIGN(JBE_OFF(*e)));
result->estSize = 2 * sizeof(JEntry) +
VARSIZE_ANY(result->numeric);
} else if (JBE_ISBOOL(*e) && key->type == jbvBool) {
result->type = jbvBool;
result->boolean = JBE_ISBOOL_TRUE(*e) != 0;
result->estSize = sizeof(JEntry);
} else {
continue;
}
if (compareJsonbScalarValue(key, result) == 0) {
return result;
}
}
} else if (flags & JB_FOBJECT & superheader) {
/* Since this is an object, account for *Pairs* of Jentrys */
char *data = (char *) (array + (superheader & JB_CMASK) * 2);
uint32 stopLow = lowbound ? *lowbound : 0,
stopMiddle;
/* Object key past by caller must be a string */
Assert(key->type == jbvString);
/* Binary search on object/pair keys *only* */
while (stopLow < count) {
JEntry *entry = NULL;
int difference;
JsonbValue candidate;
/*
* Note how we compensate for the fact that we're iterating through
* pairs (not entries) throughout.
*/
stopMiddle = stopLow + (count - stopLow) / 2;
entry = array + stopMiddle * 2;
candidate.type = jbvString;
candidate.string.val = data + JBE_OFF(*entry);
candidate.string.len = JBE_LEN(*entry);
candidate.estSize = sizeof(JEntry) + candidate.string.len;
difference = lengthCompareJsonbStringValue(&candidate, key, NULL);
if (difference == 0) {
/* Found our value (from key/value pair) */
JEntry *v = entry + 1;
if (lowbound) {
*lowbound = stopMiddle + 1;
}
if (JBE_ISNULL(*v)) {
result->type = jbvNull;
result->estSize = sizeof(JEntry);
} else if (JBE_ISSTRING(*v)) {
result->type = jbvString;
result->string.val = data + JBE_OFF(*v);
result->string.len = JBE_LEN(*v);
result->estSize = sizeof(JEntry) + result->string.len;
} else if (JBE_ISNUMERIC(*v)) {
result->type = jbvNumeric;
result->numeric = (Numeric) (data + INTALIGN(JBE_OFF(*v)));
result->estSize = 2 * sizeof(JEntry) +
VARSIZE_ANY(result->numeric);
} else if (JBE_ISBOOL(*v)) {
result->type = jbvBool;
result->boolean = JBE_ISBOOL_TRUE(*v) != 0;
result->estSize = sizeof(JEntry);
} else {
/*
* See header comments to understand why this never happens
* with arrays
*/
result->type = jbvBinary;
result->binary.data = data + INTALIGN(JBE_OFF(*v));
result->binary.len = JBE_LEN(*v) -
(INTALIGN(JBE_OFF(*v)) - JBE_OFF(*v));
result->estSize = 2 * sizeof(JEntry) + result->binary.len;
}
return result;
} else {
if (difference < 0) {
stopLow = stopMiddle + 1;
} else {
count = stopMiddle;
}
}
}
if (lowbound) {
*lowbound = stopLow;
}
}
/* Not found */
pfree(result);
return NULL;
}
/*
* Get i-th value of Jsonb array from superheader.
*
* Returns palloc()'d copy of value.
*/
JsonbValue *getIthJsonbValueFromSuperHeader(JsonbSuperHeader sheader, uint32 i)
{
uint32 superheader = *(uint32 *) sheader;
JsonbValue *result = NULL;
JEntry *array = NULL;
JEntry *e = NULL;
char *data = NULL;
result = (JsonbValue*)palloc(sizeof(JsonbValue));
if (i >= (superheader & JB_CMASK)) {
return NULL;
}
array = (JEntry *) (sheader + sizeof(uint32));
if (superheader & JB_FARRAY) {
e = array + i;
data = (char *) (array + (superheader & JB_CMASK));
} else {
elog(ERROR, "not a jsonb array");
}
if (JBE_ISNULL(*e)) {
result->type = jbvNull;
result->estSize = sizeof(JEntry);
} else if (JBE_ISSTRING(*e)) {
result->type = jbvString;
result->string.val = data + JBE_OFF(*e);
result->string.len = JBE_LEN(*e);
result->estSize = sizeof(JEntry) + result->string.len;
} else if (JBE_ISNUMERIC(*e)) {
result->type = jbvNumeric;
result->numeric = (Numeric) (data + INTALIGN(JBE_OFF(*e)));
result->estSize = 2 * sizeof(JEntry) + VARSIZE_ANY(result->numeric);
} else if (JBE_ISBOOL(*e)) {
result->type = jbvBool;
result->boolean = JBE_ISBOOL_TRUE(*e) != 0;
result->estSize = sizeof(JEntry);
} else {
result->type = jbvBinary;
result->binary.data = data + INTALIGN(JBE_OFF(*e));
result->binary.len = JBE_LEN(*e) - (INTALIGN(JBE_OFF(*e)) - JBE_OFF(*e));
result->estSize = result->binary.len + 2 * sizeof(JEntry);
}
return result;
}
/*
* Push JsonbValue into JsonbParseState.
*
* Used when parsing JSON tokens to form Jsonb, or when converting an in-memory
* JsonbValue to a Jsonb.
*
* Initial state of *JsonbParseState is NULL, since it'll be allocated here
* originally (caller will get JsonbParseState back by reference).
*
* Only sequential tokens pertaining to non-container types should pass a
* JsonbValue. There is one exception -- WJB_BEGIN_ARRAY callers may pass a
* "raw scalar" pseudo array to append that.
*/
JsonbValue *pushJsonbValue(JsonbParseState **pstate, int seq, JsonbValue *scalarVal)
{
JsonbValue *result = NULL;
switch (seq) {
case WJB_BEGIN_ARRAY:
Assert(!scalarVal || scalarVal->array.rawScalar);
*pstate = pushState(pstate);
result = &(*pstate)->contVal;
(*pstate)->contVal.type = jbvArray;
(*pstate)->contVal.estSize = 3 * sizeof(JEntry);
(*pstate)->contVal.array.nElems = 0;
(*pstate)->contVal.array.rawScalar = (scalarVal &&
scalarVal->array.rawScalar);
if (scalarVal && scalarVal->array.nElems > 0) {
/* Assume that this array is still really a scalar */
Assert(scalarVal->type == jbvArray);
(*pstate)->size = scalarVal->array.nElems;
} else {
(*pstate)->size = 4;
}
(*pstate)->contVal.array.elems = (JsonbValue*)palloc(sizeof(JsonbValue) * (*pstate)->size);
break;
case WJB_BEGIN_OBJECT:
Assert(!scalarVal);
*pstate = pushState(pstate);
result = &(*pstate)->contVal;
(*pstate)->contVal.type = jbvObject;
(*pstate)->contVal.estSize = 3 * sizeof(JEntry);
(*pstate)->contVal.object.nPairs = 0;
(*pstate)->size = 4;
(*pstate)->contVal.object.pairs = (JsonbPair*)palloc(sizeof(JsonbPair) * (*pstate)->size);
break;
case WJB_KEY:
Assert(scalarVal->type == jbvString);
appendKey(*pstate, scalarVal);
break;
case WJB_VALUE:
Assert(IsAJsonbScalar(scalarVal) || scalarVal->type == jbvBinary);
appendValue(*pstate, scalarVal);
break;
case WJB_ELEM:
Assert(IsAJsonbScalar(scalarVal) || scalarVal->type == jbvBinary);
appendElement(*pstate, scalarVal);
break;
case WJB_END_OBJECT:
uniqueifyJsonbObject(&(*pstate)->contVal);
case WJB_END_ARRAY:
/* Steps here common to WJB_END_OBJECT case */
Assert(!scalarVal);
result = &(*pstate)->contVal;
/*
* Pop stack and push current array/object as value in parent
* array/object
*/
*pstate = (*pstate)->next;
if (*pstate) {
switch ((*pstate)->contVal.type) {
case jbvArray:
appendElement(*pstate, result);
break;
case jbvObject:
appendValue(*pstate, result);
break;
default:
elog(ERROR, "invalid jsonb container type");
}
}
break;
default:
elog(ERROR, "unrecognized jsonb sequential processing token");
}
return result;
}
/*
* Given a Jsonb superheader, expand to JsonbIterator to iterate over items
* fully expanded to in-memory representation for manipulation.
*
* See JsonbIteratorNext() for notes on memory management.
*/
JsonbIterator *JsonbIteratorInit(JsonbSuperHeader sheader)
{
JsonbIterator *it = (JsonbIterator*)palloc(sizeof(JsonbIterator));
iteratorFromContainerBuf(it, sheader);
it->parent = NULL;
return it;
}
/*
* Get next JsonbValue while iterating
*
* Caller should initially pass their own, original iterator. They may get
* back a child iterator palloc()'d here instead. The function can be relied
* on to free those child iterators, lest the memory allocated for highly
* nested objects become unreasonable, but only if callers don't end iteration
* early (by breaking upon having found something in a search, for example).
*
* Callers in such a scenario, that are particularly sensitive to leaking
* memory in a long-lived context may walk the ancestral tree from the final
* iterator we left them with to its oldest ancestor, pfree()ing as they go.
* They do not have to free any other memory previously allocated for iterators
* but not accessible as direct ancestors of the iterator they're last passed
* back.
*
* Returns "Jsonb sequential processing" token value. Iterator "state"
* reflects the current stage of the process in a less granular fashion, and is
* mostly used here to track things internally with respect to particular
* iterators.
*
* Clients of this function should not have to handle any jbvBinary values
* (since recursive calls will deal with this), provided skipNested is false.
* It is our job to expand the jbvBinary representation without bothering them
* with it. However, clients should not take it upon themselves to touch array
* or Object element/pair buffers, since their element/pair pointers are
* garbage.
*/
int JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
{
JsonbIterState state;
/* Guard against stack overflow due to overly complex Jsonb */
check_stack_depth();
/* Recursive caller may have original caller's iterator */
if (*it == NULL) {
return WJB_DONE;
}
state = (*it)->state;
if ((*it)->containerType == JB_FARRAY) {
if (state == jbi_start) {
/* Set v to array on first array call */
val->type = jbvArray;
val->array.nElems = (*it)->nElems;
/*
* v->array.elems is not actually set, because we aren't doing a
* full conversion
*/
val->array.rawScalar = (*it)->isScalar;
(*it)->i = 0;
/* Set state for next call */
(*it)->state = jbi_elem;
return WJB_BEGIN_ARRAY;
} else if (state == jbi_elem) {
if ((uint)(*it)->i >= (*it)->nElems) {
/*
* All elements within array already processed. Report this to
* caller, and give it back original parent iterator (which
* independently tracks iteration progress at its level of
* nesting).
*/
*it = freeAndGetParent(*it);
return WJB_END_ARRAY;
} else if (formIterIsContainer(it, val, &(*it)->meta[(*it)->i++], skipNested)) {
/*
* New child iterator acquired within formIterIsContainer.
* Recurse into container. Don't directly return jbvBinary
* value to top-level client.
*/
return JsonbIteratorNext(it, val, skipNested);
} else {
/* Scalar item in array */
return WJB_ELEM;
}
}
} else if ((*it)->containerType == JB_FOBJECT) {
if (state == jbi_start) {
/* Set v to object on first object call */
val->type = jbvObject;
val->object.nPairs = (*it)->nElems;
/*
* v->object.pairs is not actually set, because we aren't doing a
* full conversion
*/
(*it)->i = 0;
/* Set state for next call */
(*it)->state = jbi_key;
return WJB_BEGIN_OBJECT;
} else if (state == jbi_key) {
if ((uint)(*it)->i >= (*it)->nElems) {
/*
* All pairs within object already processed. Report this to
* caller, and give it back original containing iterator (which
* independently tracks iteration progress at its level of
* nesting).
*/
*it = freeAndGetParent(*it);
return WJB_END_OBJECT;
} else {
/*
* Return binary item key (ensured by setting skipNested to
* false directly). No child iterator, no further recursion.
* When control reaches here, it's probably from a recursive
* call.
*/
if (formIterIsContainer(it, val, &(*it)->meta[(*it)->i * 2], false)) {
elog(ERROR, "unexpected container as object key");
}
Assert(val->type == jbvString);
/* Set state for next call */
(*it)->state = jbi_value;
return WJB_KEY;
}
} else if (state == jbi_value) {
/* Set state for next call */
(*it)->state = jbi_key;
/*
* Value may be a container, in which case we recurse with new,
* child iterator. If it is, don't bother !skipNested callers with
* dealing with the jbvBinary representation.
*/
if (formIterIsContainer(it, val, &(*it)->meta[((*it)->i++) * 2 + 1], skipNested)) {
return JsonbIteratorNext(it, val, skipNested);
} else {
return WJB_VALUE;
}
}
}
elog(ERROR, "invalid iterator state");
return WJB_DONE;
}
/*
* Worker for "contains" operator's function
*
* Formally speaking, containment is top-down, unordered subtree isomorphism.
*
* Takes iterators that belong to some container type. These iterators
* "belong" to those values in the sense that they've just been initialized in
* respect of them by the caller (perhaps in a nested fashion).
*
* "val" is lhs Jsonb, and mContained is rhs Jsonb when called from top level.
* We determine if mContained is contained within val.
*/
bool JsonbDeepContains(JsonbIterator **val, JsonbIterator **mContained)
{
uint32 rval,
rcont;
JsonbValue vval,
vcontained;
/*
* Guard against stack overflow due to overly complex Jsonb.
*
* Functions called here independently take this precaution, but that might
* not be sufficient since this is also a recursive function.
*/
check_stack_depth();
rval = JsonbIteratorNext(val, &vval, false);
rcont = JsonbIteratorNext(mContained, &vcontained, false);
if (rval != rcont) {
/*
* The differing return values can immediately be taken as indicating
* two differing container types at this nesting level, which is
* sufficient reason to give up entirely (but it should be the case
* that they're both some container type).
*/
Assert(rval == WJB_BEGIN_OBJECT || rval == WJB_BEGIN_ARRAY);
Assert(rcont == WJB_BEGIN_OBJECT || rcont == WJB_BEGIN_ARRAY);
return false;
} else if (rcont == WJB_BEGIN_OBJECT) {
JsonbValue *lhsVal; /* lhsVal is from pair in lhs object */
Assert(vcontained.type == jbvObject);
/* Work through rhs "is it contained within?" object */
for (;;) {
rcont = JsonbIteratorNext(mContained, &vcontained, false);
/*
* When we get through caller's rhs "is it contained within?"
* object without failing to find one of its values, it's
* contained.
*/
if (rcont == WJB_END_OBJECT) {
return true;
}
Assert(rcont == WJB_KEY);
/* First, find value by key... */
lhsVal = findJsonbValueFromSuperHeader((*val)->buffer, JB_FOBJECT, NULL, &vcontained);
if (!lhsVal) {
return false;
}
/*
* ...at this stage it is apparent that there is at least a key
* match for this rhs pair.
*/
rcont = JsonbIteratorNext(mContained, &vcontained, true);
Assert(rcont == WJB_VALUE);
/*
* Compare rhs pair's value with lhs pair's value just found using
* key
*/
if (lhsVal->type != vcontained.type) {
return false;
} else if (IsAJsonbScalar(lhsVal)) {
if (compareJsonbScalarValue(lhsVal, &vcontained) != 0) {
return false;
}
} else {
/* Nested container value (object or array) */
JsonbIterator *nestval = NULL;
JsonbIterator *nestContained = NULL;
Assert(lhsVal->type == jbvBinary);
Assert(vcontained.type == jbvBinary);
nestval = JsonbIteratorInit(lhsVal->binary.data);
nestContained = JsonbIteratorInit(vcontained.binary.data);
/*
* Match "value" side of rhs datum object's pair recursively.
* It's a nested structure.
*
* Note that nesting still has to "match up" at the right
* nesting sub-levels. However, there need only be zero or
* more matching pairs (or elements) at each nesting level
* (provided the *rhs* pairs/elements *all* match on each
* level), which enables searching nested structures for a
* single String or other primitive type sub-datum quite
* effectively (provided the user constructed the rhs nested
* structure such that we "know where to look").
*
* In other words, the mapping of container nodes in the rhs
* "vcontained" Jsonb to internal nodes on the lhs is
* injective, and parent-child edges on the rhs must be mapped
* to parent-child edges on the lhs to satisfy the condition of
* containment (plus of course the mapped nodes must be equal).
*/
if (!JsonbDeepContains(&nestval, &nestContained)) {
return false;
}
}
}
} else if (rcont == WJB_BEGIN_ARRAY) {
JsonbValue *lhsConts = NULL;
uint32 nLhsElems = vval.array.nElems;
Assert(vcontained.type == jbvArray);
/*
* Handle distinction between "raw scalar" pseudo arrays, and real
* arrays.
*
* A raw scalar may contain another raw scalar, and an array may
* contain a raw scalar, but a raw scalar may not contain an array. We
* don't do something like this for the object case, since objects can
* only contain pairs, never raw scalars (a pair is represented by an
* rhs object argument with a single contained pair).
*/
if (vval.array.rawScalar && !vcontained.array.rawScalar) {
return false;
}
/* Work through rhs "is it contained within?" array */
for (;;) {
rcont = JsonbIteratorNext(mContained, &vcontained, true);
/*
* When we get through caller's rhs "is it contained within?" array
* without failing to find one of its values, it's contained.
*/
if (rcont == WJB_END_ARRAY) {
return true;
}
Assert(rcont == WJB_ELEM);
if (IsAJsonbScalar(&vcontained)) {
if (!findJsonbValueFromSuperHeader((*val)->buffer, JB_FARRAY, NULL, &vcontained)) {
return false;
}
} else {
uint32 i;
/*
* If this is first container found in rhs array (at this
* depth), initialize temp lhs array of containers
*/
if (lhsConts == NULL) {
uint32 j = 0;
/* Make room for all possible values */
lhsConts = (JsonbValue*)palloc(sizeof(JsonbValue) * nLhsElems);
for (i = 0; i < nLhsElems; i++) {
/* Store all lhs elements in temp array */
rcont = JsonbIteratorNext(val, &vval, true);
Assert(rcont == WJB_ELEM);
if (vval.type == jbvBinary) {
lhsConts[j++] = vval;
}
}
/* No container elements in temp array, so give up now */
if (j == 0) {
return false;
}
/* We may have only partially filled array */
nLhsElems = j;
}
/* XXX: Nested array containment is O(N^2) */
for (i = 0; i < nLhsElems; i++) {
/* Nested container value (object or array) */
JsonbIterator *nestval = NULL;
JsonbIterator *nestContained = NULL;
bool contains;
nestval = JsonbIteratorInit(lhsConts[i].binary.data);
nestContained = JsonbIteratorInit(vcontained.binary.data);
contains = JsonbDeepContains(&nestval, &nestContained);
if (nestval) {
pfree(nestval);
}
if (nestContained) {
pfree(nestContained);
}
if (contains) {
break;
}
}
/*
* Report rhs container value is not contained if couldn't
* match rhs container to *some* lhs cont
*/
if (i == nLhsElems) {
return false;
}
}
}
} else {
elog(ERROR, "invalid jsonb container type");
}
elog(ERROR, "unexpectedly fell off end of jsonb container");
return false;
}
/*
* Convert a Postgres text array to a Jsonb array, sorted and with
* de-duplicated key elements. This is used for searching an object for items
* in the array, so we enforce that the number of strings cannot exceed
* JSONB_MAX_PAIRS.
*/
JsonbValue *arrayToJsonbSortedArray(ArrayType *array)
{
Datum *key_datums = NULL;
bool *key_nulls = NULL;
int elem_count;
JsonbValue *result = NULL;
int i,
j;
/* Extract data for sorting */
deconstruct_array(array, TEXTOID, -1, false, 'i', &key_datums, &key_nulls, &elem_count);
if (elem_count == 0) {
return NULL;
}
/*
* A text array uses at least eight bytes per element, so any overflow in
* "key_count * sizeof(JsonbPair)" is small enough for palloc() to catch.
* However, credible improvements to the array format could invalidate that
* assumption. Therefore, use an explicit check rather than relying on
* palloc() to complain.
*/
if ((uint)elem_count > JSONB_MAX_PAIRS) {
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of array elements (%d) exceeds maximum allowed Jsonb pairs (%zu)",
elem_count, JSONB_MAX_PAIRS)));
}
result = (JsonbValue*)palloc(sizeof(JsonbValue));
result->type = jbvArray;
result->array.rawScalar = false;
result->array.elems = (JsonbValue*)palloc(sizeof(JsonbPair) * elem_count);
for (i = 0, j = 0; i < elem_count; i++) {
if (!key_nulls[i]) {
result->array.elems[j].type = jbvString;
result->array.elems[j].string.val = VARDATA(key_datums[i]);
result->array.elems[j].string.len = VARSIZE(key_datums[i]) - VARHDRSZ;
j++;
}
}
result->array.nElems = j;
uniqueifyJsonbArray(result);
return result;
}
/*
* Hash a JsonbValue scalar value, mixing in the hash value with an existing
* hash provided by the caller.
*
* Some callers may wish to independently XOR in JB_FOBJECT and JB_FARRAY
* flags.
*/
void JsonbHashScalarValue(const JsonbValue * scalarVal, uint32 * hash)
{
int tmp;
/*
* Combine hash values of successive keys, values and elements by rotating
* the previous value left 1 bit, then XOR'ing in the new
* key/value/element's hash value.
*/
*hash = (*hash << 1) | (*hash >> 31);
switch (scalarVal->type) {
case jbvNull:
*hash ^= 0x01;
return;
case jbvString:
tmp = hash_any((unsigned char *) scalarVal->string.val, scalarVal->string.len);
*hash ^= tmp;
return;
case jbvNumeric:
/* Must be unaffected by trailing zeroes */
tmp = DatumGetInt32(DirectFunctionCall1(hash_numeric, NumericGetDatum(scalarVal->numeric)));
*hash ^= tmp;
return;
case jbvBool:
*hash ^= scalarVal->boolean? 0x02:0x04;
return;
default:
elog(ERROR, "invalid jsonb scalar type");
}
}
/*
* Are two scalar JsonbValues of the same type a and b equal?
*
* Does not use lexical comparisons. Therefore, it is essentially that this
* never be used against Strings for anything other than searching for values
* within a single jsonb.
*/
static int compareJsonbScalarValue(JsonbValue * aScalar, JsonbValue * bScalar)
{
if (aScalar->type == bScalar->type) {
switch (aScalar->type) {
case jbvNull:
return 0;
case jbvString:
return lengthCompareJsonbStringValue(aScalar, bScalar, NULL);
case jbvNumeric:
return DatumGetInt32(DirectFunctionCall2(numeric_cmp,
PointerGetDatum(aScalar->numeric),
PointerGetDatum(bScalar->numeric)));
case jbvBool:
if (aScalar->boolean != bScalar->boolean) {
return (aScalar->boolean > bScalar->boolean) ? 1 : -1;
} else {
return 0;
}
default:
elog(ERROR, "invalid jsonb scalar type");
}
}
elog(ERROR, "jsonb scalar type mismatch");
return 0;
}
/*
* Standard lexical qsort() comparator of jsonb strings.
*
* Sorts strings lexically, using the default database collation. Used by
* B-Tree operators, where a lexical sort order is generally expected.
*/
static int lexicalCompareJsonbStringValue(const void *a, const void *b)
{
const JsonbValue *va = (const JsonbValue *) a;
const JsonbValue *vb = (const JsonbValue *) b;
Assert(va->type == jbvString);
Assert(vb->type == jbvString);
return varstr_cmp(va->string.val, va->string.len, vb->string.val, vb->string.len, DEFAULT_COLLATION_OID);
}
/*
* Given a JsonbValue, convert to Jsonb and store in preallocated Jsonb buffer
* sufficiently large to fit the value
*/
static Size convertJsonb(JsonbValue * val, Jsonb *buffer)
{
convertState state;
Size len;
/* Should not already have binary representation */
Assert(val->type != jbvBinary);
state.buffer = buffer;
/* Start from superheader */
state.ptr = VARDATA(state.buffer);
state.levelSz = 8;
state.allState = (convertLevel*)palloc(sizeof(convertLevel) * state.levelSz);
walkJsonbValueConversion(val, &state, 0);
len = state.ptr - VARDATA(state.buffer);
Assert(len <= (uint)val->estSize);
return len;
}
/*
* Walk the tree representation of Jsonb, as part of the process of converting
* a JsonbValue to a Jsonb.
*
* This high-level function takes care of recursion into sub-containers, but at
* the top level calls putJsonbValueConversion once per sequential processing
* token (in a manner similar to generic iteration).
*/
static void walkJsonbValueConversion(JsonbValue * val, convertState * cstate, uint32 nestlevel)
{
int i;
check_stack_depth();
if (!val)
return;
switch (val->type) {
case jbvArray:
putJsonbValueConversion(cstate, val, WJB_BEGIN_ARRAY, nestlevel);
for (i = 0; i < val->array.nElems; i++) {
if (IsAJsonbScalar(&val->array.elems[i]) ||
val->array.elems[i].type == jbvBinary) {
putJsonbValueConversion(cstate, val->array.elems + i, WJB_ELEM, nestlevel);
} else {
walkJsonbValueConversion(val->array.elems + i, cstate, nestlevel + 1);
}
}
putJsonbValueConversion(cstate, val, WJB_END_ARRAY, nestlevel);
break;
case jbvObject:
putJsonbValueConversion(cstate, val, WJB_BEGIN_OBJECT, nestlevel);
for (i = 0; i < val->object.nPairs; i++) {
putJsonbValueConversion(cstate, &val->object.pairs[i].key, WJB_KEY, nestlevel);
if (IsAJsonbScalar(&val->object.pairs[i].value) ||
val->object.pairs[i].value.type == jbvBinary) {
putJsonbValueConversion(cstate, &val->object.pairs[i].value, WJB_VALUE, nestlevel);
} else {
walkJsonbValueConversion(&val->object.pairs[i].value, cstate, nestlevel + 1);
}
}
putJsonbValueConversion(cstate, val, WJB_END_OBJECT, nestlevel);
break;
default:
elog(ERROR, "unknown type of jsonb container");
}
}
/*
* walkJsonbValueConversion() worker. Add padding sufficient to int-align our
* access to conversion buffer.
*/
static inline short addPaddingInt(convertState *cstate)
{
short padlen, p;
padlen = INTALIGN(cstate->ptr - VARDATA(cstate->buffer)) - (cstate->ptr - VARDATA(cstate->buffer));
for (p = padlen; p > 0; p--) {
*cstate->ptr = '\0';
cstate->ptr++;
}
return padlen;
}
/*
* walkJsonbValueConversion() worker.
*
* As part of the process of converting an arbitrary JsonbValue to a Jsonb,
* copy over an arbitrary individual JsonbValue. This function may copy any
* type of value, even containers (Objects/arrays). However, it is not
* responsible for recursive aspects of walking the tree (so only top-level
* Object/array details are handled).
*
* No details about their keys/values/elements are handled recursively -
* rather, the function is called as required for the start of an Object/Array,
* and the end (i.e. there is one call per sequential processing WJB_* token).
*/
static void putJsonbValueConversion(convertState *cstate, JsonbValue *val, uint32 flags, uint32 level)
{
if (level == cstate->levelSz) {
cstate->levelSz *= 2;
cstate->allState = (convertLevel*)repalloc(cstate->allState, sizeof(convertLevel) * cstate->levelSz);
}
cstate->contPtr = cstate->allState + level;
if (flags & (WJB_BEGIN_ARRAY | WJB_BEGIN_OBJECT)) {
Assert(((flags & WJB_BEGIN_ARRAY) && val->type == jbvArray) ||
((flags & WJB_BEGIN_OBJECT) && val->type == jbvObject));
/* Initialize pointer into conversion buffer at this level */
cstate->contPtr->begin = cstate->ptr;
addPaddingInt(cstate);
/* Initialize everything else at this level */
cstate->contPtr->header = (uint32 *) cstate->ptr;
/* Advance past header */
cstate->ptr += sizeof(uint32);
cstate->contPtr->meta = (JEntry *) cstate->ptr;
cstate->contPtr->i = 0;
if (val->type == jbvArray) {
*cstate->contPtr->header = val->array.nElems | JB_FARRAY;
cstate->ptr += sizeof(JEntry) * val->array.nElems;
if (val->array.rawScalar) {
Assert(val->array.nElems == 1);
Assert(level == 0);
*cstate->contPtr->header |= JB_FSCALAR;
}
} else {
*cstate->contPtr->header = val->object.nPairs | JB_FOBJECT;
cstate->ptr += sizeof(JEntry) * val->object.nPairs * 2;
}
} else if (flags & WJB_ELEM) {
putScalarConversion(cstate, val, level, cstate->contPtr->i);
cstate->contPtr->i++;
} else if (flags & WJB_KEY) {
Assert(val->type == jbvString);
putScalarConversion(cstate, val, level, cstate->contPtr->i * 2);
} else if (flags & WJB_VALUE) {
putScalarConversion(cstate, val, level, cstate->contPtr->i * 2 + 1);
cstate->contPtr->i++;
} else if (flags & (WJB_END_ARRAY | WJB_END_OBJECT)) {
convertLevel *prevPtr = NULL; /* Prev container pointer */
uint32 len,
i;
Assert(((flags & WJB_END_ARRAY) && val->type == jbvArray) ||
((flags & WJB_END_OBJECT) && val->type == jbvObject));
if (level == 0) {
return;
}
len = cstate->ptr - (char *) cstate->contPtr->begin;
prevPtr = cstate->contPtr - 1;
if (*prevPtr->header & JB_FARRAY) {
i = prevPtr->i;
prevPtr->meta[i].header = JENTRY_ISNEST;
if (i == 0) {
prevPtr->meta[0].header |= JENTRY_ISFIRST | len;
} else {
prevPtr->meta[i].header |= (prevPtr->meta[i - 1].header & JENTRY_POSMASK) + len;
}
} else if (*prevPtr->header & JB_FOBJECT) {
i = 2 * prevPtr->i + 1; /* Value, not key */
prevPtr->meta[i].header = JENTRY_ISNEST;
prevPtr->meta[i].header |= (prevPtr->meta[i - 1].header & JENTRY_POSMASK) + len;
} else {
elog(ERROR, "invalid jsonb container type");
}
Assert(cstate->ptr - cstate->contPtr->begin <= val->estSize);
prevPtr->i++;
} else {
elog(ERROR, "unknown flag encountered during jsonb tree walk");
}
}
/*
* As part of the process of converting an arbitrary JsonbValue to a Jsonb,
* serialize and copy a scalar value into buffer.
*
* This is a worker function for putJsonbValueConversion() (itself a worker for
* walkJsonbValueConversion()). It handles the details with regard to Jentry
* metadata peculiar to each scalar type.
*/
static void putScalarConversion(convertState *cstate, JsonbValue *scalarVal, uint32 level, uint32 i)
{
int strlen;
int numlen;
short padlen;
errno_t rc = 0;
cstate->contPtr = cstate->allState + level;
if (i == 0) {
cstate->contPtr->meta[0].header = JENTRY_ISFIRST;
} else {
cstate->contPtr->meta[i].header = 0;
}
switch (scalarVal->type) {
case jbvNull:
cstate->contPtr->meta[i].header |= JENTRY_ISNULL;
if (i > 0) {
cstate->contPtr->meta[i].header |=
cstate->contPtr->meta[i - 1].header & JENTRY_POSMASK;
}
break;
case jbvString:
strlen = scalarVal->string.len > 0 ? scalarVal->string.len : 1;
rc = memcpy_s(cstate->ptr, strlen, scalarVal->string.val, strlen);
securec_check(rc, "\0", "\0");
cstate->ptr += scalarVal->string.len;
if (i == 0) {
cstate->contPtr->meta[0].header |= scalarVal->string.len;
} else {
cstate->contPtr->meta[i].header |=
(cstate->contPtr->meta[i - 1].header & JENTRY_POSMASK) + scalarVal->string.len;
}
break;
case jbvNumeric:
numlen = VARSIZE_ANY(scalarVal->numeric);
padlen = addPaddingInt(cstate);
rc = memcpy_s(cstate->ptr, numlen, scalarVal->numeric, numlen);
securec_check(rc, "\0", "\0");
cstate->ptr += numlen;
cstate->contPtr->meta[i].header |= JENTRY_ISNUMERIC;
if (i == 0) {
cstate->contPtr->meta[0].header |= padlen + numlen;
} else {
cstate->contPtr->meta[i].header |=
(cstate->contPtr->meta[i - 1].header & JENTRY_POSMASK) + padlen + numlen;
}
break;
case jbvBool:
cstate->contPtr->meta[i].header |= (scalarVal->boolean) ? JENTRY_ISTRUE : JENTRY_ISFALSE;
if (i > 0) {
cstate->contPtr->meta[i].header |= cstate->contPtr->meta[i - 1].header & JENTRY_POSMASK;
}
break;
default:
elog(ERROR, "invalid jsonb scalar type");
}
}
/*
* Given superheader pointer into buffer, initialize iterator. Must be a
* container type.
*/
static void iteratorFromContainerBuf(JsonbIterator *it, JsonbSuperHeader sheader)
{
uint32 superheader = *(uint32 *) sheader;
it->containerType = superheader & (JB_FARRAY | JB_FOBJECT);
it->nElems = superheader & JB_CMASK;
it->buffer = sheader;
/* Array starts just after header */
it->meta = (JEntry *) (sheader + sizeof(uint32));
it->state = jbi_start;
switch (it->containerType) {
case JB_FARRAY:
it->dataProper =
(char *) it->meta + it->nElems * sizeof(JEntry);
it->isScalar = (superheader & JB_FSCALAR) != 0;
/* This is either a "raw scalar", or an array */
Assert(!it->isScalar || it->nElems == 1);
break;
case JB_FOBJECT:
/*
* Offset reflects that nElems indicates JsonbPairs in an object.
* Each key and each value contain Jentry metadata just the same.
*/
it->dataProper = (char *) it->meta + it->nElems * sizeof(JEntry) * 2;
break;
default:
elog(ERROR, "unknown type of jsonb container");
}
}
/*
* JsonbIteratorNext() worker
*
* Returns bool indicating if v was a non-jbvBinary container, and thus if
* further recursion is required by caller (according to its skipNested
* preference). If it is required, we set the caller's iterator for further
* recursion into the nested value. If we're going to skip nested items, just
* set v to a jbvBinary value, but don't set caller's iterator.
*
* Unlike with containers (either in this function or in any
* JsonbIteratorNext() infrastructure), we fully convert from what is
* ultimately a Jsonb on-disk representation, to a JsonbValue in-memory
* representation (for scalar values only). JsonbIteratorNext() initializes
* container Jsonbvalues, but without a sane private buffer. For scalar values
* it has to be done for real (even if we don't actually allocate more memory
* to do this. The point is that our JsonbValues scalars can be passed around
* anywhere).
*/
static bool formIterIsContainer(JsonbIterator **it, JsonbValue *val, JEntry *ent, bool skipNested)
{
if (JBE_ISNULL(*ent)) {
val->type = jbvNull;
val->estSize = sizeof(JEntry);
return false;
} else if (JBE_ISSTRING(*ent)) {
val->type = jbvString;
val->string.val = (*it)->dataProper + JBE_OFF(*ent);
val->string.len = JBE_LEN(*ent);
val->estSize = sizeof(JEntry) + val->string.len;
return false;
} else if (JBE_ISNUMERIC(*ent)) {
val->type = jbvNumeric;
val->numeric = (Numeric) ((*it)->dataProper + INTALIGN(JBE_OFF(*ent)));
val->estSize = 2 * sizeof(JEntry) + VARSIZE_ANY(val->numeric);
return false;
} else if (JBE_ISBOOL(*ent)) {
val->type = jbvBool;
val->boolean = JBE_ISBOOL_TRUE(*ent) != 0;
val->estSize = sizeof(JEntry);
return false;
} else if (skipNested) {
val->type = jbvBinary;
val->binary.data = (*it)->dataProper + INTALIGN(JBE_OFF(*ent));
val->binary.len = JBE_LEN(*ent) - (INTALIGN(JBE_OFF(*ent)) - JBE_OFF(*ent));
val->estSize = val->binary.len + 2 * sizeof(JEntry);
return false;
} else {
/*
* Must be container type, so setup caller's iterator to point to that,
* and return indication of that.
*
* Get child iterator.
*/
JsonbIterator *child = (JsonbIterator*)palloc(sizeof(JsonbIterator));
iteratorFromContainerBuf(child, (*it)->dataProper + INTALIGN(JBE_OFF(*ent)));
child->parent = *it;
*it = child;
return true;
}
}
/*
* JsonbIteratorNext() worker: Return parent, while freeing memory for current
* iterator
*/
static JsonbIterator *freeAndGetParent(JsonbIterator *it)
{
JsonbIterator *v = it->parent;
pfree(it);
return v;
}
/*
* pushJsonbValue() worker: Iteration-like forming of Jsonb
*/
static JsonbParseState *pushState(JsonbParseState **pstate)
{
JsonbParseState *ns = (JsonbParseState*)palloc(sizeof(JsonbParseState));
ns->next = *pstate;
return ns;
}
/*
* pushJsonbValue() worker: Append a pair key to state when generating a Jsonb
*/
static void appendKey(JsonbParseState *pstate, JsonbValue *string)
{
JsonbValue *object = &pstate->contVal;
Assert(object->type == jbvObject);
Assert(string->type == jbvString);
if ((uint)object->object.nPairs >= JSONB_MAX_PAIRS) {
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of jsonb object pairs exceeds the maximum allowed (%zu)",
JSONB_MAX_PAIRS)));
}
if ((uint)object->object.nPairs >= pstate->size) {
pstate->size *= 2;
object->object.pairs = (JsonbPair*)repalloc(object->object.pairs, sizeof(JsonbPair) * pstate->size);
}
object->object.pairs[object->object.nPairs].key = *string;
object->object.pairs[object->object.nPairs].order = object->object.nPairs;
object->estSize += string->estSize;
}
/*
* pushJsonbValue() worker: Append a pair value to state when generating a
* Jsonb
*/
static void appendValue(JsonbParseState *pstate, JsonbValue *scalarVal)
{
JsonbValue *object = &pstate->contVal;
Assert(object->type == jbvObject);
object->object.pairs[object->object.nPairs++].value = *scalarVal;
object->estSize += scalarVal->estSize;
}
/*
* pushJsonbValue() worker: Append an element to state when generating a Jsonb
*/
static void appendElement(JsonbParseState *pstate, JsonbValue *scalarVal)
{
JsonbValue *array = &pstate->contVal;
Assert(array->type == jbvArray);
if ((uint)array->array.nElems >= JSONB_MAX_ELEMS) {
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of jsonb array elements exceeds the maximum allowed (%zu)",
JSONB_MAX_ELEMS)));
}
if ((uint)array->array.nElems >= pstate->size) {
pstate->size *= 2;
array->array.elems = (JsonbValue*)repalloc(array->array.elems, sizeof(JsonbValue) * pstate->size);
}
array->array.elems[array->array.nElems++] = *scalarVal;
array->estSize += scalarVal->estSize;
}
/*
* Compare two jbvString JsonbValue values, a and b.
*
* This is a special qsort_arg() comparator used to sort strings in certain
* internal contexts where it is sufficient to have a well-defined sort order.
* In particular, object pair keys are sorted according to this criteria to
* facilitate cheap binary searches where we don't care about lexical sort
* order.
*
* a and b are first sorted based on their length. If a tie-breaker is
* required, only then do we consider string binary equality.
*
* Third argument 'binequal' may point to a bool. If it's set, *binequal is set
* to true iff a and b have full binary equality, since some callers have an
* interest in whether the two values are equal or merely equivalent.
*/
static int lengthCompareJsonbStringValue(const void *a, const void *b, void *binequal)
{
const JsonbValue *va = (const JsonbValue *) a;
const JsonbValue *vb = (const JsonbValue *) b;
int res;
Assert(va->type == jbvString);
Assert(vb->type == jbvString);
if (va->string.len == vb->string.len) {
res = memcmp(va->string.val, vb->string.val, va->string.len);
if (res == 0 && binequal) {
*((bool *) binequal) = true;
}
} else {
res = (va->string.len > vb->string.len) ? 1 : -1;
}
return res;
}
/*
* qsort_arg() comparator to compare JsonbPair values.
*
* Function implemented in terms of lengthCompareJsonbStringValue(), and thus the
* same "arg setting" hack will be applied here in respect of the pair's key
* values.
*
* N.B: String comparisons here are "length-wise"
*
* Pairs with equals keys are ordered such that the order field is respected.
*/
static int lengthCompareJsonbPair(const void *a, const void *b, void *binequal)
{
const JsonbPair *pa = (const JsonbPair *) a;
const JsonbPair *pb = (const JsonbPair *) b;
int res;
res = lengthCompareJsonbStringValue(&pa->key, &pb->key, binequal);
/*
* Guarantee keeping order of equal pair. Unique algorithm will prefer
* first element as value.
*/
if (res == 0) {
res = (pa->order > pb->order) ? -1 : 1;
}
return res;
}
/*
* Sort and unique-ify pairs in JsonbValue object
*/
static void uniqueifyJsonbObject(JsonbValue * object)
{
bool hasNonUniq = false;
Assert(object->type == jbvObject);
if (object->object.nPairs > 1) {
qsort_arg(object->object.pairs, object->object.nPairs, sizeof(JsonbPair), lengthCompareJsonbPair, &hasNonUniq);
}
if (hasNonUniq) {
JsonbPair *ptr = object->object.pairs + 1,
*res = object->object.pairs;
while (ptr - object->object.pairs < object->object.nPairs) {
/* Avoid copying over duplicate */
if (lengthCompareJsonbStringValue(ptr, res, NULL) == 0) {
object->estSize -= ptr->key.estSize + ptr->value.estSize;
} else {
res++;
if (ptr != res) {
errno_t rc = memcpy_s(res, sizeof(JsonbPair), ptr, sizeof(JsonbPair));
securec_check(rc, "\0", "\0");
}
}
ptr++;
}
object->object.nPairs = res + 1 - object->object.pairs;
}
}
/*
* Sort and unique-ify JsonbArray.
*
* Sorting uses internal ordering.
*/
static void uniqueifyJsonbArray(JsonbValue *array)
{
bool hasNonUniq = false;
Assert(array->type == jbvArray);
/*
* Actually sort values, determining if any were equal on the basis of full
* binary equality (rather than just having the same string length).
*/
if (array->array.nElems > 1) {
qsort_arg(array->array.elems, array->array.nElems,
sizeof(JsonbValue), lengthCompareJsonbStringValue,
&hasNonUniq);
}
if (hasNonUniq) {
JsonbValue *ptr = array->array.elems + 1,
*res = array->array.elems;
while (ptr - array->array.elems < array->array.nElems) {
/* Avoid copying over duplicate */
if (lengthCompareJsonbStringValue(ptr, res, NULL) != 0) {
res++;
*res = *ptr;
}
ptr++;
}
array->array.nElems = res + 1 - array->array.elems;
}
}
| 37.375811 | 119 | 0.577835 | [
"object"
] |
043196ab7868c9706c659edd611f5e3f485e907c | 3,995 | cpp | C++ | qt-creator-4.14/src/libs/aggregation/examples/text/main.cpp | peng1ei/qtcreator-plugin | ca4f9c6c7ddd899bcdbac7a6a4c5e383495e7a65 | [
"MIT"
] | 1 | 2021-12-28T23:27:04.000Z | 2021-12-28T23:27:04.000Z | qt-creator-4.14/src/libs/aggregation/examples/text/main.cpp | peng1ei/qtcreator-plugin | ca4f9c6c7ddd899bcdbac7a6a4c5e383495e7a65 | [
"MIT"
] | null | null | null | qt-creator-4.14/src/libs/aggregation/examples/text/main.cpp | peng1ei/qtcreator-plugin | ca4f9c6c7ddd899bcdbac7a6a4c5e383495e7a65 | [
"MIT"
] | 1 | 2021-12-29T11:25:37.000Z | 2021-12-29T11:25:37.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "main.h"
#include <QApplication>
MyMain::MyMain(QWidget *parent, Qt::WFlags flags)
: QWidget(parent, flags)
{
ui.setupUi(this);
connect(ui.comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MyMain::select);
}
void MyMain::add(IComboEntry *obj)
{
m_entries.append(obj);
ui.comboBox->addItem(obj->title());
}
void MyMain::select(int index)
{
IComboEntry *entry = m_entries.at(index);
// with multiple inheritance we would use qobject_cast here
// instead we use query, to get the components if they exist
IText1 *t1 = Aggregation::query<IText1>(entry);
IText2 *t2 = Aggregation::query<IText2>(entry);
IText3 *t3 = Aggregation::query<IText3>(entry);
// set the label texts and enable/disable, depending on whether
// the respective interface implementations exist
ui.text1->setText(t1 ? t1->text() : tr("N/A"));
ui.text2->setText(t2 ? t2->text() : tr("N/A"));
ui.text3->setText(t3 ? t3->text() : tr("N/A"));
ui.text1->setEnabled(t1);
ui.text2->setEnabled(t2);
ui.text3->setEnabled(t3);
}
MyMain::~MyMain()
{
// the following deletes all the Aggregate and IComboEntry and ITextX
// objects, as well as any other components we might have added
qDeleteAll(m_entries);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyMain w;
// create and set up some objects
// the first does only implement the required IComboEntry
// we don't need an aggregation for this
IComboEntry *obj1 = new IComboEntry("Entry without text");
// the second additionally provides an IText2 implementation
// adding a component to the aggregation is done by setting the aggregation as the parent of the component
Aggregation::Aggregate *obj2 = new Aggregation::Aggregate;
obj2->add(new IComboEntry("Entry with text 2"));
obj2->add(new IText2("This is a text for label 2"));
// and so on... two more objects...
Aggregation::Aggregate *obj3 = new Aggregation::Aggregate;
obj3->add(new IComboEntry("Entry with text 1 and 2"));
obj3->add(new IText1("I love Qt!"));
obj3->add(new IText2("There are software companies..."));
Aggregation::Aggregate *obj4 = new Aggregation::Aggregate;
obj4->add(new IComboEntry("Entry with text 1 and 3"));
obj4->add(new IText1("Some text written here."));
obj4->add(new IText3("I'm a troll."));
// the API takes IComboEntries, so we convert the them to it
// the MyMain object takes the ownership of the whole aggregations
w.add(Aggregation::query<IComboEntry>(obj1));
w.add(Aggregation::query<IComboEntry>(obj2));
w.add(Aggregation::query<IComboEntry>(obj3));
w.add(Aggregation::query<IComboEntry>(obj4));
w.show();
return app.exec();
}
| 38.413462 | 110 | 0.671339 | [
"object"
] |
0435374d69a18960b03f3baa922bc2280580bf1e | 511 | cpp | C++ | atc/abc235/c.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | 3 | 2022-03-30T14:14:57.000Z | 2022-03-31T04:30:32.000Z | atc/abc235/c.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | null | null | null | atc/abc235/c.cpp | Zilanlann/cp-code | 0500acbf6fb05a66f7bdbdf0e0a8bd6170126a4a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
typedef long long ll;
using namespace std;
map<int, vector<int>> ma;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
//IO
int n, t;
cin >> n >> t;
for (int i = 1; i <= n; i++) {
int a;
cin >> a;
ma[a].push_back(i);
}
while (t--) {
int x, k;
cin >> x >> k;
if (k > ma[x].size())
cout << -1 << "\n";
else {
cout << ma[x][k - 1] << "\n";
}
}
return 0;
}
| 14.194444 | 35 | 0.448141 | [
"vector"
] |
043c0db6f5fe6195f0b76c982c0349f2e91150bd | 5,635 | cpp | C++ | domain/test/unit/domain/domaindecomp.cpp | j-piccinali/SPH-EXA_mini-app | c3ba4d37f2edf433710d5c0bc2362ec35e75df32 | [
"MIT"
] | 16 | 2022-01-17T19:50:38.000Z | 2022-03-28T08:09:58.000Z | domain/test/unit/domain/domaindecomp.cpp | j-piccinali/SPH-EXA_mini-app | c3ba4d37f2edf433710d5c0bc2362ec35e75df32 | [
"MIT"
] | 41 | 2019-10-08T19:53:55.000Z | 2021-11-23T06:56:03.000Z | domain/test/unit/domain/domaindecomp.cpp | j-piccinali/SPH-EXA_mini-app | c3ba4d37f2edf433710d5c0bc2362ec35e75df32 | [
"MIT"
] | 13 | 2021-12-06T09:12:52.000Z | 2022-03-28T08:07:38.000Z | /*
* MIT License
*
* Copyright (c) 2021 CSCS, ETH Zurich
* 2021 University of Basel
*
* 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.
*/
/*! @file
* @brief Space filling curve octree assignment to ranks tests
*
* @author Sebastian Keller <sebastian.f.keller@gmail.com>
*/
#include <algorithm>
#include <numeric>
#include "gtest/gtest.h"
#include "cstone/domain/domaindecomp.hpp"
#include "cstone/tree/octree.hpp"
#include "coord_samples/random.hpp"
using namespace cstone;
TEST(DomainDecomposition, singleRangeSfcSplit)
{
{
int nSplits = 2;
std::vector<unsigned> counts{5, 5, 5, 5, 5, 6};
auto splits = singleRangeSfcSplit(counts, nSplits);
SpaceCurveAssignment ref(nSplits);
ref.addRange(Rank(0), 0, 3, 15);
ref.addRange(Rank(1), 3, 6, 16);
EXPECT_EQ(ref, splits);
}
{
int nSplits = 2;
std::vector<unsigned> counts{5, 5, 5, 15, 1, 0};
auto splits = singleRangeSfcSplit(counts, nSplits);
SpaceCurveAssignment ref(nSplits);
ref.addRange(Rank(0), 0, 3, 15);
ref.addRange(Rank(1), 3, 6, 16);
EXPECT_EQ(ref, splits);
}
{
int nSplits = 2;
std::vector<unsigned> counts{15, 0, 1, 5, 5, 5};
auto splits = singleRangeSfcSplit(counts, nSplits);
SpaceCurveAssignment ref(nSplits);
ref.addRange(Rank(0), 0, 3, 16);
ref.addRange(Rank(1), 3, 6, 15);
EXPECT_EQ(ref, splits);
}
{
int nSplits = 7;
std::vector<unsigned> counts{4, 3, 4, 3, 4, 3, 4, 3, 4, 3};
// should be grouped |4|7|3|7|4|7|3|
auto splits = singleRangeSfcSplit(counts, nSplits);
SpaceCurveAssignment ref(nSplits);
ref.addRange(Rank(0), 0, 1, 4);
ref.addRange(Rank(1), 1, 3, 7);
ref.addRange(Rank(2), 3, 4, 3);
ref.addRange(Rank(3), 4, 6, 7);
ref.addRange(Rank(4), 6, 7, 4);
ref.addRange(Rank(5), 7, 9, 7);
ref.addRange(Rank(6), 9, 10, 3);
EXPECT_EQ(ref, splits);
}
}
//! @brief test that the SfcLookupKey can lookup the rank for a given code
TEST(DomainDecomposition, AssignmentFindRank)
{
int nRanks = 4;
SpaceCurveAssignment assignment(nRanks);
assignment.addRange(Rank(0), 0, 1, 0);
assignment.addRange(Rank(1), 1, 3, 0);
assignment.addRange(Rank(2), 3, 4, 0);
assignment.addRange(Rank(3), 4, 5, 0);
EXPECT_EQ(0, assignment.findRank(0));
EXPECT_EQ(1, assignment.findRank(1));
EXPECT_EQ(1, assignment.findRank(2));
EXPECT_EQ(2, assignment.findRank(3));
EXPECT_EQ(3, assignment.findRank(4));
}
/*! @brief test SendList creation from a SFC assignment
*
* This test creates an array with SFC keys and an
* SFC assignment with SFC keys ranges.
* CreateSendList then translates the code ranges into indices
* valid for the SFC key array.
*/
template<class KeyType>
void createSendList()
{
std::vector<KeyType> tree{0, 2, 6, 8, 10};
std::vector<KeyType> codes{0, 0, 1, 3, 4, 5, 6, 6, 9};
int nRanks = 2;
SpaceCurveAssignment assignment(nRanks);
assignment.addRange(Rank(0), 0, 2, 0);
assignment.addRange(Rank(1), 2, 4, 0);
// note: codes input needs to be sorted
auto sendList = createSendList<KeyType>(assignment, tree, codes);
EXPECT_EQ(sendList[0].totalCount(), 6);
EXPECT_EQ(sendList[1].totalCount(), 3);
EXPECT_EQ(sendList[0].rangeStart(0), 0);
EXPECT_EQ(sendList[0].rangeEnd(0), 6);
EXPECT_EQ(sendList[1].rangeStart(0), 6);
EXPECT_EQ(sendList[1].rangeEnd(0), 9);
}
TEST(DomainDecomposition, createSendList)
{
createSendList<unsigned>();
createSendList<uint64_t>();
}
template<class KeyType>
void extractRange()
{
int bufferSize = 64;
// the source array from which to extract the buffer
std::vector<double> x(bufferSize);
std::iota(begin(x), end(x), 0);
SendManifest manifest;
manifest.addRange(0, 8);
manifest.addRange(40, 42);
manifest.addRange(50, 50);
std::vector<int> ordering(bufferSize);
std::iota(begin(ordering), end(ordering), 0);
// non-default ordering will make x appear sorted despite two elements being swapped
std::swap(x[0], x[1]);
std::swap(ordering[0], ordering[1]);
std::vector<double> output(manifest.totalCount());
extractRange(manifest, x.data(), ordering.data(), output.data());
// note sorted reference
std::vector<double> ref{0, 1, 2, 3, 4, 5, 6, 7, 40, 41};
EXPECT_EQ(output, ref);
}
TEST(DomainDecomposition, extractRange)
{
extractRange<unsigned>();
extractRange<uint64_t>();
}
| 30.79235 | 88 | 0.656433 | [
"vector"
] |
043dd68756829ce79cee281d2775afdbda3c39e6 | 3,287 | cpp | C++ | src/Engine/Geometry/Model.cpp | Chainsawkitten/Deathcap | 37ed5afccd3113d34612d89c6e6508e8da9a0d7f | [
"MIT"
] | 3 | 2017-09-08T06:05:10.000Z | 2017-10-28T04:22:20.000Z | src/Engine/Geometry/Model.cpp | Chainsawkitten/Deathcap | 37ed5afccd3113d34612d89c6e6508e8da9a0d7f | [
"MIT"
] | 894 | 2017-08-30T09:57:28.000Z | 2018-01-30T12:35:38.000Z | src/Engine/Geometry/Model.cpp | Chainsawkitten/LargeGameProjectEngine | 37ed5afccd3113d34612d89c6e6508e8da9a0d7f | [
"MIT"
] | 1 | 2020-11-06T23:59:58.000Z | 2020-11-06T23:59:58.000Z | #include "Model.hpp"
#include <cstring>
#include "../Hymn.hpp"
#include <Utility/Log.hpp>
#include "MeshData.hpp"
using namespace Geometry;
Model::Model() {
}
Model::~Model() {
}
Json::Value Model::Save() const {
Json::Value model;
model["name"] = name;
model["type"] = type == STATIC ? "Static" : "Skin";
return model;
}
void Model::Load(const std::string& name) {
std::size_t pos = name.find_last_of('/');
this->name = name.substr(pos + 1);
path = name.substr(0, pos + 1);
Load((Hymn().GetPath() + "/" + name + ".asset").c_str());
}
void Model::Load(const char* filename) {
if (assetFile.Open(filename, AssetFileHandler::READ)) {
assetFile.LoadMeshData(0);
MeshData * meshData = assetFile.GetStaticMeshData();
type = meshData->isSkinned ? SKIN : STATIC;
if (meshData->CPU) {
vertexPositionData.resize(meshData->numVertices);
if (meshData->isSkinned)
for (std::size_t i = 0; i < meshData->numVertices; ++i)
vertexPositionData[i] = meshData->skinnedVertices[i].position;
else
for (std::size_t i = 0; i < meshData->numVertices; ++i)
vertexPositionData[i] = meshData->staticVertices[i].position;
vertexIndexData.resize(meshData->numIndices);
std::memcpy(vertexIndexData.data(), meshData->indices, sizeof(uint32_t) * meshData->numIndices);
}
if (meshData->GPU) {
if (meshData->isSkinned) {
GenerateVertexBuffer(vertexBuffer, meshData->skinnedVertices, meshData->numVertices);
GenerateIndexBuffer(meshData->indices, meshData->numIndices, indexBuffer);
GenerateSkinVertexArray(vertexBuffer, indexBuffer, vertexArray);
} else {
GenerateVertexBuffer(vertexBuffer, meshData->staticVertices, meshData->numVertices);
GenerateIndexBuffer(meshData->indices, meshData->numIndices, indexBuffer);
GenerateStaticVertexArray(vertexBuffer, indexBuffer, vertexArray);
}
}
CreateAxisAlignedBoundingBox(meshData->aabbDim, meshData->aabbOrigin, meshData->aabbMinpos, meshData->aabbMaxpos);
assetFile.Close();
}
}
Model::Type Model::GetType() const {
return type;
}
void Model::GenerateVertexBuffer(GLuint& vertexBuffer,
Video::Geometry::VertexType::StaticVertex * vertices, unsigned int numVerticies) {
vertexBuffer = Video::Geometry::VertexType::StaticVertex::GenerateVertexBuffer(vertices, numVerticies);
}
void Model::GenerateVertexBuffer(GLuint& vertexBuffer,
Video::Geometry::VertexType::SkinVertex * vertices, unsigned int numVerticies) {
vertexBuffer = Video::Geometry::VertexType::SkinVertex::GenerateVertexBuffer(vertices, numVerticies);
}
void Model::GenerateStaticVertexArray(const GLuint vertexBuffer, const GLuint indexBuffer, GLuint& vertexArray) {
vertexArray = Video::Geometry::VertexType::StaticVertex::GenerateVertexArray(vertexBuffer, indexBuffer);
}
void Model::GenerateSkinVertexArray(const GLuint vertexBuffer, const GLuint indexBuffer, GLuint& vertexArray) {
vertexArray = Video::Geometry::VertexType::SkinVertex::GenerateVertexArray(vertexBuffer, indexBuffer);
}
| 36.932584 | 122 | 0.671129 | [
"geometry",
"model"
] |
043e11e1f7cb59828d981ac3132e3d3d48c5e6e9 | 1,154 | cpp | C++ | PROJECTS/smarthome/setup/agentsFactory/agentsFactory.cpp | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null | PROJECTS/smarthome/setup/agentsFactory/agentsFactory.cpp | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null | PROJECTS/smarthome/setup/agentsFactory/agentsFactory.cpp | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null | #include <agentsFactory.h>
#include <pthread.h>
#include <control.h>
#include <assert.h>
#include <cstdlib>
AgentsFactory_t::AgentsFactory_t(IRegistrar_t* _reg, IPublisher_t* _pub, const string& _soDirPath) //string as SO Dir path
{
string config = _soDirPath + '/' + "config.txt";
m_reader = new TxtReader_t(config.c_str());
m_vec = new vector<IAgent_t*>;
m_soloader = new SoLoader_t(_reg, _pub, _soDirPath);
}
AgentsFactory_t::~AgentsFactory_t()
{
delete m_reader;
delete m_vec;
delete m_soloader;
}
void AgentsFactory_t::BuildAgents()
{
for(;;)
//for(int i=0;i<1;++i)
{
AgentConfig_t config = m_reader->ReadSingleConfigSet();
if(config.GetId() == "0") //eof have been reached
{
return;
}
IAgent_t* pAgent = m_soloader->LoadAgent(config);
assert(pAgent != 0);
this->m_vec->push_back(pAgent);
}
}
void* ActivatorThread(void* ptr)
{
IAgent_t* pagent = (IAgent_t*)ptr;
pagent->Run();
return 0;
}
void AgentsFactory_t::ActivateAgents()
{
size_t size = m_vec->size();
for(size_t j = 0; j < size; ++j)
{
pthread_t activatorthread;
pthread_create(&activatorthread, 0, ActivatorThread, (*m_vec)[j]);
}
}
| 19.559322 | 122 | 0.686308 | [
"vector"
] |
04403e5688fcb9df0fcdf33d053729100d5953f2 | 7,129 | cpp | C++ | PongRoyale/Classes/GameScene.cpp | PongRoyale/GameClient | 942ce859c31e4dc494c564cc2728b70332afe67b | [
"MIT"
] | null | null | null | PongRoyale/Classes/GameScene.cpp | PongRoyale/GameClient | 942ce859c31e4dc494c564cc2728b70332afe67b | [
"MIT"
] | null | null | null | PongRoyale/Classes/GameScene.cpp | PongRoyale/GameClient | 942ce859c31e4dc494c564cc2728b70332afe67b | [
"MIT"
] | 1 | 2020-12-12T02:06:02.000Z | 2020-12-12T02:06:02.000Z | /****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
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 "GameScene.h"
USING_NS_CC;
Scene* GameScene::createScene()
{
Scene* scene = GameScene::createWithPhysics();
scene->getPhysicsWorld()->setGravity(Vec2(0, 0));
auto layer = GameScene::create();
scene->addChild(layer);
return scene;
}
// Print useful error message instead of segfaulting when files are not there.
static void problemLoading(const char* filename)
{
printf("Error while loading: %s\n", filename);
printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in GameScene.cpp\n");
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
//////////////////////////////
// 1. super init first
if ( !Scene::init() )
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// Add your paddle
auto you = createPaddleSprite(
cocos2d::Vec2((origin.x + visibleSize.width) / 2.0, 10));
addChild(you);
auto listener1 = cocos2d::EventListenerTouchOneByOne::create();
listener1->onTouchBegan = [=](Touch* touch, Event* event){
float dx = 75;
if (touch->getLocation().x < visibleSize.width / 2 + origin.x) {
dx = -dx;
}
auto moveBy = MoveBy::create(1, Vec2(dx, 0));
you->runAction(RepeatForever::create(moveBy));
return true; // if you are consuming it
};
// trigger when you let up
listener1->onTouchEnded = [=](Touch* touch, Event* event){
you->stopAllActions();
return true;
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this);
// Add Pong Ball
auto ball = createPongSprite(
cocos2d::Vec2((origin.x + visibleSize.width) / 2.0, visibleSize.height / 2 + origin.y));
addChild(ball);
// Add Top Wall
auto topWall = createWallSprite(
cocos2d::Vec2(origin.x + visibleSize.width / 2.0, visibleSize.height + origin.y),
visibleSize, UP);
addChild(topWall);
// Add Right Wall
auto rightWall = createWallSprite(
cocos2d::Vec2(origin.x + visibleSize.width, visibleSize.height/2.0 + origin.y),
visibleSize, RIGHT);
addChild(rightWall);
// Add Left Wall
auto leftWall = createWallSprite(
cocos2d::Vec2(origin.x, visibleSize.height/2.0 + origin.y),
visibleSize, LEFT);
addChild(leftWall);
// Add Bottom Wall
auto bottomWall = createWallSprite(
cocos2d::Vec2(origin.x + visibleSize.width/2.0, origin.y),
visibleSize, BOTTOM);
addChild(bottomWall);
// adds contact event listener
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onContactBegin, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the scene
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(GameScene::menuCloseCallback, this));
if (closeItem == nullptr ||
closeItem->getContentSize().width <= 0 ||
closeItem->getContentSize().height <= 0)
{
problemLoading("'CloseNormal.png' and 'CloseSelected.png'");
}
else
{
float x = origin.x + visibleSize.width - closeItem->getContentSize().width/2;
float y = origin.y + closeItem->getContentSize().height/2;
closeItem->setPosition(Vec2(x,y));
}
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
return true;
}
bool GameScene::onContactBegin(cocos2d::PhysicsContact &contact)
{
printf("HELLO WOLRD HERE\n");
PhysicsBody* bodyA = contact.getShapeA()->getBody();
PhysicsBody* bodyB = contact.getShapeB()->getBody();
//auto nodeA = contact.getShapeA()->getBody()->getNode();
auto v = bodyA->getVelocity();
// Hit top wall
if (bodyB->getCategoryBitmask() & (1<<3)) {
printf("HIT TOP WALL\n");
//bodyA->setVelocity(cocos2d::Vec2(v.x, -v.y));
auto nodeA = (Sprite *) contact.getShapeA()->getBody()->getNode();
nodeA->removeFromParent();
} else if (bodyB->getCategoryBitmask() & (1<<4))
{ // Hit Left Wall
printf("HIT Left WALL\n");
bodyA->setVelocity(cocos2d::Vec2(-v.x, v.y));
} else if (bodyB->getCategoryBitmask() & (1<<5))
{ // Hit Left Wall
printf("HIT Left WALL\n");
bodyA->setVelocity(cocos2d::Vec2(-v.x, v.y));
} else if (bodyB->getCategoryBitmask() & (1<<6))
{ // Hit Bottom Wall
printf("HIT Bottom WALL\n");
bodyA->setVelocity(cocos2d::Vec2(v.x, -v.y));
} else
{ // Assume its paddle
printf("HIT PADDLE\n");
bodyA->setVelocity(cocos2d::Vec2(v.x, -v.y));
}
return true;
}
void GameScene::menuCloseCallback(Ref* pSender)
{
//Close the cocos2d-x game scene and quit the application
//Director::getInstance()->end();
Director::getInstance()->popScene();
/*To navigate back to native iOS screen(if present) without quitting the application ,do not use Director::getInstance()->end() as given above,instead trigger a custom event created in RootViewController.mm as below*/
//EventCustom customEndEvent("game_scene_close_event");
//_eventDispatcher->dispatchEvent(&customEndEvent);
}
| 32.852535 | 222 | 0.629261 | [
"object"
] |
04432b5a577019c1f0a792a17138ad05cc92e852 | 4,505 | hpp | C++ | inference-engine/src/legacy_api/src/shape_infer/const_infer/ie_pow_const_infer.hpp | anton-potapov/openvino | 84119afe9a8c965e0a0cd920fff53aee67b05108 | [
"Apache-2.0"
] | 1 | 2021-07-30T17:03:50.000Z | 2021-07-30T17:03:50.000Z | inference-engine/src/legacy_api/src/shape_infer/const_infer/ie_pow_const_infer.hpp | anton-potapov/openvino | 84119afe9a8c965e0a0cd920fff53aee67b05108 | [
"Apache-2.0"
] | 4 | 2021-04-01T08:29:48.000Z | 2021-08-30T16:12:52.000Z | inference-engine/src/legacy_api/src/shape_infer/const_infer/ie_pow_const_infer.hpp | anton-potapov/openvino | 84119afe9a8c965e0a0cd920fff53aee67b05108 | [
"Apache-2.0"
] | 3 | 2021-03-09T08:27:29.000Z | 2021-04-07T04:58:54.000Z | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <ie_blob.h>
#include <ie_layers.h>
#include <precision_utils.h>
#include <cmath>
#include <ie_precision.hpp>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "broadcast_offset.hpp"
namespace InferenceEngine {
namespace ShapeInfer {
class PowConstInfer : public ConstInferImpl {
public:
explicit PowConstInfer(const std::string& type): ConstInferImpl(type) {}
struct fp16tofp32 {
inline float operator()(ie_fp16 value) {
return static_cast<float>(PrecisionUtils::f16tof32(value));
}
};
struct fp32tofp16 {
inline ie_fp16 operator()(float value) {
return static_cast<float>(PrecisionUtils::f32tof16(value));
}
};
template <typename dataType>
struct noConversion {
inline dataType operator()(dataType value) {
return value;
}
};
template <typename inDatatype1, typename inDatatype2, typename outDatatype, class ConversionInData1,
class ConversionInData2, class ConversionOutData>
void pow(const std::vector<Blob::CPtr>& inData, const std::map<std::string, std::string>& params,
const std::map<std::string, Blob::Ptr>& blobs, std::vector<Blob::Ptr>& outData) {
auto* firstBlobBuffer = inData[0]->cbuffer().as<inDatatype1*>();
auto* secondBlobBuffer = inData[1]->cbuffer().as<inDatatype2*>();
if (!firstBlobBuffer || !secondBlobBuffer) {
THROW_IE_EXCEPTION << "empty input data";
}
auto outBlob = *outData.begin();
auto* outBuffer = outBlob->buffer().as<outDatatype*>();
if (!outBuffer) THROW_IE_EXCEPTION << "empty output data";
BroadcastOffset outOff(outBlob->getTensorDesc().getDims(), outBlob->getTensorDesc().getDims());
BroadcastOffset inOff1(inData[0]->getTensorDesc().getDims(), outBlob->getTensorDesc().getDims());
BroadcastOffset inOff2(inData[1]->getTensorDesc().getDims(), outBlob->getTensorDesc().getDims());
for (size_t i = 0; i < outBlob->size(); i++) {
SizeVector offsetDims = outOff.offset_dims(i);
outBuffer[outOff.offset(offsetDims)] =
ConversionOutData()(std::pow(ConversionInData1()(firstBlobBuffer[inOff1.offset(offsetDims)]),
ConversionInData2()(secondBlobBuffer[inOff2.offset(offsetDims)])));
}
}
void inferImpl(const std::vector<Blob::CPtr>& inData, const std::map<std::string, std::string>& params,
const std::map<std::string, Blob::Ptr>& blobs, std::vector<Blob::Ptr>& outData) override {
size_t numInputs = inData.size();
if (inData.size() != 2)
THROW_IE_EXCEPTION << "Unsupported number of inputs: " << numInputs << ". 2 inputs is supported";
auto compare =
getPrecisionMask(inData[0]->getTensorDesc().getPrecision(), inData[1]->getTensorDesc().getPrecision(),
outData[0]->getTensorDesc().getPrecision());
switch (compare) {
case getPrecisionMask(Precision::FP32, Precision::FP32, Precision::FP32):
pow<float, float, float, noConversion<float>, noConversion<float>, noConversion<float>>(inData, params,
blobs, outData);
break;
case getPrecisionMask(Precision::I32, Precision::I32, Precision::FP32):
pow<int32_t, int32_t, float, noConversion<int32_t>, noConversion<int32_t>, noConversion<float>>(
inData, params, blobs, outData);
break;
case getPrecisionMask(Precision::FP16, Precision::FP16, Precision::FP16):
pow<ie_fp16, ie_fp16, ie_fp16, noConversion<ie_fp16>, noConversion<ie_fp16>, noConversion<ie_fp16>>(
inData, params, blobs, outData);
break;
case getPrecisionMask(Precision::I32, Precision::I32, Precision::FP16):
pow<int32_t, int32_t, float, noConversion<int32_t>, noConversion<int32_t>, fp32tofp16>(inData, params,
blobs, outData);
break;
default:
THROW_IE_EXCEPTION << "Not supported data type in port 0";
}
}
};
} // namespace ShapeInfer
} // namespace InferenceEngine | 44.166667 | 116 | 0.611543 | [
"vector"
] |
0446a0a1977b06ac3db7c128491257818e121d85 | 9,975 | cpp | C++ | src/mame/drivers/fidel_cc7.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/fidel_cc7.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/fidel_cc7.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:hap
// thanks-to:Berger
/******************************************************************************
Fidelity Chess Challenger 7 (BCC)
------------------------
It was Fidelity's most sold chess computer. The first version was released in
1979, and a newer PCB revision was produced in 1980.
Zilog Z80A, 3.579MHz from XTAL
Z80 IRQ/NMI unused, no timer IC.
This is a cost-reduced design from CC10, no special I/O chips.
Backgammon Challenger (BKC) is the same PCB, with the speaker connection going
to the display panel instead.
CC7 (BCC) was also bootlegged around 1981 by Splice Industria Brasileira,
as "Byte XD-300". Mostek MK3880N-4 @ 4MHz, ROM contents is same as BCC REVB.
RE information from netlist by Berger (1st version PCB)
Memory map:
-----------
0000-0FFF: 4K 2332 ROM CN19103N BCC-REVB (or CN19064N BCC)
2000-2FFF: ROM/RAM bus conflict!
3000-3FFF: 256 bytes RAM (2111 SRAM x2)
4000-FFFF: Z80 A14/A15 not connected
Port map (Write):
---------
D0-D3: digit select and keypad mux
D4: CHECK led
D5: LOSE led
A0-A2: NE591 A0-A2
D7: NE591 D (_C not used)
NE591 Q0-Q6: digit segments A-G
NE591 Q7: buzzer
Port map (Read):
---------
D0-D3: keypad row
******************************************************************************/
#include "emu.h"
#include "cpu/z80/z80.h"
#include "sound/dac.h"
#include "video/pwm.h"
#include "speaker.h"
// internal artwork
#include "fidel_bcc.lh" // clickable
#include "fidel_bkc.lh" // clickable
namespace {
class bcc_state : public driver_device
{
public:
bcc_state(const machine_config &mconfig, device_type type, const char *tag) :
driver_device(mconfig, type, tag),
m_maincpu(*this, "maincpu"),
m_display(*this, "display"),
m_dac(*this, "dac"),
m_inputs(*this, "IN.%u", 0)
{ }
// machine configs
void bcc(machine_config &config);
void bkc(machine_config &config);
protected:
virtual void machine_start() override;
private:
// devices/pointers
required_device<cpu_device> m_maincpu;
required_device<pwm_display_device> m_display;
optional_device<dac_bit_interface> m_dac;
required_ioport_array<4> m_inputs;
// address maps
void main_map(address_map &map);
void main_io(address_map &map);
// I/O handlers
u8 input_r();
void control_w(offs_t offset, u8 data);
u8 m_inp_mux = 0;
u8 m_7seg_data = 0;
};
void bcc_state::machine_start()
{
// register for savestates
save_item(NAME(m_inp_mux));
save_item(NAME(m_7seg_data));
}
/******************************************************************************
I/O
******************************************************************************/
// TTL
void bcc_state::control_w(offs_t offset, u8 data)
{
// a0-a2,d7: digit segment data via NE591
u8 mask = 1 << (offset & 7);
m_7seg_data = (m_7seg_data & ~mask) | ((data & 0x80) ? mask : 0);
// BCC: NE591 Q7 is speaker out
if (m_dac != nullptr)
m_dac->write(BIT(m_7seg_data, 7));
// d0-d3: led select, input mux
// d4,d5: upper leds(direct)
m_display->matrix(data & 0x3f, m_7seg_data);
m_inp_mux = data & 0xf;
}
u8 bcc_state::input_r()
{
u8 data = 0;
// d0-d3: multiplexed inputs
for (int i = 0; i < 4; i++)
if (BIT(m_inp_mux, i))
data |= m_inputs[i]->read();
return data;
}
/******************************************************************************
Address Maps
******************************************************************************/
void bcc_state::main_map(address_map &map)
{
map.unmap_value_high();
map.global_mask(0x3fff);
map(0x0000, 0x0fff).rom();
map(0x3000, 0x30ff).mirror(0x0f00).ram();
}
void bcc_state::main_io(address_map &map)
{
map.global_mask(0x07);
map(0x00, 0x07).rw(FUNC(bcc_state::input_r), FUNC(bcc_state::control_w));
}
/******************************************************************************
Input Ports
******************************************************************************/
static INPUT_PORTS_START( bcc )
PORT_START("IN.0")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("EN") PORT_CODE(KEYCODE_ENTER) PORT_CODE(KEYCODE_ENTER_PAD)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("PV") PORT_CODE(KEYCODE_V)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("D4") PORT_CODE(KEYCODE_4) PORT_CODE(KEYCODE_4_PAD) PORT_CODE(KEYCODE_D)
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("H8") PORT_CODE(KEYCODE_8) PORT_CODE(KEYCODE_8_PAD) PORT_CODE(KEYCODE_H)
PORT_START("IN.1")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("CL") PORT_CODE(KEYCODE_DEL) PORT_CODE(KEYCODE_BACKSPACE)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("PB") PORT_CODE(KEYCODE_O)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("C3") PORT_CODE(KEYCODE_3) PORT_CODE(KEYCODE_3_PAD) PORT_CODE(KEYCODE_C)
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("G7") PORT_CODE(KEYCODE_7) PORT_CODE(KEYCODE_7_PAD) PORT_CODE(KEYCODE_G)
PORT_START("IN.2")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("CB") PORT_CODE(KEYCODE_SPACE)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("DM") PORT_CODE(KEYCODE_M)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("B2") PORT_CODE(KEYCODE_2) PORT_CODE(KEYCODE_2_PAD) PORT_CODE(KEYCODE_B)
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("F6") PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_6_PAD) PORT_CODE(KEYCODE_F)
PORT_START("IN.3")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("RE") PORT_CODE(KEYCODE_R)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("LV") PORT_CODE(KEYCODE_L)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("A1") PORT_CODE(KEYCODE_1) PORT_CODE(KEYCODE_1_PAD) PORT_CODE(KEYCODE_A)
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("E5") PORT_CODE(KEYCODE_5) PORT_CODE(KEYCODE_5_PAD) PORT_CODE(KEYCODE_E)
INPUT_PORTS_END
static INPUT_PORTS_START( bkc )
PORT_START("IN.0")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("EN") PORT_CODE(KEYCODE_ENTER) PORT_CODE(KEYCODE_ENTER_PAD)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("9") PORT_CODE(KEYCODE_9) PORT_CODE(KEYCODE_9_PAD)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("6") PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_6_PAD)
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("3") PORT_CODE(KEYCODE_3) PORT_CODE(KEYCODE_3_PAD)
PORT_START("IN.1")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("CL") PORT_CODE(KEYCODE_DEL) PORT_CODE(KEYCODE_BACKSPACE)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("8") PORT_CODE(KEYCODE_8) PORT_CODE(KEYCODE_8_PAD)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("5") PORT_CODE(KEYCODE_5) PORT_CODE(KEYCODE_5_PAD)
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("2") PORT_CODE(KEYCODE_2) PORT_CODE(KEYCODE_2_PAD)
PORT_START("IN.2")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("GM") PORT_CODE(KEYCODE_SPACE)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("7") PORT_CODE(KEYCODE_7) PORT_CODE(KEYCODE_7_PAD)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("4") PORT_CODE(KEYCODE_4) PORT_CODE(KEYCODE_4_PAD)
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("1") PORT_CODE(KEYCODE_1) PORT_CODE(KEYCODE_1_PAD)
PORT_START("IN.3")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("RE") PORT_CODE(KEYCODE_R)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("PB") PORT_CODE(KEYCODE_O)
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("PV") PORT_CODE(KEYCODE_V)
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_NAME("0") PORT_CODE(KEYCODE_0) PORT_CODE(KEYCODE_0_PAD)
INPUT_PORTS_END
/******************************************************************************
Machine Configs
******************************************************************************/
void bcc_state::bkc(machine_config &config)
{
/* basic machine hardware */
Z80(config, m_maincpu, 3.579545_MHz_XTAL);
m_maincpu->set_addrmap(AS_PROGRAM, &bcc_state::main_map);
m_maincpu->set_addrmap(AS_IO, &bcc_state::main_io);
/* video hardware */
PWM_DISPLAY(config, m_display).set_size(6, 8);
m_display->set_segmask(0xf, 0x7f);
config.set_default_layout(layout_fidel_bkc);
}
void bcc_state::bcc(machine_config &config)
{
bkc(config);
config.set_default_layout(layout_fidel_bcc);
/* sound hardware */
SPEAKER(config, "speaker").front_center();
DAC_1BIT(config, m_dac).add_route(ALL_OUTPUTS, "speaker", 0.25);
}
/******************************************************************************
ROM Definitions
******************************************************************************/
ROM_START( cc7 ) // PCB label 510-380
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "101-32016", 0x0000, 0x1000, CRC(b9076c52) SHA1(09b17ac6cd6a1c5c62aea3649f3367bcf4405598) ) // 2332
ROM_END
ROM_START( cc7a )
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "cn19103n_bcc-revb", 0x0000, 0x1000, CRC(a397d471) SHA1(9b12bc442fccee40f4d8500c792bc9d886c5e1a5) ) // 2332
ROM_END
ROM_START( backgamc ) // model BKC, PCB label P-380A-5
ROM_REGION( 0x10000, "maincpu", 0 )
ROM_LOAD( "cn19255n_101-32012", 0x0000, 0x1000, CRC(0a8a19b7) SHA1(d6f0dd44b33c9b79570cf0ceac02a036ec91ba57) ) // 2332
ROM_END
} // anonymous namespace
/******************************************************************************
Drivers
******************************************************************************/
// YEAR NAME PARENT CMP MACHINE INPUT STATE INIT COMPANY, FULLNAME, FLAGS
CONS( 1980, cc7, 0, 0, bcc, bcc, bcc_state, empty_init, "Fidelity Electronics", "Chess Challenger \"7\" (set 1)", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
CONS( 1979, cc7a, cc7, 0, bcc, bcc, bcc_state, empty_init, "Fidelity Electronics", "Chess Challenger \"7\" (set 2)", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
CONS( 1979, backgamc, 0, 0, bkc, bkc, bcc_state, empty_init, "Fidelity Electronics", "Backgammon Challenger", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK | MACHINE_NO_SOUND_HW )
| 35.498221 | 194 | 0.666165 | [
"model"
] |
04502bb55dbe198f89a763b043cf9d9230b82e78 | 1,214 | hpp | C++ | include/eve/function/comparison.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | include/eve/function/comparison.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | include/eve/function/comparison.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#pragma once
// helper file to include all comparison functions and operators
#include <eve/function/is_equal.hpp>
#include <eve/function/is_less.hpp>
#include <eve/function/is_greater.hpp>
#include <eve/function/is_greater_equal.hpp>
#include <eve/function/is_less_equal.hpp>
#include <eve/function/is_lessgreater.hpp>
#include <eve/function/is_not_equal.hpp>
#include <eve/function/is_not_greater_equal.hpp>
#include <eve/function/is_not_greater.hpp>
#include <eve/function/is_not_less.hpp>
#include <eve/function/is_not_less_equal.hpp>
#include <eve/function/is_eqz.hpp>
#include <eve/function/is_nez.hpp>
#include <eve/function/is_ltz.hpp>
#include <eve/function/is_gtz.hpp>
#include <eve/function/is_gez.hpp>
#include <eve/function/is_lez.hpp>
#include <eve/function/is_nltz.hpp>
#include <eve/function/is_ngtz.hpp>
#include <eve/function/is_ngez.hpp>
#include <eve/function/is_nlez.hpp>
| 37.9375 | 100 | 0.654036 | [
"vector"
] |
0450897a241fdb8f62ea50a14b29543c0a4ef3fb | 649 | cpp | C++ | 88.Merge Sorted Array/test.cpp | ReZeroS/LeetCode | 807ae800437e0b6224bd4672f28007388625437b | [
"MIT"
] | 2 | 2018-10-24T03:34:44.000Z | 2020-07-16T15:34:44.000Z | 88.Merge Sorted Array/test.cpp | ReZeroS/LeetCode | 807ae800437e0b6224bd4672f28007388625437b | [
"MIT"
] | null | null | null | 88.Merge Sorted Array/test.cpp | ReZeroS/LeetCode | 807ae800437e0b6224bd4672f28007388625437b | [
"MIT"
] | null | null | null | class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int point = m + n - 1;
int index1 = m - 1;
int index2 = n - 1;
for(int i = point; i >= 0; --i){
if(index2 < 0){
nums1[i] = nums1[index1--];
continue;
}
if(index1 < 0){
nums1[i] = nums2[index2--];
continue;
}
if(nums1[index1] > nums2[index2]){
nums1[i] = nums1[index1--];
}
else {
nums1[i] = nums2[index2--];
}
}
}
};
| 25.96 | 70 | 0.372881 | [
"vector"
] |
0450aa1fdf994f9d6c28086c6d5fdd68dd9fc36b | 3,416 | hpp | C++ | networkit/cpp/centrality/GroupClosenessGrowShrinkImpl.hpp | muik/networkit | d263481a153279d2bf1d5a8433783f00713abcde | [
"MIT"
] | null | null | null | networkit/cpp/centrality/GroupClosenessGrowShrinkImpl.hpp | muik/networkit | d263481a153279d2bf1d5a8433783f00713abcde | [
"MIT"
] | null | null | null | networkit/cpp/centrality/GroupClosenessGrowShrinkImpl.hpp | muik/networkit | d263481a153279d2bf1d5a8433783f00713abcde | [
"MIT"
] | null | null | null | /*
* GroupClosenessGrowShrinkImpl.hpp
*
* Created on: 19.12.2019
* Author: Eugenio Angriman <angrimae@hu-berlin.de>
*/
#ifndef NETWORKIT_CENTRALITY_GROUP_CLOSENESS_GROW_SHRINK_IMPL_HPP_
#define NETWORKIT_CENTRALITY_GROUP_CLOSENESS_GROW_SHRINK_IMPL_HPP_
#ifdef __AVX2__
#include <immintrin.h>
#include <networkit/auxiliary/AlignedAllocator.hpp>
#endif // __AVX2__
#include <cmath>
#include <functional>
#include <limits>
#include <queue>
#include <random>
#include <unordered_map>
#include <vector>
#include <networkit/distance/Diameter.hpp>
#include <networkit/graph/Graph.hpp>
#include <tlx/container/d_ary_addressable_int_heap.hpp>
namespace NetworKit {
namespace GroupClosenessGrowShrinkDetails {
template <typename WeightType>
class GroupClosenessGrowShrinkImpl final {
static constexpr WeightType infdistance = std::numeric_limits<WeightType>::max();
// Number of packed repetitions done at once to estimate the DAG size
static constexpr count K = 16;
static constexpr float maxInt16 = static_cast<float>(std::numeric_limits<uint16_t>::max());
public:
GroupClosenessGrowShrinkImpl(const Graph &G, std::vector<node> group, bool extended = false,
count insertions = 0, count maxIterations = 100);
void run();
std::vector<node> groupMaxCloseness() const;
count numberOfIterations() const;
private:
const Graph *G;
std::vector<node> group;
// Whether or not to use the extended version of the grow-shrink algorithm.
const bool extended;
// Number of consecutive node insertions and removals per iteration.
count insertions;
// Maximum number of iterations allowed.
const count maxIterations;
std::vector<std::reference_wrapper<std::mt19937_64>> urngs;
std::vector<WeightType> distance, distance_;
std::vector<bool> visited;
std::vector<uint32_t> sumOfMins;
std::unordered_map<node, index> idxMap;
std::vector<WeightType> increment;
std::vector<node> nearest, nearest_, stack;
std::queue<index> nextIdx;
count totalSwaps, stackSize;
static count computeConsecutiveInsertions(const Graph &G, size_t groupSize);
void init();
#ifdef __AVX2__
union RandItem {
uint16_t items[K];
__m256i vec;
};
std::vector<RandItem, AlignedAllocator<RandItem, sizeof(RandItem)>> randVec;
#else
std::vector<uint16_t> randVec;
#endif // __AVX2__
std::vector<std::uniform_int_distribution<uint32_t>> intDistributions;
void initRandomVec();
struct CompareDistance {
CompareDistance(const std::vector<WeightType> &distance) : distance(&distance) {}
bool operator()(const node x, const node y) const noexcept {
return (*distance)[x] < (*distance)[y];
}
private:
const std::vector<WeightType> *distance;
};
tlx::d_ary_addressable_int_heap<node, 2, CompareDistance> heap;
tlx::d_ary_addressable_int_heap<node, 2, CompareDistance> heap_;
void dijkstra();
bool findAndSwap();
void bfsFromGroup();
void computeFarnessIncrement();
// Computes real decrement of farness
WeightType computeFarnessDecrement(node v);
node estimateHighestDecrement();
node extractQueueTop(std::queue<node> &q);
};
} // namespace GroupClosenessGrowShrinkDetails
} // namespace NetworKit
#endif // NETWORKIT_CENTRALITY_GROUP_CLOSENESS_GROW_SHRINK_IMPL_HPP_
| 29.448276 | 96 | 0.721019 | [
"vector"
] |
045306e577f10227a264c99b91de28e17d9491ca | 6,750 | cpp | C++ | QuantExt/qle/termstructures/crossccyfixfloatmtmresetswaphelper.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 335 | 2016-10-07T16:31:10.000Z | 2022-03-02T07:12:03.000Z | QuantExt/qle/termstructures/crossccyfixfloatmtmresetswaphelper.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 59 | 2016-10-31T04:20:24.000Z | 2022-01-03T16:39:57.000Z | QuantExt/qle/termstructures/crossccyfixfloatmtmresetswaphelper.cpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 180 | 2016-10-08T14:23:50.000Z | 2022-03-28T10:43:05.000Z | /*
Copyright (C) 2021 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <qle/pricingengines/crossccyswapengine.hpp>
#ifdef QL_USE_INDEXED_COUPON
#include <ql/cashflows/floatingratecoupon.hpp>
#endif
#include <qle/termstructures/crossccyfixfloatmtmresetswaphelper.hpp>
#include <boost/make_shared.hpp>
namespace QuantExt {
namespace {
void no_deletion(YieldTermStructure*) {}
} // namespace
CrossCcyFixFloatMtMResetSwapHelper::CrossCcyFixFloatMtMResetSwapHelper(
const Handle<Quote>& rate, const Handle<Quote>& spotFx, Natural settlementDays, const Calendar& paymentCalendar,
BusinessDayConvention paymentConvention, const Period& tenor, const Currency& fixedCurrency,
Frequency fixedFrequency, BusinessDayConvention fixedConvention, const DayCounter& fixedDayCount,
const boost::shared_ptr<IborIndex>& index, const Handle<YieldTermStructure>& floatDiscount,
const Handle<Quote>& spread, bool endOfMonth, bool resetsOnFloatLeg)
: RelativeDateRateHelper(rate), spotFx_(spotFx), settlementDays_(settlementDays), paymentCalendar_(paymentCalendar),
paymentConvention_(paymentConvention), tenor_(tenor), fixedCurrency_(fixedCurrency),
fixedFrequency_(fixedFrequency), fixedConvention_(fixedConvention), fixedDayCount_(fixedDayCount), index_(index),
floatDiscount_(floatDiscount), spread_(spread), endOfMonth_(endOfMonth), resetsOnFloatLeg_(resetsOnFloatLeg){
QL_REQUIRE(!spotFx_.empty(), "Spot FX quote cannot be empty.");
QL_REQUIRE(fixedCurrency_ != index_->currency(), "Fixed currency should not equal float leg currency.");
registerWith(spotFx_);
registerWith(index_);
registerWith(floatDiscount_);
registerWith(spread_);
initializeDates();
}
void CrossCcyFixFloatMtMResetSwapHelper::initializeDates() {
// Swap start and end
Date referenceDate = evaluationDate_ = Settings::instance().evaluationDate();
referenceDate = paymentCalendar_.adjust(referenceDate);
Date start = paymentCalendar_.advance(referenceDate, settlementDays_ * Days);
Date end = start + tenor_;
// Fixed schedule
Schedule fixedSchedule(start, end, Period(fixedFrequency_), paymentCalendar_, fixedConvention_, fixedConvention_,
DateGeneration::Backward, endOfMonth_);
// Float schedule
Schedule floatSchedule(start, end, index_->tenor(), paymentCalendar_, paymentConvention_, paymentConvention_,
DateGeneration::Backward, endOfMonth_);
Real nominal = 1.0;
// build an FX index for forward rate projection (TODO - review settlement and calendar)
Natural paymentLag = 0;
Spread floatSpread = spread_.empty() ? 0.0 : spread_->value();
boost::shared_ptr<FxIndex> fxIdx;
if (resetsOnFloatLeg_) {
fxIdx = boost::make_shared<FxIndex>("dummy", settlementDays_, fixedCurrency_, index_->currency(), paymentCalendar_,
spotFx_, termStructureHandle_, floatDiscount_);
} else {
fxIdx = boost::make_shared<FxIndex>("dummy", settlementDays_, index_->currency(), fixedCurrency_, paymentCalendar_,
spotFx_, floatDiscount_, termStructureHandle_);
}
swap_ = boost::make_shared<CrossCcyFixFloatMtMResetSwap>(nominal, fixedCurrency_, fixedSchedule, 0.0, fixedDayCount_, paymentConvention_,
paymentLag, paymentCalendar_, index_->currency(), floatSchedule, index_, floatSpread, paymentConvention_,
paymentLag, paymentCalendar_, fxIdx, resetsOnFloatLeg_);
// Attach engine
boost::shared_ptr<PricingEngine> engine = boost::make_shared<CrossCcySwapEngine>(
fixedCurrency_, termStructureHandle_, index_->currency(), floatDiscount_, spotFx_);
swap_->setPricingEngine(engine);
earliestDate_ = swap_->startDate();
latestDate_ = swap_->maturityDate();
/* May need to adjust latestDate_ if you are projecting libor based
on tenor length rather than from accrual date to accrual date. */
#ifdef QL_USE_INDEXED_COUPON
Size numCashflows = swap_->leg(1).size();
Date endDate = latestDate_;
if (numCashflows > 0) {
for (Size i = numCashflows - 1; i >= 0; i--) {
boost::shared_ptr<FloatingRateCoupon> lastFloating =
boost::dynamic_pointer_cast<FloatingRateCoupon>(swap_->leg(1)[i]);
if (!lastFloating)
continue;
else {
Date fixingValueDate = domesticCcyIndex_->valueDate(lastFloating->fixingDate());
endDate = domesticCcyIndex_->maturityDate(fixingValueDate);
Date endValueDate = domesticCcyIndex_->maturityDate(fixingValueDate);
latestDate_ = std::max(latestDate_, endValueDate);
break;
}
}
}
#endif
}
void CrossCcyFixFloatMtMResetSwapHelper::setTermStructure(YieldTermStructure* t) {
boost::shared_ptr<YieldTermStructure> temp(t, no_deletion);
termStructureHandle_.linkTo(temp, false);
RelativeDateRateHelper::setTermStructure(t);
}
void CrossCcyFixFloatMtMResetSwapHelper::update() {
// Maybe FX spot quote or spread quote changed
if (!close(spotFx_->value(), swap_->nominal()) ||
(!spread_.empty() && !close(spread_->value(), swap_->floatSpread()))) {
initializeDates();
}
// Maybe evaluation date changed. RelativeDateRateHelper will take care of this
// Note: if initializeDates() was called in above if statement, it will not be called
// again in RelativeDateRateHelper::update() because evaluationDate_ is set in
// initializeDates(). So, redundant instrument builds are avoided.
RelativeDateRateHelper::update();
}
Real CrossCcyFixFloatMtMResetSwapHelper::impliedQuote() const {
QL_REQUIRE(termStructure_, "Term structure needs to be set");
swap_->recalculate();
return swap_->fairFixedRate();
}
void CrossCcyFixFloatMtMResetSwapHelper::accept(AcyclicVisitor& v) {
Visitor<CrossCcyFixFloatMtMResetSwapHelper>* v1 = dynamic_cast<Visitor<CrossCcyFixFloatMtMResetSwapHelper>*>(&v);
if (v1)
v1->visit(*this);
else
RateHelper::accept(v);
}
} // namespace QuantExt
| 44.117647 | 141 | 0.734815 | [
"model"
] |
04550ae4ae791030a1dda980b2f01b0c66b29953 | 1,166 | cpp | C++ | Dynamic Programming/palindrome-partitioning-ii.cpp | atitoa93/interviewbit-solutions | 9723c9cb767119bf5751e465548de4046b5a3d33 | [
"MIT"
] | null | null | null | Dynamic Programming/palindrome-partitioning-ii.cpp | atitoa93/interviewbit-solutions | 9723c9cb767119bf5751e465548de4046b5a3d33 | [
"MIT"
] | null | null | null | Dynamic Programming/palindrome-partitioning-ii.cpp | atitoa93/interviewbit-solutions | 9723c9cb767119bf5751e465548de4046b5a3d33 | [
"MIT"
] | null | null | null | // https://www.interviewbit.com/problems/palindrome-partitioning-ii/
int bt(vector <int> &dp, vector <vector <int> > &p, string &s, int idx) {
if (idx == s.size()) return 0;
int &ret = dp[idx];
if (~ret) return ret;
ret = s.size();
for (int i = idx; i < s.size(); ++i) {
if (p[idx][i]) {
ret = min(ret, bt(dp, p, s, i + 1) + 1);
}
}
return ret;
}
int solve(vector <int> &dp, vector <vector <int> > &p, string &s) {
int n = s.size();
for (int i = 0; i < n; ++i) {
if (p[0][i]) dp[i] = 0;
else {
dp[i] = i;
for (int j = 1; j <= i; ++j) {
if (p[j][i]) {
dp[i] = min(dp[i], dp[j - 1] + 1);
}
}
}
}
return dp[n - 1];
}
int Solution::minCut(string A) {
int n = A.size();
vector <int> dp(n, -1);
vector <vector <int> > p(n, vector <int> (n));
for (int i = 0; i < n; ++i) {
int l = i, r = i;
while (l >= 0 && r < n && A[l] == A[r])
p[l--][r++] = 1;
l = i, r = i + 1;
while (l >= 0 && r < n && A[l] == A[r])
p[l--][r++] = 1;
}
// building table
return solve(dp, p, A);
// recursive
// return bt(dp, p, A, 0) - 1;
}
| 20.821429 | 73 | 0.429674 | [
"vector"
] |
0455c14b6cbd78c30c00e541f770d2e598873931 | 1,198 | cpp | C++ | leetcode.com/Weekly Contest 253/4/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2020-08-20T11:02:49.000Z | 2020-08-20T11:02:49.000Z | leetcode.com/Weekly Contest 253/4/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | null | null | null | leetcode.com/Weekly Contest 253/4/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2022-01-01T23:23:13.000Z | 2022-01-01T23:23:13.000Z | #include <bits/stdc++.h>
using namespace std;
int __fastio = []() { ios_base::sync_with_stdio(false); cout << fixed << setprecision(10); cin.tie(nullptr); return 0; } ();
class Solution {
public:
vector<int> longestObstacleCourseAtEachPosition(vector<int>& A) {
int n = A.size();
vector<int> res(n);
vector<int> S;
int m = 0;
auto chk = [&](int x) {
if (m && S[m-1] <= x) return m;
int l = 0, r = m - 1;
while (l < r) {
// x = 3
// 1 1 2 2 3 3 (4) 4
// 1 1 2 2 3 3 3 4
// x = 5
// 1 1 2 2 3 3 3 4 5
// find first S[i] > x
int m = (l + r) >> 1;
if (S[m] > x) {
r = m;
} else {
l = m + 1;
}
}
return l;
};
int j = 0;
for (int x: A) {
int i = chk(x);
if (i == m) {
++m;
S.push_back(x);
} else {
S[i] = x;
}
res[j++] = i + 1;
}
return res;
}
};
| 26.622222 | 124 | 0.328047 | [
"vector"
] |
0456061fb632f388401bf0a9b12457984a80f412 | 13,596 | cpp | C++ | source/common/rendering/vulkan/shaders/vk_shader.cpp | madame-rachelle/Raze | 67c8187d620e6cf9e99543cab5c5746dd31007af | [
"RSA-MD"
] | null | null | null | source/common/rendering/vulkan/shaders/vk_shader.cpp | madame-rachelle/Raze | 67c8187d620e6cf9e99543cab5c5746dd31007af | [
"RSA-MD"
] | null | null | null | source/common/rendering/vulkan/shaders/vk_shader.cpp | madame-rachelle/Raze | 67c8187d620e6cf9e99543cab5c5746dd31007af | [
"RSA-MD"
] | null | null | null | /*
** Vulkan backend
** Copyright (c) 2016-2020 Magnus Norddahl
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
*/
#include "vk_shader.h"
#include "vulkan/system/vk_builders.h"
#include "hw_shaderpatcher.h"
#include "filesystem.h"
#include "engineerrors.h"
#include "version.h"
#include <ShaderLang.h>
VkShaderManager::VkShaderManager(VulkanDevice *device) : device(device)
{
ShInitialize();
const char *mainvp = "shaders/glsl/main.vp";
const char *mainfp = "shaders/glsl/main.fp";
for (int j = 0; j < MAX_PASS_TYPES; j++)
{
bool gbufferpass = j;
for (int i = 0; defaultshaders[i].ShaderName != nullptr; i++)
{
VkShaderProgram prog;
prog.vert = LoadVertShader(defaultshaders[i].ShaderName, mainvp, defaultshaders[i].Defines);
prog.frag = LoadFragShader(defaultshaders[i].ShaderName, mainfp, defaultshaders[i].gettexelfunc, defaultshaders[i].lightfunc, defaultshaders[i].Defines, true, gbufferpass);
mMaterialShaders[j].push_back(std::move(prog));
if (i < SHADER_NoTexture)
{
VkShaderProgram natprog;
natprog.vert = LoadVertShader(defaultshaders[i].ShaderName, mainvp, defaultshaders[i].Defines);
natprog.frag = LoadFragShader(defaultshaders[i].ShaderName, mainfp, defaultshaders[i].gettexelfunc, defaultshaders[i].lightfunc, defaultshaders[i].Defines, false, gbufferpass);
mMaterialShadersNAT[j].push_back(std::move(natprog));
}
}
for (unsigned i = 0; i < usershaders.Size(); i++)
{
FString name = ExtractFileBase(usershaders[i].shader);
FString defines = defaultshaders[usershaders[i].shaderType].Defines + usershaders[i].defines;
VkShaderProgram prog;
prog.vert = LoadVertShader(name, mainvp, defines);
prog.frag = LoadFragShader(name, mainfp, usershaders[i].shader, defaultshaders[usershaders[i].shaderType].lightfunc, defines, true, gbufferpass);
mMaterialShaders[j].push_back(std::move(prog));
}
for (int i = 0; i < MAX_EFFECTS; i++)
{
VkShaderProgram prog;
prog.vert = LoadVertShader(effectshaders[i].ShaderName, effectshaders[i].vp, effectshaders[i].defines);
prog.frag = LoadFragShader(effectshaders[i].ShaderName, effectshaders[i].fp1, effectshaders[i].fp2, effectshaders[i].fp3, effectshaders[i].defines, true, gbufferpass);
mEffectShaders[j].push_back(std::move(prog));
}
}
}
VkShaderManager::~VkShaderManager()
{
ShFinalize();
}
VkShaderProgram *VkShaderManager::GetEffect(int effect, EPassType passType)
{
if (effect >= 0 && effect < MAX_EFFECTS && mEffectShaders[passType][effect].frag)
{
return &mEffectShaders[passType][effect];
}
return nullptr;
}
VkShaderProgram *VkShaderManager::Get(unsigned int eff, bool alphateston, EPassType passType)
{
// indices 0-2 match the warping modes, 3 no texture, the following are custom
if (!alphateston && eff <= 2)
{
return &mMaterialShadersNAT[passType][eff]; // Non-alphatest shaders are only created for default, warp1+2. The rest won't get used anyway
}
else if (eff < (unsigned int)mMaterialShaders[passType].size())
{
return &mMaterialShaders[passType][eff];
}
return nullptr;
}
static const char *shaderBindings = R"(
// This must match the HWViewpointUniforms struct
layout(set = 0, binding = 0, std140) uniform ViewpointUBO {
mat4 ProjectionMatrix;
mat4 ViewMatrix;
mat4 NormalViewMatrix;
vec4 uCameraPos;
vec4 uClipLine;
float uGlobVis; // uGlobVis = R_GetGlobVis(r_visibility) / 32.0
int uPalLightLevels;
int uViewHeight; // Software fuzz scaling
float uClipHeight;
float uClipHeightDirection;
int uShadowmapFilter;
};
// light buffers
layout(set = 0, binding = 1, std430) buffer LightBufferSSO
{
vec4 lights[];
};
layout(set = 0, binding = 2, std140) uniform MatricesUBO {
mat4 ModelMatrix;
mat4 NormalModelMatrix;
mat4 TextureMatrix;
};
struct StreamData
{
vec4 uObjectColor;
vec4 uObjectColor2;
vec4 uDynLightColor;
vec4 uAddColor;
vec4 uTextureAddColor;
vec4 uTextureModulateColor;
vec4 uTextureBlendColor;
vec4 uFogColor;
float uDesaturationFactor;
float uInterpolationFactor;
float timer; // timer data for material shaders
int useVertexData;
vec4 uVertexColor;
vec4 uVertexNormal;
vec4 uGlowTopPlane;
vec4 uGlowTopColor;
vec4 uGlowBottomPlane;
vec4 uGlowBottomColor;
vec4 uGradientTopPlane;
vec4 uGradientBottomPlane;
vec4 uSplitTopPlane;
vec4 uSplitBottomPlane;
vec4 uDetailParms;
#ifdef NPOT_EMULATION
vec2 uNpotEmulation;
#endif
};
layout(set = 0, binding = 3, std140) uniform StreamUBO {
StreamData data[MAX_STREAM_DATA];
};
layout(set = 0, binding = 4) uniform sampler2D ShadowMap;
// textures
layout(set = 1, binding = 0) uniform sampler2D tex;
layout(set = 1, binding = 1) uniform sampler2D texture2;
layout(set = 1, binding = 2) uniform sampler2D texture3;
layout(set = 1, binding = 3) uniform sampler2D texture4;
layout(set = 1, binding = 4) uniform sampler2D texture5;
layout(set = 1, binding = 5) uniform sampler2D texture6;
layout(set = 1, binding = 6) uniform sampler2D texture7;
layout(set = 1, binding = 7) uniform sampler2D texture8;
layout(set = 1, binding = 8) uniform sampler2D texture9;
layout(set = 1, binding = 9) uniform sampler2D texture10;
layout(set = 1, binding = 10) uniform sampler2D texture11;
// This must match the PushConstants struct
layout(push_constant) uniform PushConstants
{
int uTextureMode;
float uAlphaThreshold;
vec2 uClipSplit;
// Lighting + Fog
float uLightLevel;
float uFogDensity;
float uLightFactor;
float uLightDist;
int uFogEnabled;
// dynamic lights
int uLightIndex;
// Blinn glossiness and specular level
vec2 uSpecularMaterial;
int uDataIndex;
int padding1, padding2, padding3;
};
// material types
#if defined(SPECULAR)
#define normaltexture texture2
#define speculartexture texture3
#define brighttexture texture4
#define detailtexture texture5
#define glowtexture texture6
#elif defined(PBR)
#define normaltexture texture2
#define metallictexture texture3
#define roughnesstexture texture4
#define aotexture texture5
#define brighttexture texture6
#define detailtexture texture7
#define glowtexture texture8
#else
#define brighttexture texture2
#define detailtexture texture3
#define glowtexture texture4
#endif
#define uObjectColor data[uDataIndex].uObjectColor
#define uObjectColor2 data[uDataIndex].uObjectColor2
#define uDynLightColor data[uDataIndex].uDynLightColor
#define uAddColor data[uDataIndex].uAddColor
#define uTextureBlendColor data[uDataIndex].uTextureBlendColor
#define uTextureModulateColor data[uDataIndex].uTextureModulateColor
#define uTextureAddColor data[uDataIndex].uTextureAddColor
#define uFogColor data[uDataIndex].uFogColor
#define uDesaturationFactor data[uDataIndex].uDesaturationFactor
#define uInterpolationFactor data[uDataIndex].uInterpolationFactor
#define timer data[uDataIndex].timer
#define useVertexData data[uDataIndex].useVertexData
#define uVertexColor data[uDataIndex].uVertexColor
#define uVertexNormal data[uDataIndex].uVertexNormal
#define uGlowTopPlane data[uDataIndex].uGlowTopPlane
#define uGlowTopColor data[uDataIndex].uGlowTopColor
#define uGlowBottomPlane data[uDataIndex].uGlowBottomPlane
#define uGlowBottomColor data[uDataIndex].uGlowBottomColor
#define uGradientTopPlane data[uDataIndex].uGradientTopPlane
#define uGradientBottomPlane data[uDataIndex].uGradientBottomPlane
#define uSplitTopPlane data[uDataIndex].uSplitTopPlane
#define uSplitBottomPlane data[uDataIndex].uSplitBottomPlane
#define uDetailParms data[uDataIndex].uDetailParms
#define uNpotEmulation data[uDataIndex].uNpotEmulation
#define SUPPORTS_SHADOWMAPS
#define VULKAN_COORDINATE_SYSTEM
#define HAS_UNIFORM_VERTEX_DATA
// GLSL spec 4.60, 8.15. Noise Functions
// https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf
// "The noise functions noise1, noise2, noise3, and noise4 have been deprecated starting with version 4.4 of GLSL.
// When not generating SPIR-V they are defined to return the value 0.0 or a vector whose components are all 0.0.
// When generating SPIR-V the noise functions are not declared and may not be used."
// However, we need to support mods with custom shaders created for OpenGL renderer
float noise1(float) { return 0; }
vec2 noise2(vec2) { return vec2(0); }
vec3 noise3(vec3) { return vec3(0); }
vec4 noise4(vec4) { return vec4(0); }
)";
std::unique_ptr<VulkanShader> VkShaderManager::LoadVertShader(FString shadername, const char *vert_lump, const char *defines)
{
FString code = GetTargetGlslVersion();
code << defines;
code << "\n#define MAX_STREAM_DATA " << std::to_string(MAX_STREAM_DATA).c_str() << "\n";
#ifdef NPOT_EMULATION
code << "#define NPOT_EMULATION\n";
#endif
code << shaderBindings;
if (!device->UsedDeviceFeatures.shaderClipDistance) code << "#define NO_CLIPDISTANCE_SUPPORT\n";
code << "#line 1\n";
code << LoadPrivateShaderLump(vert_lump).GetChars() << "\n";
ShaderBuilder builder;
builder.setVertexShader(code);
return builder.create(shadername.GetChars(), device);
}
std::unique_ptr<VulkanShader> VkShaderManager::LoadFragShader(FString shadername, const char *frag_lump, const char *material_lump, const char *light_lump, const char *defines, bool alphatest, bool gbufferpass)
{
FString code = GetTargetGlslVersion();
code << defines;
code << "\n$placeholder$"; // here the code can later add more needed #defines.
code << "\n#define MAX_STREAM_DATA " << std::to_string(MAX_STREAM_DATA).c_str() << "\n";
code << shaderBindings;
FString placeholder = "\n";
if (!device->UsedDeviceFeatures.shaderClipDistance) code << "#define NO_CLIPDISTANCE_SUPPORT\n";
if (!alphatest) code << "#define NO_ALPHATEST\n";
if (gbufferpass) code << "#define GBUFFER_PASS\n";
code << "\n#line 1\n";
code << LoadPrivateShaderLump(frag_lump).GetChars() << "\n";
if (material_lump)
{
if (material_lump[0] != '#')
{
FString pp_code = LoadPublicShaderLump(material_lump);
if (pp_code.IndexOf("ProcessMaterial") < 0 && pp_code.IndexOf("SetupMaterial") < 0)
{
// this looks like an old custom hardware shader.
// add ProcessMaterial function that calls the older ProcessTexel function
if (pp_code.IndexOf("GetTexCoord") >= 0)
{
code << "\n" << LoadPrivateShaderLump("shaders/glsl/func_defaultmat2.fp").GetChars() << "\n";
}
else
{
code << "\n" << LoadPrivateShaderLump("shaders/glsl/func_defaultmat.fp").GetChars() << "\n";
if (pp_code.IndexOf("ProcessTexel") < 0)
{
// this looks like an even older custom hardware shader.
// We need to replace the ProcessTexel call to make it work.
code.Substitute("material.Base = ProcessTexel();", "material.Base = Process(vec4(1.0));");
}
}
if (pp_code.IndexOf("ProcessLight") >= 0)
{
// The ProcessLight signatured changed. Forward to the old one.
code << "\nvec4 ProcessLight(vec4 color);\n";
code << "\nvec4 ProcessLight(Material material, vec4 color) { return ProcessLight(color); }\n";
}
}
code << "\n#line 1\n";
code << RemoveLegacyUserUniforms(pp_code).GetChars();
code.Substitute("gl_TexCoord[0]", "vTexCoord"); // fix old custom shaders.
if (pp_code.IndexOf("ProcessLight") < 0)
{
code << "\n" << LoadPrivateShaderLump("shaders/glsl/func_defaultlight.fp").GetChars() << "\n";
}
// ProcessMaterial must be considered broken because it requires the user to fill in data they possibly cannot know all about.
if (pp_code.IndexOf("ProcessMaterial") >= 0 && pp_code.IndexOf("SetupMaterial") < 0)
{
// This reactivates the old logic and disables all features that cannot be supported with that method.
placeholder << "#define LEGACY_USER_SHADER\n";
}
}
else
{
// material_lump is not a lump name but the source itself (from generated shaders)
code << (material_lump + 1) << "\n";
}
}
code.Substitute("$placeholder$", placeholder);
if (light_lump)
{
code << "\n#line 1\n";
code << LoadPrivateShaderLump(light_lump).GetChars();
}
ShaderBuilder builder;
builder.setFragmentShader(code);
return builder.create(shadername.GetChars(), device);
}
FString VkShaderManager::GetTargetGlslVersion()
{
return "#version 450 core\n";
}
FString VkShaderManager::LoadPublicShaderLump(const char *lumpname)
{
int lump = fileSystem.CheckNumForFullName(lumpname);
if (lump == -1) I_Error("Unable to load '%s'", lumpname);
FileData data = fileSystem.ReadFile(lump);
return data.GetString();
}
FString VkShaderManager::LoadPrivateShaderLump(const char *lumpname)
{
int lump = fileSystem.CheckNumForFullName(lumpname, 0);
if (lump == -1) I_Error("Unable to load '%s'", lumpname);
FileData data = fileSystem.ReadFile(lump);
return data.GetString();
}
| 33.99 | 210 | 0.737643 | [
"vector"
] |
04590b98fe9ae46cc6c379a78b4db342501f350d | 200 | cpp | C++ | platform/shared/stlport/test/compiler/movable.cpp | mensfeld/rhodes | 2962610a314ed563a0b7c83fcae6136913a1b033 | [
"MIT"
] | 173 | 2015-01-02T11:14:08.000Z | 2022-03-05T09:54:54.000Z | platform/shared/stlport/test/compiler/movable.cpp | sdwood/rhodes | 8228aa40708dcbcc1d3967a479d1d84364022255 | [
"MIT"
] | 263 | 2015-01-05T04:35:22.000Z | 2021-09-07T06:00:02.000Z | platform/shared/stlport/test/compiler/movable.cpp | sdwood/rhodes | 8228aa40708dcbcc1d3967a479d1d84364022255 | [
"MIT"
] | 77 | 2015-01-12T20:57:18.000Z | 2022-02-17T15:15:14.000Z | #include <list>
#include <vector>
#include <string>
using namespace std;
struct S :
public string
{
};
void test()
{
list<S> l;
l.push_back( S() );
vector<S> v;
v.push_back( S() );
}
| 9.52381 | 21 | 0.585 | [
"vector"
] |
045e02b7a22f60f7d72d73f4d22aba7fe677363e | 8,793 | cpp | C++ | src/apps/luageneric/luageneric_test.cpp | ammarheidari/CCF | 296871cf4eb5fe6d81c83ab8c3d12a198bb9ca5d | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-05-11T10:58:13.000Z | 2019-05-11T10:58:13.000Z | src/apps/luageneric/luageneric_test.cpp | ammarheidari/CCF | 296871cf4eb5fe6d81c83ab8c3d12a198bb9ca5d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/apps/luageneric/luageneric_test.cpp | ammarheidari/CCF | 296871cf4eb5fe6d81c83ab8c3d12a198bb9ca5d | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-05-11T10:58:20.000Z | 2019-05-11T10:58:20.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest/doctest.h"
#include "ds/files.h"
#include "ds/logger.h"
#include "enclave/appinterface.h"
#include "genesisgen/genesisgen.h"
#include "luainterp/luainterp.h"
#include "node/rpc/jsonrpc.h"
#include "node/rpc/test/node_stub.h"
#include "runtime_config/default_whitelists.h"
#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace ccfapp;
using namespace ccf;
using namespace std;
using namespace jsonrpc;
using namespace nlohmann;
namespace ccf
{
bool operator==(const MemberInfo& mi0, const MemberInfo& mi1)
{
return mi0.status == mi1.status && mi0.keyshare == mi1.keyshare;
}
}
void check_error(const vector<uint8_t> v, const int expected)
{
const auto j_error = json::from_msgpack(v);
CHECK(j_error[ERR][CODE] == expected);
}
template <typename T>
void check_success(const vector<uint8_t> v, const T& expected)
{
const Response<json> r = json::from_msgpack(v);
CHECK(T(r.result) == expected);
}
void set_whitelists(GenesisGenerator& network)
{
for (const auto& wl : default_whitelists)
network.set_whitelist(wl.first, wl.second);
}
auto init_frontend(
GenesisGenerator& network,
StubNotifier& notifier,
const int n_users,
const int n_members)
{
// create users with fake certs (no crypto here)
for (uint8_t i = 0; i < n_users; i++)
network.add_user({i});
for (uint8_t i = 0; i < n_members; i++)
network.add_member({i});
set_whitelists(network);
const auto env_script = R"xxx(
return {
__environment = [[
env = {
error_codes = {
PARSE_ERROR = -32700,
INVALID_REQUEST = -32600,
METHOD_NOT_FOUND = -32601,
INVALID_PARAMS = -32602,
INTERNAL_ERROR = -32603,
INVALID_CLIENT_SIGNATURE = -32605,
INVALID_CALLER_ID = -32606,
INSUFFICIENT_RIGHTS = -32006,
DENIED = -32007
}
}
function env.jsucc (result)
return {result = result}
end
function env.jerr (code, message)
return {error = {code = code, message = message}}
end
]]})xxx";
network.set_app_scripts(
lua::Interpreter().invoke<nlohmann::json>(env_script));
network.finalize_raw();
return get_rpc_handler(network, notifier);
}
void set_default_handler(GenesisGenerator& network, Script dh)
{
Store::Tx tx;
tx.get_view(network.app_scripts)->put(UserScriptIds::DEFAULT_HANDLER, dh);
REQUIRE(tx.commit() == kv::CommitSuccess::OK);
}
using Params = map<string, json>;
auto make_pc(string method, Params params)
{
return json::to_msgpack(ProcedureCall<Params>{method, 0, params});
}
template <typename F, typename K, typename V>
void check_store_load(F frontend, K k, V v)
{
const Cert u0 = {0};
// store
const auto pc0 = make_pc("store", {{"k", k}, {"v", v}});
check_success(frontend->process(u0, pc0), true);
// load and check that we get the right result
const auto pc1 = make_pc("load", {{"k", k}});
check_success(frontend->process(u0, pc1), v);
}
TEST_CASE("simple lua apps")
{
GenesisGenerator network;
StubNotifier notifier;
// create network with 1 user and 3 active members
auto frontend = init_frontend(network, notifier, 1, 3);
const Cert u0 = {0};
SUBCASE("echo")
{
constexpr auto app = R"xxx(
tables, gov_tables, caller_id, method, params = ...
-- define handlers
handlers = {}
function handlers.echo()
return env.jsucc(params.verb)
end
-- call handler
return handlers[method]()
)xxx";
set_default_handler(network, {app});
// call "echo" function with "hello"
const string verb = "hello";
const auto pc = make_pc("echo", {{"verb", verb}});
check_success(frontend->process(u0, pc), verb);
}
SUBCASE("store/load different types in generic table")
{
constexpr auto app = R"xxx(
tables, gov_tables, caller_id, method, params = ...
handlers = {}
function handlers.store()
local r = tables.priv0:put(params.k, params.v)
return env.jsucc(r)
end
function handlers.load()
local v = tables.priv0:get(params.k)
if not v then
return env.jerr(env.error_codes.INVALID_PARAMS, "key does not exist")
end
return env.jsucc(v)
end
return handlers[method]()
)xxx";
set_default_handler(network, {app});
// (1) store/load vector -> vector
check_store_load(
frontend,
vector<string>{"abc", "ddeeeee"}, // key
vector<int>(100, 99) // value
);
// (2) store/load string -> map
check_store_load(
frontend,
string("abc"), // key
map<string, int>{{"def", 1}, {"ghij", 2}} // value
);
// (3) attempt to read non-existing key (set of integers)
const auto pc = make_pc("load", {{"k", set{5, 6, 7}}});
check_error(frontend->process(u0, pc), ErrorCodes::INVALID_PARAMS);
}
SUBCASE("access gov tables")
{
constexpr auto app = R"xxx(
tables, gov_tables, caller_id, method, params = ...
handlers = {}
-- allowed
function handlers.get_members()
local members = {}
gov_tables.members:foreach(
function(k, v) members[tostring(k)] = v end )
return env.jsucc(members)
end
-- not allowed
function handlers.put_member()
return env.jsucc(gov_tables.members:put(params.k, params.v))
end
return handlers[method]()
)xxx";
set_default_handler(network, {app});
// (1) read out members table
const auto pc = make_pc("get_members", {});
// expect to see 3 members in state active
map<string, MemberInfo> expected = {{"0", {MemberStatus::ACTIVE}},
{"1", {MemberStatus::ACTIVE}},
{"2", {MemberStatus::ACTIVE}}};
check_success(frontend->process(u0, pc), expected);
// (2) try to write to members table
const auto pc1 = make_pc(
"put_member", {{"k", 99}, {"v", MemberInfo{MemberStatus::ACTIVE}}});
check_error(frontend->process(u0, pc1), ErrorCodes::SCRIPT_ERROR);
}
}
TEST_CASE("simple bank")
{
GenesisGenerator network;
StubNotifier notifier;
// create network with 1 user and 3 active members
auto frontend = init_frontend(network, notifier, 1, 3);
const Cert u0 = {0};
constexpr auto app = R"xxx(
tables, gov_tables, caller_id, method, params = ...
handlers = {}
function handlers.SB_create()
local dst = params.dst
if tables.priv0:get(dst) then
return env.jerr(env.error_codes.INVALID_PARAMS, "account already exists")
end
tables.priv0:put(dst, params.amt)
return env.jsucc("OK")
end
function handlers.SB_read()
local acc = params.account
local amt = tables.priv0:get(acc)
if not amt then
return env.jerr(env.error_codes.INVALID_PARAMS, "account " .. acc .. " does not exist")
end
return env.jsucc(amt)
end
function handlers.SB_transfer()
local src = params.src
local dst = params.dst
local src_n = tables.priv0:get(src)
if not src_n then
return env.jerr(env.error_codes.INVALID_PARAMS, "source account does not exist")
end
local dst_n = tables.priv0:get(dst)
if not dst_n then
return env.jerr(env.error_codes.INVALID_PARAMS, "destination account does not exist")
end
local amt = params.amt
if src_n < amt then
return env.jerr(env.error_codes.INVALID_PARAMS, "insufficient funds")
end
tables.priv0:put(src, src_n - amt)
tables.priv0:put(dst, dst_n + amt)
return env.jsucc("OK")
end
return handlers[method]()
)xxx";
set_default_handler(network, {app});
{
const auto pc = make_pc("SB_create", {{"dst", 1}, {"amt", 123}});
check_success<string>(frontend->process(u0, pc), "OK");
const auto pc1 = make_pc("SB_read", {{"account", 1}});
check_success(frontend->process(u0, pc1), 123);
}
{
const auto pc = make_pc("SB_create", {{"dst", 2}, {"amt", 999}});
check_success<string>(frontend->process(u0, pc), "OK");
const auto pc1 = make_pc("SB_read", {{"account", 2}});
check_success(frontend->process(u0, pc1), 999);
}
{
const auto pc = make_pc("SB_read", {{"account", 3}});
check_error(frontend->process(u0, pc), ErrorCodes::INVALID_PARAMS);
}
{
const auto pc =
make_pc("SB_transfer", {{"src", 1}, {"dst", 2}, {"amt", 5}});
check_success<string>(frontend->process(u0, pc), "OK");
const auto pc1 = make_pc("SB_read", {{"account", 1}});
check_success(frontend->process(u0, pc1), 123 - 5);
const auto pc2 = make_pc("SB_read", {{"account", 2}});
check_success(frontend->process(u0, pc2), 999 + 5);
}
} | 26.972393 | 95 | 0.639827 | [
"vector"
] |
046c1b048ef3f772e31ff7bd8f3fffc87b9ef791 | 1,520 | hpp | C++ | src/io/reference/threadsafe_fasta.hpp | roryk/octopus | 0ec2839c33b846107278696ee04ce6d7d0f69a54 | [
"MIT"
] | null | null | null | src/io/reference/threadsafe_fasta.hpp | roryk/octopus | 0ec2839c33b846107278696ee04ce6d7d0f69a54 | [
"MIT"
] | null | null | null | src/io/reference/threadsafe_fasta.hpp | roryk/octopus | 0ec2839c33b846107278696ee04ce6d7d0f69a54 | [
"MIT"
] | null | null | null | // Copyright (c) 2015-2020 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#ifndef threadsafe_fasta_hpp
#define threadsafe_fasta_hpp
#include <string>
#include <vector>
#include <mutex>
#include <memory>
#include <boost/filesystem/path.hpp>
#include "reference_reader.hpp"
#include "fasta.hpp"
namespace octopus {
class GenomicRegion;
namespace io {
class ThreadsafeFasta : public ReferenceReader
{
public:
using Path = Fasta::Path;
using ContigName = ReferenceReader::ContigName;
using GenomicSize = ReferenceReader::GenomicSize;
using GeneticSequence = ReferenceReader::GeneticSequence;
ThreadsafeFasta() = delete;
ThreadsafeFasta(std::unique_ptr<Fasta> fasta);
ThreadsafeFasta(const ThreadsafeFasta&);
ThreadsafeFasta& operator=(ThreadsafeFasta);
ThreadsafeFasta(ThreadsafeFasta&&);
ThreadsafeFasta& operator=(ThreadsafeFasta&&);
private:
std::unique_ptr<Fasta> fasta_;
mutable std::mutex mutex_;
std::unique_ptr<ReferenceReader> do_clone() const override;
bool do_is_open() const noexcept override;
std::string do_fetch_reference_name() const override;
std::vector<ContigName> do_fetch_contig_names() const override;
GenomicSize do_fetch_contig_size(const ContigName& contig) const override;
GeneticSequence do_fetch_sequence(const GenomicRegion& region) const override;
};
} // namespace io
} // namespace octopus
#endif
| 26.666667 | 96 | 0.735526 | [
"vector"
] |
046f109d93ebf4fa776ce03ac32b63990a2b64e7 | 188 | cpp | C++ | examples/line_plot/loglog/loglog_6.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | 2 | 2020-09-02T14:02:26.000Z | 2020-10-28T07:00:44.000Z | examples/line_plot/loglog/loglog_6.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | null | null | null | examples/line_plot/loglog/loglog_6.cpp | kurogane1031/matplotplusplus | 44d21156edba8effe1e764a8642b0b70590d597b | [
"MIT"
] | 2 | 2020-09-01T16:22:07.000Z | 2020-09-02T14:02:27.000Z | #include <cmath>
#include <matplot/matplot.h>
int main() {
using namespace matplot;
std::vector<double> y = {0.001,0.01,0.1,1,10,100};
loglog(y);
wait();
return 0;
} | 15.666667 | 54 | 0.590426 | [
"vector"
] |
047f49420213bb0f46f53acb39c5f3fc3295b40e | 10,732 | cpp | C++ | hackathon/ouyang/angleinterafly/angle_marker.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/ouyang/angleinterafly/angle_marker.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | hackathon/ouyang/angleinterafly/angle_marker.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | /*
*
*for finding the branchs with strange angles and display it in terafly with red marker.
*Ou Yang 8/21/2018
*
*/
#include "angle_marker.h"
#include <math.h>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define PI 3.14159265359
#define min(a,b) (a)<(b)?(a):(b)
#define max(a,b) (a)>(b)?(a):(b)
#define dist(a,b) sqrt(((a).x-(b).x)*((a).x-(b).x)+((a).y-(b).y)*((a).y-(b).y)+((a).z-(b).z)*((a).z-(b).z))
#define getParent(n,nt) ((nt).listNeuron.at(n).pn<0)?(1000000000):((nt).hashNeuron.value((nt).listNeuron.at(n).pn))
#define angle(a,b,c) (acos((((b).x-(a).x)*((c).x-(a).x)+((b).y-(a).y)*((c).y-(a).y)+((b).z-(a).z)*((c).z-(a).z))/(dist(a,b)*dist(a,c)))*180.0/PI)
//double Width=0, Height=0, Depth=0, Diameter=0, Length=0, Volume=0, Surface=0, Hausdorff=0;
QVector<QVector<V3DLONG> > childs;
struct angles angle_calculate(const NeuronTree & nt)
{
QList<NeuronSWC> neuron = nt.listNeuron;
struct angles result;
vector<long> ids;
// Reorder tree ids so that neuron.at(i).n=i+1
for(V3DLONG i=0;i<neuron.size();i++)
{
ids.push_back(neuron.at(i).n);
}
for(V3DLONG i=0;i<neuron.size();i++)
{
neuron[i].n=i+1;
if(neuron.at(i).pn !=-1)
{
neuron[i].pn=find(ids.begin(), ids.end(),neuron.at(i).pn) - ids.begin()+1;
}
}
//get the childslist
V3DLONG neuronNum = nt.listNeuron.size();
childs = QVector< QVector<V3DLONG> >(neuronNum, QVector<V3DLONG>() );
for (V3DLONG i=0;i<neuronNum;i++)
{
V3DLONG par = nt.listNeuron[i].pn;
if (par<0) continue;
childs[nt.hashNeuron.value(par)].push_back(i);
}
//qDebug()<<childs.size();
//find the dendrite id
vector<int> typelist;
for(int i=0;i<neuron.size();i++){
if (neuron[i].type==3 || neuron[i].type==4){
typelist.push_back(i);}
}
//qDebug()<<typelist.size();
//find the branch points id of dendrite
vector<int> branchid;
branchid=deletetipbranch(nt);
/*for (int i=0;i<typelist.size();i++)
{
int sum=0;
int a=typelist.at(i);
for(int j=1;j<typelist.size();j++)
{
int b=typelist.at(j);
if (neuron.at(a).n==neuron.at(b).pn)
{
sum=sum+1;}
}
if(sum>1 && sum<3)
{
branchid.push_back(a);
}
}*/
//qDebug()<<branchid.size();
//calculate both local and remote angle
//I found that many branch nodes' child point is itself
vector<double> localang;
vector<double> remoteang;
for(int i=0;i<branchid.size();i++)
{
//double max_local_ang = 0;
//double max_remote_ang = 0;
double local_ang;
double remote_ang;
int ch_local1 = childs[branchid.at(i)][0];
int ch_local2 = childs[branchid.at(i)][1];
local_ang = angle(neuron.at(branchid.at(i)),neuron.at(ch_local1),neuron.at(ch_local2));
int ch_remote1 = getRemoteChild(branchid.at(i)).at(0);
int ch_remote2 = getRemoteChild(branchid.at(i)).at(1);
remote_ang = angle(neuron.at(branchid.at(i)),neuron.at(ch_remote1),neuron.at(ch_remote2));
//if (local_ang<=0)
// local_ang = 360-local_ang;
//if (local_ang==local_ang)
// max_local_ang = max(max_local_ang,local_ang);
//if (remote_ang==remote_ang)
// max_remote_ang = max(max_remote_ang,remote_ang);
localang.push_back(local_ang);
remoteang.push_back(remote_ang);
//i choose to plot local angle,but both angles should be ploted in R,i just don't know how to plot two kinds of nodes in R
}
result.a=localang;
result.b=remoteang;
result.c=branchid;
return result;
};
vector<int> deletetipbranch(const NeuronTree & nt)
{
QList<NeuronSWC> neuron = nt.listNeuron;
vector<long> ids;
for(V3DLONG i=0;i<neuron.size();i++)
{
ids.push_back(neuron.at(i).n);
}
for(V3DLONG i=0;i<neuron.size();i++)
{
neuron[i].n=i+1;
if(neuron.at(i).pn !=-1)
{
neuron[i].pn=find(ids.begin(), ids.end(),neuron.at(i).pn) - ids.begin()+1;
}
}
//get the childslist
V3DLONG neuronNum = nt.listNeuron.size();
childs = QVector< QVector<V3DLONG> >(neuronNum, QVector<V3DLONG>() );
for (V3DLONG i=0;i<neuronNum;i++)
{
V3DLONG par = nt.listNeuron[i].pn;
if (par<0) continue;
childs[nt.hashNeuron.value(par)].push_back(i);
}
//find the dendrite id
vector<int> typelist;
for(int i=0;i<neuron.size();i++){
if (neuron[i].type==3 || neuron[i].type==4){
typelist.push_back(i);}
}
//find the branch points id of dendrite
vector<int> branchid;
for (int i=0;i<typelist.size();i++)
{
int sum=0;
int a=typelist.at(i);
for(int j=1;j<typelist.size();j++)
{
int b=typelist.at(j);
if (neuron.at(a).n==neuron.at(b).pn)
{
sum=sum+1;}
}
if(sum>1 && sum<3)
{
branchid.push_back(a);
}
}
cout<<"total branch number:"<<branchid.size()<<endl;
//find the tips of dendrite
vector<int> tipslist;
for (int i=0;i<typelist.size();i++)
{
int sum=0;
for (int j=1;j<typelist.size();j++)
{
if (neuron.at(typelist.at(i)).n==neuron.at(typelist.at(j)).pn)
{
sum=sum+1;
}
}
if (sum<1)
{
tipslist.push_back(typelist.at(i));
}
}
//qDebug()<<tipslist.size();
vector<int> remotenode1;
vector<int> remotenode2;
vector<int> branch_of_remotenode;
for(int i=0;i<branchid.size();i++){
int ch_remote1 = getRemoteChild(branchid.at(i)).at(0);
int ch_remote2 = getRemoteChild(branchid.at(i)).at(1);
remotenode1.push_back(ch_remote1);
remotenode2.push_back(ch_remote2);
branch_of_remotenode.push_back(branchid.at(i));
//branch_of_remotenode.push_back(branchid.at(i));
}
//qDebug()<<branch_of_remotenode.size();
//qDebug()<<remotenode.size();
//qDebug()<<branchid.size();
//delete the fake branches
vector<int> probranchnodes;
vector<int> resultbranches;
for(int i=0;i<remotenode1.size();i++){
// for(int j=0;j<tipslist.size();j++){
int distancefromtiptobranch1;
int distancefromtiptobranch2;
distancefromtiptobranch1=dist(neuron.at(remotenode1.at(i)),neuron.at(branch_of_remotenode.at(i)));
distancefromtiptobranch2=dist(neuron.at(remotenode2.at(i)),neuron.at(branch_of_remotenode.at(i)));
if((childs[remotenode1.at(i)].size()!=0 || distancefromtiptobranch1>30) && (childs[remotenode2.at(i)].size()!=0 || distancefromtiptobranch2>30))
resultbranches.push_back(branch_of_remotenode.at(i));
else probranchnodes.push_back(branch_of_remotenode.at(i));
}
cout<<"fake branch number:"<<probranchnodes.size()<<endl;
//delete the branch node created by wrong connection during sorting
vector<int> Result;
vector<int> pro;
vector<int> trash;
for(int i=0;i<resultbranches.size();i++){
for(int j=i+1;j<resultbranches.size();j++){
double dis;
dis=dist(neuron.at(resultbranches.at(i)),neuron.at(resultbranches.at(j)));
//disofbranchs.push_back(dis);
if(dis<8){
pro.push_back(resultbranches.at(i));
pro.push_back(resultbranches.at(j));
}
//else{
// Result.push_back(resultbranches.at(i));
// Result.push_back(resultbranches.at(j));
//}
}}
vector<int>:: iterator it,it1;
for(it=++pro.begin();it!=pro.end();)
{
it1=find(pro.begin(),it,*it);
if(it1!=it)
it=pro.erase(it);
else
it++;
}
cout<<"branch numbers of wrong connection:"<<pro.size()<<endl;
for(int i=0;i<resultbranches.size();i++){
int cout=0;
for(int j=0;j<pro.size();j++){
if(resultbranches.at(i)==pro.at(j)) cout=cout+1;
}
if(cout==0) Result.push_back(resultbranches.at(i));
else trash.push_back(resultbranches.at(i));
}
return Result;
}
QVector<V3DLONG> getRemoteChild(int t)
{
QVector<V3DLONG> rchildlist;
rchildlist.clear();
int tmp;
for (int i=0;i<childs[t].size();i++)
{
tmp = childs[t].at(i);
while (childs[tmp].size()==1)
tmp = childs[tmp].at(0);
rchildlist.append(tmp);
}
return rchildlist;
}
/*QVector<V3DLONG> getchildsofsingletree(NeuronTree & nt,vector<int> root){
V3DLONG neuronNum = nt.size();
childs = QVector< QVector<V3DLONG> >(neuronNum, QVector<V3DLONG>() );
for (V3DLONG i=0;i<neuronNum;i++)
{
V3DLONG par = nt.listNeuron[i].pn;
if (par<0) continue;
childs[nt.hashNeuron.value(par)].push_back(i);
}
QVector<int> singletreechild;
allchildslist.clear();
int exam;
do{
if(childs[f].size()==1) a=childs[f].at(0);
else if(childs[f].size()==2) {
b=childs[f].at(0);
c=childs[f].at(1);}
}while();
*/
| 33.85489 | 168 | 0.493943 | [
"vector"
] |
0487a72557f94cba26f4c060b7b121b2f3c9f7a2 | 3,687 | cpp | C++ | src/lib/operators/export_csv.cpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | 2 | 2019-01-22T19:44:32.000Z | 2019-01-22T19:52:33.000Z | src/lib/operators/export_csv.cpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | 69 | 2019-05-24T10:01:32.000Z | 2019-12-13T19:09:05.000Z | src/lib/operators/export_csv.cpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | null | null | null | #include "export_csv.hpp"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "json.hpp"
#include "import_export/csv_meta.hpp"
#include "import_export/csv_writer.hpp"
#include "storage/materialize.hpp"
#include "storage/reference_segment.hpp"
#include "constant_mappings.hpp"
#include "resolve_type.hpp"
namespace opossum {
ExportCsv::ExportCsv(const std::shared_ptr<const AbstractOperator>& in, const std::string& filename)
: AbstractReadOnlyOperator(OperatorType::ExportCsv, in), _filename(filename) {}
const std::string ExportCsv::name() const { return "ExportCSV"; }
std::shared_ptr<const Table> ExportCsv::_on_execute() {
_generate_meta_info_file(_input_left->get_output(), _filename + CsvMeta::META_FILE_EXTENSION);
_generate_content_file(_input_left->get_output(), _filename);
return _input_left->get_output();
}
std::shared_ptr<AbstractOperator> ExportCsv::_on_deep_copy(
const std::shared_ptr<AbstractOperator>& copied_input_left,
const std::shared_ptr<AbstractOperator>& copied_input_right) const {
return std::make_shared<ExportCsv>(copied_input_left, _filename);
}
void ExportCsv::_on_set_parameters(const std::unordered_map<ParameterID, AllTypeVariant>& parameters) {}
void ExportCsv::_generate_meta_info_file(const std::shared_ptr<const Table>& table, const std::string& meta_file_path) {
CsvMeta meta{};
// Column Types
for (ColumnID column_id{0}; column_id < table->column_count(); ++column_id) {
ColumnMeta column_meta;
column_meta.name = table->column_name(column_id);
column_meta.type = data_type_to_string.left.at(table->column_data_type(column_id));
column_meta.nullable = table->column_is_nullable(column_id);
meta.columns.push_back(column_meta);
}
nlohmann::json meta_json = meta;
std::ofstream meta_file_stream(meta_file_path);
meta_file_stream << std::setw(4) << meta_json << std::endl;
}
void ExportCsv::_generate_content_file(const std::shared_ptr<const Table>& table, const std::string& csv_file) {
/**
* A naively exported csv file is a materialized file in row format.
* This offers some advantages, but also disadvantages.
* The advantages are that it is very straight forward to implement for any segment type
* as it does not care about representation of values. Also, probably, the main reason for this,
* it makes is very easy to load this data into a different database.
* The disadvantage is that it can be quite slow if the data has been compressed before.
* Also, it does not involve the column-oriented style used in OpossumDB.
*/
// Open file for writing
CsvWriter writer(csv_file);
/**
* Multiple rows containing the values of each respective row are written.
* Therefore we first iterate through the chunks, then through the rows
* in the chunks and afterwards through the segments of the chunks.
*
* This is a lot of iterating, but to convert a column-based table to
* a row-based representation takes some effort.
*/
for (ChunkID chunk_id{0}; chunk_id < table->chunk_count(); ++chunk_id) {
const auto chunk = table->get_chunk(chunk_id);
for (ChunkOffset chunk_offset = 0; chunk_offset < chunk->size(); ++chunk_offset) {
for (ColumnID column_id{0}; column_id < table->column_count(); ++column_id) {
const auto segment = chunk->get_segment(column_id);
// The previous implementation did a double dispatch (at least two virtual method calls)
// So the subscript operator cannot be much slower.
const auto value = (*segment)[chunk_offset];
writer.write(value);
}
writer.end_line();
}
}
}
} // namespace opossum
| 36.87 | 120 | 0.7361 | [
"vector"
] |
048b06b2926abdc8e6078ce4ea8e2d6bec6298cb | 7,906 | cpp | C++ | Motor2D/MenuScene.cpp | ArmisJoe/2DGame | 95d3a4fd203da21b0cf9c8dc28c2f8c07c74123f | [
"MIT"
] | null | null | null | Motor2D/MenuScene.cpp | ArmisJoe/2DGame | 95d3a4fd203da21b0cf9c8dc28c2f8c07c74123f | [
"MIT"
] | null | null | null | Motor2D/MenuScene.cpp | ArmisJoe/2DGame | 95d3a4fd203da21b0cf9c8dc28c2f8c07c74123f | [
"MIT"
] | null | null | null | #include "MenuScene.h"
#include "Render.h"
#include "Application.h"
#include "Input.h"
#include "SceneManager.h"
#include "Window.h"
#include "Audio.h"
#include "Fonts.h"
#include "FogOfWar.h"
MenuScene::MenuScene() : SceneElement("menu")
{
}
MenuScene::~MenuScene()
{
}
bool MenuScene::Awake(pugi::xml_node & config)
{
return true;
}
bool MenuScene::Start()
{
bool ret = true;
App->render->camera.x = 0;
App->render->camera.y = 0;
uint x, y;
App->win->GetWindowSize(x, y);
elements = App->gui->GetElements("MENUSCENE");
elements[1].position.first = (x / 3) * 2 - (x / 8);
elements[1].position.second = (y / 2) - (y / 3);
elements[2].position.first = (x / 3) + (x / 10);
elements[2].position.second = elements[1].position.second;
elements[3].position.first = (x / 4) + (x / 20);
elements[3].position.second = elements[1].position.second;
elements[4].position.first = elements[3].position.first + (x / 150);
elements[4].position.second = elements[1].position.second + (y / 13);
elements[5].position.first = elements[3].position.first + (x / 150) + elements[4].rect.w + (x/40);
elements[5].position.second = elements[4].position.second;
elements[6].position.first = elements[1].position.first + x / 180;
elements[6].position.second = elements[1].position.second + y / 50;
elements[7].position.first = elements[6].position.first;
elements[7].position.second = elements[6].position.second + y / 100 + elements[6].detect_sections.front().h;
elements[8].position.first = elements[7].position.first;
elements[8].position.second = elements[7].position.second + y / 100 + elements[7].detect_sections.front().h;
elements[9].position.first = elements[2].position.first + (x / 100);
elements[9].position.second = elements[2].position.second + (y / 15);
elements[10].position.first = elements[9].position.first;
elements[10].position.second = elements[9].position.second + (y / 20);
elements[11].position.first = elements[3].position.first + (x / 30);
elements[11].position.second = elements[3].position.second + (y / 5) + (y / 30);
elements[12].position.first = elements[11].position.first;
elements[12].position.second = elements[11].position.second + (y / 15);
for (uint it = 0; it < elements.size(); ++it) {
switch (elements[it].type)
{
case IMAGE:
images.push_back((Image*)App->gui->CreateImage(elements[it].texture, elements[it].position.first, elements[it].position.second, elements[it].rect));
images.back()->loaded_tex = true;
break;
case BUTTON:
buttons.push_back((Button*)App->gui->CreateButton(elements[it].texture, elements[it].position.first, elements[it].position.second, elements[it].blit_sections, elements[it].detect_sections, elements[it].tier));
buttons.back()->loaded_tex = true;
break;
}
}
new_game_lbl = (Label*)App->gui->CreateLabel("New Game", buttons[NEWGAME]->pos.first + x / 20, buttons[NEWGAME]->pos.second, App->font->fonts[EIGHTEEN]);
load_game_lbl = (Label*)App->gui->CreateLabel("Load Game", buttons[LOADGAME]->pos.first + x / 20, buttons[LOADGAME]->pos.second, App->font->fonts[EIGHTEEN]);
freepeople_lbl = (Label*)App->gui->CreateLabel("FREE PEOPLE", images[FREEPEOPLE]->pos.first + x / 40, images[FREEPEOPLE]->pos.second + images[FREEPEOPLE]->section.h + y / 500, nullptr);
sauronarmy_lbl = (Label*)App->gui->CreateLabel("SAURON ARMY", images[SAURONARMY]->pos.first + x / 40, images[SAURONARMY]->pos.second + images[SAURONARMY]->section.h + y / 500, nullptr);
map_lbl = (Label*)App->gui->CreateLabel("Map: Riverdale", images[BACKGROUND_SKIRMISH]->pos.first + x / 15, images[BACKGROUND_SKIRMISH]->pos.second + y / 500, App->font->fonts[FOURTEEN]);
skirmish_menu.in_window.push_back(images[BACKGROUND_SKIRMISH]);
skirmish_menu.in_window.push_back(images[FREEPEOPLE]);
skirmish_menu.in_window.push_back(images[SAURONARMY]);
skirmish_menu.in_window.push_back(buttons[NEWGAME]);
skirmish_menu.in_window.push_back(buttons[LOADGAME]);
skirmish_menu.in_window.push_back(new_game_lbl);
skirmish_menu.in_window.push_back(load_game_lbl);
skirmish_menu.in_window.push_back(map_lbl);
skirmish_menu.in_window.push_back(freepeople_lbl);
skirmish_menu.in_window.push_back(sauronarmy_lbl);
skirmish_menu.WindowOff();
skirmish_menu.SetFocus(images[BACKGROUND_SKIRMISH]->pos.first, images[BACKGROUND_SKIRMISH]->pos.second, x, y);
settings_lbl = (Label*)App->gui->CreateLabel("Settings", images[SETTINGS]->pos.first + x / 100, images[SETTINGS]->pos.second, App->font->fonts[TWENTYSIX]);
if (App->audio->active == true) {
mute_lbl = (Label*)App->gui->CreateLabel("MUTE", buttons[MUTE]->pos.first + x / 50, buttons[MUTE]->pos.second + y / 150, App->font->fonts[FOURTEEN]);
}
else mute_lbl = (Label*)App->gui->CreateLabel("UNMUTE", buttons[MUTE]->pos.first + x / 50, buttons[MUTE]->pos.second + y / 150, App->font->fonts[FOURTEEN]);
if (!App->win->IsFullScreen()) {
window_lbl = (Label*)App->gui->CreateLabel("FULLSCREEN", buttons[SCREEN]->pos.first + x / 100, buttons[SCREEN]->pos.second + y / 150, App->font->fonts[FOURTEEN]);
}
else window_lbl = (Label*)App->gui->CreateLabel("WINDOWED", buttons[SCREEN]->pos.first + x / 100, buttons[SCREEN]->pos.second + y / 150, App->font->fonts[FOURTEEN]);
ui_menu.in_window.push_back(images[SETTINGS]);
ui_menu.in_window.push_back(buttons[MUTE]);
ui_menu.in_window.push_back(buttons[SCREEN]);
ui_menu.in_window.push_back(settings_lbl);
ui_menu.in_window.push_back(mute_lbl);
ui_menu.in_window.push_back(window_lbl);
ui_menu.WindowOff();
ui_menu.SetFocus(elements[0].position.first, elements[0].position.second, x, y);
App->gui->SetPriority();
// Menu Main Theme
App->audio->PlayMusic("audio/music/m_menu.ogg", 0.0f);
return ret;
}
bool MenuScene::PreUpdate()
{
return true;
}
bool MenuScene::Update(float dt)
{
// --------------------------------------------
// UI
//---------------------------------------------
if (buttons[MUTE]->current == CLICKUP)
{
if (App->audio->active == true) {
App->audio->PlayMusic(nullptr, 0.0f);
App->audio->active = false;
mute_lbl->SetString("UNMUTE");
}
else {
App->audio->active = true;
App->audio->PlayMusic("audio/music/m_menu.ogg");
mute_lbl->SetString("MUTE");
}
}
if (buttons[SCREEN]->current == CLICKUP)
{
if (App->win->IsFullScreen()) {
App->win->ChangeToWindow();
window_lbl->SetString("FULLSCREEN");
}
else {
App->win->ChangeToFullScreen();
window_lbl->SetString("WINDOWED");
}
}
if (ui_menu.IsEnabled()) App->gui->Focus(ui_menu.FocusArea());
if (buttons[OPTIONS]->current == CLICKUP) {
if (!ui_menu.IsEnabled()) {
ui_menu.WindowOn();
}
else {
ui_menu.WindowOff();
}
}
if (images[FREEPEOPLE]->current == CLICKUP) {
team = 0;
}
else if (images[SAURONARMY]->current == CLICKUP) {
team = 1;
}
// ---------------------------------------
return true;
}
bool MenuScene::PostUpdate()
{
if (buttons[SKIRMISH]->current == CLICKUP)
{
//App->sceneManager->ChangeScene(this, App->sceneManager->level1_scene);
team = -1;
}
else if (buttons[2]->current == CLICKUP)
{
App->quit = true;
}
else if (buttons[NEWGAME]->current == CLICKUP)
{
}
if (final_team != team)
{
final_team = team;
if (final_team == 0)
{
App->gui->DestroyUIElement(ring);
ring = (Image*)App->gui->CreateImage("gui/ring.png", images[FREEPEOPLE]->pos.first, images[FREEPEOPLE]->pos.second, { 0,0, 125, 70 });
}
else if (final_team == 1)
{
App->gui->DestroyUIElement(ring);
ring = (Image*)App->gui->CreateImage("gui/ring.png", images[SAURONARMY]->pos.first, images[SAURONARMY]->pos.second, {0,0, 125, 70});
}
else if (final_team == -1)
App->gui->DestroyUIElement(ring);
}
return true;
}
bool MenuScene::CleanUp()
{
ui_menu.WindowOff();
ui_menu.CleanUp();
skirmish_menu.CleanUp();
App->gui->DestroyALLUIElements();
elements.clear();
images.clear();
buttons.clear();
return true;
}
| 32.804979 | 212 | 0.678346 | [
"render"
] |
048ba33fe041fba9a9f21772eef8468b28f2b9b4 | 15,849 | cc | C++ | mediapipe/calculators/util/non_max_suppression_calculator.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | 2 | 2021-01-18T13:32:40.000Z | 2021-05-13T12:28:35.000Z | mediapipe/calculators/util/non_max_suppression_calculator.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | null | null | null | mediapipe/calculators/util/non_max_suppression_calculator.cc | Ensteinjun/mediapipe | 38be2ec58f2a1687f4ffca287094c7bbd7791f58 | [
"Apache-2.0"
] | 3 | 2021-01-19T14:40:59.000Z | 2021-06-09T13:43:49.000Z | // Copyright 2019 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "mediapipe/calculators/util/non_max_suppression_calculator.pb.h"
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/detection.pb.h"
#include "mediapipe/framework/formats/image_frame.h"
#include "mediapipe/framework/formats/location.h"
#include "mediapipe/framework/port/logging.h"
#include "mediapipe/framework/port/rectangle.h"
#include "mediapipe/framework/port/status.h"
namespace mediapipe {
typedef std::vector<Detection> Detections;
typedef std::vector<std::pair<int, float>> IndexedScores;
namespace {
constexpr char kImageTag[] = "IMAGE";
bool SortBySecond(const std::pair<int, float>& indexed_score_0,
const std::pair<int, float>& indexed_score_1) {
return (indexed_score_0.second > indexed_score_1.second);
}
// Removes all but the max scoring label and its score from the detection.
// Returns true if the detection has at least one label.
bool RetainMaxScoringLabelOnly(Detection* detection) {
if (detection->label_id_size() == 0 && detection->label_size() == 0) {
return false;
}
CHECK(detection->label_id_size() == detection->score_size() ||
detection->label_size() == detection->score_size())
<< "Number of scores must be equal to number of detections.";
std::vector<std::pair<int, float>> indexed_scores;
for (int k = 0; k < detection->score_size(); ++k) {
indexed_scores.push_back(std::make_pair(k, detection->score(k)));
}
std::sort(indexed_scores.begin(), indexed_scores.end(), SortBySecond);
const int top_index = indexed_scores[0].first;
detection->clear_score();
detection->add_score(indexed_scores[0].second);
if (detection->label_id_size() > top_index) {
const int top_label_id = detection->label_id(top_index);
detection->clear_label_id();
detection->add_label_id(top_label_id);
} else {
const std::string top_label = detection->label(top_index);
detection->clear_label();
detection->add_label(top_label);
}
return true;
}
// Computes an overlap similarity between two rectangles. Similarity measure is
// defined by overlap_type parameter.
float OverlapSimilarity(
const NonMaxSuppressionCalculatorOptions::OverlapType overlap_type,
const Rectangle_f& rect1, const Rectangle_f& rect2) {
if (!rect1.Intersects(rect2)) return 0.0f;
const float intersection_area = Rectangle_f(rect1).Intersect(rect2).Area();
float normalization;
switch (overlap_type) {
case NonMaxSuppressionCalculatorOptions::JACCARD:
normalization = Rectangle_f(rect1).Union(rect2).Area();
break;
case NonMaxSuppressionCalculatorOptions::MODIFIED_JACCARD:
normalization = rect2.Area();
break;
case NonMaxSuppressionCalculatorOptions::INTERSECTION_OVER_UNION:
normalization = rect1.Area() + rect2.Area() - intersection_area;
break;
default:
LOG(FATAL) << "Unrecognized overlap type: " << overlap_type;
}
return normalization > 0.0f ? intersection_area / normalization : 0.0f;
}
// Computes an overlap similarity between two locations by first extracting the
// relative box (dimension normalized by frame width/height) from the location.
float OverlapSimilarity(
const int frame_width, const int frame_height,
const NonMaxSuppressionCalculatorOptions::OverlapType overlap_type,
const Location& location1, const Location& location2) {
const auto rect1 = location1.ConvertToRelativeBBox(frame_width, frame_height);
const auto rect2 = location2.ConvertToRelativeBBox(frame_width, frame_height);
return OverlapSimilarity(overlap_type, rect1, rect2);
}
// Computes an overlap similarity between two locations by first extracting the
// relative box from the location. It assumes that a relative-box representation
// is already available in the location, and therefore frame width and height
// are not needed for further normalization.
float OverlapSimilarity(
const NonMaxSuppressionCalculatorOptions::OverlapType overlap_type,
const Location& location1, const Location& location2) {
const auto rect1 = location1.GetRelativeBBox();
const auto rect2 = location2.GetRelativeBBox();
return OverlapSimilarity(overlap_type, rect1, rect2);
}
} // namespace
// A calculator performing non-maximum suppression on a set of detections.
// Inputs:
// 1. IMAGE (optional): A stream of ImageFrame used to obtain the frame size.
// No image data is used. Not needed if the detection bounding boxes are
// already represented in normalized dimensions (0.0~1.0).
// 2. A variable number of input streams of type std::vector<Detection>. The
// exact number of such streams should be set via num_detection_streams
// field in the calculator options.
//
// Outputs: a single stream of type std::vector<Detection> containing a subset
// of the input detections after non-maximum suppression.
//
// Example config:
// node {
// calculator: "NonMaxSuppressionCalculator"
// input_stream: "IMAGE:frames"
// input_stream: "detections1"
// input_stream: "detections2"
// output_stream: "detections"
// options {
// [mediapipe.NonMaxSuppressionCalculatorOptions.ext] {
// num_detection_streams: 2
// max_num_detections: 10
// min_suppression_threshold: 0.2
// overlap_type: JACCARD
// }
// }
// }
class NonMaxSuppressionCalculator : public CalculatorBase {
public:
NonMaxSuppressionCalculator() = default;
~NonMaxSuppressionCalculator() override = default;
static mediapipe::Status GetContract(CalculatorContract* cc) {
const auto& options = cc->Options<NonMaxSuppressionCalculatorOptions>();
if (cc->Inputs().HasTag(kImageTag)) {
cc->Inputs().Tag(kImageTag).Set<ImageFrame>();
}
for (int k = 0; k < options.num_detection_streams(); ++k) {
cc->Inputs().Index(k).Set<Detections>();
}
cc->Outputs().Index(0).Set<Detections>();
return mediapipe::OkStatus();
}
mediapipe::Status Open(CalculatorContext* cc) override {
cc->SetOffset(TimestampDiff(0));
options_ = cc->Options<NonMaxSuppressionCalculatorOptions>();
CHECK_GT(options_.num_detection_streams(), 0)
<< "At least one detection stream need to be specified.";
CHECK_NE(options_.max_num_detections(), 0)
<< "max_num_detections=0 is not a valid value. Please choose a "
<< "positive number of you want to limit the number of output "
<< "detections, or set -1 if you do not want any limit.";
return mediapipe::OkStatus();
}
mediapipe::Status Process(CalculatorContext* cc) override {
// Add all input detections to the same vector.
Detections input_detections;
for (int i = 0; i < options_.num_detection_streams(); ++i) {
const auto& detections_packet = cc->Inputs().Index(i).Value();
// Check whether this stream has a packet for this timestamp.
if (detections_packet.IsEmpty()) {
continue;
}
const auto& detections = detections_packet.Get<Detections>();
input_detections.insert(input_detections.end(), detections.begin(),
detections.end());
}
// Check if there are any detections at all.
if (input_detections.empty()) {
if (options_.return_empty_detections()) {
cc->Outputs().Index(0).Add(new Detections(), cc->InputTimestamp());
}
return mediapipe::OkStatus();
}
// Remove all but the maximum scoring label from each input detection. This
// corresponds to non-maximum suppression among detections which have
// identical locations.
Detections pruned_detections;
pruned_detections.reserve(input_detections.size());
for (auto& detection : input_detections) {
if (RetainMaxScoringLabelOnly(&detection)) {
pruned_detections.push_back(detection);
}
}
// Copy all the scores (there is a single score in each detection after
// the above pruning) to an indexed vector for sorting. The first value is
// the index of the detection in the original vector from which the score
// stems, while the second is the actual score.
IndexedScores indexed_scores;
indexed_scores.reserve(pruned_detections.size());
for (int index = 0; index < pruned_detections.size(); ++index) {
indexed_scores.push_back(
std::make_pair(index, pruned_detections[index].score(0)));
}
std::sort(indexed_scores.begin(), indexed_scores.end(), SortBySecond);
const int max_num_detections =
(options_.max_num_detections() > -1)
? options_.max_num_detections()
: static_cast<int>(indexed_scores.size());
// A set of detections and locations, wrapping the location data from each
// detection, which are retained after the non-maximum suppression.
auto* retained_detections = new Detections();
retained_detections->reserve(max_num_detections);
if (options_.algorithm() == NonMaxSuppressionCalculatorOptions::WEIGHTED) {
WeightedNonMaxSuppression(indexed_scores, pruned_detections,
max_num_detections, cc, retained_detections);
} else {
NonMaxSuppression(indexed_scores, pruned_detections, max_num_detections,
cc, retained_detections);
}
cc->Outputs().Index(0).Add(retained_detections, cc->InputTimestamp());
return mediapipe::OkStatus();
}
private:
void NonMaxSuppression(const IndexedScores& indexed_scores,
const Detections& detections, int max_num_detections,
CalculatorContext* cc, Detections* output_detections) {
std::vector<Location> retained_locations;
retained_locations.reserve(max_num_detections);
// We traverse the detections by decreasing score.
for (const auto& indexed_score : indexed_scores) {
const auto& detection = detections[indexed_score.first];
if (options_.min_score_threshold() > 0 &&
detection.score(0) < options_.min_score_threshold()) {
break;
}
const Location location(detection.location_data());
bool suppressed = false;
// The current detection is suppressed iff there exists a retained
// detection, whose location overlaps more than the specified
// threshold with the location of the current detection.
for (const auto& retained_location : retained_locations) {
float similarity;
if (cc->Inputs().HasTag(kImageTag)) {
const auto& frame = cc->Inputs().Tag(kImageTag).Get<ImageFrame>();
similarity = OverlapSimilarity(frame.Width(), frame.Height(),
options_.overlap_type(),
retained_location, location);
} else {
similarity = OverlapSimilarity(options_.overlap_type(),
retained_location, location);
}
if (similarity > options_.min_suppression_threshold()) {
suppressed = true;
break;
}
}
if (!suppressed) {
output_detections->push_back(detection);
retained_locations.push_back(location);
}
if (output_detections->size() >= max_num_detections) {
break;
}
}
}
void WeightedNonMaxSuppression(const IndexedScores& indexed_scores,
const Detections& detections,
int max_num_detections, CalculatorContext* cc,
Detections* output_detections) {
IndexedScores remained_indexed_scores;
remained_indexed_scores.assign(indexed_scores.begin(),
indexed_scores.end());
IndexedScores remained;
IndexedScores candidates;
output_detections->clear();
while (!remained_indexed_scores.empty()) {
const int original_indexed_scores_size = remained_indexed_scores.size();
const auto& detection = detections[remained_indexed_scores[0].first];
if (options_.min_score_threshold() > 0 &&
detection.score(0) < options_.min_score_threshold()) {
break;
}
remained.clear();
candidates.clear();
const Location location(detection.location_data());
// This includes the first box.
for (const auto& indexed_score : remained_indexed_scores) {
Location rest_location(detections[indexed_score.first].location_data());
float similarity =
OverlapSimilarity(options_.overlap_type(), rest_location, location);
if (similarity > options_.min_suppression_threshold()) {
candidates.push_back(indexed_score);
} else {
remained.push_back(indexed_score);
}
}
auto weighted_detection = detection;
if (!candidates.empty()) {
const int num_keypoints =
detection.location_data().relative_keypoints_size();
std::vector<float> keypoints(num_keypoints * 2);
float w_xmin = 0.0f;
float w_ymin = 0.0f;
float w_xmax = 0.0f;
float w_ymax = 0.0f;
float total_score = 0.0f;
for (const auto& candidate : candidates) {
total_score += candidate.second;
const auto& location_data =
detections[candidate.first].location_data();
const auto& bbox = location_data.relative_bounding_box();
w_xmin += bbox.xmin() * candidate.second;
w_ymin += bbox.ymin() * candidate.second;
w_xmax += (bbox.xmin() + bbox.width()) * candidate.second;
w_ymax += (bbox.ymin() + bbox.height()) * candidate.second;
for (int i = 0; i < num_keypoints; ++i) {
keypoints[i * 2] +=
location_data.relative_keypoints(i).x() * candidate.second;
keypoints[i * 2 + 1] +=
location_data.relative_keypoints(i).y() * candidate.second;
}
}
auto* weighted_location = weighted_detection.mutable_location_data()
->mutable_relative_bounding_box();
weighted_location->set_xmin(w_xmin / total_score);
weighted_location->set_ymin(w_ymin / total_score);
weighted_location->set_width((w_xmax / total_score) -
weighted_location->xmin());
weighted_location->set_height((w_ymax / total_score) -
weighted_location->ymin());
for (int i = 0; i < num_keypoints; ++i) {
auto* keypoint = weighted_detection.mutable_location_data()
->mutable_relative_keypoints(i);
keypoint->set_x(keypoints[i * 2] / total_score);
keypoint->set_y(keypoints[i * 2 + 1] / total_score);
}
}
output_detections->push_back(weighted_detection);
// Breaks the loop if the size of indexed scores doesn't change after an
// iteration.
if (original_indexed_scores_size == remained.size()) {
break;
} else {
remained_indexed_scores = std::move(remained);
}
}
}
NonMaxSuppressionCalculatorOptions options_;
};
REGISTER_CALCULATOR(NonMaxSuppressionCalculator);
} // namespace mediapipe
| 41.166234 | 80 | 0.6755 | [
"vector"
] |
0494b435bb4fd1a2d25261dc0e6653005a060a14 | 1,411 | cpp | C++ | kpl_phylogenetic/kpl_qmatrix.cpp | kellerberrin/OSM_Gene_Cpp | 4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4 | [
"MIT"
] | 1 | 2021-04-09T16:24:06.000Z | 2021-04-09T16:24:06.000Z | kpl_phylogenetic/kpl_qmatrix.cpp | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | null | null | null | kpl_phylogenetic/kpl_qmatrix.cpp | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | null | null | null | //
// Created by kellerberrin on 13/12/19.
//
#include "kpl_qmatrix.h"
#include <numeric>
namespace kpl = kellerberrin::phylogenetic;
// member function bodies go here
kpl::QMatrix::QMatrix() {
//std::cout << "Creating a QMatrix object" << std::endl;
}
kpl::QMatrix::~QMatrix() {
//std::cout << "Destroying a QMatrix object" << std::endl;
}
void kpl::QMatrix::setActive(bool activate) {
_is_active = activate;
recalcRateMatrix();
}
void kpl::QMatrix::clear() {
_is_active = false;
_state_freqs_fixed = false;
_exchangeabilities_fixed = false;
_omega_fixed = false;
}
void kpl::QMatrix::fixStateFreqs(bool is_fixed) {
_state_freqs_fixed = is_fixed;
}
void kpl::QMatrix::fixExchangeabilities(bool is_fixed) {
_exchangeabilities_fixed = is_fixed;
}
void kpl::QMatrix::fixOmega(bool is_fixed) {
_omega_fixed = is_fixed;
}
bool kpl::QMatrix::isFixedStateFreqs() const {
return _state_freqs_fixed;
}
bool kpl::QMatrix::isFixedExchangeabilities() const {
return _exchangeabilities_fixed;
}
bool kpl::QMatrix::isFixedOmega() const {
return _omega_fixed;
}
void kpl::QMatrix::normalizeFreqsOrExchangeabilities(QMatrix::freq_xchg_ptr_t v) {
// Be sure elements of v sum to 1.0 and assert that they are all positive
double sum_v = std::accumulate(v->begin(), v->end(), 0.0);
for (auto & x : *v) {
assert(x > 0.0);
x /= sum_v;
}
}
| 14.397959 | 82 | 0.686038 | [
"object"
] |
0496bf6f1adc78bc0296ad41b606e548b0c0fd3c | 1,647 | cpp | C++ | CPP/Graph/207/CourseSchedule.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/Graph/207/CourseSchedule.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/Graph/207/CourseSchedule.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | //
// Created by Insomnia on 2018/7/19.
//
#include <iostream>
#include <vector>
using namespace std;
struct GraphNode {
int label;
vector<GraphNode *> neighbors;
GraphNode(int x) : label(x) {}
};
class Solution {
public:
//其中的 pair, second 依赖first
//-1 没有访问过, 0 正在访问, 1 已经访问完成
bool canFinish(int numCourses, vector<pair<int, int>> &prerequisites) {
vector<GraphNode *> graph;
vector<int> visit;
for (int i = 0; i < numCourses; ++i) {
graph.push_back(new GraphNode(i));
visit.push_back(-1);
}
for (int j = 0; j < prerequisites.size(); ++j) {
GraphNode *begin = graph[prerequisites[j].second];
GraphNode *end = graph[prerequisites[j].first];
begin->neighbors.push_back(end);
}
for (int k = 0; k < graph.size(); ++k) {
if (visit[k] == -1 && !DFS_graph(graph[k], visit)) {
return false;
}
}
for (int l = 0; l < numCourses; ++l) {
delete graph[l];
}
return true;
}
private:
bool DFS_graph(GraphNode *node, vector<int> &visit) {
visit[node->label] = 0;
for (int i = 0; i < node->neighbors.size(); ++i) {
if (visit[node->neighbors[i]->label] == -1) {
if (DFS_graph(node->neighbors[i], visit) == 0) {
return false;
}
} else if (visit[node->neighbors[i]->label] == 0) {
return false;
}
}
visit[node->label] = 1;
return true;
}
};
int main() {
return 0;
}
| 23.197183 | 75 | 0.493625 | [
"vector"
] |
0496d92bd30976340480f7a2e01c19653ac30168 | 583 | cpp | C++ | MyTask/common/base/basefragment.cpp | SuperSLD/MyTask | a428b1e410800018662ec9b1c970b68fc7fe7b69 | [
"MIT"
] | 3 | 2021-04-03T16:19:20.000Z | 2021-04-06T20:37:23.000Z | MyTask/common/base/basefragment.cpp | SuperSLD/MyTask | a428b1e410800018662ec9b1c970b68fc7fe7b69 | [
"MIT"
] | null | null | null | MyTask/common/base/basefragment.cpp | SuperSLD/MyTask | a428b1e410800018662ec9b1c970b68fc7fe7b69 | [
"MIT"
] | 3 | 2021-09-13T12:47:03.000Z | 2021-11-27T07:45:59.000Z | #include "basefragment.h"
#include <QVBoxLayout>
BaseFragment::BaseFragment() {}
BaseFragment::~BaseFragment() {}
void BaseFragment::onPause() {}
void BaseFragment::onResume() {}
void BaseFragment::setData(BaseModel* model) {}
void BaseFragment::clearList(QLayout *list) {
QLayoutItem* child;
while(list->count()!=0)
{
child = list->takeAt(0);
if(child->layout() != 0)
{
clearList(child->layout());
}
else if(child->widget() != 0)
{
delete child->widget();
}
delete child;
}
}
| 22.423077 | 47 | 0.571184 | [
"model"
] |
049ef48dcca0397ac9ab1336e8807a6e40cfa7dd | 513 | cpp | C++ | learningCpp/exercise6_3.cpp | mcshen99/learningCpp | 6251ae0645a01b15a8fa560b010f5a323943b10d | [
"MIT"
] | null | null | null | learningCpp/exercise6_3.cpp | mcshen99/learningCpp | 6251ae0645a01b15a8fa560b010f5a323943b10d | [
"MIT"
] | null | null | null | learningCpp/exercise6_3.cpp | mcshen99/learningCpp | 6251ae0645a01b15a8fa560b010f5a323943b10d | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
//makes a vector u containing 100 ten times and copies them to a new vector v.
int main() {
vector<int> u(10, 100);
for (vector<int>::const_iterator iter = u.begin(); iter != u.end(); ++iter) {
cout << *iter << " ";
}
cout << endl;
vector<int> v;
copy(u.begin(), u.end(), v.begin());
for (vector<int>::const_iterator iter = v.begin(); iter != v.end(); ++iter) {
cout << *iter << " ";
}
cout << endl;
return 0;
}
| 19.730769 | 78 | 0.60039 | [
"vector"
] |
049f6dd13ed98490089ba848e47264fdc44f2462 | 10,121 | hpp | C++ | hpx/hpx_start_impl.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | hpx/hpx_start_impl.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | hpx/hpx_start_impl.hpp | kempj/hpx | ffdbfed5dfa029a0f2e97e7367cb66d12103df67 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2013 Hartmut Kaiser
//
// 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(HPX_START_IMPL_OCT_04_2012_0252PM)
#define HPX_START_IMPL_OCT_04_2012_0252PM
#if !defined(HPX_START_OCT_04_2012_0148PM)
# error Do not directly include hpx/hpx_start_impl.hpp, use hpx/hpx_start.hpp instead!
#endif
namespace hpx
{
/// \cond NOINTERNAL
namespace detail
{
HPX_EXPORT int run_or_start(
util::function_nonser<int(boost::program_options::variables_map& vm)> const& f,
boost::program_options::options_description const& desc_cmdline,
int argc, char** argv, std::vector<std::string> const& ini_config,
startup_function_type const& startup,
shutdown_function_type const& shutdown, hpx::runtime_mode mode,
bool blocking);
}
/// \endcond
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is the main, non-blocking entry point for any HPX application.
/// This function (or one of its overloads below) should be called from the
/// users `main()` function. It will set up the HPX runtime environment and
/// schedule the function given by \p f as a HPX thread. It will return
/// immediatly after that. Use `hpx::wait` and `hpx::stop` to synchronize
/// with the runtime system's execution.
inline bool start(
util::function_nonser<int(boost::program_options::variables_map& vm)> const& f,
boost::program_options::options_description const& desc_cmdline,
int argc, char** argv, std::vector<std::string> const& cfg,
util::function_nonser<void()> const& startup,
util::function_nonser<void()> const& shutdown,
hpx::runtime_mode mode)
{
util::set_hpx_prefix(HPX_PREFIX);
return 0 == detail::run_or_start(f, desc_cmdline, argc, argv, cfg,
startup, shutdown, mode, false);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is the main, non-blocking entry point for any HPX application.
/// This function (or one of its overloads below) should be called from the
/// users `main()` function. It will set up the HPX runtime environment and
/// schedule the function given by \p f as a HPX thread. It will return
/// immediatly after that. Use `hpx::wait` and `hpx::stop` to synchronize
/// with the runtime system's execution.
inline bool
start(int (*f)(boost::program_options::variables_map& vm),
boost::program_options::options_description const& desc_cmdline,
int argc, char** argv, util::function_nonser<void()> const& startup,
util::function_nonser<void()> const& shutdown, hpx::runtime_mode mode)
{
std::vector<std::string> cfg;
return start(f, desc_cmdline, argc, argv, cfg, startup, shutdown, mode);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is a simplified main, non-blocking entry point, which can be used
/// to set up the runtime for an HPX application (the runtime system will be
/// set up in console mode or worker mode depending on the command line
/// settings). It will return immediatly after that. Use `hpx::wait` and
/// `hpx::stop` to synchronize with the runtime system's execution.
inline bool
start(boost::program_options::options_description const& desc_cmdline,
int argc, char** argv, util::function_nonser<void()> const& startup,
util::function_nonser<void()> const& shutdown, hpx::runtime_mode mode)
{
return start(static_cast<hpx_main_type>(::hpx_main), desc_cmdline,
argc, argv, startup, shutdown, mode);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is a simplified main, non-blocking entry point, which can be used
/// to set up the runtime for an HPX application (the runtime system will
/// be set up in console mode or worker mode depending on the command line
/// settings). It will return immediatly after that. Use `hpx::wait` and
/// `hpx::stop` to synchronize with the runtime system's execution.
inline bool
start(boost::program_options::options_description const& desc_cmdline,
int argc, char** argv, std::vector<std::string> const& cfg,
util::function_nonser<void()> const& startup,
util::function_nonser<void()> const& shutdown, hpx::runtime_mode mode)
{
return start(static_cast<hpx_main_type>(::hpx_main), desc_cmdline,
argc, argv, cfg, startup, shutdown, mode);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is a simplified main, non-blocking entry point, which can be used
/// to set up the runtime for an HPX application (the runtime system will
/// be set up in console mode or worker mode depending on the command line
/// settings). It will return immediatly after that. Use `hpx::wait` and
/// `hpx::stop` to synchronize with the runtime system's execution.
inline bool
start(int argc, char** argv, std::vector<std::string> const& cfg,
hpx::runtime_mode mode)
{
using boost::program_options::options_description;
options_description desc_commandline(
"Usage: " HPX_APPLICATION_STRING " [options]");
util::function_nonser<void()> const empty;
return start(desc_commandline, argc, argv, cfg, empty, empty, mode);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is a simplified main, non-blocking entry point, which can be used
/// to set up the runtime for an HPX application (the runtime system will
/// be set up in console mode or worker mode depending on the command line
/// settings). It will return immediatly after that. Use `hpx::wait` and
/// `hpx::stop` to synchronize with the runtime system's execution.
inline bool
start(boost::program_options::options_description const& desc_cmdline, int argc,
char** argv, hpx::runtime_mode mode)
{
util::function_nonser<void()> const empty;
return start(static_cast<hpx_main_type>(::hpx_main), desc_cmdline,
argc, argv, empty, empty, mode);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is a simplified main, non-blocking entry point, which can be used
/// to set up the runtime for an HPX application (the runtime system will
/// be set up in console mode or worker mode depending on the command line
/// settings). It will return immediatly after that. Use `hpx::wait` and
/// `hpx::stop` to synchronize with the runtime system's execution.
inline bool
start(std::string const& app_name, int argc, char** argv,
hpx::runtime_mode mode)
{
util::function_nonser<void()> const empty;
return start(static_cast<hpx_main_type>(::hpx_main), app_name, argc, argv,
empty, empty, mode);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is a simplified main, non-blocking entry point, which can be used
/// to set up the runtime for an HPX application (the runtime system will
/// be set up in console mode or worker mode depending on the command line
/// settings). It will return immediatly after that. Use `hpx::wait` and
/// `hpx::stop` to synchronize with the runtime system's execution.
inline bool start(int argc, char** argv, hpx::runtime_mode mode)
{
return start(static_cast<hpx_main_type>(::hpx_main),
HPX_APPLICATION_STRING, argc, argv, mode);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is a simplified main, non-blocking entry point, which can be used
/// to set up the runtime for an HPX application (the runtime system will
/// be set up in console mode or worker mode depending on the command line
/// settings). It will return immediatly after that. Use `hpx::wait` and
/// `hpx::stop` to synchronize with the runtime system's execution.
inline bool start(std::vector<std::string> const& cfg,
hpx::runtime_mode mode)
{
using boost::program_options::options_description;
options_description desc_commandline(
std::string("Usage: ") + HPX_APPLICATION_STRING + " [options]");
char *dummy_argv[2] = { const_cast<char*>(HPX_APPLICATION_STRING), 0 };
util::function_nonser<void()> const empty;
return start(static_cast<hpx_main_type>(::hpx_main), desc_commandline,
1, dummy_argv, cfg, empty, empty, mode);
}
/// \brief Main non-blocking entry point for launching the HPX runtime system.
///
/// This is a simplified main, non-blocking entry point, which can be used
/// to set up the runtime for an HPX application (the runtime system will
/// be set up in console mode or worker mode depending on the command line
/// settings). It will return immediatly after that. Use `hpx::wait` and
/// `hpx::stop` to synchronize with the runtime system's execution.
inline bool start(int (*f)(boost::program_options::variables_map& vm),
std::string const& app_name, int argc, char** argv,
hpx::runtime_mode mode)
{
using boost::program_options::options_description;
options_description desc_commandline(
"Usage: " + app_name + " [options]");
if (argc == 0 || argv == 0)
{
char *dummy_argv[2] = { const_cast<char*>(app_name.c_str()), 0 };
return start(desc_commandline, 1, dummy_argv, mode);
}
util::function_nonser<void()> const empty;
return start(f, desc_commandline, argc, argv, empty, empty, mode);
}
}
#endif
| 47.074419 | 91 | 0.671772 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.