code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package transmission
// Copyright 2015, JuanDeFu.ca. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
import (
"encoding/json"
"fmt"
"log"
"strings"
)
/*
Method name
torrent-add
*/
/*
Either "filename" OR "metainfo" MUST be included.
*/
/*
Response arguments:
On success, a "torrent-added" object contains
id, name, and hashString.
On failure due to a duplicate torrent existing,
a "torrent-duplicate" object in the same form.
*/
type Add_Argument struct {
Cookies string `json:"cookies,omitempty"`
DownloadDir string `json:"download-dir,omitempty"`
Filename string `json:"filename,omitempty"`
MetaInfo string `json:"metainfo,omitempty"`
Paused bool `json:"paused,omitempty"`
PeerLimit int `json:"peer-limit,omitempty"`
BandwidthPriority int `json:"bandwidthPriority,omitempty"`
FilesWanted []*File `json:"files-wanted,omitempty"`
FilesUnwanted []*File `json:"files-unwanted,omitempty"`
PriorityHigh []*File `json:"priority-high,omitempty"`
PriorityLow []*File `json:"priority-low,omitempty"`
PriorityNormal []*File `json:"priority-normal,omitempty"`
}
type Add_Response struct {
Torrent *Torrent `json:"torrent-added,omitempty"`
}
func (self *Client) AddTorrent(
location string,
path string,
) (
*Torrent,
error,
) {
if location == "" {
return nil, fmt.Errorf("Transmission.AddTorrent(): location empty")
}
if path == "" {
return nil, fmt.Errorf("Transmission.AddTorrent(): path empty")
}
if !strings.HasPrefix(path, "/") {
return nil, fmt.Errorf("Transmission.AddTorrent(): path doesn't start with /")
}
request := &Request{}
request.Method = "torrent-add"
access := Add_Argument{}
access.Filename = location
access.DownloadDir = path
request.Args = access
var result *Response
var err error
for i := 0; i < 5; i++ {
if result, err = self.Request(request); err == nil && result != nil {
if result.Result == "success" {
torrent := Add_Response{}
if err2 := json.Unmarshal(result.Args, &torrent); err2 != nil {
log.Printf("Transmission.AddTorrent(): failed to unmarshal %s | raw: %v\n", err2, result.Args)
} else {
return torrent.Torrent, nil
}
} else {
return nil, fmt.Errorf("Transmission.AddTorrent(): failed to add: %s", result.Result)
}
}
}
return nil, fmt.Errorf("Transmission.AddTorrent(): failed to get torrents: %s", err)
}
|
sabey/transmission
|
torrent_add.go
|
GO
|
bsd-3-clause
| 2,493 |
package main.data.core;
public interface Function<A, B> {
B apply(A a);
}
|
nhibberd/search
|
src/main/data/core/Function.java
|
Java
|
bsd-3-clause
| 79 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.team649.frc2014.subsystems;
import com.team649.frc2014.RobotMap;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kabi
*/
public class ClawRollerSubsystem extends Subsystem {
private final SpeedController motor;
public static final double ROLLER_SPIN_SHOOT_SPEED = 1;
public static final double ROLLER_SPIN_INTAKE_SPEED = -.4;
public static final double ROLLER_SPIN_PURGE_SPEED = .4;
public static final double ROLLER_SPIN_OFF_SPEED = 0;
public static final double ROLLER_SPIN_REALIGN_SPEED = -.2;
public ClawRollerSubsystem() {
motor = new Victor(RobotMap.CLAW_ROLLER.MOTOR);
}
protected void initDefaultCommand() {
}
public void runMotor(double speed) {
motor.set(speed);
}
}
|
SaratogaMSET/649code2014
|
src/com/team649/frc2014/subsystems/ClawRollerSubsystem.java
|
Java
|
bsd-3-clause
| 1,047 |
<?php
return array (
'Search' => 'Pesquisar',
);
|
LeonidLyalin/vova
|
common/humhub/protected/humhub/modules/search/messages/pt/base.php
|
PHP
|
bsd-3-clause
| 51 |
// 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 "ash/common/system/ime/tray_ime_chromeos.h"
#include <vector>
#include "ash/common/session/session_state_delegate.h"
#include "ash/common/system/chromeos/ime_menu/ime_list_view.h"
#include "ash/common/system/tray/hover_highlight_view.h"
#include "ash/common/system/tray/system_tray.h"
#include "ash/common/system/tray/system_tray_delegate.h"
#include "ash/common/system/tray/system_tray_notifier.h"
#include "ash/common/system/tray/tray_constants.h"
#include "ash/common/system/tray/tray_details_view.h"
#include "ash/common/system/tray/tray_item_more.h"
#include "ash/common/system/tray/tray_item_view.h"
#include "ash/common/system/tray/tray_utils.h"
#include "ash/common/system/tray_accessibility.h"
#include "ash/common/wm_shell.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "grit/ash_resources.h"
#include "grit/ash_strings.h"
#include "ui/accessibility/ax_enums.h"
#include "ui/accessibility/ax_view_state.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/keyboard/keyboard_util.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace tray {
// A |HoverHighlightView| that uses bold or normal font depending on whether
// it is selected. This view exposes itself as a checkbox to the accessibility
// framework.
class SelectableHoverHighlightView : public HoverHighlightView {
public:
SelectableHoverHighlightView(ViewClickListener* listener,
const base::string16& label,
bool selected)
: HoverHighlightView(listener), selected_(selected) {
AddLabel(label, gfx::ALIGN_LEFT, selected);
}
~SelectableHoverHighlightView() override {}
protected:
// Overridden from views::View.
void GetAccessibleState(ui::AXViewState* state) override {
HoverHighlightView::GetAccessibleState(state);
state->role = ui::AX_ROLE_CHECK_BOX;
if (selected_)
state->AddStateFlag(ui::AX_STATE_CHECKED);
}
private:
bool selected_;
DISALLOW_COPY_AND_ASSIGN(SelectableHoverHighlightView);
};
class IMEDefaultView : public TrayItemMore {
public:
explicit IMEDefaultView(SystemTrayItem* owner, const base::string16& label)
: TrayItemMore(owner, true) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetImage(bundle.GetImageNamed(IDR_AURA_UBER_TRAY_IME).ToImageSkia());
UpdateLabel(label);
}
~IMEDefaultView() override {}
void UpdateLabel(const base::string16& label) {
SetLabel(label);
SetAccessibleName(label);
}
private:
DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};
class IMEDetailedView : public ImeListView {
public:
IMEDetailedView(SystemTrayItem* owner,
LoginStatus login,
bool show_keyboard_toggle)
: ImeListView(owner, show_keyboard_toggle, ImeListView::HIDE_SINGLE_IME),
login_(login) {
SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate();
IMEInfoList list;
delegate->GetAvailableIMEList(&list);
IMEPropertyInfoList property_list;
delegate->GetCurrentIMEProperties(&property_list);
Update(list, property_list, show_keyboard_toggle,
ImeListView::HIDE_SINGLE_IME);
}
~IMEDetailedView() override {}
void Update(const IMEInfoList& list,
const IMEPropertyInfoList& property_list,
bool show_keyboard_toggle,
SingleImeBehavior single_ime_behavior) override {
ImeListView::Update(list, property_list, show_keyboard_toggle,
single_ime_behavior);
if (login_ != LoginStatus::NOT_LOGGED_IN && login_ != LoginStatus::LOCKED &&
!WmShell::Get()->GetSessionStateDelegate()->IsInSecondaryLoginScreen())
AppendSettings();
AppendHeaderEntry();
}
private:
// ImeListView:
void OnViewClicked(views::View* sender) override {
ImeListView::OnViewClicked(sender);
SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate();
if (sender == footer()->content()) {
TransitionToDefaultView();
} else if (sender == settings_) {
WmShell::Get()->RecordUserMetricsAction(
UMA_STATUS_AREA_IME_SHOW_DETAILED);
delegate->ShowIMESettings();
}
}
void AppendHeaderEntry() { CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this); }
void AppendSettings() {
HoverHighlightView* container = new HoverHighlightView(this);
container->AddLabel(
ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
IDS_ASH_STATUS_TRAY_IME_SETTINGS),
gfx::ALIGN_LEFT, false /* highlight */);
AddChildView(container);
settings_ = container;
}
LoginStatus login_;
views::View* settings_;
DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};
} // namespace tray
TrayIME::TrayIME(SystemTray* system_tray)
: SystemTrayItem(system_tray, UMA_IME),
tray_label_(NULL),
default_(NULL),
detailed_(NULL),
keyboard_suppressed_(false),
is_visible_(true) {
SystemTrayNotifier* tray_notifier = WmShell::Get()->system_tray_notifier();
tray_notifier->AddVirtualKeyboardObserver(this);
tray_notifier->AddAccessibilityObserver(this);
tray_notifier->AddIMEObserver(this);
}
TrayIME::~TrayIME() {
SystemTrayNotifier* tray_notifier = WmShell::Get()->system_tray_notifier();
tray_notifier->RemoveIMEObserver(this);
tray_notifier->RemoveAccessibilityObserver(this);
tray_notifier->RemoveVirtualKeyboardObserver(this);
}
void TrayIME::OnKeyboardSuppressionChanged(bool suppressed) {
keyboard_suppressed_ = suppressed;
Update();
}
void TrayIME::OnAccessibilityModeChanged(
AccessibilityNotificationVisibility notify) {
Update();
}
void TrayIME::Update() {
UpdateTrayLabel(current_ime_, ime_list_.size());
if (default_) {
default_->SetVisible(ShouldDefaultViewBeVisible());
default_->UpdateLabel(GetDefaultViewLabel(ime_list_.size() > 1));
}
if (detailed_)
detailed_->Update(ime_list_, property_list_, ShouldShowKeyboardToggle(),
ImeListView::HIDE_SINGLE_IME);
}
void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
if (tray_label_) {
bool visible = count > 1 && is_visible_;
tray_label_->SetVisible(visible);
// Do not change label before hiding because this change is noticeable.
if (!visible)
return;
if (current.third_party) {
tray_label_->label()->SetText(current.short_name +
base::UTF8ToUTF16("*"));
} else {
tray_label_->label()->SetText(current.short_name);
}
SetTrayLabelItemBorder(tray_label_, system_tray()->shelf_alignment());
tray_label_->Layout();
}
}
bool TrayIME::ShouldShowKeyboardToggle() {
return keyboard_suppressed_ &&
!WmShell::Get()->accessibility_delegate()->IsVirtualKeyboardEnabled();
}
base::string16 TrayIME::GetDefaultViewLabel(bool show_ime_label) {
if (show_ime_label) {
IMEInfo current;
WmShell::Get()->system_tray_delegate()->GetCurrentIME(¤t);
return current.name;
} else {
// Display virtual keyboard status instead.
int id = keyboard::IsKeyboardEnabled()
? IDS_ASH_STATUS_TRAY_KEYBOARD_ENABLED
: IDS_ASH_STATUS_TRAY_KEYBOARD_DISABLED;
return ui::ResourceBundle::GetSharedInstance().GetLocalizedString(id);
}
}
views::View* TrayIME::CreateTrayView(LoginStatus status) {
CHECK(tray_label_ == NULL);
tray_label_ = new TrayItemView(this);
tray_label_->CreateLabel();
SetupLabelForTray(tray_label_->label());
// Hide IME tray when it is created, it will be updated when it is notified
// of the IME refresh event.
tray_label_->SetVisible(false);
return tray_label_;
}
views::View* TrayIME::CreateDefaultView(LoginStatus status) {
CHECK(default_ == NULL);
default_ =
new tray::IMEDefaultView(this, GetDefaultViewLabel(ime_list_.size() > 1));
default_->SetVisible(ShouldDefaultViewBeVisible());
return default_;
}
views::View* TrayIME::CreateDetailedView(LoginStatus status) {
CHECK(detailed_ == NULL);
detailed_ =
new tray::IMEDetailedView(this, status, ShouldShowKeyboardToggle());
return detailed_;
}
void TrayIME::DestroyTrayView() {
tray_label_ = NULL;
}
void TrayIME::DestroyDefaultView() {
default_ = NULL;
}
void TrayIME::DestroyDetailedView() {
detailed_ = NULL;
}
void TrayIME::UpdateAfterLoginStatusChange(LoginStatus status) {}
void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) {
SetTrayLabelItemBorder(tray_label_, alignment);
tray_label_->Layout();
}
void TrayIME::OnIMERefresh() {
// Caches the current ime state.
SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate();
ime_list_.clear();
property_list_.clear();
delegate->GetCurrentIME(¤t_ime_);
delegate->GetAvailableIMEList(&ime_list_);
delegate->GetCurrentIMEProperties(&property_list_);
Update();
}
void TrayIME::OnIMEMenuActivationChanged(bool is_active) {
is_visible_ = !is_active;
if (is_visible_)
OnIMERefresh();
else
Update();
}
bool TrayIME::ShouldDefaultViewBeVisible() {
return is_visible_ && (ime_list_.size() > 1 || property_list_.size() > 1 ||
ShouldShowKeyboardToggle());
}
} // namespace ash
|
danakj/chromium
|
ash/common/system/ime/tray_ime_chromeos.cc
|
C++
|
bsd-3-clause
| 9,556 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\apidoc\helpers;
use phpDocumentor\Reflection\DocBlock\Type\Collection;
use yii\apidoc\models\MethodDoc;
use yii\apidoc\models\TypeDoc;
/**
* Class ApiMarkdownTrait
*
* @property TypeDoc $renderingContext
*/
trait ApiMarkdownTrait
{
/**
* @marker [[
*/
protected function parseApiLinks($text)
{
$context = $this->renderingContext;
if (preg_match('/^\[\[([\w\d\\\\\(\):$]+)(\|[^\]]*)?\]\]/', $text, $matches)) {
$offset = strlen($matches[0]);
$object = $matches[1];
$title = (empty($matches[2]) || $matches[2] == '|') ? null : substr($matches[2], 1);
if (($pos = strpos($object, '::')) !== false) {
$typeName = substr($object, 0, $pos);
$subjectName = substr($object, $pos + 2);
if ($context !== null) {
// Collection resolves relative types
$typeName = (new Collection([$typeName], $context->phpDocContext))->__toString();
}
/** @var $type TypeDoc */
$type = static::$renderer->apiContext->getType($typeName);
if ($type === null) {
static::$renderer->apiContext->errors[] = [
'file' => ($context !== null) ? $context->sourceFile : null,
'message' => 'broken link to ' . $typeName . '::' . $subjectName . (($context !== null) ? ' in ' . $context->name : ''),
];
return [
['brokenApiLink', '<span class="broken-link">' . $typeName . '::' . $subjectName . '</span>'],
$offset
];
} else {
if (($subject = $type->findSubject($subjectName)) !== null) {
if ($title === null) {
$title = $type->name . '::' . $subject->name;
if ($subject instanceof MethodDoc) {
$title .= '()';
}
}
return [
['apiLink', static::$renderer->createSubjectLink($subject, $title)],
$offset
];
} else {
static::$renderer->apiContext->errors[] = [
'file' => ($context !== null) ? $context->sourceFile : null,
'message' => 'broken link to ' . $type->name . '::' . $subjectName . (($context !== null) ? ' in ' . $context->name : ''),
];
return [
['brokenApiLink', '<span class="broken-link">' . $type->name . '::' . $subjectName . '</span>'],
$offset
];
}
}
} elseif ($context !== null && ($subject = $context->findSubject($object)) !== null) {
return [
['apiLink', static::$renderer->createSubjectLink($subject, $title)],
$offset
];
}
if ($context !== null) {
// Collection resolves relative types
$object = (new Collection([$object], $context->phpDocContext))->__toString();
}
if (($type = static::$renderer->apiContext->getType($object)) !== null) {
return [
['apiLink', static::$renderer->createTypeLink($type, null, $title)],
$offset
];
} elseif (strpos($typeLink = static::$renderer->createTypeLink($object, null, $title), '<a href') !== false) {
return [
['apiLink', $typeLink],
$offset
];
}
static::$renderer->apiContext->errors[] = [
'file' => ($context !== null) ? $context->sourceFile : null,
'message' => 'broken link to ' . $object . (($context !== null) ? ' in ' . $context->name : ''),
];
return [
['brokenApiLink', '<span class="broken-link">' . $object . '</span>'],
$offset
];
}
return [['text', '[['], 2];
}
/**
* Renders API link
* @param array $block
* @return string
*/
protected function renderApiLink($block)
{
return $block[1];
}
/**
* Renders API link that is broken i.e. points nowhere
* @param array $block
* @return string
*/
protected function renderBrokenApiLink($block)
{
return $block[1];
}
/**
* Consume lines for a blockquote element
*/
protected function consumeQuote($lines, $current)
{
$block = parent::consumeQuote($lines, $current);
$blockTypes = [
'warning',
'note',
'info',
'tip',
];
// check whether this is a special Info, Note, Warning, Tip block
$content = $block[0]['content'];
$first = reset($content);
if (isset($first[0]) && $first[0] === 'paragraph') {
$parfirst = reset($first['content']);
if (isset($parfirst[0]) && $parfirst[0] === 'text') {
foreach ($blockTypes as $type) {
if (strncasecmp("$type: ", $parfirst[1], $len = strlen($type) + 2) === 0) {
// remove block indicator
$block[0]['content'][0]['content'][0][1] = substr($parfirst[1], $len);
// add translated block indicator as bold text
array_unshift($block[0]['content'][0]['content'], [
'strong',
[
['text', $this->translateBlockType($type)],
],
]);
$block[0]['blocktype'] = $type;
break;
}
}
}
}
return $block;
}
protected abstract function translateBlockType($type);
/**
* Renders a blockquote
*/
protected function renderQuote($block)
{
$class = '';
if (isset($block['blocktype'])) {
$class = ' class="' . $block['blocktype'] . '"';
}
return "<blockquote{$class}>" . $this->renderAbsy($block['content']) . "</blockquote>\n";
}
}
|
Bladefidz/ocfa_yii
|
vendor/yiisoft/yii2-apidoc/helpers/ApiMarkdownTrait.php
|
PHP
|
bsd-3-clause
| 6,745 |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 OpenSimulator 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 DEVELOPERS ``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 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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
/// <summary>
/// This class stores and retrieves dynamic objects.
/// </summary>
/// <remarks>
/// Experimental - DO NOT USE. Does not yet have namespace support.
/// </remarks>
public class DOMap
{
private IDictionary<string, object> m_map;
private ReaderWriterLock m_mapRwLock = new ReaderWriterLock();
public void Add(string ns, string objName, object dynObj)
{
DAMap.ValidateNamespace(ns);
m_mapRwLock.AcquireWriterLock(-1);
try
{
if (m_map == null)
m_map = new Dictionary<string, object>();
m_map.Add(objName, dynObj);
}
finally
{
m_mapRwLock.ReleaseWriterLock();
}
}
public bool ContainsKey(string key)
{
m_mapRwLock.AcquireReaderLock(-1);
try
{
return Get(key) != null;
}
finally
{
m_mapRwLock.ReleaseReaderLock();
}
}
/// <summary>
/// Get a dynamic object
/// </summary>
/// <remarks>
/// Not providing an index method so that users can't casually overwrite each other's objects.
/// </remarks>
/// <param name='key'></param>
public object Get(string key)
{
m_mapRwLock.AcquireReaderLock(-1);
try
{
if (m_map == null)
return null;
else
return m_map[key];
}
finally
{
m_mapRwLock.ReleaseReaderLock();
}
}
public bool Remove(string key)
{
m_mapRwLock.AcquireWriterLock(-1);
try
{
if (m_map == null)
return false;
else
return m_map.Remove(key);
}
finally
{
m_mapRwLock.ReleaseWriterLock();
}
}
}
}
|
ft-/arribasim-dev-extras
|
OpenSim/Framework/DOMap.cs
|
C#
|
bsd-3-clause
| 4,063 |
// Copyright 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 "cc/layers/picture_layer_impl.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
#include "base/time/time.h"
#include "base/trace_event/trace_event_argument.h"
#include "cc/base/math_util.h"
#include "cc/debug/debug_colors.h"
#include "cc/debug/micro_benchmark_impl.h"
#include "cc/debug/traced_value.h"
#include "cc/layers/append_quads_data.h"
#include "cc/layers/solid_color_layer_impl.h"
#include "cc/output/begin_frame_args.h"
#include "cc/quads/checkerboard_draw_quad.h"
#include "cc/quads/debug_border_draw_quad.h"
#include "cc/quads/picture_draw_quad.h"
#include "cc/quads/solid_color_draw_quad.h"
#include "cc/quads/tile_draw_quad.h"
#include "cc/tiles/tile_manager.h"
#include "cc/tiles/tiling_set_raster_queue_all.h"
#include "cc/trees/layer_tree_impl.h"
#include "cc/trees/occlusion.h"
#include "ui/gfx/geometry/quad_f.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
namespace {
// This must be > 1 as we multiply or divide by this to find a new raster
// scale during pinch.
const float kMaxScaleRatioDuringPinch = 2.0f;
// When creating a new tiling during pinch, snap to an existing
// tiling's scale if the desired scale is within this ratio.
const float kSnapToExistingTilingRatio = 1.2f;
// Even for really wide viewports, at some point GPU raster should use
// less than 4 tiles to fill the viewport. This is set to 256 as a
// sane minimum for now, but we might want to tune this for low-end.
const int kMinHeightForGpuRasteredTile = 256;
// When making odd-sized tiles, round them up to increase the chances
// of using the same tile size.
const int kTileRoundUp = 64;
} // namespace
namespace cc {
PictureLayerImpl::PictureLayerImpl(
LayerTreeImpl* tree_impl,
int id,
bool is_mask,
scoped_refptr<SyncedScrollOffset> scroll_offset)
: LayerImpl(tree_impl, id, scroll_offset),
twin_layer_(nullptr),
tilings_(CreatePictureLayerTilingSet()),
ideal_page_scale_(0.f),
ideal_device_scale_(0.f),
ideal_source_scale_(0.f),
ideal_contents_scale_(0.f),
raster_page_scale_(0.f),
raster_device_scale_(0.f),
raster_source_scale_(0.f),
raster_contents_scale_(0.f),
low_res_raster_contents_scale_(0.f),
raster_source_scale_is_fixed_(false),
was_screen_space_transform_animating_(false),
only_used_low_res_last_append_quads_(false),
is_mask_(is_mask),
nearest_neighbor_(false) {
layer_tree_impl()->RegisterPictureLayerImpl(this);
}
PictureLayerImpl::~PictureLayerImpl() {
if (twin_layer_)
twin_layer_->twin_layer_ = nullptr;
layer_tree_impl()->UnregisterPictureLayerImpl(this);
}
const char* PictureLayerImpl::LayerTypeAsString() const {
return "cc::PictureLayerImpl";
}
scoped_ptr<LayerImpl> PictureLayerImpl::CreateLayerImpl(
LayerTreeImpl* tree_impl) {
return PictureLayerImpl::Create(tree_impl, id(), is_mask_,
synced_scroll_offset());
}
void PictureLayerImpl::PushPropertiesTo(LayerImpl* base_layer) {
PictureLayerImpl* layer_impl = static_cast<PictureLayerImpl*>(base_layer);
DCHECK_EQ(layer_impl->is_mask_, is_mask_);
LayerImpl::PushPropertiesTo(base_layer);
// Twin relationships should never change once established.
DCHECK_IMPLIES(twin_layer_, twin_layer_ == layer_impl);
DCHECK_IMPLIES(twin_layer_, layer_impl->twin_layer_ == this);
// The twin relationship does not need to exist before the first
// PushPropertiesTo from pending to active layer since before that the active
// layer can not have a pile or tilings, it has only been created and inserted
// into the tree at that point.
twin_layer_ = layer_impl;
layer_impl->twin_layer_ = this;
layer_impl->SetNearestNeighbor(nearest_neighbor_);
// Solid color layers have no tilings.
DCHECK_IMPLIES(raster_source_->IsSolidColor(), tilings_->num_tilings() == 0);
// The pending tree should only have a high res (and possibly low res) tiling.
DCHECK_LE(tilings_->num_tilings(),
layer_tree_impl()->create_low_res_tiling() ? 2u : 1u);
layer_impl->set_gpu_raster_max_texture_size(gpu_raster_max_texture_size_);
layer_impl->UpdateRasterSource(raster_source_, &invalidation_,
tilings_.get());
DCHECK(invalidation_.IsEmpty());
// After syncing a solid color layer, the active layer has no tilings.
DCHECK_IMPLIES(raster_source_->IsSolidColor(),
layer_impl->tilings_->num_tilings() == 0);
layer_impl->raster_page_scale_ = raster_page_scale_;
layer_impl->raster_device_scale_ = raster_device_scale_;
layer_impl->raster_source_scale_ = raster_source_scale_;
layer_impl->raster_contents_scale_ = raster_contents_scale_;
layer_impl->low_res_raster_contents_scale_ = low_res_raster_contents_scale_;
layer_impl->SanityCheckTilingState();
// We always need to push properties.
// See http://crbug.com/303943
// TODO(danakj): Stop always pushing properties since we don't swap tilings.
needs_push_properties_ = true;
}
void PictureLayerImpl::AppendQuads(RenderPass* render_pass,
AppendQuadsData* append_quads_data) {
// The bounds and the pile size may differ if the pile wasn't updated (ie.
// PictureLayer::Update didn't happen). In that case the pile will be empty.
DCHECK_IMPLIES(!raster_source_->GetSize().IsEmpty(),
bounds() == raster_source_->GetSize())
<< " bounds " << bounds().ToString() << " pile "
<< raster_source_->GetSize().ToString();
SharedQuadState* shared_quad_state =
render_pass->CreateAndAppendSharedQuadState();
if (raster_source_->IsSolidColor()) {
PopulateSharedQuadState(shared_quad_state);
AppendDebugBorderQuad(
render_pass, bounds(), shared_quad_state, append_quads_data);
SolidColorLayerImpl::AppendSolidQuads(
render_pass, draw_properties().occlusion_in_content_space,
shared_quad_state, visible_layer_rect(),
raster_source_->GetSolidColor(), append_quads_data);
return;
}
float max_contents_scale = MaximumTilingContentsScale();
PopulateScaledSharedQuadState(shared_quad_state, max_contents_scale);
Occlusion scaled_occlusion =
draw_properties()
.occlusion_in_content_space.GetOcclusionWithGivenDrawTransform(
shared_quad_state->quad_to_target_transform);
if (current_draw_mode_ == DRAW_MODE_RESOURCELESS_SOFTWARE) {
AppendDebugBorderQuad(
render_pass, shared_quad_state->quad_layer_bounds, shared_quad_state,
append_quads_data, DebugColors::DirectPictureBorderColor(),
DebugColors::DirectPictureBorderWidth(layer_tree_impl()));
gfx::Rect geometry_rect = shared_quad_state->visible_quad_layer_rect;
gfx::Rect opaque_rect = contents_opaque() ? geometry_rect : gfx::Rect();
gfx::Rect visible_geometry_rect =
scaled_occlusion.GetUnoccludedContentRect(geometry_rect);
if (visible_geometry_rect.IsEmpty())
return;
gfx::Rect quad_content_rect = shared_quad_state->visible_quad_layer_rect;
gfx::Size texture_size = quad_content_rect.size();
gfx::RectF texture_rect = gfx::RectF(texture_size);
PictureDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<PictureDrawQuad>();
quad->SetNew(shared_quad_state, geometry_rect, opaque_rect,
visible_geometry_rect, texture_rect, texture_size,
nearest_neighbor_, RGBA_8888, quad_content_rect,
max_contents_scale, raster_source_);
ValidateQuadResources(quad);
return;
}
AppendDebugBorderQuad(render_pass, shared_quad_state->quad_layer_bounds,
shared_quad_state, append_quads_data);
if (ShowDebugBorders()) {
for (PictureLayerTilingSet::CoverageIterator iter(
tilings_.get(), max_contents_scale,
shared_quad_state->visible_quad_layer_rect, ideal_contents_scale_);
iter; ++iter) {
SkColor color;
float width;
if (*iter && iter->draw_info().IsReadyToDraw()) {
TileDrawInfo::Mode mode = iter->draw_info().mode();
if (mode == TileDrawInfo::SOLID_COLOR_MODE) {
color = DebugColors::SolidColorTileBorderColor();
width = DebugColors::SolidColorTileBorderWidth(layer_tree_impl());
} else if (mode == TileDrawInfo::OOM_MODE) {
color = DebugColors::OOMTileBorderColor();
width = DebugColors::OOMTileBorderWidth(layer_tree_impl());
} else if (iter.resolution() == HIGH_RESOLUTION) {
color = DebugColors::HighResTileBorderColor();
width = DebugColors::HighResTileBorderWidth(layer_tree_impl());
} else if (iter.resolution() == LOW_RESOLUTION) {
color = DebugColors::LowResTileBorderColor();
width = DebugColors::LowResTileBorderWidth(layer_tree_impl());
} else if (iter->contents_scale() > max_contents_scale) {
color = DebugColors::ExtraHighResTileBorderColor();
width = DebugColors::ExtraHighResTileBorderWidth(layer_tree_impl());
} else {
color = DebugColors::ExtraLowResTileBorderColor();
width = DebugColors::ExtraLowResTileBorderWidth(layer_tree_impl());
}
} else {
color = DebugColors::MissingTileBorderColor();
width = DebugColors::MissingTileBorderWidth(layer_tree_impl());
}
DebugBorderDrawQuad* debug_border_quad =
render_pass->CreateAndAppendDrawQuad<DebugBorderDrawQuad>();
gfx::Rect geometry_rect = iter.geometry_rect();
gfx::Rect visible_geometry_rect = geometry_rect;
debug_border_quad->SetNew(shared_quad_state,
geometry_rect,
visible_geometry_rect,
color,
width);
}
}
// Keep track of the tilings that were used so that tilings that are
// unused can be considered for removal.
last_append_quads_tilings_.clear();
// Ignore missing tiles outside of viewport for tile priority. This is
// normally the same as draw viewport but can be independently overridden by
// embedders like Android WebView with SetExternalDrawConstraints.
gfx::Rect scaled_viewport_for_tile_priority = gfx::ScaleToEnclosingRect(
viewport_rect_for_tile_priority_in_content_space_, max_contents_scale);
size_t missing_tile_count = 0u;
size_t on_demand_missing_tile_count = 0u;
only_used_low_res_last_append_quads_ = true;
for (PictureLayerTilingSet::CoverageIterator iter(
tilings_.get(), max_contents_scale,
shared_quad_state->visible_quad_layer_rect, ideal_contents_scale_);
iter; ++iter) {
gfx::Rect geometry_rect = iter.geometry_rect();
gfx::Rect opaque_rect = contents_opaque() ? geometry_rect : gfx::Rect();
gfx::Rect visible_geometry_rect =
scaled_occlusion.GetUnoccludedContentRect(geometry_rect);
if (visible_geometry_rect.IsEmpty())
continue;
append_quads_data->visible_layer_area +=
visible_geometry_rect.width() * visible_geometry_rect.height();
bool has_draw_quad = false;
if (*iter && iter->draw_info().IsReadyToDraw()) {
const TileDrawInfo& draw_info = iter->draw_info();
switch (draw_info.mode()) {
case TileDrawInfo::RESOURCE_MODE: {
gfx::RectF texture_rect = iter.texture_rect();
// The raster_contents_scale_ is the best scale that the layer is
// trying to produce, even though it may not be ideal. Since that's
// the best the layer can promise in the future, consider those as
// complete. But if a tile is ideal scale, we don't want to consider
// it incomplete and trying to replace it with a tile at a worse
// scale.
if (iter->contents_scale() != raster_contents_scale_ &&
iter->contents_scale() != ideal_contents_scale_ &&
geometry_rect.Intersects(scaled_viewport_for_tile_priority)) {
append_quads_data->num_incomplete_tiles++;
}
TileDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<TileDrawQuad>();
quad->SetNew(shared_quad_state, geometry_rect, opaque_rect,
visible_geometry_rect, draw_info.resource_id(),
texture_rect, draw_info.resource_size(),
draw_info.contents_swizzled(), nearest_neighbor_);
ValidateQuadResources(quad);
iter->draw_info().set_was_ever_used_to_draw();
has_draw_quad = true;
break;
}
case TileDrawInfo::SOLID_COLOR_MODE: {
SolidColorDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect,
draw_info.solid_color(), false);
ValidateQuadResources(quad);
iter->draw_info().set_was_ever_used_to_draw();
has_draw_quad = true;
break;
}
case TileDrawInfo::OOM_MODE:
break; // Checkerboard.
}
}
if (!has_draw_quad) {
if (draw_checkerboard_for_missing_tiles()) {
CheckerboardDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<CheckerboardDrawQuad>();
SkColor color = DebugColors::DefaultCheckerboardColor();
quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect,
color, ideal_device_scale_);
} else {
SkColor color = SafeOpaqueBackgroundColor();
SolidColorDrawQuad* quad =
render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>();
quad->SetNew(shared_quad_state,
geometry_rect,
visible_geometry_rect,
color,
false);
ValidateQuadResources(quad);
}
if (geometry_rect.Intersects(scaled_viewport_for_tile_priority)) {
append_quads_data->num_missing_tiles++;
++missing_tile_count;
}
append_quads_data->approximated_visible_content_area +=
visible_geometry_rect.width() * visible_geometry_rect.height();
append_quads_data->checkerboarded_visible_content_area +=
visible_geometry_rect.width() * visible_geometry_rect.height();
continue;
}
if (iter.resolution() != HIGH_RESOLUTION) {
append_quads_data->approximated_visible_content_area +=
visible_geometry_rect.width() * visible_geometry_rect.height();
}
// If we have a draw quad, but it's not low resolution, then
// mark that we've used something other than low res to draw.
if (iter.resolution() != LOW_RESOLUTION)
only_used_low_res_last_append_quads_ = false;
if (last_append_quads_tilings_.empty() ||
last_append_quads_tilings_.back() != iter.CurrentTiling()) {
last_append_quads_tilings_.push_back(iter.CurrentTiling());
}
}
if (missing_tile_count) {
TRACE_EVENT_INSTANT2("cc",
"PictureLayerImpl::AppendQuads checkerboard",
TRACE_EVENT_SCOPE_THREAD,
"missing_tile_count",
missing_tile_count,
"on_demand_missing_tile_count",
on_demand_missing_tile_count);
}
// Aggressively remove any tilings that are not seen to save memory. Note
// that this is at the expense of doing cause more frequent re-painting. A
// better scheme would be to maintain a tighter visible_layer_rect for the
// finer tilings.
CleanUpTilingsOnActiveLayer(last_append_quads_tilings_);
}
bool PictureLayerImpl::UpdateTiles(bool resourceless_software_draw) {
if (!resourceless_software_draw) {
visible_rect_for_tile_priority_ = visible_layer_rect();
}
if (!CanHaveTilings()) {
ideal_page_scale_ = 0.f;
ideal_device_scale_ = 0.f;
ideal_contents_scale_ = 0.f;
ideal_source_scale_ = 0.f;
SanityCheckTilingState();
return false;
}
// Remove any non-ideal tilings that were not used last time we generated
// quads to save memory and processing time. Note that pending tree should
// only have one or two tilings (high and low res), so only clean up the
// active layer. This cleans it up here in case AppendQuads didn't run.
// If it did run, this would not remove any additional tilings.
if (layer_tree_impl()->IsActiveTree())
CleanUpTilingsOnActiveLayer(last_append_quads_tilings_);
UpdateIdealScales();
if (!raster_contents_scale_ || ShouldAdjustRasterScale()) {
RecalculateRasterScales();
AddTilingsForRasterScale();
}
DCHECK(raster_page_scale_);
DCHECK(raster_device_scale_);
DCHECK(raster_source_scale_);
DCHECK(raster_contents_scale_);
DCHECK(low_res_raster_contents_scale_);
was_screen_space_transform_animating_ =
draw_properties().screen_space_transform_is_animating;
if (draw_transform_is_animating())
raster_source_->SetShouldAttemptToUseDistanceFieldText();
double current_frame_time_in_seconds =
(layer_tree_impl()->CurrentBeginFrameArgs().frame_time -
base::TimeTicks()).InSecondsF();
UpdateViewportRectForTilePriorityInContentSpace();
// The tiling set can require tiles for activation any of the following
// conditions are true:
// - This layer produced a high-res or non-ideal-res tile last frame.
// - We're in requires high res to draw mode.
// - We're not in smoothness takes priority mode.
// To put different, the tiling set can't require tiles for activation if
// we're in smoothness mode and only used low-res or checkerboard to draw last
// frame and we don't need high res to draw.
//
// The reason for this is that we should be able to activate sooner and get a
// more up to date recording, so we don't run out of recording on the active
// tree.
bool can_require_tiles_for_activation =
!only_used_low_res_last_append_quads_ || RequiresHighResToDraw() ||
!layer_tree_impl()->SmoothnessTakesPriority();
static const Occlusion kEmptyOcclusion;
const Occlusion& occlusion_in_content_space =
layer_tree_impl()->settings().use_occlusion_for_tile_prioritization
? draw_properties().occlusion_in_content_space
: kEmptyOcclusion;
// Pass |occlusion_in_content_space| for |occlusion_in_layer_space| since
// they are the same space in picture layer, as contents scale is always 1.
bool updated = tilings_->UpdateTilePriorities(
viewport_rect_for_tile_priority_in_content_space_, ideal_contents_scale_,
current_frame_time_in_seconds, occlusion_in_content_space,
can_require_tiles_for_activation);
return updated;
}
void PictureLayerImpl::UpdateViewportRectForTilePriorityInContentSpace() {
// If visible_rect_for_tile_priority_ is empty or
// viewport_rect_for_tile_priority is set to be different from the device
// viewport, try to inverse project the viewport into layer space and use
// that. Otherwise just use visible_rect_for_tile_priority_
gfx::Rect visible_rect_in_content_space = visible_rect_for_tile_priority_;
gfx::Rect viewport_rect_for_tile_priority =
layer_tree_impl()->ViewportRectForTilePriority();
if (visible_rect_in_content_space.IsEmpty() ||
layer_tree_impl()->DeviceViewport() != viewport_rect_for_tile_priority) {
gfx::Transform view_to_layer(gfx::Transform::kSkipInitialization);
if (screen_space_transform().GetInverse(&view_to_layer)) {
// Transform from view space to content space.
visible_rect_in_content_space =
gfx::ToEnclosingRect(MathUtil::ProjectClippedRect(
view_to_layer, viewport_rect_for_tile_priority));
// We have to allow for a viewport that is outside of the layer bounds in
// order to compute tile priorities correctly for offscreen content that
// is going to make it on screen. However, we also have to limit the
// viewport since it can be very large due to screen_space_transforms. As
// a heuristic, we clip to bounds padded by skewport_extrapolation_limit *
// maximum tiling scale, since this should allow sufficient room for
// skewport calculations.
gfx::Rect padded_bounds(bounds());
int padding_amount = layer_tree_impl()
->settings()
.skewport_extrapolation_limit_in_content_pixels *
MaximumTilingContentsScale();
padded_bounds.Inset(-padding_amount, -padding_amount);
visible_rect_in_content_space.Intersect(padded_bounds);
}
}
viewport_rect_for_tile_priority_in_content_space_ =
visible_rect_in_content_space;
}
PictureLayerImpl* PictureLayerImpl::GetPendingOrActiveTwinLayer() const {
if (!twin_layer_ || !twin_layer_->IsOnActiveOrPendingTree())
return nullptr;
return twin_layer_;
}
void PictureLayerImpl::UpdateRasterSource(
scoped_refptr<RasterSource> raster_source,
Region* new_invalidation,
const PictureLayerTilingSet* pending_set) {
// The bounds and the pile size may differ if the pile wasn't updated (ie.
// PictureLayer::Update didn't happen). In that case the pile will be empty.
DCHECK_IMPLIES(!raster_source->GetSize().IsEmpty(),
bounds() == raster_source->GetSize())
<< " bounds " << bounds().ToString() << " pile "
<< raster_source->GetSize().ToString();
// The |raster_source_| is initially null, so have to check for that for the
// first frame.
bool could_have_tilings = raster_source_.get() && CanHaveTilings();
raster_source_.swap(raster_source);
// The |new_invalidation| must be cleared before updating tilings since they
// access the invalidation through the PictureLayerTilingClient interface.
invalidation_.Clear();
invalidation_.Swap(new_invalidation);
bool can_have_tilings = CanHaveTilings();
DCHECK_IMPLIES(
pending_set,
can_have_tilings == GetPendingOrActiveTwinLayer()->CanHaveTilings());
// Need to call UpdateTiles again if CanHaveTilings changed.
if (could_have_tilings != can_have_tilings)
layer_tree_impl()->set_needs_update_draw_properties();
if (!can_have_tilings) {
RemoveAllTilings();
return;
}
// We could do this after doing UpdateTiles, which would avoid doing this for
// tilings that are going to disappear on the pending tree (if scale changed).
// But that would also be more complicated, so we just do it here for now.
if (pending_set) {
tilings_->UpdateTilingsToCurrentRasterSourceForActivation(
raster_source_, pending_set, invalidation_, MinimumContentsScale(),
MaximumContentsScale());
} else {
tilings_->UpdateTilingsToCurrentRasterSourceForCommit(
raster_source_, invalidation_, MinimumContentsScale(),
MaximumContentsScale());
}
}
void PictureLayerImpl::UpdateCanUseLCDTextAfterCommit() {
// This function is only allowed to be called after commit, due to it not
// being smart about sharing tiles and because otherwise it would cause
// flashes by switching out tiles in place that may be currently on screen.
DCHECK(layer_tree_impl()->IsSyncTree());
// Don't allow the LCD text state to change once disabled.
if (!RasterSourceUsesLCDText())
return;
if (can_use_lcd_text() == RasterSourceUsesLCDText())
return;
// Raster sources are considered const, so in order to update the state
// a new one must be created and all tiles recreated.
scoped_refptr<RasterSource> new_raster_source =
raster_source_->CreateCloneWithoutLCDText();
raster_source_.swap(new_raster_source);
// Synthetically invalidate everything.
gfx::Rect bounds_rect(bounds());
invalidation_ = Region(bounds_rect);
tilings_->UpdateRasterSourceDueToLCDChange(raster_source_, invalidation_);
SetUpdateRect(bounds_rect);
DCHECK(!RasterSourceUsesLCDText());
}
bool PictureLayerImpl::RasterSourceUsesLCDText() const {
return raster_source_ ? raster_source_->CanUseLCDText()
: layer_tree_impl()->settings().can_use_lcd_text;
}
void PictureLayerImpl::NotifyTileStateChanged(const Tile* tile) {
if (layer_tree_impl()->IsActiveTree()) {
gfx::RectF layer_damage_rect =
gfx::ScaleRect(tile->content_rect(), 1.f / tile->contents_scale());
AddDamageRect(layer_damage_rect);
}
if (tile->draw_info().NeedsRaster()) {
PictureLayerTiling* tiling =
tilings_->FindTilingWithScale(tile->contents_scale());
if (tiling)
tiling->set_all_tiles_done(false);
}
}
void PictureLayerImpl::DidBeginTracing() {
raster_source_->DidBeginTracing();
}
void PictureLayerImpl::ReleaseResources() {
// Recreate tilings with new settings, since some of those might change when
// we release resources.
tilings_ = nullptr;
ResetRasterScale();
}
void PictureLayerImpl::RecreateResources() {
tilings_ = CreatePictureLayerTilingSet();
// To avoid an edge case after lost context where the tree is up to date but
// the tilings have not been managed, request an update draw properties
// to force tilings to get managed.
layer_tree_impl()->set_needs_update_draw_properties();
}
skia::RefPtr<SkPicture> PictureLayerImpl::GetPicture() {
return raster_source_->GetFlattenedPicture();
}
Region PictureLayerImpl::GetInvalidationRegion() {
// |invalidation_| gives the invalidation contained in the source frame, but
// is not cleared after drawing from the layer. However, update_rect() is
// cleared once the invalidation is drawn, which is useful for debugging
// visualizations. This method intersects the two to give a more exact
// representation of what was invalidated that is cleared after drawing.
return IntersectRegions(invalidation_, update_rect());
}
ScopedTilePtr PictureLayerImpl::CreateTile(float contents_scale,
const gfx::Rect& content_rect) {
int flags = 0;
// We don't handle solid color masks, so we shouldn't bother analyzing those.
// Otherwise, always analyze to maximize memory savings.
if (!is_mask_)
flags = Tile::USE_PICTURE_ANALYSIS;
return layer_tree_impl()->tile_manager()->CreateTile(
content_rect.size(), content_rect, contents_scale, id(),
layer_tree_impl()->source_frame_number(), flags);
}
const Region* PictureLayerImpl::GetPendingInvalidation() {
if (layer_tree_impl()->IsPendingTree())
return &invalidation_;
if (layer_tree_impl()->IsRecycleTree())
return nullptr;
DCHECK(layer_tree_impl()->IsActiveTree());
if (PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer())
return &twin_layer->invalidation_;
return nullptr;
}
const PictureLayerTiling* PictureLayerImpl::GetPendingOrActiveTwinTiling(
const PictureLayerTiling* tiling) const {
PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer();
if (!twin_layer)
return nullptr;
return twin_layer->tilings_->FindTilingWithScale(tiling->contents_scale());
}
bool PictureLayerImpl::RequiresHighResToDraw() const {
return layer_tree_impl()->RequiresHighResToDraw();
}
gfx::Rect PictureLayerImpl::GetEnclosingRectInTargetSpace() const {
return GetScaledEnclosingRectInTargetSpace(MaximumTilingContentsScale());
}
gfx::Size PictureLayerImpl::CalculateTileSize(
const gfx::Size& content_bounds) const {
int max_texture_size =
layer_tree_impl()->resource_provider()->max_texture_size();
if (is_mask_) {
// Masks are not tiled, so if we can't cover the whole mask with one tile,
// we shouldn't have such a tiling at all.
DCHECK_LE(content_bounds.width(), max_texture_size);
DCHECK_LE(content_bounds.height(), max_texture_size);
return content_bounds;
}
int default_tile_width = 0;
int default_tile_height = 0;
if (layer_tree_impl()->use_gpu_rasterization()) {
// For GPU rasterization, we pick an ideal tile size using the viewport
// so we don't need any settings. The current approach uses 4 tiles
// to cover the viewport vertically.
int viewport_width = gpu_raster_max_texture_size_.width();
int viewport_height = gpu_raster_max_texture_size_.height();
default_tile_width = viewport_width;
// Also, increase the height proportionally as the width decreases, and
// pad by our border texels to make the tiles exactly match the viewport.
int divisor = 4;
if (content_bounds.width() <= viewport_width / 2)
divisor = 2;
if (content_bounds.width() <= viewport_width / 4)
divisor = 1;
default_tile_height = MathUtil::RoundUp(viewport_height, divisor) / divisor;
// Grow default sizes to account for overlapping border texels.
default_tile_width += 2 * PictureLayerTiling::kBorderTexels;
default_tile_height += 2 * PictureLayerTiling::kBorderTexels;
default_tile_height =
std::max(default_tile_height, kMinHeightForGpuRasteredTile);
} else {
// For CPU rasterization we use tile-size settings.
const LayerTreeSettings& settings = layer_tree_impl()->settings();
int max_untiled_content_width = settings.max_untiled_layer_size.width();
int max_untiled_content_height = settings.max_untiled_layer_size.height();
default_tile_width = settings.default_tile_size.width();
default_tile_height = settings.default_tile_size.height();
// If the content width is small, increase tile size vertically.
// If the content height is small, increase tile size horizontally.
// If both are less than the untiled-size, use a single tile.
if (content_bounds.width() < default_tile_width)
default_tile_height = max_untiled_content_height;
if (content_bounds.height() < default_tile_height)
default_tile_width = max_untiled_content_width;
if (content_bounds.width() < max_untiled_content_width &&
content_bounds.height() < max_untiled_content_height) {
default_tile_height = max_untiled_content_height;
default_tile_width = max_untiled_content_width;
}
}
int tile_width = default_tile_width;
int tile_height = default_tile_height;
// Clamp the tile width/height to the content width/height to save space.
if (content_bounds.width() < default_tile_width) {
tile_width = std::min(tile_width, content_bounds.width());
tile_width = MathUtil::RoundUp(tile_width, kTileRoundUp);
tile_width = std::min(tile_width, default_tile_width);
}
if (content_bounds.height() < default_tile_height) {
tile_height = std::min(tile_height, content_bounds.height());
tile_height = MathUtil::RoundUp(tile_height, kTileRoundUp);
tile_height = std::min(tile_height, default_tile_height);
}
// Under no circumstance should we be larger than the max texture size.
tile_width = std::min(tile_width, max_texture_size);
tile_height = std::min(tile_height, max_texture_size);
return gfx::Size(tile_width, tile_height);
}
void PictureLayerImpl::GetContentsResourceId(ResourceId* resource_id,
gfx::Size* resource_size) const {
// The bounds and the pile size may differ if the pile wasn't updated (ie.
// PictureLayer::Update didn't happen). In that case the pile will be empty.
DCHECK_IMPLIES(!raster_source_->GetSize().IsEmpty(),
bounds() == raster_source_->GetSize())
<< " bounds " << bounds().ToString() << " pile "
<< raster_source_->GetSize().ToString();
gfx::Rect content_rect(bounds());
PictureLayerTilingSet::CoverageIterator iter(
tilings_.get(), 1.f, content_rect, ideal_contents_scale_);
// Mask resource not ready yet.
if (!iter || !*iter) {
*resource_id = 0;
return;
}
// Masks only supported if they fit on exactly one tile.
DCHECK(iter.geometry_rect() == content_rect)
<< "iter rect " << iter.geometry_rect().ToString() << " content rect "
<< content_rect.ToString();
const TileDrawInfo& draw_info = iter->draw_info();
if (!draw_info.IsReadyToDraw() ||
draw_info.mode() != TileDrawInfo::RESOURCE_MODE) {
*resource_id = 0;
return;
}
*resource_id = draw_info.resource_id();
*resource_size = draw_info.resource_size();
}
void PictureLayerImpl::SetNearestNeighbor(bool nearest_neighbor) {
if (nearest_neighbor_ == nearest_neighbor)
return;
nearest_neighbor_ = nearest_neighbor;
NoteLayerPropertyChanged();
}
PictureLayerTiling* PictureLayerImpl::AddTiling(float contents_scale) {
DCHECK(CanHaveTilings());
DCHECK_GE(contents_scale, MinimumContentsScale());
DCHECK_LE(contents_scale, MaximumContentsScale());
DCHECK(raster_source_->HasRecordings());
return tilings_->AddTiling(contents_scale, raster_source_);
}
void PictureLayerImpl::RemoveAllTilings() {
tilings_->RemoveAllTilings();
// If there are no tilings, then raster scales are no longer meaningful.
ResetRasterScale();
}
void PictureLayerImpl::AddTilingsForRasterScale() {
// Reset all resolution enums on tilings, we'll be setting new values in this
// function.
tilings_->MarkAllTilingsNonIdeal();
PictureLayerTiling* high_res =
tilings_->FindTilingWithScale(raster_contents_scale_);
// We always need a high res tiling, so create one if it doesn't exist.
if (!high_res)
high_res = AddTiling(raster_contents_scale_);
// Try and find a low res tiling.
PictureLayerTiling* low_res = nullptr;
if (raster_contents_scale_ == low_res_raster_contents_scale_)
low_res = high_res;
else
low_res = tilings_->FindTilingWithScale(low_res_raster_contents_scale_);
// Only create new low res tilings when the transform is static. This
// prevents wastefully creating a paired low res tiling for every new high res
// tiling during a pinch or a CSS animation.
bool can_have_low_res = layer_tree_impl()->create_low_res_tiling();
bool needs_low_res = !low_res;
bool is_pinching = layer_tree_impl()->PinchGestureActive();
bool is_animating = draw_properties().screen_space_transform_is_animating;
if (can_have_low_res && needs_low_res && !is_pinching && !is_animating)
low_res = AddTiling(low_res_raster_contents_scale_);
// Set low-res if we have one.
if (low_res && low_res != high_res)
low_res->set_resolution(LOW_RESOLUTION);
// Make sure we always have one high-res (even if high == low).
high_res->set_resolution(HIGH_RESOLUTION);
if (layer_tree_impl()->IsPendingTree()) {
// On the pending tree, drop any tilings that are non-ideal since we don't
// need them to activate anyway.
tilings_->RemoveNonIdealTilings();
}
SanityCheckTilingState();
}
bool PictureLayerImpl::ShouldAdjustRasterScale() const {
if (was_screen_space_transform_animating_ !=
draw_properties().screen_space_transform_is_animating)
return true;
if (draw_properties().screen_space_transform_is_animating &&
raster_contents_scale_ != ideal_contents_scale_ &&
ShouldAdjustRasterScaleDuringScaleAnimations())
return true;
bool is_pinching = layer_tree_impl()->PinchGestureActive();
if (is_pinching && raster_page_scale_) {
// We change our raster scale when it is:
// - Higher than ideal (need a lower-res tiling available)
// - Too far from ideal (need a higher-res tiling available)
float ratio = ideal_page_scale_ / raster_page_scale_;
if (raster_page_scale_ > ideal_page_scale_ ||
ratio > kMaxScaleRatioDuringPinch)
return true;
}
if (!is_pinching) {
// When not pinching, match the ideal page scale factor.
if (raster_page_scale_ != ideal_page_scale_)
return true;
}
// Always match the ideal device scale factor.
if (raster_device_scale_ != ideal_device_scale_)
return true;
// When the source scale changes we want to match it, but not when animating
// or when we've fixed the scale in place.
if (!draw_properties().screen_space_transform_is_animating &&
!raster_source_scale_is_fixed_ &&
raster_source_scale_ != ideal_source_scale_)
return true;
if (raster_contents_scale_ > MaximumContentsScale())
return true;
if (raster_contents_scale_ < MinimumContentsScale())
return true;
return false;
}
void PictureLayerImpl::RecalculateRasterScales() {
float old_raster_contents_scale = raster_contents_scale_;
float old_raster_page_scale = raster_page_scale_;
float old_raster_source_scale = raster_source_scale_;
raster_device_scale_ = ideal_device_scale_;
raster_page_scale_ = ideal_page_scale_;
raster_source_scale_ = ideal_source_scale_;
raster_contents_scale_ = ideal_contents_scale_;
// If we're not animating, or leaving an animation, and the
// ideal_source_scale_ changes, then things are unpredictable, and we fix
// the raster_source_scale_ in place.
if (old_raster_source_scale &&
!draw_properties().screen_space_transform_is_animating &&
!was_screen_space_transform_animating_ &&
old_raster_source_scale != ideal_source_scale_)
raster_source_scale_is_fixed_ = true;
// TODO(danakj): Adjust raster source scale closer to ideal source scale at
// a throttled rate. Possibly make use of invalidation_.IsEmpty() on pending
// tree. This will allow CSS scale changes to get re-rastered at an
// appropriate rate. (crbug.com/413636)
if (raster_source_scale_is_fixed_) {
raster_contents_scale_ /= raster_source_scale_;
raster_source_scale_ = 1.f;
}
// During pinch we completely ignore the current ideal scale, and just use
// a multiple of the previous scale.
bool is_pinching = layer_tree_impl()->PinchGestureActive();
if (is_pinching && old_raster_contents_scale) {
// See ShouldAdjustRasterScale:
// - When zooming out, preemptively create new tiling at lower resolution.
// - When zooming in, approximate ideal using multiple of kMaxScaleRatio.
bool zooming_out = old_raster_page_scale > ideal_page_scale_;
float desired_contents_scale = old_raster_contents_scale;
if (zooming_out) {
while (desired_contents_scale > ideal_contents_scale_)
desired_contents_scale /= kMaxScaleRatioDuringPinch;
} else {
while (desired_contents_scale < ideal_contents_scale_)
desired_contents_scale *= kMaxScaleRatioDuringPinch;
}
raster_contents_scale_ = tilings_->GetSnappedContentsScale(
desired_contents_scale, kSnapToExistingTilingRatio);
raster_page_scale_ =
raster_contents_scale_ / raster_device_scale_ / raster_source_scale_;
}
// If we're not re-rasterizing during animation, rasterize at the maximum
// scale that will occur during the animation, if the maximum scale is
// known. However we want to avoid excessive memory use. If the scale is
// smaller than what we would choose otherwise, then it's always better off
// for us memory-wise. But otherwise, we don't choose a scale at which this
// layer's rastered content would become larger than the viewport.
if (draw_properties().screen_space_transform_is_animating &&
!ShouldAdjustRasterScaleDuringScaleAnimations()) {
bool can_raster_at_maximum_scale = false;
bool should_raster_at_starting_scale = false;
float maximum_scale = draw_properties().maximum_animation_contents_scale;
float starting_scale = draw_properties().starting_animation_contents_scale;
if (maximum_scale) {
gfx::Size bounds_at_maximum_scale = gfx::ToCeiledSize(
gfx::ScaleSize(raster_source_->GetSize(), maximum_scale));
int64 maximum_area = static_cast<int64>(bounds_at_maximum_scale.width()) *
static_cast<int64>(bounds_at_maximum_scale.height());
gfx::Size viewport = layer_tree_impl()->device_viewport_size();
int64 viewport_area = static_cast<int64>(viewport.width()) *
static_cast<int64>(viewport.height());
if (maximum_area <= viewport_area)
can_raster_at_maximum_scale = true;
}
if (starting_scale && starting_scale > maximum_scale) {
gfx::Size bounds_at_starting_scale = gfx::ToCeiledSize(
gfx::ScaleSize(raster_source_->GetSize(), starting_scale));
int64 start_area = static_cast<int64>(bounds_at_starting_scale.width()) *
static_cast<int64>(bounds_at_starting_scale.height());
gfx::Size viewport = layer_tree_impl()->device_viewport_size();
int64 viewport_area = static_cast<int64>(viewport.width()) *
static_cast<int64>(viewport.height());
if (start_area <= viewport_area)
should_raster_at_starting_scale = true;
}
// Use the computed scales for the raster scale directly, do not try to use
// the ideal scale here. The current ideal scale may be way too large in the
// case of an animation with scale, and will be constantly changing.
if (should_raster_at_starting_scale)
raster_contents_scale_ = starting_scale;
else if (can_raster_at_maximum_scale)
raster_contents_scale_ = maximum_scale;
else
raster_contents_scale_ = 1.f * ideal_page_scale_ * ideal_device_scale_;
}
raster_contents_scale_ =
std::max(raster_contents_scale_, MinimumContentsScale());
raster_contents_scale_ =
std::min(raster_contents_scale_, MaximumContentsScale());
DCHECK_GE(raster_contents_scale_, MinimumContentsScale());
DCHECK_LE(raster_contents_scale_, MaximumContentsScale());
// If this layer would create zero or one tiles at this content scale,
// don't create a low res tiling.
gfx::Size raster_bounds = gfx::ToCeiledSize(
gfx::ScaleSize(raster_source_->GetSize(), raster_contents_scale_));
gfx::Size tile_size = CalculateTileSize(raster_bounds);
bool tile_covers_bounds = tile_size.width() >= raster_bounds.width() &&
tile_size.height() >= raster_bounds.height();
if (tile_size.IsEmpty() || tile_covers_bounds) {
low_res_raster_contents_scale_ = raster_contents_scale_;
return;
}
float low_res_factor =
layer_tree_impl()->settings().low_res_contents_scale_factor;
low_res_raster_contents_scale_ =
std::max(raster_contents_scale_ * low_res_factor, MinimumContentsScale());
DCHECK_LE(low_res_raster_contents_scale_, raster_contents_scale_);
DCHECK_GE(low_res_raster_contents_scale_, MinimumContentsScale());
DCHECK_LE(low_res_raster_contents_scale_, MaximumContentsScale());
}
void PictureLayerImpl::CleanUpTilingsOnActiveLayer(
const std::vector<PictureLayerTiling*>& used_tilings) {
DCHECK(layer_tree_impl()->IsActiveTree());
if (tilings_->num_tilings() == 0)
return;
float min_acceptable_high_res_scale = std::min(
raster_contents_scale_, ideal_contents_scale_);
float max_acceptable_high_res_scale = std::max(
raster_contents_scale_, ideal_contents_scale_);
PictureLayerImpl* twin = GetPendingOrActiveTwinLayer();
if (twin && twin->CanHaveTilings()) {
min_acceptable_high_res_scale = std::min(
min_acceptable_high_res_scale,
std::min(twin->raster_contents_scale_, twin->ideal_contents_scale_));
max_acceptable_high_res_scale = std::max(
max_acceptable_high_res_scale,
std::max(twin->raster_contents_scale_, twin->ideal_contents_scale_));
}
PictureLayerTilingSet* twin_set = twin ? twin->tilings_.get() : nullptr;
tilings_->CleanUpTilings(
min_acceptable_high_res_scale, max_acceptable_high_res_scale,
used_tilings, layer_tree_impl()->create_low_res_tiling(), twin_set);
DCHECK_GT(tilings_->num_tilings(), 0u);
SanityCheckTilingState();
}
float PictureLayerImpl::MinimumContentsScale() const {
float setting_min = layer_tree_impl()->settings().minimum_contents_scale;
// If the contents scale is less than 1 / width (also for height),
// then it will end up having less than one pixel of content in that
// dimension. Bump the minimum contents scale up in this case to prevent
// this from happening.
int min_dimension = std::min(raster_source_->GetSize().width(),
raster_source_->GetSize().height());
if (!min_dimension)
return setting_min;
return std::max(1.f / min_dimension, setting_min);
}
float PictureLayerImpl::MaximumContentsScale() const {
// Masks can not have tilings that would become larger than the
// max_texture_size since they use a single tile for the entire
// tiling. Other layers can have tilings of any scale.
if (!is_mask_)
return std::numeric_limits<float>::max();
int max_texture_size =
layer_tree_impl()->resource_provider()->max_texture_size();
float max_scale_width =
static_cast<float>(max_texture_size) / bounds().width();
float max_scale_height =
static_cast<float>(max_texture_size) / bounds().height();
float max_scale = std::min(max_scale_width, max_scale_height);
// We require that multiplying the layer size by the contents scale and
// ceiling produces a value <= |max_texture_size|. Because for large layer
// sizes floating point ambiguity may crop up, making the result larger or
// smaller than expected, we use a slightly smaller floating point value for
// the scale, to help ensure that the resulting content bounds will never end
// up larger than |max_texture_size|.
return nextafterf(max_scale, 0.f);
}
void PictureLayerImpl::ResetRasterScale() {
raster_page_scale_ = 0.f;
raster_device_scale_ = 0.f;
raster_source_scale_ = 0.f;
raster_contents_scale_ = 0.f;
low_res_raster_contents_scale_ = 0.f;
raster_source_scale_is_fixed_ = false;
}
bool PictureLayerImpl::CanHaveTilings() const {
if (raster_source_->IsSolidColor())
return false;
if (!DrawsContent())
return false;
if (!raster_source_->HasRecordings())
return false;
// If the |raster_source_| has a recording it should have non-empty bounds.
DCHECK(!raster_source_->GetSize().IsEmpty());
if (MaximumContentsScale() < MinimumContentsScale())
return false;
return true;
}
void PictureLayerImpl::SanityCheckTilingState() const {
#if DCHECK_IS_ON()
if (!CanHaveTilings()) {
DCHECK_EQ(0u, tilings_->num_tilings());
return;
}
if (tilings_->num_tilings() == 0)
return;
// We should only have one high res tiling.
DCHECK_EQ(1, tilings_->NumHighResTilings());
#endif
}
bool PictureLayerImpl::ShouldAdjustRasterScaleDuringScaleAnimations() const {
return layer_tree_impl()->use_gpu_rasterization();
}
float PictureLayerImpl::MaximumTilingContentsScale() const {
float max_contents_scale = tilings_->GetMaximumContentsScale();
return std::max(max_contents_scale, MinimumContentsScale());
}
scoped_ptr<PictureLayerTilingSet>
PictureLayerImpl::CreatePictureLayerTilingSet() {
const LayerTreeSettings& settings = layer_tree_impl()->settings();
return PictureLayerTilingSet::Create(
GetTree(), this, settings.max_tiles_for_interest_area,
layer_tree_impl()->use_gpu_rasterization()
? settings.gpu_rasterization_skewport_target_time_in_seconds
: settings.skewport_target_time_in_seconds,
settings.skewport_extrapolation_limit_in_content_pixels);
}
void PictureLayerImpl::UpdateIdealScales() {
DCHECK(CanHaveTilings());
float min_contents_scale = MinimumContentsScale();
DCHECK_GT(min_contents_scale, 0.f);
ideal_page_scale_ = IsAffectedByPageScale()
? layer_tree_impl()->current_page_scale_factor()
: 1.f;
ideal_device_scale_ = layer_tree_impl()->device_scale_factor();
ideal_contents_scale_ =
std::max(draw_properties().ideal_contents_scale, min_contents_scale);
ideal_source_scale_ =
ideal_contents_scale_ / ideal_page_scale_ / ideal_device_scale_;
}
void PictureLayerImpl::GetDebugBorderProperties(
SkColor* color,
float* width) const {
*color = DebugColors::TiledContentLayerBorderColor();
*width = DebugColors::TiledContentLayerBorderWidth(layer_tree_impl());
}
void PictureLayerImpl::GetAllPrioritizedTilesForTracing(
std::vector<PrioritizedTile>* prioritized_tiles) const {
if (!tilings_)
return;
tilings_->GetAllPrioritizedTilesForTracing(prioritized_tiles);
}
void PictureLayerImpl::AsValueInto(
base::trace_event::TracedValue* state) const {
LayerImpl::AsValueInto(state);
state->SetDouble("ideal_contents_scale", ideal_contents_scale_);
state->SetDouble("geometry_contents_scale", MaximumTilingContentsScale());
state->BeginArray("tilings");
tilings_->AsValueInto(state);
state->EndArray();
MathUtil::AddToTracedValue("tile_priority_rect",
viewport_rect_for_tile_priority_in_content_space_,
state);
MathUtil::AddToTracedValue("visible_rect", visible_layer_rect(), state);
state->BeginArray("pictures");
raster_source_->AsValueInto(state);
state->EndArray();
state->BeginArray("invalidation");
invalidation_.AsValueInto(state);
state->EndArray();
state->BeginArray("coverage_tiles");
for (PictureLayerTilingSet::CoverageIterator iter(
tilings_.get(), 1.f, gfx::Rect(raster_source_->GetSize()),
ideal_contents_scale_);
iter; ++iter) {
state->BeginDictionary();
MathUtil::AddToTracedValue("geometry_rect", iter.geometry_rect(), state);
if (*iter)
TracedValue::SetIDRef(*iter, state, "tile");
state->EndDictionary();
}
state->EndArray();
}
size_t PictureLayerImpl::GPUMemoryUsageInBytes() const {
return tilings_->GPUMemoryUsageInBytes();
}
void PictureLayerImpl::RunMicroBenchmark(MicroBenchmarkImpl* benchmark) {
benchmark->RunOnLayer(this);
}
WhichTree PictureLayerImpl::GetTree() const {
return layer_tree_impl()->IsActiveTree() ? ACTIVE_TREE : PENDING_TREE;
}
bool PictureLayerImpl::IsOnActiveOrPendingTree() const {
return !layer_tree_impl()->IsRecycleTree();
}
bool PictureLayerImpl::HasValidTilePriorities() const {
return IsOnActiveOrPendingTree() && IsDrawnRenderSurfaceLayerListMember();
}
} // namespace cc
|
SaschaMester/delicium
|
cc/layers/picture_layer_impl.cc
|
C++
|
bsd-3-clause
| 50,012 |
require 'spec_helper'
describe 'OrderPreferencesBuilder' do
# Factory order_with_line_items is incredibly slow..
let(:order) do
order = create :order
create_list :line_item, 2, order:order
order.line_items.reload
order.update!
order
end
let!(:adjustment) { order.adjustments.create! label: 'Descuento', amount:-10.0, order: order}
let(:payment) { create :payment }
let(:callback_urls) { {success: 'http://example.com/success', pending: 'http://example.com/pending', failure: 'http://example.com/failure'}}
let(:payer_data) { {email: 'jmperez@devartis.com'}}
include ActionView::Helpers::TextHelper
include ActionView::Helpers::SanitizeHelper
include Spree::ProductsHelper
context "Calling preferences_hash" do
subject { Spree::MercadoPago::OrderPreferencesBuilder.new(order, payment, callback_urls, payer_data).preferences_hash }
it 'should return external reference' do
expect(subject).to include(external_reference:payment.identifier)
end
it 'should set callback urls' do
expect(subject).to include(back_urls:callback_urls)
end
it 'should set payer data if brought' do
expect(subject).to include(payer: payer_data)
end
it 'should set an item for every line item' do
expect(subject).to include(:items)
order.line_items.each do |line_item|
expect(subject[:items]).to include({
title: line_item_description_text(line_item.variant.product.name),
unit_price: line_item.price.to_f,
quantity: line_item.quantity.to_f,
currency_id: 'ARS'
})
end
end
it 'should set its adjustments as items' do
expect(subject[:items]).to include({
title: line_item_description_text(adjustment.label),
unit_price: adjustment.amount.to_f,
quantity: 1,
currency_id: 'ARS'
})
end
it 'should only have line items and adjustments in items' do
expect(subject[:items]).to have(order.line_items.count + order.adjustments.count).items
end
end
end
|
devartis/Spree-Mercado-Pago-payment-method
|
spec/models/spree/mercado_pago/order_preferences_builder_spec.rb
|
Ruby
|
bsd-3-clause
| 2,062 |
#from django.conf import settings
#settings.INSTALLED_APPS += ("mptt", "hvad", "galleries",)
|
marcopompili/django-market
|
django_market/__init__.py
|
Python
|
bsd-3-clause
| 94 |
package com.andymark.crosslink;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class UpdateJaguarPacket implements Message {
private short[] uiMode = new short[20];
private short[] uiSetVoltage = new short[20];
@Override
public ByteBuffer getMessage() {
for (int i = 16; i < 20; i++) {
uiMode[i] = (short) 0xffff;
}
uiSetVoltage[1] = (short) 0x1999;
ByteBuffer buffer = ByteBuffer.allocate(86);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort((short) 0xaaa0); // sig
buffer.putShort((short) 86); // byte len
for (short val : uiMode) {
buffer.putShort(val);
}
for (short val : uiSetVoltage) {
buffer.putShort(val);
}
short checksum = (short) Utilities.checksum(buffer, 0, 84);
buffer.putShort(checksum);
return buffer;
}
}
|
AndyMark/AMCrosslink-Java
|
src/com/andymark/crosslink/UpdateJaguarPacket.java
|
Java
|
bsd-3-clause
| 811 |
function installthis(id)
{
var answer = confirm('Are you sure ? ');
if (answer){
//delete img...
$.post(base_url+'/zfmodules/index/installmod/id/'+id, function(data){
window.location.reload(false);
});
}
}
function installnotvalidthis(id)
{
var answer = confirm('Your module is not valid,\n if you continue, it\'s will be installed to another unique name,\n Are You sure ?');
if (answer){
//delete img...
$.post(base_url+'/zfmodules/index/installmodtovalid/id/'+id, function(data){
window.location.reload(false);
});
}
}
|
samsonasik/zf_111_support_php532_with_modulewizard
|
public/themes/zend_prj/js/modules/modules.js
|
JavaScript
|
bsd-3-clause
| 751 |
from rdr_service.model.genomics import GenomicGCValidationMetrics, GenomicSetMember
from rdr_service.tools.tool_libs.tool_base import cli_run, ToolBase
tool_cmd = 'backfill-gvcf'
tool_desc = 'Backfill the gVCF paths in genomic_gc_validation_metrics'
class GVcfBackfillTool(ToolBase):
def run(self):
super(GVcfBackfillTool, self).run()
# Get list of paths
path_list = self.get_paths_from_file()
for path in path_list:
sample_id = self.get_sample_id_from_gvcf_path(path)
metric = self.get_metric_from_sample_id(sample_id)
self.update_metric_gvcf_path(metric, path)
def get_paths_from_file(self):
path_set = set()
with open(self.args.input_file, encoding='utf-8-sig') as f:
lines = f.readlines()
for line in lines:
path_set.add(line.strip())
return list(path_set)
@staticmethod
def get_sample_id_from_gvcf_path(path):
# Based on naming convention:
# gs://prod-genomics-data-northwest/Wgs_sample_raw_data/
# SS_VCF_research/UW_A100329930_21055000718_702252_v1.hard-filtered.gvcf.gz
return path.split("_")[7]
def get_metric_from_sample_id(self, sample_id):
with self.get_session() as session:
return session.query(GenomicGCValidationMetrics).join(
GenomicSetMember,
GenomicSetMember.id == GenomicGCValidationMetrics.genomicSetMemberId
).filter(
GenomicSetMember.sampleId == sample_id
).one_or_none()
def update_metric_gvcf_path(self, metric, path):
if self.args.md5:
metric.gvcfMd5Received = 1
metric.gvcfMd5Path = path
else:
metric.gvcfReceived = 1
metric.gvcfPath = path
with self.get_session() as session:
session.merge(metric)
def add_additional_arguments(parser):
parser.add_argument('--input-file', required=True, help='path of text file with list of gVCF paths')
parser.add_argument('--md5', required=False, action="store_true", help='backfilling md5 files')
def run():
return cli_run(tool_cmd, tool_desc, GVcfBackfillTool, add_additional_arguments)
|
all-of-us/raw-data-repository
|
rdr_service/tools/tool_libs/backfill_gvcf_paths.py
|
Python
|
bsd-3-clause
| 2,248 |
// Copyright 2014 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.
// This clang plugin checks various invariants of the Blink garbage
// collection infrastructure.
//
// Checks that are implemented:
// [currently none]
#include "Config.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
using namespace clang;
using std::string;
namespace {
struct BlinkGCPluginOptions {
BlinkGCPluginOptions() {
}
};
// Main class containing checks for various invariants of the Blink
// garbage collection infrastructure.
class BlinkGCPluginConsumer : public ASTConsumer {
public:
BlinkGCPluginConsumer(CompilerInstance& instance,
const BlinkGCPluginOptions& options) {
}
virtual void HandleTranslationUnit(ASTContext& context) {
// FIXME: implement consistency checks.
}
};
class BlinkGCPluginAction : public PluginASTAction {
public:
BlinkGCPluginAction() {
}
protected:
// Overridden from PluginASTAction:
virtual ASTConsumer* CreateASTConsumer(CompilerInstance& instance,
llvm::StringRef ref) {
return new BlinkGCPluginConsumer(instance, options_);
}
virtual bool ParseArgs(const CompilerInstance& instance,
const std::vector<string>& args) {
bool parsed = true;
for (size_t i = 0; i < args.size() && parsed; ++i) {
if (args[i] == "enable-oilpan") {
// TODO: Remove this once all transition types are eliminated.
Config::set_oilpan_enabled(true);
} else {
parsed = false;
llvm::errs() << "Unknown blink-gc-plugin argument: " << args[i] << "\n";
}
}
return parsed;
}
private:
BlinkGCPluginOptions options_;
};
} // namespace
bool Config::oilpan_enabled_ = false;
static FrontendPluginRegistry::Add<BlinkGCPluginAction>
X("blink-gc-plugin", "Check Blink GC invariants");
|
ChromiumWebApps/chromium
|
tools/clang/blink_gc_plugin/BlinkGCPlugin.cpp
|
C++
|
bsd-3-clause
| 2,082 |
using Shuttle.Core.Data;
using Shuttle.Core.Infrastructure;
namespace Shuttle.Scheduling
{
public class ScheduleQuery : IScheduleQuery
{
private readonly IDatabaseGateway _databaseGateway;
private readonly IScheduleQueryFactory _queryFactory;
public ScheduleQuery(IDatabaseGateway databaseGateway, IScheduleQueryFactory queryFactory)
{
Guard.AgainstNull(databaseGateway, "databaseGateway");
Guard.AgainstNull(queryFactory, "queryFactory");
_databaseGateway = databaseGateway;
_queryFactory = queryFactory;
}
public bool HasScheduleStructures(DataSource source)
{
return _databaseGateway.GetScalarUsing<int>(source, _queryFactory.HasScheduleStructures()) == 1;
}
}
}
|
yonglehou/shuttle-scheduling
|
Shuttle.Scheduling/DataAccess/Queries/ScheduleQuery.cs
|
C#
|
bsd-3-clause
| 703 |
#!/usr/bin/python2
"""Syncs to a given Cobalt build id.
Syncs current gclient instance to a given build id, as
generated by "build_id.py" and stored on carbon-airlock-95823.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import json
import os
import shutil
import subprocess
import sys
import requests
_BUILD_ID_QUERY_URL = (
"https://carbon-airlock-95823.appspot.com/build_version/search")
_BUILD_ID_QUERY_PARAMETER_NAME = "build_number"
class SubprocessFailedException(Exception):
"""Exception for non-zero subprocess exits."""
def __init__(self, command):
super(SubprocessFailedException, self).__init__() # pylint: disable=super-with-arguments
self.command = command
def __str__(self):
return "Subprocess failed '{0}'".format(self.command)
def _RunGitCommand(gitargs, **kwargs):
"""Runs a git command with "gitargs", returning the output splitlines().
Args:
gitargs: Commandline args that follow 'git'.
**kwargs: Keyword args for Popen.
Returns:
All of stdout, as an array of lines.
Raises:
SubprocessFailedException: if the exit code is nonzero.
"""
result_tuple = _RunGitCommandReturnExitCode(gitargs, **kwargs)
if result_tuple[0] != 0:
raise SubprocessFailedException(" ".join(["git"] + gitargs))
return result_tuple[1]
def _RunGitCommandReturnExitCode(gitargs, **kwargs):
"""Runs a git command with "gitargs", returning the exit code and output.
Args:
gitargs: Commandline args that follow 'git'.
**kwargs: Keyword args for Popen.
Returns:
Tuple of (exit code, all of stdout as an array of lines).
"""
popen_args = ["git"] + gitargs
with subprocess.Popen(popen_args, stdout=subprocess.PIPE, **kwargs) as p:
output = p.stdout.read().splitlines()
return p.wait(), output
def main():
dev_null = open(os.devnull, "w") # pylint: disable=consider-using-with
arg_parser = argparse.ArgumentParser(
description="Syncs to a given Cobalt build id")
arg_parser.add_argument("buildid", nargs=1)
arg_parser.add_argument(
"--force",
default=False,
action="store_true",
help="Deletes directories that don't match the requested format.")
args = arg_parser.parse_args()
r = requests.get(
_BUILD_ID_QUERY_URL,
params={_BUILD_ID_QUERY_PARAMETER_NAME: args.buildid[0]})
if not r.ok:
print(
"HTTP request failed\n{0} {1}\n{2}".format(r.status_code, r.reason,
r.text),
file=sys.stderr)
return 1
# The response starts with a security-related close expression line
outer_json = json.loads(r.text.splitlines()[1])
hashes = json.loads(outer_json["deps"])
git_root = os.getcwd()
for relpath, rep_hash in hashes.items():
path = os.path.normpath(os.path.join(git_root, relpath))
if not os.path.exists(path):
# No warning in this case, we will attempt to clone the repository in
# the next pass through the repos.
continue
is_dirty = (
bool(
_RunGitCommandReturnExitCode(["diff", "--no-ext-diff", "--quiet"],
cwd=path,
stderr=dev_null)[0]) or
bool(
_RunGitCommandReturnExitCode(
["diff", "--no-ext-diff", "--quiet", "--cached"],
cwd=path,
stderr=dev_null)[0]))
if is_dirty:
print("{0} is dirty, please resolve".format(relpath))
return 1
(requested_repo, _) = rep_hash.split("@")
remote_url = _RunGitCommand(["config", "--get", "remote.origin.url"],
cwd=path)[0].strip().decode("utf-8")
if requested_repo.endswith(".git"):
if remote_url + ".git" == requested_repo:
print(("WARNING: You are syncing to {0} instead of {1}. While these "
"point to the same repo, the differing extension will cause "
"different build ids to be generated. If you need the same "
"id, you'll need to specifically clone {0} (note the .git "
"extension).").format(requested_repo, remote_url))
remote_url += ".git"
if remote_url != requested_repo:
if args.force and path != git_root:
shutil.rmtree(path)
else:
print(("{0} exists but does not point to the requested repo for that "
"path, {1}. Either replace that directory manually or run this "
"script with --force. --force will not try to remove the top "
"level repository.").format(path, requested_repo))
return 1
for relpath, rep_hash in hashes.items():
path = os.path.normpath(os.path.join(git_root, relpath))
# repo_hash has a repo path prefix like this:
# 'https://chromium.googlesource.com/chromium/llvm-project/libcxx.git
# @48198f9110397fff47fe7c37cbfa296be7d44d3d'
(requested_repo, requested_hash) = rep_hash.split("@")
if not os.path.exists(path):
print("Missing path {0}, cloning from {1}.".format(path, requested_repo))
try:
# The clone command will create all missing directories leading to the
# path. If the clone is successful, we continue on as usual and let
# the subsequent logic here checkout the appropriate git hash.
_RunGitCommand(["clone", "-q", requested_repo, path])
except SubprocessFailedException:
print("There was an error cloning the repository.")
continue
current_hash = _RunGitCommand(["rev-parse", "HEAD"], cwd=path)[0]
if requested_hash == current_hash:
continue
symbolic_ref = None
try:
symbolic_ref = _RunGitCommand(["symbolic-ref", "--short", "-q", "HEAD"],
cwd=path,
stderr=dev_null)[0]
except SubprocessFailedException:
pass
user_visible_commit = symbolic_ref if symbolic_ref else current_hash[0:7]
print("{0} was at {1} now {2}".format(path, user_visible_commit,
requested_hash[0:7]))
_RunGitCommand(["checkout", "-q", "--detach", requested_hash], cwd=path)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except SubprocessFailedException as ex:
print(str(ex), file=sys.stderr)
sys.exit(1)
|
youtube/cobalt
|
cobalt/build/sync_to_build_id.py
|
Python
|
bsd-3-clause
| 6,399 |
class LineItemController < ApplicationController
end
|
voidstart/ror_depot_reboot_1
|
app/controllers/line_item_controller.rb
|
Ruby
|
bsd-3-clause
| 53 |
from models import *
from django.db import connection
import collections
import time
import calendar
def GetCreditCardList(contactid):
cards_list = []
orders = Orders.objects.all().filter(ocustomerid = contactid)
cards_hash = {}
for order in orders:
if order.ocardno:
if order.ocardno not in cards_hash:
cards_hash[order.ocardno] = "Card Ending in %s" %order.ocardno[-4:]
# Preparing Cards List
cards_list = []
for key, value in cards_hash.items():
cards_list.append((key, value))
return cards_list
def GenerateShippingCalander():
month = [['', '', '','','', '', ''],
['', '', '','','', '', ''],
['', '', '','','', '', ''],
['', '', '','','', '', ''],
['', '', '','','', '', ''],
['', '', '','','', '', ''],
]
today = time.localtime().tm_mday
start_time = time.strptime("2013/06/01", "%Y/%m/01")
day = start_time.tm_mday
wday = start_time.tm_wday
last_day = calendar.monthrange(start_time.tm_year, start_time.tm_mon)[1]
row_no = 0
while day <= last_day:
cur_time = time.strptime(time.strftime("%Y/%m/" + str(day), start_time), "%Y/%m/%d")
day = cur_time.tm_mday
wday = cur_time.tm_wday
script = ''
bgcolor = "#FFFFFF"
if day < today:
bgcolor = "#999999"
elif day == today:
bgcolor = "#CC9966"
elif day == today + 1:
bgcolor = "#99CC00"
script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time)
elif day == today + 2:
bgcolor = "#663366"
script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time)
elif day > today + 2:
bgcolor = "#00CCCC"
script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time)
if day >= today:
if wday == 6:
bgcolor = "#DB9E9B"
script = ''
elif wday == 5:
script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time)
bgcolor = "#FFCC33"
day_hash = {'wday': wday, 'day': day, 'bgcolor':bgcolor, 'script':script}
month[row_no][wday] = day_hash
if wday == 6:
row_no += 1
day += 1
return month
def GetPriorityShippingCharge(category_id):
shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0]
return shipping_cat_obj.priority_shipping
def GetSaturdayShippingCharge(category_id):
shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0]
return shipping_cat_obj.saturday_delivery
def GetAlaskaShippingCharge(category_id):
shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0]
return shipping_cat_obj.alaska_delivery
class Error(object):
def __init__(self):
self.IsError = False
self._error_number = 0
self._error_message = ''
def RaiseError(self, p_message):
self.IsError = True
self._error_message = p_message
def Error(self):
self.IsError = False;
msg = self._error_message
self._error_message = ""
return msg
class StoreCredit(object):
def __init__(self):
self.id = 0
self.credit_value = 0.0
class MyShippingCategory(object):
def __init__(self):
self.id = -1
self.shipping_charge = 0.0
self.fuel_charge = 0.0
self.tax = 0.0
self.tax_value = 0.0
self.promotions = 0.0
self.shipping_value = 0.0
self.supplies_total = 0.0
self.freeshipping_diff = 0.0
self.shipping_items = []
class CartInfo(Error):
'''Holds final order summary of the Cart'''
def __init__(self):
super(CartInfo, self).__init__()
self.subtotal = 0.0
self.shipping_total = 0.0
self.fuelcharge_total = 0.0
self.tax_total = 0.0
self.promotions_total = 0
self.store_credit = 0.0
self.order_total = 0.0
self.is_storecredit_applied = False
self.store_credit_id = 0
self.store_credit = 0.0
self.cc_approval_code = ''
def ApplyStoreCredit(self, obj):
self.store_credit_id = obj.id
credit_value = obj.credit_value
self.store_credit = credit_value
if self.order_total >= self.store_credit:
self.order_total -= self.store_credit
self.store_credit = 0
elif self.order_total < self.store_credit and self.order_total > 0:
self.store_credit -= self.order_total
self.order_total = 0
def GetShippingCategoryID(self, catalog_id):
#pc_object = ProductCategory.objects.get(catalogid=catalog_id)
#psc_object = ProductShippingCategories.objects.get(product_category_id = pc_object.categoryid)
cursor = connection.cursor()
cursor.execute("SELECT psc.shipping_category_id, sc.category_name FROM product_shipping_categories psc "
"inner join product_category pc on (psc.product_category_id = pc.categoryid) "
"inner join shipping_category sc on (psc.shipping_category_id = sc.id)"
"where product_category_id in (SELECT categoryid FROM product_category WHERE catalogid = %d) " %catalog_id)
row = cursor.fetchone()
cursor.close()
shipping_category_id = row[0]
shipping_category_name = row[1]
return shipping_category_id, shipping_category_name
def Add(self, cart_dict, catalog_id):
items_dict = cart_dict # key is ItemID and value is CartItem object
if catalog_id in items_dict.keys():
cart_item = items_dict[catalog_id]
# Checking whether the one more item is allowed the the existing quantity.
if (cart_item.quantity + 1) > cart_item.qoh:
self.RaiseError("Quantity out of order. You can not add more items.")
return items_dict
cart_item.quantity += 1
items_dict[catalog_id] = cart_item
else:
cart_item = CartItem(catalog_id)
if cart_item.qoh <= 0:
self.RaiseError("Quantity is out of order")
return cart_dict
cart_item.shipping_category, cart_item.shipping_category_name = self.GetShippingCategoryID(catalog_id)
cart_item.quantity = 1
items_dict[catalog_id] = cart_item
return items_dict
def Delete(self, cart_dict, catalog_id):
del cart_dict[catalog_id]
return cart_dict
def Update(self, cart_dict, catalog_id, quantity):
cart_item = cart_dict[catalog_id]
if quantity <= 0:
self.RaiseError("Quantity should be greater than 0 or remove from cart")
return cart_dict
if quantity <= cart_item.qoh:
cart_item.quantity = quantity
else:
self.RaiseError("Quantity is out of order")
return cart_dict
return cart_dict
def GetOrderValue(self, cart_dict):
order_value = 0
for key, value in cart_dict.items():
value.CalculateTotals()
order_value += value.subtotal
return order_value
def GetShippingCharge(self, category_id, shipping_value, state, excluded_zip_codes):
shipping_charge = -1
fuel_charge = 0
free_shipping_diff = 0
shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0]
fuel_charge = shipping_cat_obj.fuel_charge
if shipping_cat_obj.is_free_shipping == 1:
# Return 0 as shipping charge and also get fuel charge as Tuple
shipping_charge = 0
return (shipping_charge, fuel_charge, free_shipping_diff)
if shipping_cat_obj.flatrate_shipping_charge > 0.0:
shipping_charge = shipping_cat_obj.flatrate_shipping_charge
return (shipping_charge, fuel_charge, free_shipping_diff)
# Fetching Rules.
shipping_charge_objs = ShippingCharges.objects.filter(shipping_category_id = category_id,
order_total_min__lte = shipping_value,
order_total_max__gte = shipping_value,
shipping_state = state)
# Calculating shipping charge as per the rules.
# If no rules, applying flat_rate shipping charge
if shipping_charge_objs:
shp_charge_obj = shipping_charge_objs[0]
shipping_charge = shp_charge_obj.shipping_charge
else:
shipping_charge = shp_charge_obj.flatrate_shipping_charge
# Calculating free shipping suggestion.
if shipping_charge > 0:
shipping_charge_objs = ShippingCharges.objects.filter(shipping_category_id = category_id,
shipping_charge = 0,
shipping_state = state)
if shipping_charge_objs:
shp_charge_obj = shipping_charge_objs[0]
free_shipping_diff = (shp_charge_obj.order_total_min - shipping_value)
else:
free_shipping_diff = 0
return (shipping_charge, fuel_charge, free_shipping_diff)
def GetItemsByShippingCategory(self, cart_dict):
items_dict = cart_dict
state = 'FL'
excluded_zips = []
tax_list = Tax.objects.filter(tax_country = 'US', tax_state = state)
if tax_list:
tax = tax_list[0].tax_value1
else:
tax = 7.0
# Dictionary contains shipping category id as a key and a list of items as values.
shipping_categories_dict = {}
shipping_cat_names_hash = {}
# Collecting Category wise Items
for key, item in items_dict.items():
item.CalculateTotals()
shipping_category_id = item.shipping_category
if item.shipping_category in shipping_categories_dict:
shipping_categories_dict[item.shipping_category].append(item)
else:
shipping_categories_dict[item.shipping_category] = [item]
shipping_cat_names_hash[item.shipping_category] = item.shipping_category_name
# Calculating Shipping Charge, Fuel Charge and Tax for each category
my_shipping_obj_list = []
for key, value in shipping_categories_dict.items():
shipping_category = MyShippingCategory()
shipping_category.id = key
shipping_category.name = shipping_cat_names_hash[key]
shipping_category.shipping_items = value
# Calculating Shipping Value
for item in shipping_category.shipping_items:
shipping_category.shipping_value += float(item.subtotal)
(shipping_category.shipping_charge, shipping_category.fuel_charge,
shipping_category.freeshipping_diff) = self.GetShippingCharge(shipping_category.id,
shipping_category.shipping_value,
state, excluded_zips)
shipping_category.tax = tax
shipping_category.tax_value = (shipping_category.shipping_value * shipping_category.tax)/100
shipping_category.supplies_total = (shipping_category.shipping_value +
shipping_category.shipping_charge +
shipping_category.fuel_charge +
shipping_category.tax_value -
shipping_category.promotions)
self.subtotal += shipping_category.shipping_value
self.shipping_total += shipping_category.shipping_charge
self.fuelcharge_total += shipping_category.fuel_charge
self.tax_total += shipping_category.tax_value
self.promotions_total += shipping_category.promotions
my_shipping_obj_list.append(shipping_category)
self.order_total = self.subtotal + self.shipping_total + self.fuelcharge_total + self.tax_total - self.promotions_total
# Applying Store Credit
#if self.is_storecredit_applied:
#od = collections.OrderedDict(sorted(shipping_categories_dict.items()))
return my_shipping_obj_list
def GetNumberOfItems(self, p_dict):
cart_dict = p_dict;
item_count = 0
for key, value in cart_dict.items():
item_count += value
return item_count
class CartItem(Error):
def __init__(self, item_id=None):
super(CartItem, self).__init__()
self.catalog_id = -1
self.item_name = ''
self.price = 0.0
self.saleprice = 0.0
self.quantity = 0
self.qoh = 0 # (Quantity on Hand)
self.shipping_category = 0
self.shipping_category_name = ''
self.shipping_charge = 0
self.tax_percent = 0.0
self.tax_value = 0.0
self.fuel_charge = 0.0
self.promotions = 0.0
self.is_reward_enabled = False
self.reward_points = 0
self.thumbnail = ''
self.image1 = ''
self.image2 = ''
self.image3 = ''
self.extra_fied_3 = ''
self.subtotal = 0.0
self.shipping_total = 0.0
self.fuel_charge_total = 0.0
self.promotions_total = 0.0
self.tax_total = 0.0
self.supplies_total = 0.0
if item_id:
self.FillItem(item_id)
return
def CalculateTotals(self):
if self.saleprice > 0:
self.subtotal = self.saleprice * self.quantity
else:
self.subtotal = self.price * self.quantity
self.shipping_total = 0.0
self.fuel_charge_total = 0.0
self.promotions_total = 0.0
self.tax_total = 0.0
self.supplies_total = 0.0
def FillItem(self, p_catalog_id):
'''Fills the current class object with the data fetched from the DB.
Returns: False if product not found.
'''
# Fetching product from the DB.
product_list = Products.objects.filter(catalogid=p_catalog_id)
if not product_list:
self.RaiseError("Item not found")
return False
product = product_list[0]
#product = Products()
self.catalog_id = product.catalogid
self.item_name = product.name
self.price = product.price
self.saleprice = product.saleprice
self.qoh = product.stock # (Quantity on Hand)
# No need to fill the values. Will be calculated for every category.
self.shipping_category = 0
self.shipping_charge = 0
self.tax_percent = 0.0
self.tax_value = 0.0
self.fuel_charge = 0.0
# Update this value when User is applied Coupon.
self.promotions = 0.0
if product.reward_disable == 1:
self.is_reward_enabled = False
else:
self.is_reward_enabled = True
self.reward_points = product.reward_points
self.thumbnail = product.thumbnail
self.image1 = product.image1
self.image2 = product.image2
self.image3 = product.image3
self.extra_fied_3 = product.extra_field_3
#self.subtotal = 0.0
#self.shipping_total = 0.0
#self.fuel_charge_total = 0.0
#self.promotions_total = 0.0
#self.tax_total = 0.0
#self.supplies_total = 0.0
def Set(self, p_catalog_id, p_item_name, p_price, p_saleprice, p_quantity,
p_qoh, p_shipping_category, p_shipping_charge, p_tax_percent,
p_fuel_charge, p_promotions, p_is_rewards_enabled,
p_reward_points, p_thumbnail, p_image1, p_image2, p_image3,
p_extra_field_3=""):
self.catalog_id = p_catalog_id
self.item_name = p_item_name
self.price = p_price
self.saleprice = p_saleprice
self.quantity = p_quantity
self.qoh = p_qoh # (Quantity on Hand)
self.shipping_category = p_shipping_category
self.shipping_charge = p_shipping_charge
self.tax_percent = p_tax_percent
self.fuel_charge = p_fuel_charge
self.promotions = p_promotions
self.is_reward_enabled = p_is_rewards_enabled
self.reward_points = p_reward_points
self.thumbnail = p_thumbnail
self.image1 = p_image1
self.image2 = p_image2
self.image3 = p_image3
self.extra_fied_3 = p_extra_fied_3
#
# self.id = id
# self.name = name
# self.quantity = quantity
# self.price = price
# self.saleprice = saleprice
# #self.fuelcharge = fuelcharge
# self.fuelcharge = 2.99 * quantity
# self.promotions = promotions
# if saleprice <= 0 :
# self.subtotal = price * quantity
# else:
# self.subtotal = saleprice * quantity
#
# self.shipping = shipping
# self.tax = tax
# self.taxvalue = float(self.subtotal) * float(tax)/float(100)
# self.total = float(self.subtotal) + float(shipping) + self.taxvalue + self.fuelcharge - self.promotions
# self.thumbnail = thumbnail
# self.image1 = image1
# self.image2 = image2
# self.image3 = image3
# self.extra_field_3 = extra_field_3
#
# if reward_disable == 0:
# self.reward_points = reward_points
# else:
# self.reward_points = 0
#
# product_category_list = ProductCategory.objects.filter(catalogid = id)
#
# logging.info(product_category_list[0].id)
# if product_category_list:
# category_id, category_name, parent_id = self.GetParentCategory(product_category_list[0].categoryid)
#
# (self.shipping, free_shipping_min_value) = self.GetShippingCharge(category_name, self.subtotal)
# self.free_shipping_suggestion_val = free_shipping_min_value - self.subtotal
#
#
# self.category_id = 0
# def GetParentCategory(self, category_id):
# #SELECT category_name, category_parent from category where id = 4
# cursor = connection.cursor()
# parent_id = 99999
# levels = 0
# while (parent_id > 0 and levels < 100):
# cursor.execute("SELECT id, category_name, category_parent from category where id = %d" %category_id)
# row = cursor.fetchone()
# category_id = row[0]
# category_name = row[1]
# parent_id = row[2]
# category_id = parent_id
# levels += 1
#
# return (category_id, category_name, parent_id)
#
# def GetShippingCharge(self, category_name, sub_total):
# shipping_charge = 0.0
# free_shipping_min_value = -1
# if category_name.__contains__('Marine Life'):
# free_shipping_min_value = 199
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 34.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 24.99
# else:
# shipping_charge = 0
#
# elif category_name.__contains__('Live Goods'):
# free_shipping_min_value = 199
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 34.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 24.99
# else:
# shipping_charge = 0
#
# elif category_name.__contains__('Live Rock & Sand'):
# free_shipping_min_value = 0
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 4.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 4.99
# else:
# shipping_charge = 4.99
#
# elif category_name.__contains__('FastTrack Supplies'):
# free_shipping_min_value = 0
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 4.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 4.99
# else:
# shipping_charge = 4.99
#
# elif category_name.__contains__('Aquarium Supplies On Sale'):
# free_shipping_min_value = 0
# if sub_total >= 00.01 and sub_total <= 98.99:
# shipping_charge = 4.99
# elif sub_total >= 99.00 and sub_total <= 198.99:
# shipping_charge = 4.99
# else:
# shipping_charge = 4.99
#
# return (shipping_charge, free_shipping_min_value)
|
hughsons/saltwaterfish
|
classes_bkp_0621.py
|
Python
|
bsd-3-clause
| 19,445 |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
# Download and build the data if it does not exist.
import parlai.core.build_data as build_data
import os
def buildImage(opt):
dpath = os.path.join(opt['datapath'], 'COCO-IMG')
if not build_data.built(dpath):
print('[building image data: ' + dpath + ']')
build_data.remove_dir(dpath)
build_data.make_dir(dpath)
# download the image data.
fname1 = 'train2014.zip'
fname2 = 'val2014.zip'
fname3 = 'test2014.zip'
url = 'http://msvocds.blob.core.windows.net/coco2014/'
build_data.download(dpath, url + fname1)
build_data.download(dpath, url + fname2)
build_data.download(dpath, url + fname3)
build_data.untar(dpath, fname1, False)
build_data.untar(dpath, fname2, False)
build_data.untar(dpath, fname3, False)
# Mark the data as built.
build_data.mark_done(dpath)
def build(opt):
dpath = os.path.join(opt['datapath'], 'VQA-v2')
if not build_data.built(dpath):
print('[building data: ' + dpath + ']')
build_data.remove_dir(dpath)
build_data.make_dir(dpath)
# Download the data.
fname1 = 'v2_Questions_Train_mscoco.zip'
fname2 = 'v2_Questions_Val_mscoco.zip'
fname3 = 'v2_Questions_Test_mscoco.zip'
fname4 = 'v2_Annotations_Val_mscoco.zip'
fname5 = 'v2_Annotations_Train_mscoco.zip'
url = 'http://visualqa.org/data/mscoco/vqa/'
build_data.download(dpath, url + fname1)
build_data.download(dpath, url + fname2)
build_data.download(dpath, url + fname3)
build_data.download(dpath, url + fname4)
build_data.download(dpath, url + fname5)
build_data.untar(dpath, fname1)
build_data.untar(dpath, fname2)
build_data.untar(dpath, fname3)
build_data.untar(dpath, fname4)
build_data.untar(dpath, fname5)
# Mark the data as built.
build_data.mark_done(dpath)
|
calee88/ParlAI
|
parlai/tasks/vqa_v2/build.py
|
Python
|
bsd-3-clause
| 2,271 |
--TEST--
radius_cvt_string()
--INI--
display_errors=1
error_reporting=22527
--SKIPIF--
<?php
if (!extension_loaded('radius')) echo 'SKIP: radius extension required';
?>
--FILE--
<?php
var_dump(radius_cvt_string('127.0.0.1'));
?>
--EXPECT--
string(9) "127.0.0.1"
|
LawnGnome/php-radius
|
tests/radius_cvt_string.phpt
|
PHP
|
bsd-3-clause
| 262 |
<?php
namespace common\models\articles;
use common\models\behaviors\HiddenBehavior;
use common\models\scopes\ArticleScope;
use common\models\traits\CacheTrait;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use yii\helpers\HtmlPurifier;
use common\models\User;
/**
* This is the model class for table "a_article".
*
* @property integer $id
* @property integer $user_id
* @property string $title
* @property string $description
* @property string $text
* @property integer $status
* @property integer $hidden
* @property integer $created_at
* @property integer $updated_at
*
* @property Category[] $categories
* @property User $user
*/
class Article extends \yii\db\ActiveRecord
{
use CacheTrait;
public $categoriesNames;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'a_article';
}
/**
* @inheritdoc
*/
public static function find()
{
return new ArticleScope(get_called_class());
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
HiddenBehavior::className(),
];
}
// values attribute 'status'
const STATUS_NEW = 5;
const STATUS_ON_MODERATION = 10;
const STATUS_DELETED = 15;
const STATUS_APPROVED = 20;
/**
* Available list of statuses attribute "status"
* or get status name by index
* @param null $index
* @return array|string
*/
public static function statuses($index = null)
{
$statuses = [
self::STATUS_NEW => 'New',
self::STATUS_ON_MODERATION => 'Moderation',
self::STATUS_DELETED => 'Deleted',
self::STATUS_APPROVED => 'Approved',
];
if ($index !== null) {
if (!empty($statuses[$index])) {
return $statuses[$index];
} else {
return 'error status';
}
} else {
return $statuses;
}
}
/**
* Relation many-to-many. Article-Categories
* @return $this
*/
public function getCategories()
{
return $this->hasMany(Category::className(), ['id' => 'category_id'])
->viaTable(ArticleCategory::tableName(), ['article_id' => 'id']);
}
/**
* Relation User
* @return $this
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
// scenarios
const SCENARIO_MODERATION = 'scenario_moderation';
const SCENARIO_AUTHOR_UPDATE = 'scenario_author_update';
const SCENARIO_SEARCH = 'scenario_search';
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id', 'title', 'description', 'text', 'hidden'], 'required', 'except' => self::SCENARIO_SEARCH],
[['user_id'], 'integer'],
['status', 'integer', 'on' => self::SCENARIO_MODERATION],
['status', 'in', 'range' => array_keys(self::statuses()), 'on' => self::SCENARIO_MODERATION],
[['title', 'description'], 'string', 'max' => 255],
['text', 'filter', 'filter' => function ($html) {
return HtmlPurifier::process($html);
}],
['categoriesNames', 'safe']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'title' => 'Title',
'description' => 'Description',
'text' => 'Text',
'status' => 'Status',
'hidden' => 'Hidden',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = self::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if(!Yii::$app->getUser()->can('articleUpdate', $this)) {
$query->approvedOrMy();
}
$query->visibleOrMy();
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'status' => $this->status,
]);
$query->andFilterWhere(['like', 'title', $this->title])
->andFilterWhere(['like', 'description', $this->description])
->andFilterWhere(['like', 'text', $this->text]);
return $dataProvider;
}
/**
* Get access update article
* @return bool
*/
public function isEditAvailable()
{
return Yii::$app->user->can('articleUpdateOwner', $this) || Yii::$app->user->can('articleUpdate', $this);
}
/**
* @inheritdoc
*/
public function afterFind()
{
$categoriesArticle = $this->categories;
if ($categoriesArticle) {
$this->categoriesNames = array_flip(ArrayHelper::map($categoriesArticle, 'id', 'name'));
}
parent::afterFind();
}
/**
* @inheritdoc
*/
public function afterSave($insert, $changedAttributes)
{
$articleCategories = ArticleCategory::getCache(ArticleCategory::find()
->where(['article_id' => $this->id])
->indexBy('category_id'), false);
$transaction = Yii::$app->db->beginTransaction();
try {
ArticleCategory::deleteAll([
'category_id' => array_diff_key($articleCategories, $this->categoriesNames),
'article_id' => $this->id
]);
$addedCategories = array_diff_key($this->categoriesNames, $articleCategories);
$insertData = [];
foreach ($addedCategories as $addedCategoryId) {
$insertData[] = [
'article_id' => $this->id,
'category_id' => $addedCategoryId,
];
}
if (!empty($insertData)) {
Yii::$app->db->createCommand()
->batchInsert(ArticleCategory::tableName(), array_keys($insertData[0]), $insertData)
->execute();
}
ArticleCategory::onInvalidateCache();
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
parent::afterSave($insert, $changedAttributes);
}
}
|
bereznev/yii2-blog
|
common/models/articles/Article.php
|
PHP
|
bsd-3-clause
| 5,780 |
from django.core.exceptions import ImproperlyConfigured
from django.db.models import F, fields
from django.db.models.functions import Cast, Coalesce
from django.utils.translation import gettext_lazy as _
from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting
from .utils import (
FallbackTransform,
build_localized_fieldname,
get_instance_field_value,
get_language,
)
try:
# django==3.1 moved JSONField into django.db.models
from django.db.models import JSONField
from django.db.models.fields.json import KeyTextTransform
except ImportError:
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.fields.jsonb import KeyTextTransform
SUPPORTED_FIELDS = (fields.CharField, fields.TextField)
DEFAULT_LANGUAGE = get_default_language()
def translated_field_factory(original_field, language=None, *args, **kwargs):
if not isinstance(original_field, SUPPORTED_FIELDS):
raise ImproperlyConfigured(
"{} is not supported by django-modeltrans.".format(original_field.__class__.__name__)
)
class Specific(TranslatedVirtualField, original_field.__class__):
pass
Specific.__name__ = "Translated{}".format(original_field.__class__.__name__)
return Specific(original_field, language, *args, **kwargs)
class TranslatedVirtualField:
"""
A field representing a single field translated to a specific language.
Arguments:
original_field: The original field to be translated
language: The language to translate to, or `None` to track the current active Django language.
"""
# Implementation inspired by HStoreVirtualMixin from:
# https://github.com/djangonauts/django-hstore/blob/master/django_hstore/virtual.py
def __init__(self, original_field, language=None, *args, **kwargs):
# TODO: this feels like a big hack.
self.__dict__.update(original_field.__dict__)
self.original_field = original_field
self.language = language
self.blank = kwargs["blank"]
self.null = kwargs["null"]
self.concrete = False
self._help_text = kwargs.pop("help_text", None)
@property
def original_name(self):
return self.original_field.name
@property
def help_text(self):
if self._help_text is not None:
return self._help_text
if get_modeltrans_setting("MODELTRANS_ADD_FIELD_HELP_TEXT") and self.language is None:
return _("current language: {}").format(get_language())
def contribute_to_class(self, cls, name):
self.model = cls
self.attname = name
self.name = name
self.column = None
# Use a translated verbose name:
translated_field_name = _(self.original_field.verbose_name)
if self.language is not None:
translated_field_name += " ({})".format(self.language.upper())
self.verbose_name = translated_field_name
setattr(cls, name, self)
cls._meta.add_field(self, private=True)
def db_type(self, connection):
return None
def get_instance_fallback_chain(self, instance, language):
"""
Return the fallback chain for the instance.
Most of the time, it is just the configured fallback chain, but if the per-record-fallback feature
is used, the value of the field is added (if not None).
"""
default = get_fallback_chain(language)
i18n_field = instance._meta.get_field("i18n")
if i18n_field.fallback_language_field:
record_fallback_language = get_instance_field_value(
instance, i18n_field.fallback_language_field
)
if record_fallback_language:
return (record_fallback_language, *default)
return default
def __get__(self, instance, instance_type=None):
# This method is apparently called with instance=None from django.
# django-hstor raises AttributeError here, but that doesn't solve our problem.
if instance is None:
return
if "i18n" in instance.get_deferred_fields():
raise ValueError(
"Getting translated values on a model fetched with defer('i18n') is not supported."
)
language = self.get_language()
original_value = getattr(instance, self.original_name)
if language == DEFAULT_LANGUAGE and original_value:
return original_value
# Make sure we test for containment in a dict, not in None
if instance.i18n is None:
instance.i18n = {}
field_name = build_localized_fieldname(self.original_name, language)
# Just return the value if this is an explicit field (<name>_<lang>)
if self.language is not None:
return instance.i18n.get(field_name)
# This is the _i18n version of the field, and the current language is not available,
# so we walk the fallback chain:
for fallback_language in (language,) + self.get_instance_fallback_chain(instance, language):
if fallback_language == DEFAULT_LANGUAGE:
if original_value:
return original_value
else:
continue
field_name = build_localized_fieldname(self.original_name, fallback_language)
if field_name in instance.i18n and instance.i18n[field_name]:
return instance.i18n.get(field_name)
# finally, return the original field if all else fails.
return getattr(instance, self.original_name)
def __set__(self, instance, value):
if instance.i18n is None:
instance.i18n = {}
language = self.get_language()
if language == DEFAULT_LANGUAGE:
setattr(instance, self.original_name, value)
else:
field_name = build_localized_fieldname(self.original_name, language)
# if value is None, remove field from `i18n`.
if value is None:
instance.i18n.pop(field_name, None)
else:
instance.i18n[field_name] = value
def get_field_name(self):
"""
Returns the field name for the current virtual field.
The field name is ``<original_field_name>_<language>`` in case of a specific
translation or ``<original_field_name>_i18n`` for the currently active language.
"""
if self.language is None:
lang = "i18n"
else:
lang = self.get_language()
return build_localized_fieldname(self.original_name, lang)
def get_language(self):
"""
Returns the language for this field.
In case of an explicit language (title_en), it returns "en", in case of
`title_i18n`, it returns the currently active Django language.
"""
return self.language if self.language is not None else get_language()
def output_field(self):
"""
The type of field used to Cast/Coalesce to.
Mainly because a max_length argument is required for CharField
until this PR is merged: https://github.com/django/django/pull/8758
"""
Field = self.original_field.__class__
if isinstance(self.original_field, fields.CharField):
return Field(max_length=self.original_field.max_length)
return Field()
def _localized_lookup(self, language, bare_lookup):
if language == DEFAULT_LANGUAGE:
return bare_lookup.replace(self.name, self.original_name)
# When accessing a table directly, the i18_lookup will be just "i18n", while following relations
# they are in the lookup first.
i18n_lookup = bare_lookup.replace(self.name, "i18n")
# To support per-row fallback languages, an F-expression is passed as language parameter.
if isinstance(language, F):
# abuse build_localized_fieldname without language to get "<field>_"
field_prefix = build_localized_fieldname(self.original_name, "")
return FallbackTransform(field_prefix, language, i18n_lookup)
else:
return KeyTextTransform(
build_localized_fieldname(self.original_name, language), i18n_lookup
)
def as_expression(self, bare_lookup, fallback=True):
"""
Compose an expression to get the value for this virtual field in a query.
"""
language = self.get_language()
if language == DEFAULT_LANGUAGE:
return F(self._localized_lookup(language, bare_lookup))
if not fallback:
i18n_lookup = self._localized_lookup(language, bare_lookup)
return Cast(i18n_lookup, self.output_field())
fallback_chain = get_fallback_chain(language)
# First, add the current language to the list of lookups
lookups = [self._localized_lookup(language, bare_lookup)]
# Optionnally add the lookup for the per-row fallback language
i18n_field = self.model._meta.get_field("i18n")
if i18n_field.fallback_language_field:
lookups.append(
self._localized_lookup(F(i18n_field.fallback_language_field), bare_lookup)
)
# and now, add the list of fallback languages to the lookup list
for fallback_language in fallback_chain:
lookups.append(self._localized_lookup(fallback_language, bare_lookup))
return Coalesce(*lookups, output_field=self.output_field())
class TranslationField(JSONField):
"""
This model field is used to store the translations in the translated model.
Arguments:
fields (iterable): List of model field names to make translatable.
required_languages (iterable or dict): List of languages required for the model.
If a dict is supplied, the keys must be translated field names with the value
containing a list of required languages for that specific field.
virtual_fields (bool): If `False`, do not add virtual fields to access
translated values with.
Set to `True` during migration from django-modeltranslation to prevent
collisions with it's database fields while having the `i18n` field available.
fallback_language_field: If not None, this should be the name of the field containing a
language code to use as the first language in any fallback chain.
For example: if you have a model instance with 'nl' as language_code, and set
fallback_language_field='language_code', 'nl' will always be tried after the current
language before any other language.
"""
description = "Translation storage for a model"
def __init__(
self,
fields=None,
required_languages=None,
virtual_fields=True,
fallback_language_field=None,
*args,
**kwargs,
):
self.fields = fields or ()
self.required_languages = required_languages or ()
self.virtual_fields = virtual_fields
self.fallback_language_field = fallback_language_field
kwargs["editable"] = False
kwargs["null"] = True
super().__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
del kwargs["editable"]
del kwargs["null"]
kwargs["fields"] = self.fields
kwargs["required_languages"] = self.required_languages
kwargs["virtual_fields"] = self.virtual_fields
return name, path, args, kwargs
def get_translated_fields(self):
"""Return a generator for all translated fields."""
for field in self.model._meta.get_fields():
if isinstance(field, TranslatedVirtualField):
yield field
def contribute_to_class(self, cls, name):
if name != "i18n":
raise ImproperlyConfigured('{} must have name "i18n"'.format(self.__class__.__name__))
super().contribute_to_class(cls, name)
|
zostera/django-modeltrans
|
modeltrans/fields.py
|
Python
|
bsd-3-clause
| 12,105 |
package gengateway
import (
"strings"
"testing"
"github.com/golang/protobuf/proto"
protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/ilius/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
"github.com/ilius/grpc-gateway/protoc-gen-grpc-gateway/httprule"
)
func crossLinkFixture(f *descriptor.File) *descriptor.File {
for _, m := range f.Messages {
m.File = f
}
for _, svc := range f.Services {
svc.File = f
for _, m := range svc.Methods {
m.Service = svc
for _, b := range m.Bindings {
b.Method = m
for _, param := range b.PathParams {
param.Method = m
}
}
}
}
return f
}
func TestApplyTemplateHeader(t *testing.T) {
msgdesc := &protodescriptor.DescriptorProto{
Name: proto.String("ExampleMessage"),
}
meth := &protodescriptor.MethodDescriptorProto{
Name: proto.String("Example"),
InputType: proto.String("ExampleMessage"),
OutputType: proto.String("ExampleMessage"),
}
svc := &protodescriptor.ServiceDescriptorProto{
Name: proto.String("ExampleService"),
Method: []*protodescriptor.MethodDescriptorProto{meth},
}
msg := &descriptor.Message{
DescriptorProto: msgdesc,
}
file := descriptor.File{
FileDescriptorProto: &protodescriptor.FileDescriptorProto{
Name: proto.String("example.proto"),
Package: proto.String("example"),
Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"},
MessageType: []*protodescriptor.DescriptorProto{msgdesc},
Service: []*protodescriptor.ServiceDescriptorProto{svc},
},
GoPkg: descriptor.GoPackage{
Path: "example.com/path/to/example/example.pb",
Name: "example_pb",
},
Messages: []*descriptor.Message{msg},
Services: []*descriptor.Service{
{
ServiceDescriptorProto: svc,
Methods: []*descriptor.Method{
{
MethodDescriptorProto: meth,
RequestType: msg,
ResponseType: msg,
Bindings: []*descriptor.Binding{
{
HTTPMethod: "GET",
Body: &descriptor.Body{FieldPath: nil},
},
},
},
},
},
},
}
got, err := applyTemplate(param{File: crossLinkFixture(&file)})
if err != nil {
t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err)
return
}
if want := "package example_pb\n"; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
}
func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) {
msgdesc := &protodescriptor.DescriptorProto{
Name: proto.String("ExampleMessage"),
Field: []*protodescriptor.FieldDescriptorProto{
{
Name: proto.String("nested"),
Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
TypeName: proto.String("NestedMessage"),
Number: proto.Int32(1),
},
},
}
nesteddesc := &protodescriptor.DescriptorProto{
Name: proto.String("NestedMessage"),
Field: []*protodescriptor.FieldDescriptorProto{
{
Name: proto.String("int32"),
Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(),
Number: proto.Int32(1),
},
{
Name: proto.String("bool"),
Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(),
Number: proto.Int32(2),
},
},
}
meth := &protodescriptor.MethodDescriptorProto{
Name: proto.String("Echo"),
InputType: proto.String("ExampleMessage"),
OutputType: proto.String("ExampleMessage"),
ClientStreaming: proto.Bool(false),
}
svc := &protodescriptor.ServiceDescriptorProto{
Name: proto.String("ExampleService"),
Method: []*protodescriptor.MethodDescriptorProto{meth},
}
for _, spec := range []struct {
serverStreaming bool
sigWant string
}{
{
serverStreaming: false,
sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`,
},
{
serverStreaming: true,
sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`,
},
} {
meth.ServerStreaming = proto.Bool(spec.serverStreaming)
msg := &descriptor.Message{
DescriptorProto: msgdesc,
}
nested := &descriptor.Message{
DescriptorProto: nesteddesc,
}
nestedField := &descriptor.Field{
Message: msg,
FieldDescriptorProto: msg.GetField()[0],
}
intField := &descriptor.Field{
Message: nested,
FieldDescriptorProto: nested.GetField()[0],
}
boolField := &descriptor.Field{
Message: nested,
FieldDescriptorProto: nested.GetField()[1],
}
file := descriptor.File{
FileDescriptorProto: &protodescriptor.FileDescriptorProto{
Name: proto.String("example.proto"),
Package: proto.String("example"),
MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc},
Service: []*protodescriptor.ServiceDescriptorProto{svc},
},
GoPkg: descriptor.GoPackage{
Path: "example.com/path/to/example/example.pb",
Name: "example_pb",
},
Messages: []*descriptor.Message{msg, nested},
Services: []*descriptor.Service{
{
ServiceDescriptorProto: svc,
Methods: []*descriptor.Method{
{
MethodDescriptorProto: meth,
RequestType: msg,
ResponseType: msg,
Bindings: []*descriptor.Binding{
{
HTTPMethod: "POST",
PathTmpl: httprule.Template{
Version: 1,
OpCodes: []int{0, 0},
},
PathParams: []descriptor.Parameter{
{
FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{
{
Name: "nested",
Target: nestedField,
},
{
Name: "int32",
Target: intField,
},
}),
Target: intField,
},
},
Body: &descriptor.Body{
FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{
{
Name: "nested",
Target: nestedField,
},
{
Name: "bool",
Target: boolField,
},
}),
},
},
},
},
},
},
},
}
got, err := applyTemplate(param{File: crossLinkFixture(&file)})
if err != nil {
t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err)
return
}
if want := spec.sigWant; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
if want := `marshaler.NewDecoder(req.Body).Decode(&protoReq.GetNested().Bool)`; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
if want := `val, ok = pathParams["nested.int32"]`; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
if want := `protoReq.GetNested().Int32, err = runtime.Int32P(val)`; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), ""))`; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
}
}
func TestApplyTemplateRequestWithClientStreaming(t *testing.T) {
msgdesc := &protodescriptor.DescriptorProto{
Name: proto.String("ExampleMessage"),
Field: []*protodescriptor.FieldDescriptorProto{
{
Name: proto.String("nested"),
Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
TypeName: proto.String("NestedMessage"),
Number: proto.Int32(1),
},
},
}
nesteddesc := &protodescriptor.DescriptorProto{
Name: proto.String("NestedMessage"),
Field: []*protodescriptor.FieldDescriptorProto{
{
Name: proto.String("int32"),
Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(),
Number: proto.Int32(1),
},
{
Name: proto.String("bool"),
Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(),
Number: proto.Int32(2),
},
},
}
meth := &protodescriptor.MethodDescriptorProto{
Name: proto.String("Echo"),
InputType: proto.String("ExampleMessage"),
OutputType: proto.String("ExampleMessage"),
ClientStreaming: proto.Bool(true),
}
svc := &protodescriptor.ServiceDescriptorProto{
Name: proto.String("ExampleService"),
Method: []*protodescriptor.MethodDescriptorProto{meth},
}
for _, spec := range []struct {
serverStreaming bool
sigWant string
}{
{
serverStreaming: false,
sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`,
},
{
serverStreaming: true,
sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`,
},
} {
meth.ServerStreaming = proto.Bool(spec.serverStreaming)
msg := &descriptor.Message{
DescriptorProto: msgdesc,
}
nested := &descriptor.Message{
DescriptorProto: nesteddesc,
}
nestedField := &descriptor.Field{
Message: msg,
FieldDescriptorProto: msg.GetField()[0],
}
intField := &descriptor.Field{
Message: nested,
FieldDescriptorProto: nested.GetField()[0],
}
boolField := &descriptor.Field{
Message: nested,
FieldDescriptorProto: nested.GetField()[1],
}
file := descriptor.File{
FileDescriptorProto: &protodescriptor.FileDescriptorProto{
Name: proto.String("example.proto"),
Package: proto.String("example"),
MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc},
Service: []*protodescriptor.ServiceDescriptorProto{svc},
},
GoPkg: descriptor.GoPackage{
Path: "example.com/path/to/example/example.pb",
Name: "example_pb",
},
Messages: []*descriptor.Message{msg, nested},
Services: []*descriptor.Service{
{
ServiceDescriptorProto: svc,
Methods: []*descriptor.Method{
{
MethodDescriptorProto: meth,
RequestType: msg,
ResponseType: msg,
Bindings: []*descriptor.Binding{
{
HTTPMethod: "POST",
PathTmpl: httprule.Template{
Version: 1,
OpCodes: []int{0, 0},
},
PathParams: []descriptor.Parameter{
{
FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{
{
Name: "nested",
Target: nestedField,
},
{
Name: "int32",
Target: intField,
},
}),
Target: intField,
},
},
Body: &descriptor.Body{
FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{
{
Name: "nested",
Target: nestedField,
},
{
Name: "bool",
Target: boolField,
},
}),
},
},
},
},
},
},
},
}
got, err := applyTemplate(param{File: crossLinkFixture(&file)})
if err != nil {
t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err)
return
}
if want := spec.sigWant; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
if want := `marshaler.NewDecoder(req.Body)`; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), ""))`; !strings.Contains(got, want) {
t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want)
}
}
}
|
ilius/grpc-gateway
|
protoc-gen-grpc-gateway/gengateway/template_test.go
|
GO
|
bsd-3-clause
| 13,223 |
/*
* Copyright (c) 2013 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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 copyright holders 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.
*
* Authors: Stephan Diestelhorst <stephan.diestelhorst@arm.com>
*/
// hello
/**
* @file
* Definition of a snoop filter.
*/
#include "base/misc.hh"
#include "base/trace.hh"
#include "debug/SnoopFilter.hh"
#include "mem/snoop_filter.hh"
#include "sim/system.hh"
std::pair<SnoopFilter::SnoopList, Cycles>
SnoopFilter::lookupRequest(const Packet* cpkt, const SlavePort& slave_port)
{
DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n",
__func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString());
Addr line_addr = cpkt->getAddr() & ~(linesize - 1);
SnoopMask req_port = portToMask(slave_port);
auto sf_it = cachedLocations.find(line_addr);
bool is_hit = (sf_it != cachedLocations.end());
// Create a new element through operator[] and modify in-place
SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr];
SnoopMask interested = sf_item.holder | sf_item.requested;
totRequests++;
if (is_hit) {
// Single bit set -> value is a power of two
if (isPow2(interested))
hitSingleRequests++;
else
hitMultiRequests++;
}
DPRINTF(SnoopFilter, "%s: SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
if (cpkt->needsResponse()) {
if (!cpkt->memInhibitAsserted()) {
// Max one request per address per port
panic_if(sf_item.requested & req_port, "double request :( "\
"SF value %x.%x\n", sf_item.requested, sf_item.holder);
// Mark in-flight requests to distinguish later on
sf_item.requested |= req_port;
} else {
// NOTE: The memInhibit might have been asserted by a cache closer
// to the CPU, already -> the response will not be seen by this
// filter -> we do not need to keep the in-flight request, but make
// sure that we know that that cluster has a copy
panic_if(!(sf_item.holder & req_port), "Need to hold the value!");
DPRINTF(SnoopFilter, "%s: not marking request. SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
}
DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
}
return snoopSelected(maskToPortList(interested & ~req_port), lookupLatency);
}
void
SnoopFilter::updateRequest(const Packet* cpkt, const SlavePort& slave_port,
bool will_retry)
{
DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n",
__func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString());
Addr line_addr = cpkt->getAddr() & ~(linesize - 1);
SnoopMask req_port = portToMask(slave_port);
SnoopItem& sf_item = cachedLocations[line_addr];
DPRINTF(SnoopFilter, "%s: old SF value %x.%x retry: %i\n",
__func__, sf_item.requested, sf_item.holder, will_retry);
if (will_retry) {
// Unmark a request that will come again.
sf_item.requested &= ~req_port;
return;
}
// will_retry == false
if (!cpkt->needsResponse()) {
// Packets that will not evoke a response but still need updates of the
// snoop filter; WRITEBACKs for now only
if (cpkt->cmd == MemCmd::Writeback) {
// make sure that the sender actually had the line
panic_if(sf_item.requested & req_port, "double request :( "\
"SF value %x.%x\n", sf_item.requested, sf_item.holder);
panic_if(!(sf_item.holder & req_port), "requester %x is not a "\
"holder :( SF value %x.%x\n", req_port,
sf_item.requested, sf_item.holder);
// Writebacks -> the sender does not have the line anymore
sf_item.holder &= ~req_port;
} else {
assert(0 == "Handle non-writeback, here");
}
DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
}
}
std::pair<SnoopFilter::SnoopList, Cycles>
SnoopFilter::lookupSnoop(const Packet* cpkt)
{
DPRINTF(SnoopFilter, "%s: packet addr 0x%x cmd %s\n",
__func__, cpkt->getAddr(), cpkt->cmdString());
assert(cpkt->isRequest());
// Broadcast / filter upward snoops
const bool filter_upward = true; // @todo: Make configurable
if (!filter_upward)
return snoopAll(lookupLatency);
Addr line_addr = cpkt->getAddr() & ~(linesize - 1);
auto sf_it = cachedLocations.find(line_addr);
bool is_hit = (sf_it != cachedLocations.end());
// Create a new element through operator[] and modify in-place
SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr];
DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
SnoopMask interested = (sf_item.holder | sf_item.requested);
totSnoops++;
if (is_hit) {
// Single bit set -> value is a power of two
if (isPow2(interested))
hitSingleSnoops++;
else
hitMultiSnoops++;
}
assert(cpkt->isInvalidate() == cpkt->needsExclusive());
if (cpkt->isInvalidate() && !sf_item.requested) {
// Early clear of the holder, if no other request is currently going on
// @todo: This should possibly be updated even though we do not filter
// upward snoops
sf_item.holder = 0;
}
DPRINTF(SnoopFilter, "%s: new SF value %x.%x interest: %x \n",
__func__, sf_item.requested, sf_item.holder, interested);
return snoopSelected(maskToPortList(interested), lookupLatency);
}
void
SnoopFilter::updateSnoopResponse(const Packet* cpkt,
const SlavePort& rsp_port,
const SlavePort& req_port)
{
DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n",
__func__, rsp_port.name(), req_port.name(), cpkt->getAddr(),
cpkt->cmdString());
Addr line_addr = cpkt->getAddr() & ~(linesize - 1);
SnoopMask rsp_mask = portToMask(rsp_port);
SnoopMask req_mask = portToMask(req_port);
SnoopItem& sf_item = cachedLocations[line_addr];
assert(cpkt->isResponse());
assert(cpkt->memInhibitAsserted());
DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
// The source should have the line
panic_if(!(sf_item.holder & rsp_mask), "SF value %x.%x does not have "\
"the line\n", sf_item.requested, sf_item.holder);
// The destination should have had a request in
panic_if(!(sf_item.requested & req_mask), "SF value %x.%x missing "\
"the original request\n", sf_item.requested, sf_item.holder);
// Update the residency of the cache line.
if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) {
DPRINTF(SnoopFilter, "%s: dropping %x because needs: %i shared: %i "\
"SF val: %x.%x\n", __func__, rsp_mask,
cpkt->needsExclusive(), cpkt->sharedAsserted(),
sf_item.requested, sf_item.holder);
sf_item.holder &= ~rsp_mask;
// The snoop filter does not see any ACKs from non-responding sharers
// that have been invalidated :( So below assert would be nice, but..
//assert(sf_item.holder == 0);
sf_item.holder = 0;
}
assert(cpkt->cmd != MemCmd::Writeback);
sf_item.holder |= req_mask;
sf_item.requested &= ~req_mask;
DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
}
void
SnoopFilter::updateSnoopForward(const Packet* cpkt,
const SlavePort& rsp_port, const MasterPort& req_port)
{
DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n",
__func__, rsp_port.name(), req_port.name(), cpkt->getAddr(),
cpkt->cmdString());
Addr line_addr = cpkt->getAddr() & ~(linesize - 1);
SnoopItem& sf_item = cachedLocations[line_addr];
SnoopMask rsp_mask M5_VAR_USED = portToMask(rsp_port);
assert(cpkt->isResponse());
assert(cpkt->memInhibitAsserted());
DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
// Remote (to this snoop filter) snoops update the filter already when they
// arrive from below, because we may not see any response.
if (cpkt->needsExclusive()) {
// If the request to this snoop response hit an in-flight transaction,
// the holder was not reset -> no assertion & do that here, now!
//assert(sf_item.holder == 0);
sf_item.holder = 0;
}
DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
}
void
SnoopFilter::updateResponse(const Packet* cpkt, const SlavePort& slave_port)
{
DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n",
__func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString());
Addr line_addr = cpkt->getAddr() & ~(linesize - 1);
SnoopMask slave_mask = portToMask(slave_port);
SnoopItem& sf_item = cachedLocations[line_addr];
assert(cpkt->isResponse());
DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
// Make sure we have seen the actual request, too
panic_if(!(sf_item.requested & slave_mask), "SF value %x.%x missing "\
"request bit\n", sf_item.requested, sf_item.holder);
// Update the residency of the cache line.
if (cpkt->needsExclusive() || !cpkt->sharedAsserted())
sf_item.holder = 0;
sf_item.holder |= slave_mask;
sf_item.requested &= ~slave_mask;
DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n",
__func__, sf_item.requested, sf_item.holder);
}
void
SnoopFilter::regStats()
{
totRequests
.name(name() + ".tot_requests")
.desc("Total number of requests made to the snoop filter.");
hitSingleRequests
.name(name() + ".hit_single_requests")
.desc("Number of requests hitting in the snoop filter with a single "\
"holder of the requested data.");
hitMultiRequests
.name(name() + ".hit_multi_requests")
.desc("Number of requests hitting in the snoop filter with multiple "\
"(>1) holders of the requested data.");
totSnoops
.name(name() + ".tot_snoops")
.desc("Total number of snoops made to the snoop filter.");
hitSingleSnoops
.name(name() + ".hit_single_snoops")
.desc("Number of snoops hitting in the snoop filter with a single "\
"holder of the requested data.");
hitMultiSnoops
.name(name() + ".hit_multi_snoops")
.desc("Number of snoops hitting in the snoop filter with multiple "\
"(>1) holders of the requested data.");
}
SnoopFilter *
SnoopFilterParams::create()
{
return new SnoopFilter(this);
}
|
SteveXiSong/ECE757-SnoopingPredictions
|
src/mem/snoop_filter.cc
|
C++
|
bsd-3-clause
| 13,192 |
/*
* $Id: GridAttributeDialog.java,v 1.2 2006/01/19 14:45:50 luca Exp $
*
* This software is provided by NOAA for full, free and open release. It is
* understood by the recipient/user that NOAA assumes no liability for any
* errors contained in the code. Although this software is released without
* conditions or restrictions in its use, it is expected that appropriate
* credit be given to its author and to the National Oceanic and Atmospheric
* Administration should the software be included by the recipient as an
* element in other product development.
*/
package gov.noaa.pmel.sgt.swing.prop;
import javax.swing.*;
import java.awt.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.event.TableModelEvent;
import java.util.Vector;
import java.io.File;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.StreamTokenizer;
import gov.noaa.pmel.sgt.GridCartesianRenderer;
import gov.noaa.pmel.sgt.GridAttribute;
import gov.noaa.pmel.sgt.ContourLineAttribute;
import gov.noaa.pmel.sgt.DefaultContourLineAttribute;
import gov.noaa.pmel.sgt.ContourLevels;
import gov.noaa.pmel.sgt.ColorMap;
import gov.noaa.pmel.sgt.IndexedColor;
import gov.noaa.pmel.sgt.swing.ColorSwatchIcon;
import gov.noaa.pmel.sgt.IndexedColorMap;
import gov.noaa.pmel.sgt.LinearTransform;
import gov.noaa.pmel.sgt.JPane;
import gov.noaa.pmel.sgt.ContourLevelNotFoundException;
import gov.noaa.pmel.sgt.dm.SGTGrid;
import gov.noaa.pmel.util.Range2D;
import java.awt.event.*;
import it.unitn.ing.rista.util.Misc;
/**
* Edits the <code>GridAttribute</code>. This dialog does not make a
* copy of the attribute so changes "Applied" will cause
* <code>sgt</code> to redraw the plot using the properties
* immediately unless a <code>JPane</code> was supplied.
*
* <p> Example of <code>GridAttributeDialog</code> use:
* <pre>
* JPane pane_;
* CartesianRenderer rend = ((CartesianGraph)pane_.getFirstLayer().getGraph()).getRenderer();
* ...
* GridAttributeDialog gad = new GridAttributeDialog();
* gad.setJPane(pane_);
* gad.setGridCartesianRenderer((GridCartesianRenderer)rend);
* gad.setVisible(true);
* </pre>
*
* @author Donald Denbo
* @version $Revision: 1.2 $, $Date: 2006/01/19 14:45:50 $
* @since 2.0
* @see NewLevelsDialog
* @see ContourLineAttributeDialog
* @see DefaultContourLineAttributeDialog
*/
public class GridAttributeDialog extends JDialog {
private GridAttribute attr_;
private ContourLevels conLevels_;
private ColorMap colorMap_;
private JPane[] paneList_ = null;
private int contourLevelIndex_ = 0;
private int colorMapIndex_ = 1;
private JTable conLevelTable_;
private ConLevelTableModel conLevelModel_;
private SGTGrid grid_ = null;
private JToggleButton[] colorButtons_ = new JToggleButton[256];
/**
* Constructor.
*/
public GridAttributeDialog(Frame parent) {
super(parent);
try {
jbInit();
pack();
} catch(Exception ex) {
ex.printStackTrace();
}
}
void jbInit() throws Exception {
getContentPane().setLayout(new BorderLayout(0,0));
setSize(516,374);
setVisible(false);
mainPanel.setPreferredSize(new Dimension(516, 36));
getContentPane().add(TabbedPane, "Center");
ContourLevelsPanel.setLayout(new BorderLayout(0,0));
TabbedPane.add(ContourLevelsPanel, "ContourLevelsPanel");
ContourLevelsPanel.setBounds(2,27,511,271);
ContourLevelsPanel.setVisible(false);
ContourLevelsPanel.add(gridScrollPane, "Center");
controlPanel.setLayout(new GridBagLayout());
ContourLevelsPanel.add(controlPanel, "East");
JPanel1.setBorder(titledBorder1);
JPanel1.setLayout(new GridBagLayout());
controlPanel.add(JPanel1, new GridBagConstraints(0,1,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,0,0,0),0,0));
editButton.setToolTipText("Edit attribute of selected level.");
editButton.setText("Edit Attribute");
editButton.setActionCommand("Change Value");
JPanel1.add(editButton, new GridBagConstraints(0,0,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(5,5,0,5),0,0));
aboveButton.setToolTipText("Insert level above selected level.");
aboveButton.setText("Insert Level Above");
aboveButton.setActionCommand("Before Item");
JPanel1.add(aboveButton, new GridBagConstraints(0,1,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,0,5),0,0));
belowButton.setToolTipText("Insert level below selected level.");
belowButton.setText("Insert Level Below");
belowButton.setActionCommand("After Item");
JPanel1.add(belowButton, new GridBagConstraints(0,2,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,0,5),0,0));
deleteButton.setToolTipText("Delete the selected level.");
deleteButton.setText("Delete Level");
deleteButton.setActionCommand("Delete Item");
JPanel1.add(deleteButton, new GridBagConstraints(0,3,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,2,5),0,0));
JPanel4.setBorder(titledBorder4);
JPanel4.setLayout(new GridBagLayout());
controlPanel.add(JPanel4, new GridBagConstraints(0,3,1,1,0.0,0.0,
GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,0,0,0),0,0));
defaultButton.setToolTipText("Edit default attributes.");
defaultButton.setText("Edit Default Attributes");
defaultButton.setActionCommand("Edit Default Attributes");
JPanel4.add(defaultButton, new GridBagConstraints(0,0,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(2,5,2,5),0,0));
sortButton.setToolTipText("Sort levels by value.");
sortButton.setText("Sort Levels");
sortButton.setActionCommand("Sort");
controlPanel.add(sortButton, new GridBagConstraints(0,4,1,1,0.0,0.0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(5,5,5,5),0,0));
newConLevelButton.setToolTipText("Create new contour level set.");
newConLevelButton.setText("New...");
newConLevelButton.setActionCommand("New...");
controlPanel.add(newConLevelButton, new GridBagConstraints(0,0,1,1,1.0,0.0,
GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,5,0,5),0,0));
ColorMapPanel.setLayout(new BorderLayout(0,0));
TabbedPane.add(ColorMapPanel, "ColorMapPanel");
ColorMapPanel.setBounds(2,27,511,271);
ColorMapPanel.setVisible(false);
colorControlPanel.setLayout(new GridBagLayout());
ColorMapPanel.add(colorControlPanel, "East");
colorMapPanel.setBorder(titledBorder2);
colorMapPanel.setLayout(new GridBagLayout());
colorControlPanel.add(colorMapPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0));
newColorMapButton.setToolTipText("Create new color map.");
newColorMapButton.setText("New...");
newColorMapButton.setActionCommand("New...");
colorMapPanel.add(newColorMapButton, new GridBagConstraints(0,0,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0));
loadColorMapButton.setToolTipText("Load color map from disk.");
loadColorMapButton.setText("Load...");
loadColorMapButton.setActionCommand("Load...");
colorMapPanel.add(loadColorMapButton, new GridBagConstraints(0,1,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0));
saveColorMapButton.setToolTipText("Save color map to disk.");
saveColorMapButton.setText("Save...");
saveColorMapButton.setActionCommand("Save...");
colorMapPanel.add(saveColorMapButton, new GridBagConstraints(0,2,1,1,0.0,0.0,
GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0));
colorPanel.setLayout(new CardLayout(0,0));
ColorMapPanel.add(colorPanel, "Center");
CLIndexedPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
colorPanel.add("CLIndexed", CLIndexedPanel);
CLTransformPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
colorPanel.add("CLTransform", CLTransformPanel);
CLTransformPanel.setVisible(false);
IndexedPanel.setLayout(new GridBagLayout());
colorPanel.add("Indexed", IndexedPanel);
IndexedPanel.setVisible(false);
colorButtonsPanel.setLayout(new GridLayout(16,16,1,1));
IndexedPanel.add(colorButtonsPanel, new GridBagConstraints(0,0,1,1,1.0,1.0,
GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0));
TransformPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
colorPanel.add("Transform", TransformPanel);
TransformPanel.setVisible(false);
TabbedPane.setSelectedComponent(ContourLevelsPanel);
TabbedPane.setSelectedIndex(0);
TabbedPane.setTitleAt(0,"Contour Levels");
TabbedPane.setTitleAt(1,"Color Map");
buttonPanel.setBorder(etchedBorder1);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
getContentPane().add(buttonPanel, "South");
okButton.setText("OK");
okButton.setActionCommand("OK");
buttonPanel.add(okButton);
applyButton.setText("Apply");
applyButton.setActionCommand("Apply");
buttonPanel.add(applyButton);
cancelButton.setText("Cancel");
cancelButton.setActionCommand("Cancel");
buttonPanel.add(cancelButton);
mainPanel.setLayout(new GridBagLayout());
getContentPane().add(mainPanel, "North");
JLabel5.setText("Grid Style:");
mainPanel.add(JLabel5, new GridBagConstraints(0,0,1,1,0.0,0.0,
GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(5,5,0,5),0,0));
gridStyleComboBox.setModel(stringComboBoxModel1);
mainPanel.add(gridStyleComboBox, new GridBagConstraints(1,0,1,1,0.0,0.0,
GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0));
{
String[] tempString = new String[5];
tempString[0] = "RASTER";
tempString[1] = "AREA_FILL";
tempString[2] = "CONTOUR";
tempString[3] = "RASTER_CONTOUR";
tempString[4] = "AREA_FILL_CONTOUR";
for(int i=0; i < tempString.length; i++) {
stringComboBoxModel1.addElement(tempString[i]);
}
}
gridStyleComboBox.setSelectedIndex(0);
setTitle("GridAttribute Properties");
SymWindow aSymWindow = new SymWindow();
this.addWindowListener(aSymWindow);
SymAction lSymAction = new SymAction();
cancelButton.addActionListener(lSymAction);
okButton.addActionListener(lSymAction);
applyButton.addActionListener(lSymAction);
gridStyleComboBox.addActionListener(lSymAction);
newConLevelButton.addActionListener(lSymAction);
newColorMapButton.addActionListener(lSymAction);
loadColorMapButton.addActionListener(lSymAction);
editButton.addActionListener(lSymAction);
aboveButton.addActionListener(lSymAction);
belowButton.addActionListener(lSymAction);
deleteButton.addActionListener(lSymAction);
sortButton.addActionListener(lSymAction);
saveColorMapButton.addActionListener(lSymAction);
defaultButton.addActionListener(lSymAction);
makeColorToggleButtons();
}
private void makeColorToggleButtons() {
Insets insets = new Insets(0,0,0,0);
ButtonGroup bg = new ButtonGroup();
ColorSwatchIcon csi = null;
for(int i=0; i < 256; i++) {
JToggleButton tb = new JToggleButton("");
if(System.getProperty("mrj.version") == null ||
!UIManager.getSystemLookAndFeelClassName().equals(UIManager.getLookAndFeel().getClass().getName()))
tb.setMargin(insets);
csi = new ColorSwatchIcon(Color.white, 8, 8);
tb.setIcon(csi);
colorButtons_[i] = tb;
colorButtonsPanel.add(tb);
bg.add(tb);
}
}
/** Used internally. */
public void addNotify() {
// Record the size of the window prior to calling parents addNotify.
Dimension d = getSize();
super.addNotify();
if (fComponentsAdjusted)
return;
// Adjust components according to the insets
Insets ins = getInsets();
setSize(ins.left + ins.right + d.width, ins.top + ins.bottom + d.height);
Component components[] = getContentPane().getComponents();
for (int i = 0; i < components.length; i++) {
Point p = components[i].getLocation();
p.translate(ins.left, ins.top);
components[i].setLocation(p);
}
fComponentsAdjusted = true;
}
// Used for addNotify check.
boolean fComponentsAdjusted = false;
/**
* Constructor.
*/
public GridAttributeDialog(String title) {
this();
setTitle(title);
}
/**
* Default constructor.
*/
public GridAttributeDialog() {
this((Frame)null);
}
/**
* Make the dialog visible.
*/
public void setVisible(boolean b) {
if(b) {
setLocation(50, 50);
}
super.setVisible(b);
}
class SymWindow extends java.awt.event.WindowAdapter {
public void windowClosing(java.awt.event.WindowEvent event) {
Object object = event.getSource();
if (object == GridAttributeDialog.this)
GridAttributeDialog_WindowClosing(event);
}
}
void GridAttributeDialog_WindowClosing(java.awt.event.WindowEvent event) {
dispose();
}
//{{DECLARE_CONTROLS
javax.swing.JTabbedPane TabbedPane = new javax.swing.JTabbedPane();
javax.swing.JPanel ContourLevelsPanel = new javax.swing.JPanel();
javax.swing.JScrollPane gridScrollPane = new javax.swing.JScrollPane();
javax.swing.JPanel controlPanel = new javax.swing.JPanel();
javax.swing.JPanel JPanel1 = new javax.swing.JPanel();
javax.swing.JButton editButton = new javax.swing.JButton();
javax.swing.JButton aboveButton = new javax.swing.JButton();
javax.swing.JButton belowButton = new javax.swing.JButton();
javax.swing.JButton deleteButton = new javax.swing.JButton();
javax.swing.JPanel JPanel4 = new javax.swing.JPanel();
javax.swing.JButton defaultButton = new javax.swing.JButton();
javax.swing.JButton sortButton = new javax.swing.JButton();
javax.swing.JButton newConLevelButton = new javax.swing.JButton();
javax.swing.JPanel ColorMapPanel = new javax.swing.JPanel();
javax.swing.JPanel colorControlPanel = new javax.swing.JPanel();
javax.swing.JPanel colorMapPanel = new javax.swing.JPanel();
javax.swing.JButton newColorMapButton = new javax.swing.JButton();
javax.swing.JButton loadColorMapButton = new javax.swing.JButton();
javax.swing.JButton saveColorMapButton = new javax.swing.JButton();
javax.swing.JPanel colorPanel = new javax.swing.JPanel();
javax.swing.JPanel CLIndexedPanel = new javax.swing.JPanel();
javax.swing.JPanel CLTransformPanel = new javax.swing.JPanel();
javax.swing.JPanel IndexedPanel = new javax.swing.JPanel();
javax.swing.JPanel colorButtonsPanel = new javax.swing.JPanel();
javax.swing.JPanel TransformPanel = new javax.swing.JPanel();
javax.swing.JPanel buttonPanel = new javax.swing.JPanel();
javax.swing.JButton okButton = new javax.swing.JButton();
javax.swing.JButton applyButton = new javax.swing.JButton();
javax.swing.JButton cancelButton = new javax.swing.JButton();
javax.swing.JPanel mainPanel = new javax.swing.JPanel();
javax.swing.JLabel JLabel5 = new javax.swing.JLabel();
javax.swing.JComboBox gridStyleComboBox = new javax.swing.JComboBox();
javax.swing.border.EtchedBorder etchedBorder1 = new javax.swing.border.EtchedBorder();
DefaultComboBoxModel stringComboBoxModel1 = new DefaultComboBoxModel();
javax.swing.border.EtchedBorder etchedBorder2 = new javax.swing.border.EtchedBorder();
javax.swing.border.TitledBorder titledBorder1 = new javax.swing.border.TitledBorder("Contour Level");
javax.swing.border.EmptyBorder emptyBorder1 = new javax.swing.border.EmptyBorder(5,0,0,0);
javax.swing.border.TitledBorder titledBorder4 = new javax.swing.border.TitledBorder("Default Attributes");
javax.swing.border.TitledBorder titledBorder2 = new javax.swing.border.TitledBorder("Color Map");
//}}
class SymAction implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent event) {
Object object = event.getSource();
if (object == cancelButton)
cancelButton_actionPerformed(event);
else if (object == okButton)
okButton_actionPerformed(event);
else if (object == applyButton)
applyButton_actionPerformed(event);
else if (object == gridStyleComboBox)
gridStyleComboBox_actionPerformed(event);
if (object == newConLevelButton)
newConLevelButton_actionPerformed(event);
if (object == newColorMapButton)
newColorMapButton_actionPerformed(event);
else if (object == loadColorMapButton)
loadColorMapButton_actionPerformed(event);
else if (object == editButton)
editButton_actionPerformed(event);
else if (object == aboveButton)
aboveButton_actionPerformed(event);
else if (object == belowButton)
belowButton_actionPerformed(event);
else if (object == deleteButton)
deleteButton_actionPerformed(event);
else if (object == sortButton)
sortButton_actionPerformed(event);
else if (object == saveColorMapButton)
saveColorMapButton_actionPerformed(event);
else if (object == defaultButton)
defaultButton_actionPerformed(event);
}
}
void cancelButton_actionPerformed(java.awt.event.ActionEvent event) {
this.setVisible(false);
}
void okButton_actionPerformed(java.awt.event.ActionEvent event) {
updateGridAttribute();
this.setVisible(false);
}
void applyButton_actionPerformed(java.awt.event.ActionEvent event) {
updateGridAttribute();
}
/**
* Set the parent <code>JPane</code>. This reference to
* <code>JPane</code> is used to enable/disable
* {@link gov.noaa.pmel.sgt.JPane#setBatch(boolean) batching} so
* multiple property changes are made at one time.
*/
public void setJPane(JPane pane) {
paneList_ = new JPane[1];
paneList_[0] = pane;
}
/**
* Get the first parent pane.
*/
public JPane getJPane() {
if(paneList_ != null) {
return paneList_[0];
} else {
return null;
}
}
/**
* Set the parent <code>JPane</code>s. These references to
* <code>JPane</code> are used to enable/disable
* {@link gov.noaa.pmel.sgt.JPane#setBatch(boolean) batching} so
* multiple property changes are made at one time. A second
* <code>JPane</code> is often used for a <code>ColorKey</code>.
*/
public void setJPaneList(JPane[] list) {
paneList_ = list;
}
/** Get an array of parent panes. */
public JPane[] getJPaneList() {
return paneList_;
}
/**
* Set the <code>GridCartesianRenderer</code>. Specifying the
* renderer give <code>GridAttributeDialog</code> a reference to the
* data and <code>GridAttribute</code> allowing automated
* computation of <code>ColorMap</code> and
* <code>ContourLevels</code> ranges.
*
* @see #setGridAttribute(GridAttribute)
*/
public void setGridCartesianRenderer(GridCartesianRenderer render) {
grid_ = render.getGrid();
setGridAttribute((GridAttribute)render.getAttribute());
}
/**
* Set the <code>GridAttribute</code>.
*/
public void setGridAttribute(GridAttribute attr) {
attr_ = attr;
colorMap_ = attr.getColorMap();
conLevels_ = attr.getContourLevels();
//
// style
//
int style = attr_.getStyle();
gridStyleComboBox.setSelectedIndex(style);
//
// contour ?
//
enableContourLevels(style);
initContourLevels();
//
// raster ?
//
enableColorMap(style);
initColorMap();
//
setCurrentTab();
}
private void enableContourLevels(int style) {
boolean isContour = (style == GridAttribute.CONTOUR ||
style == GridAttribute.RASTER_CONTOUR ||
style == GridAttribute.AREA_FILL_CONTOUR);
TabbedPane.setEnabledAt(contourLevelIndex_, isContour);
Component[] list = ContourLevelsPanel.getComponents();
boolean clExists = conLevels_ != null;
for(int i=0; i < list.length; i++) {
list[i].setEnabled(clExists);
}
newConLevelButton.setEnabled(true);
}
private void enableColorMap(int style) {
boolean isRaster = style != GridAttribute.CONTOUR;
TabbedPane.setEnabledAt(colorMapIndex_, isRaster);
Component[] list = ColorMapPanel.getComponents();
boolean cmExists = colorMap_ != null;
for(int i=0; i < list.length; i++) {
list[i].setEnabled(cmExists);
}
newColorMapButton.setEnabled(true);
}
private void setCurrentTab() {
if(!TabbedPane.isEnabledAt(TabbedPane.getSelectedIndex())) {
//
// change to other tab
//
if(TabbedPane.getSelectedIndex() == colorMapIndex_) {
TabbedPane.setSelectedIndex(contourLevelIndex_);
} else {
TabbedPane.setSelectedIndex(colorMapIndex_);
}
}
}
private void initContourLevels() {
createConLevelTable();
}
private void initColorMap() {
ColorSwatchIcon csi;
int i;
if(colorMap_ instanceof IndexedColor) {
int maxindx = ((IndexedColor)colorMap_).getMaximumIndex();
for(i=0; i <= maxindx; i++) {
csi = new ColorSwatchIcon((IndexedColor)colorMap_, i, 8);
colorButtons_[i].setIcon(csi);
colorButtons_[i].setEnabled(true);
}
for(i=maxindx+1; i < 256; i++) {
csi = new ColorSwatchIcon(Color.white, 8, 8);
colorButtons_[i].setIcon(csi);
colorButtons_[i].setEnabled(false);
}
((CardLayout)colorPanel.getLayout()).show(colorPanel, "Indexed");
}
}
void updateGridAttribute() {
if(paneList_ != null) {
for(int i=0; i < paneList_.length; i++) {
paneList_[i].setBatch(true, "GridAttributeDialog");
}
}
updateConLevels();
attr_.setContourLevels(conLevels_);
attr_.setColorMap(colorMap_);
attr_.setStyle(gridStyleComboBox.getSelectedIndex());
if(paneList_ != null) {
for(int i=0; i < paneList_.length; i++) {
paneList_[i].setBatch(false, "GridAttributeDialog");
}
}
}
/**
* Test entry point.
*/
public static void main(String[] args) {
Range2D range = new Range2D(-20.0f, 45.0f, 5.0f);
ContourLevels clevels = ContourLevels.getDefault(range);
GridAttribute attr = new GridAttribute(clevels);
GridAttributeDialog la = new GridAttributeDialog();
la.setGridAttribute(attr);
la.setTitle("Test GridAttribute Dialog");
la.setVisible(true);
}
void gridStyleComboBox_actionPerformed(java.awt.event.ActionEvent event) {
int style = gridStyleComboBox.getSelectedIndex();
//
enableContourLevels(style);
enableColorMap(style);
setCurrentTab();
//
}
void newConLevelButton_actionPerformed(java.awt.event.ActionEvent event) {
NewLevelsDialog nld = new NewLevelsDialog();
int result = nld.showDialog(grid_);
if(result == NewLevelsDialog.OK_RESPONSE) {
Range2D range = nld.getRange();
conLevels_ = ContourLevels.getDefault(range);
initContourLevels();
}
}
void newColorMapButton_actionPerformed(java.awt.event.ActionEvent event) {
//
// this will be replaced by a specialized dialog
//
//
// define default colormap (ps.64)
//
int[] red =
{ 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 7, 23, 39, 55, 71, 87,103,
119,135,151,167,183,199,215,231,
247,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,246,228,211,193,175,158,140};
int[] green =
{ 0, 0, 0, 0, 0, 0, 0, 0,
0, 11, 27, 43, 59, 75, 91,107,
123,139,155,171,187,203,219,235,
251,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,247,231,215,199,183,167,151,
135,119,103, 87, 71, 55, 39, 23,
7, 0, 0, 0, 0, 0, 0, 0};
int[] blue =
{ 0,143,159,175,191,207,223,239,
255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,
255,247,231,215,199,183,167,151,
135,119,103, 87, 71, 55, 39, 23,
7, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
//
colorMap_ = new IndexedColorMap(red, green, blue);
((IndexedColorMap)colorMap_).setTransform(new LinearTransform(0.0,
(double)red.length,
0.0, 1.0));
initColorMap();
}
void loadColorMapButton_actionPerformed(ActionEvent event) {
int[] r = new int[256];
int[] g = new int[256];
int[] b = new int[256];
int lastindx = -1;
File file = null;
StreamTokenizer st = null;
JFileChooser chooser = new JFileChooser("C:/local/pal");
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
Reader rdr = new BufferedReader(new FileReader(file));
st = new StreamTokenizer(rdr);
} catch (java.io.FileNotFoundException e) {
System.out.println(e);
return;
}
try {
st.nextToken();
while(st.ttype != StreamTokenizer.TT_EOF) {
lastindx++;
if(st.ttype == StreamTokenizer.TT_NUMBER) {
r[lastindx] = (int)st.nval;
st.nextToken();
g[lastindx] = (int)st.nval;
st.nextToken();
b[lastindx] = (int)st.nval;
}
if(st.nextToken() == StreamTokenizer.TT_EOL) st.nextToken();
}
} catch (java.io.IOException e) {
System.out.println(e);
}
int[] red = new int[lastindx+1];
int[] green = new int[lastindx+1];
int[] blue = new int[lastindx+1];
for(int i=0; i <= lastindx; i++) {
red[i] = r[i];
green[i] = g[i];
blue[i] = b[i];
}
colorMap_ = new IndexedColorMap(red, green, blue);
((IndexedColorMap)colorMap_).setTransform(new LinearTransform(0.0,
(double)red.length,
0.0, 1.0));
initColorMap();
}
}
void editButton_actionPerformed(java.awt.event.ActionEvent event) {
ContourLineAttribute attr;
int index = conLevelTable_.getSelectedRow();
if(index < 0) return;
ContourLineAttributeDialog clad = new ContourLineAttributeDialog();
attr = (ContourLineAttribute)
((ContourLineAttribute)conLevelModel_.getValueAt(index,1)).copy();
int result = clad.showDialog(attr);
if(result == ContourLineAttributeDialog.OK_RESPONSE) {
attr = clad.getContourLineAttribute();
conLevelModel_.setValueAt(attr, index, 1);
}
}
void aboveButton_actionPerformed(java.awt.event.ActionEvent event) {
int index = conLevelTable_.getSelectedRow();
if(index < 0) return;
conLevelModel_.insert(index,
new Double(0.0),
new ContourLineAttribute(ContourLineAttribute.SOLID));
}
void belowButton_actionPerformed(java.awt.event.ActionEvent event) {
int index = conLevelTable_.getSelectedRow();
if(index < 0) return;
conLevelModel_.insert(index + 1,
new Double(0.0),
new ContourLineAttribute(ContourLineAttribute.SOLID));
}
void deleteButton_actionPerformed(java.awt.event.ActionEvent event) {
int index = conLevelTable_.getSelectedRow();
if(index < 0) return;
conLevelModel_.remove(index);
}
void sortButton_actionPerformed(java.awt.event.ActionEvent event) {
conLevelModel_.sort();
}
void defaultButton_actionPerformed(java.awt.event.ActionEvent event) {
DefaultContourLineAttribute attr;
DefaultContourLineAttributeDialog dclad = new DefaultContourLineAttributeDialog();
attr = conLevels_.getDefaultContourLineAttribute();
int result = dclad.showDialog((DefaultContourLineAttribute)attr.copy());
if(result == DefaultContourLineAttributeDialog.OK_RESPONSE) {
attr = dclad.getDefaultContourLineAttribute();
conLevels_.setDefaultContourLineAttribute(attr);
}
}
void saveColorMapButton_actionPerformed(java.awt.event.ActionEvent event) {
// to do: code goes here.
}
void createConLevelTable() {
Double val;
ContourLineAttribute attr;
conLevelModel_ = new ConLevelTableModel();
conLevelTable_ = new JTable(conLevelModel_);
conLevelTable_.setSize(1000,1000);
ListSelectionModel lsm = conLevelTable_.getSelectionModel();
lsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
TableColumn tc;
tc = conLevelTable_.getColumnModel().getColumn(0);
tc.setPreferredWidth(250);
tc = conLevelTable_.getColumnModel().getColumn(1);
tc.setPreferredWidth(750);
gridScrollPane.getViewport().add(conLevelTable_);
//
if(conLevels_ == null) return;
int size = conLevels_.size();
for(int i=0; i < size; i++) {
try {
val = new Double(conLevels_.getLevel(i));
attr = conLevels_.getContourLineAttribute(i);
conLevelModel_.add(val, attr);
} catch (ContourLevelNotFoundException e) {
System.out.println(e);
}
}
}
private void updateConLevels() {
if(conLevels_ == null) return;
ContourLevels cl = new ContourLevels();
Double val;
ContourLineAttribute attr;
conLevelModel_.sort();
int size = conLevelModel_.getRowCount();
for(int i=0; i < size; i++) {
val = (Double)conLevelModel_.getValueAt(i,0);
attr = (ContourLineAttribute)conLevelModel_.getValueAt(i,1);
cl.addLevel(val.doubleValue(), attr);
}
cl.setDefaultContourLineAttribute(conLevels_.getDefaultContourLineAttribute());
conLevels_ = cl;
}
class ConLevelTableModel extends AbstractTableModel {
Vector values = new Vector();
Vector attr = new Vector();
String[] titles = {"Value", "Attribute"};
public void add(Double val, ContourLineAttribute cla) {
values.addElement(val);
attr.addElement(cla);
}
public void insert(int row, Double val, ContourLineAttribute cla) {
values.insertElementAt(val, row);
attr.insertElementAt(cla, row);
fireTableChanged(new TableModelEvent(this, row, row,
TableModelEvent.ALL_COLUMNS,
TableModelEvent.INSERT));
}
public void remove(int row) {
values.removeElementAt(row);
attr.removeElementAt(row);
fireTableChanged(new TableModelEvent(this, row, row,
TableModelEvent.ALL_COLUMNS,
TableModelEvent.DELETE));
}
public void sort() {
//
// use brain-dead bubble sort (there will be few lines)
//
int i, temp;
int size = values.size();
Double a, b;
int[] index = new int[size];
boolean flipped = true;
for(i=0; i < size; i++) {
index[i] = i;
}
while(flipped) {
flipped = false;
for(i=0; i < size-1; i++) {
a = (Double)values.elementAt(index[i]);
b = (Double)values.elementAt(index[i+1]);
if(a.doubleValue() > b.doubleValue()) {
// if(a.compareTo(b) > 0) { // jdk1.2
temp = index[i];
index[i] = index[i+1];
index[i+1] = temp;
flipped = true;
}
}
}
Vector oldValues = values;
Vector oldAttr = attr;
values = new Vector(size);
attr = new Vector(size);
for(i=0; i < size; i++) {
values.addElement(oldValues.elementAt(index[i]));
attr.addElement(oldAttr.elementAt(index[i]));
}
fireTableChanged(new TableModelEvent(this));
}
public Object getValueAt(int row, int col) {
if(col == 0) {
return values.elementAt(row);
} else {
return attr.elementAt(row);
}
}
public void setValueAt(Object obj, int row, int col) {
if(col == 0) {
if(obj instanceof Double) {
values.setElementAt(obj, row);
} else if(obj instanceof String) {
values.setElementAt(new Double((String)obj), row);
}
} else {
attr.setElementAt(obj, row);
}
fireTableCellUpdated(row, col);
}
public int getRowCount() {
return values.size();
}
public int getColumnCount() {
return 2;
}
public String getColumnName(int col) {
return titles[col];
}
public boolean isCellEditable(int row, int col) {
return col == 0;
}
}
}
|
luttero/Maud
|
src/gov/noaa/pmel/sgt/swing/prop/GridAttributeDialog.java
|
Java
|
bsd-3-clause
| 32,899 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/proxy/proxy_service_v8.h"
#include "base/logging.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread_checker.h"
#include "net/proxy/network_delegate_error_observer.h"
#include "net/proxy/proxy_resolver.h"
#include "net/proxy/proxy_resolver_factory.h"
#include "net/proxy/proxy_resolver_v8_tracing_wrapper.h"
#include "net/proxy/proxy_service.h"
namespace net {
// static
ProxyService* CreateProxyServiceUsingV8ProxyResolver(
ProxyConfigService* proxy_config_service,
ProxyScriptFetcher* proxy_script_fetcher,
scoped_ptr<DhcpProxyScriptFetcher> dhcp_proxy_script_fetcher,
HostResolver* host_resolver,
NetLog* net_log,
NetworkDelegate* network_delegate) {
DCHECK(proxy_config_service);
DCHECK(proxy_script_fetcher);
DCHECK(dhcp_proxy_script_fetcher);
DCHECK(host_resolver);
ProxyService* proxy_service = new ProxyService(
proxy_config_service,
make_scoped_ptr(new ProxyResolverFactoryV8TracingWrapper(
host_resolver, net_log,
base::Bind(&NetworkDelegateErrorObserver::Create, network_delegate,
base::ThreadTaskRunnerHandle::Get()))),
net_log);
// Configure fetchers to use for PAC script downloads and auto-detect.
proxy_service->SetProxyScriptFetchers(proxy_script_fetcher,
dhcp_proxy_script_fetcher.Pass());
return proxy_service;
}
} // namespace net
|
Chilledheart/chromium
|
net/proxy/proxy_service_v8.cc
|
C++
|
bsd-3-clause
| 1,609 |
<?php
/**
* PradoBase class file.
*
* This is the file that establishes the PRADO component model
* and error handling mechanism.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.pradosoft.com/
* @copyright Copyright © 2005-2011 PradoSoft
* @license http://www.pradosoft.com/license/
* @version $Id: PradoBase.php 3168 2012-06-25 10:43:31Z ctrlaltca $
* @package System
*/
/**
* Defines the PRADO framework installation path.
*/
if(!defined('PRADO_DIR'))
define('PRADO_DIR',dirname(__FILE__));
/**
* Defines the default permission for writable directories and files
*/
if(!defined('PRADO_CHMOD'))
define('PRADO_CHMOD',0777);
/**
* PradoBase class.
*
* PradoBase implements a few fundamental static methods.
*
* To use the static methods, Use Prado as the class name rather than PradoBase.
* PradoBase is meant to serve as the base class of Prado. The latter might be
* rewritten for customization.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: PradoBase.php 3168 2012-06-25 10:43:31Z ctrlaltca $
* @package System
* @since 3.0
*/
class PradoBase
{
/**
* File extension for Prado class files.
*/
const CLASS_FILE_EXT='.php';
/**
* @var array list of path aliases
*/
private static $_aliases=array('System'=>PRADO_DIR);
/**
* @var array list of namespaces currently in use
*/
private static $_usings=array();
/**
* @var TApplication the application instance
*/
private static $_application=null;
/**
* @var TLogger logger instance
*/
private static $_logger=null;
/**
* @var array list of class exists checks
*/
protected static $classExists = array();
/**
* @return string the version of Prado framework
*/
public static function getVersion()
{
return '3.2.0';
}
/**
* Initializes error handlers.
* This method set error and exception handlers to be functions
* defined in this class.
*/
public static function initErrorHandlers()
{
/**
* Sets error handler to be Prado::phpErrorHandler
*/
set_error_handler(array('PradoBase','phpErrorHandler'));
/**
* Sets exception handler to be Prado::exceptionHandler
*/
set_exception_handler(array('PradoBase','exceptionHandler'));
}
/**
* Class autoload loader.
* This method is provided to be invoked within an __autoload() magic method.
* @param string class name
*/
public static function autoload($className)
{
include_once($className.self::CLASS_FILE_EXT);
if(!class_exists($className,false) && !interface_exists($className,false))
self::fatalError("Class file for '$className' cannot be found.");
}
/**
* @param integer the type of "powered logo". Valid values include 0 and 1.
* @return string a string that can be displayed on your Web page showing powered-by-PRADO information
*/
public static function poweredByPrado($logoType=0)
{
$logoName=$logoType==1?'powered2':'powered';
if(self::$_application!==null)
{
$am=self::$_application->getAssetManager();
$url=$am->publishFilePath(self::getPathOfNamespace('System.'.$logoName,'.gif'));
}
else
$url='http://www.pradosoft.com/images/'.$logoName.'.gif';
return '<a title="Powered by PRADO" href="http://www.pradosoft.com/" target="_blank"><img src="'.$url.'" style="border-width:0px;" alt="Powered by PRADO" /></a>';
}
/**
* PHP error handler.
* This method should be registered as PHP error handler using
* {@link set_error_handler}. The method throws an exception that
* contains the error information.
* @param integer the level of the error raised
* @param string the error message
* @param string the filename that the error was raised in
* @param integer the line number the error was raised at
*/
public static function phpErrorHandler($errno,$errstr,$errfile,$errline)
{
if(error_reporting() & $errno)
throw new TPhpErrorException($errno,$errstr,$errfile,$errline);
}
/**
* Default exception handler.
* This method should be registered as default exception handler using
* {@link set_exception_handler}. The method tries to use the errorhandler
* module of the Prado application to handle the exception.
* If the application or the module does not exist, it simply echoes the
* exception.
* @param Exception exception that is not caught
*/
public static function exceptionHandler($exception)
{
if(self::$_application!==null && ($errorHandler=self::$_application->getErrorHandler())!==null)
{
$errorHandler->handleError(null,$exception);
}
else
{
echo $exception;
}
exit(1);
}
/**
* Stores the application instance in the class static member.
* This method helps implement a singleton pattern for TApplication.
* Repeated invocation of this method or the application constructor
* will cause the throw of an exception.
* This method should only be used by framework developers.
* @param TApplication the application instance
* @throws TInvalidOperationException if this method is invoked twice or more.
*/
public static function setApplication($application)
{
if(self::$_application!==null)
throw new TInvalidOperationException('prado_application_singleton_required');
self::$_application=$application;
}
/**
* @return TApplication the application singleton, null if the singleton has not be created yet.
*/
public static function getApplication()
{
return self::$_application;
}
/**
* @return string the path of the framework
*/
public static function getFrameworkPath()
{
return PRADO_DIR;
}
/**
* Serializes a data.
* The original PHP serialize function has a bug that may not serialize
* properly an object.
* @param mixed data to be serialized
* @return string the serialized data
*/
public static function serialize($data)
{
return serialize($data);
}
/**
* Unserializes a data.
* The original PHP unserialize function has a bug that may not unserialize
* properly an object.
* @param string data to be unserialized
* @return mixed unserialized data, null if unserialize failed
*/
public static function unserialize($str)
{
return unserialize($str);
}
/**
* Creates a component with the specified type.
* A component type can be either the component class name
* or a namespace referring to the path of the component class file.
* For example, 'TButton', 'System.Web.UI.WebControls.TButton' are both
* valid component type.
* This method can also pass parameters to component constructors.
* All parameters passed to this method except the first one (the component type)
* will be supplied as component constructor parameters.
* @param string component type
* @return TComponent component instance of the specified type
* @throws TInvalidDataValueException if the component type is unknown
*/
public static function createComponent($type)
{
if(!isset(self::$classExists[$type]))
self::$classExists[$type] = class_exists($type, false);
if( !isset(self::$_usings[$type]) && !self::$classExists[$type]) {
self::using($type);
self::$classExists[$type] = class_exists($type, false);
}
if( ($pos = strrpos($type, '.')) !== false)
$type = substr($type,$pos+1);
if(($n=func_num_args())>1)
{
$args = func_get_args();
switch($n) {
case 2:
return new $type($args[1]);
break;
case 3:
return new $type($args[1], $args[2]);
break;
case 4:
return new $type($args[1], $args[2], $args[3]);
break;
case 5:
return new $type($args[1], $args[2], $args[3], $args[4]);
break;
default:
$s='$args[1]';
for($i=2;$i<$n;++$i)
$s.=",\$args[$i]";
eval("\$component=new $type($s);");
return $component;
break;
}
}
else
return new $type;
}
/**
* Uses a namespace.
* A namespace ending with an asterisk '*' refers to a directory, otherwise it represents a PHP file.
* If the namespace corresponds to a directory, the directory will be appended
* to the include path. If the namespace corresponds to a file, it will be included (include_once).
* @param string namespace to be used
* @param boolean whether to check the existence of the class after the class file is included
* @throws TInvalidDataValueException if the namespace is invalid
*/
public static function using($namespace,$checkClassExistence=true)
{
if(isset(self::$_usings[$namespace]) || class_exists($namespace,false))
return;
if(($pos=strrpos($namespace,'.'))===false) // a class name
{
try
{
include_once($namespace.self::CLASS_FILE_EXT);
}
catch(Exception $e)
{
if($checkClassExistence && !class_exists($namespace,false))
throw new TInvalidOperationException('prado_component_unknown',$namespace,$e->getMessage());
else
throw $e;
}
}
else if(($path=self::getPathOfNamespace($namespace,self::CLASS_FILE_EXT))!==null)
{
$className=substr($namespace,$pos+1);
if($className==='*') // a directory
{
self::$_usings[$namespace]=$path;
set_include_path(get_include_path().PATH_SEPARATOR.$path);
}
else // a file
{
self::$_usings[$namespace]=$path;
if(!$checkClassExistence || !class_exists($className,false))
{
try
{
include_once($path);
}
catch(Exception $e)
{
if($checkClassExistence && !class_exists($className,false))
throw new TInvalidOperationException('prado_component_unknown',$className,$e->getMessage());
else
throw $e;
}
}
}
}
else
throw new TInvalidDataValueException('prado_using_invalid',$namespace);
}
/**
* Translates a namespace into a file path.
* The first segment of the namespace is considered as a path alias
* which is replaced with the actual path. The rest segments are
* subdirectory names appended to the aliased path.
* If the namespace ends with an asterisk '*', it represents a directory;
* Otherwise it represents a file whose extension name is specified by the second parameter (defaults to empty).
* Note, this method does not ensure the existence of the resulting file path.
* @param string namespace
* @param string extension to be appended if the namespace refers to a file
* @return string file path corresponding to the namespace, null if namespace is invalid
*/
public static function getPathOfNamespace($namespace, $ext='')
{
if(self::CLASS_FILE_EXT === $ext || empty($ext))
{
if(isset(self::$_usings[$namespace]))
return self::$_usings[$namespace];
if(isset(self::$_aliases[$namespace]))
return self::$_aliases[$namespace];
}
$segs = explode('.',$namespace);
$alias = array_shift($segs);
if(null !== ($file = array_pop($segs)) && null !== ($root = self::getPathOfAlias($alias)))
return rtrim($root.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR ,$segs),'/\\').(($file === '*') ? '' : DIRECTORY_SEPARATOR.$file.$ext);
return null;
}
/**
* @param string alias to the path
* @return string the path corresponding to the alias, null if alias not defined.
*/
public static function getPathOfAlias($alias)
{
return isset(self::$_aliases[$alias])?self::$_aliases[$alias]:null;
}
protected static function getPathAliases()
{
return self::$_aliases;
}
/**
* @param string alias to the path
* @param string the path corresponding to the alias
* @throws TInvalidOperationException if the alias is already defined
* @throws TInvalidDataValueException if the path is not a valid file path
*/
public static function setPathOfAlias($alias,$path)
{
if(isset(self::$_aliases[$alias]))
throw new TInvalidOperationException('prado_alias_redefined',$alias);
else if(($rp=realpath($path))!==false && is_dir($rp))
{
if(strpos($alias,'.')===false)
self::$_aliases[$alias]=$rp;
else
throw new TInvalidDataValueException('prado_aliasname_invalid',$alias);
}
else
throw new TInvalidDataValueException('prado_alias_invalid',$alias,$path);
}
/**
* Fatal error handler.
* This method displays an error message together with the current call stack.
* The application will exit after calling this method.
* @param string error message
*/
public static function fatalError($msg)
{
echo '<h1>Fatal Error</h1>';
echo '<p>'.$msg.'</p>';
if(!function_exists('debug_backtrace'))
return;
echo '<h2>Debug Backtrace</h2>';
echo '<pre>';
$index=-1;
foreach(debug_backtrace() as $t)
{
$index++;
if($index==0) // hide the backtrace of this function
continue;
echo '#'.$index.' ';
if(isset($t['file']))
echo basename($t['file']) . ':' . $t['line'];
else
echo '<PHP inner-code>';
echo ' -- ';
if(isset($t['class']))
echo $t['class'] . $t['type'];
echo $t['function'] . '(';
if(isset($t['args']) && sizeof($t['args']) > 0)
{
$count=0;
foreach($t['args'] as $item)
{
if(is_string($item))
{
$str=htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES);
if (strlen($item) > 70)
echo "'". substr($str, 0, 70) . "...'";
else
echo "'" . $str . "'";
}
else if (is_int($item) || is_float($item))
echo $item;
else if (is_object($item))
echo get_class($item);
else if (is_array($item))
echo 'array(' . count($item) . ')';
else if (is_bool($item))
echo $item ? 'true' : 'false';
else if ($item === null)
echo 'NULL';
else if (is_resource($item))
echo get_resource_type($item);
$count++;
if (count($t['args']) > $count)
echo ', ';
}
}
echo ")\n";
}
echo '</pre>';
exit(1);
}
/**
* Returns a list of user preferred languages.
* The languages are returned as an array. Each array element
* represents a single language preference. The languages are ordered
* according to user preferences. The first language is the most preferred.
* @return array list of user preferred languages.
*/
public static function getUserLanguages()
{
static $languages=null;
if($languages===null)
{
if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
$languages[0]='en';
else
{
$languages=array();
foreach(explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']) as $language)
{
$array=explode(';q=',trim($language));
$languages[trim($array[0])]=isset($array[1])?(float)$array[1]:1.0;
}
arsort($languages);
$languages=array_keys($languages);
if(empty($languages))
$languages[0]='en';
}
}
return $languages;
}
/**
* Returns the most preferred language by the client user.
* @return string the most preferred language by the client user, defaults to English.
*/
public static function getPreferredLanguage()
{
static $language=null;
if($language===null)
{
$langs=Prado::getUserLanguages();
$lang=explode('-',$langs[0]);
if(empty($lang[0]) || !ctype_alpha($lang[0]))
$language='en';
else
$language=$lang[0];
}
return $language;
}
/**
* Writes a log message.
* This method wraps {@link log()} by checking the application mode.
* When the application is in Debug mode, debug backtrace information is appended
* to the message and the message is logged at DEBUG level.
* When the application is in Performance mode, this method does nothing.
* Otherwise, the message is logged at INFO level.
* @param string message to be logged
* @param string category of the message
* @param (string|TControl) control of the message
* @see log, getLogger
*/
public static function trace($msg,$category='Uncategorized',$ctl=null)
{
if(self::$_application && self::$_application->getMode()===TApplicationMode::Performance)
return;
if(!self::$_application || self::$_application->getMode()===TApplicationMode::Debug)
{
$trace=debug_backtrace();
if(isset($trace[0]['file']) && isset($trace[0]['line']))
$msg.=" (line {$trace[0]['line']}, {$trace[0]['file']})";
$level=TLogger::DEBUG;
}
else
$level=TLogger::INFO;
self::log($msg,$level,$category,$ctl);
}
/**
* Logs a message.
* Messages logged by this method may be retrieved via {@link TLogger::getLogs}
* and may be recorded in different media, such as file, email, database, using
* {@link TLogRouter}.
* @param string message to be logged
* @param integer level of the message. Valid values include
* TLogger::DEBUG, TLogger::INFO, TLogger::NOTICE, TLogger::WARNING,
* TLogger::ERROR, TLogger::ALERT, TLogger::FATAL.
* @param string category of the message
* @param (string|TControl) control of the message
*/
public static function log($msg,$level=TLogger::INFO,$category='Uncategorized',$ctl=null)
{
if(self::$_logger===null)
self::$_logger=new TLogger;
self::$_logger->log($msg,$level,$category,$ctl);
}
/**
* @return TLogger message logger
*/
public static function getLogger()
{
if(self::$_logger===null)
self::$_logger=new TLogger;
return self::$_logger;
}
/**
* Converts a variable into a string representation.
* This method achieves the similar functionality as var_dump and print_r
* but is more robust when handling complex objects such as PRADO controls.
* @param mixed variable to be dumped
* @param integer maximum depth that the dumper should go into the variable. Defaults to 10.
* @param boolean whether to syntax highlight the output. Defaults to false.
* @return string the string representation of the variable
*/
public static function varDump($var,$depth=10,$highlight=false)
{
Prado::using('System.Util.TVarDumper');
return TVarDumper::dump($var,$depth,$highlight);
}
/**
* Localize a text to the locale/culture specified in the globalization handler.
* @param string text to be localized.
* @param array a set of parameters to substitute.
* @param string a different catalogue to find the localize text.
* @param string the input AND output charset.
* @return string localized text.
* @see TTranslate::formatter()
* @see TTranslate::init()
*/
public static function localize($text, $parameters=array(), $catalogue=null, $charset=null)
{
Prado::using('System.I18N.Translation');
$app = Prado::getApplication()->getGlobalization(false);
$params = array();
foreach($parameters as $key => $value)
$params['{'.$key.'}'] = $value;
//no translation handler provided
if($app===null || ($config = $app->getTranslationConfiguration())===null)
return strtr($text, $params);
if ($catalogue===null)
$catalogue=isset($config['catalogue'])?$config['catalogue']:'messages';
Translation::init($catalogue);
//globalization charset
$appCharset = $app===null ? '' : $app->getCharset();
//default charset
$defaultCharset = ($app===null) ? 'UTF-8' : $app->getDefaultCharset();
//fall back
if(empty($charset)) $charset = $appCharset;
if(empty($charset)) $charset = $defaultCharset;
return Translation::formatter($catalogue)->format($text,$params,$catalogue,$charset);
}
}
/**
* Includes the classes essential for PradoBase class
*/
PradoBase::using('System.TComponent');
PradoBase::using('System.Exceptions.TException');
PradoBase::using('System.Util.TLogger');
|
wiccano/WDEPRDO
|
framework/PradoBase.php
|
PHP
|
bsd-3-clause
| 19,078 |
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !cgo,!windows,!plan9 android vita
package user
import (
"errors"
"fmt"
"os"
"runtime"
"strconv"
)
func init() {
groupImplemented = false
}
func current() (*User, error) {
u := &User{
Uid: currentUID(),
Gid: currentGID(),
Username: os.Getenv("USER"),
Name: "", // ignored
HomeDir: os.Getenv("HOME"),
}
// On NaCL and Android, return a dummy user instead of failing.
switch runtime.GOOS {
case "nacl":
if u.Uid == "" {
u.Uid = "1"
}
if u.Username == "" {
u.Username = "nacl"
}
if u.HomeDir == "" {
u.HomeDir = "/"
}
case "android":
if u.Uid == "" {
u.Uid = "1"
}
if u.Username == "" {
u.Username = "android"
}
if u.HomeDir == "" {
u.HomeDir = "/sdcard"
}
}
// cgo isn't available, but if we found the minimum information
// without it, use it:
if u.Uid != "" && u.Username != "" && u.HomeDir != "" {
return u, nil
}
return u, fmt.Errorf("user: Current not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
func listGroups(*User) ([]string, error) {
if runtime.GOOS == "android" {
return nil, errors.New("user: GroupIds not implemented on Android")
}
return nil, errors.New("user: GroupIds requires cgo")
}
func currentUID() string {
if id := os.Getuid(); id >= 0 {
return strconv.Itoa(id)
}
// Note: Windows returns -1, but this file isn't used on
// Windows anyway, so this empty return path shouldn't be
// used.
return ""
}
func currentGID() string {
if id := os.Getgid(); id >= 0 {
return strconv.Itoa(id)
}
return ""
}
|
codestation/go
|
src/os/user/lookup_stubs.go
|
GO
|
bsd-3-clause
| 1,709 |
package main
import "fmt"
import "time"
type Ball struct{ hits int }
func main() {
table := make(chan *Ball)
go player("ping", table)
go player("pong", table)
table <- new(Ball) // game on; toss the ball
time.Sleep(1 * time.Second)
<-table // game over; grab the ball
panic("show the stack")
}
func player(name string, table chan *Ball) {
for {
ball := <-table
ball.hits++
fmt.Println(name, ball.hits)
time.Sleep(100 * time.Millisecond)
table <- ball
}
}
|
immortal/sandbox
|
go/goroutine/ping-pong/main.go
|
GO
|
bsd-3-clause
| 480 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.03.15 at 01:54:55 PM MEZ
//
// Based on the XML schmema: TigerXMLHeader.xsd
// Reference: http://www.coli.uni-saarland.de/projects/salsa/
//
package tigerxml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for headType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="headType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="meta" type="{}metaType" minOccurs="0"/>
* <element name="annotation" type="{}annotationType" minOccurs="0"/>
* </sequence>
* <attribute name="external" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "headType", propOrder = {
"meta",
"annotation"
})
public class Head {
protected Meta meta;
protected Annotation annotation;
@XmlAttribute
@XmlSchemaType(name = "anyURI")
protected String external;
/**
* Gets the value of the meta property.
*
* @return
* possible object is
* {@link Meta }
*
*/
public Meta getMeta() {
return meta;
}
/**
* Sets the value of the meta property.
*
* @param value
* allowed object is
* {@link Meta }
*
*/
public void setMeta(Meta value) {
this.meta = value;
}
/**
* Gets the value of the annotation property.
*
* @return
* possible object is
* {@link Annotation }
*
*/
public Annotation getAnnotation() {
if (annotation == null) {
annotation = new Annotation();
}
return annotation;
}
/**
* Sets the value of the annotation property.
*
* @param value
* allowed object is
* {@link Annotation }
*
*/
public void setAnnotation(Annotation value) {
this.annotation = value;
}
/**
* Gets the value of the external property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExternal() {
return external;
}
/**
* Sets the value of the external property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExternal(String value) {
this.external = value;
}
}
|
svoos/CorpusConverter
|
src/main/java/tigerxml/Head.java
|
Java
|
bsd-3-clause
| 3,131 |
package main
// Single sender
// Multiple receivers - round-robin
// Durable
// Delayed acknowledgment
import (
"fmt"
"time"
"github.com/streadway/amqp"
)
const (
broker = "amqp://localhost"
queue1 = "gs3-queue"
// Should queue persist beyond broker restart?
durable = true
// Should queue be deleted once all clients have disconnected?
autoDelete = false
exclusive = false
nowait = false
nolocal = false // not supported
autoAck = false
)
func main() {
conn, err := amqp.Dial(broker)
if err != nil {
fmt.Printf("Couldn't open amqp connection: %v\n", err)
return
}
defer conn.Close()
chn, err := conn.Channel()
if err != nil {
fmt.Printf("Couldn't open amqp channel: %v\n", err)
return
}
defer chn.Close()
qq, err := chn.QueueDeclare(queue1, durable, autoDelete, exclusive, nowait, nil)
if err != nil {
fmt.Printf("Couldn't open amqp queue: %v\n", err)
return
}
fmt.Printf("Queue declared: %s (%d, %d)\n", qq.Name, qq.Consumers, qq.Messages)
recv, err := chn.Consume(queue1, "", autoAck, exclusive, nolocal, nowait, nil)
if err != nil {
fmt.Printf("Couldn't open amqp queue for receiving: %v\n", err)
return
}
var msg amqp.Delivery
lastAckd := 0
i := 1
go func() {
for {
if len(msg.Body) > 0 && lastAckd < i {
fmt.Printf("acking up to %d\n", i)
msg.Ack(true)
lastAckd = i
}
time.Sleep(5000 * time.Millisecond)
}
}()
for msg = range recv {
fmt.Printf("[%03d] msg: %v\n", i, msg)
i++
}
fmt.Printf("messages done...\n")
}
|
dterei/Scraps
|
amqp/gs3/recv.go
|
GO
|
bsd-3-clause
| 1,522 |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import collections
import itertools
from contextlib import contextmanager
import six
from cryptography import utils
from cryptography.exceptions import (
InternalError, UnsupportedAlgorithm, _Reasons
)
from cryptography.hazmat.backends.interfaces import (
CMACBackend, CipherBackend, DERSerializationBackend, DSABackend,
EllipticCurveBackend, HMACBackend, HashBackend, PBKDF2HMACBackend,
PEMSerializationBackend, RSABackend, X509Backend
)
from cryptography.hazmat.backends.openssl.ciphers import (
_AESCTRCipherContext, _CipherContext
)
from cryptography.hazmat.backends.openssl.cmac import _CMACContext
from cryptography.hazmat.backends.openssl.dsa import (
_DSAParameters, _DSAPrivateKey, _DSAPublicKey
)
from cryptography.hazmat.backends.openssl.ec import (
_EllipticCurvePrivateKey, _EllipticCurvePublicKey
)
from cryptography.hazmat.backends.openssl.hashes import _HashContext
from cryptography.hazmat.backends.openssl.hmac import _HMACContext
from cryptography.hazmat.backends.openssl.rsa import (
_RSAPrivateKey, _RSAPublicKey
)
from cryptography.hazmat.backends.openssl.x509 import (
_Certificate, _CertificateSigningRequest
)
from cryptography.hazmat.bindings.openssl.binding import Binding
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa
from cryptography.hazmat.primitives.asymmetric.padding import (
MGF1, OAEP, PKCS1v15, PSS
)
from cryptography.hazmat.primitives.ciphers.algorithms import (
AES, ARC4, Blowfish, CAST5, Camellia, IDEA, SEED, TripleDES
)
from cryptography.hazmat.primitives.ciphers.modes import (
CBC, CFB, CFB8, CTR, ECB, GCM, OFB
)
_MemoryBIO = collections.namedtuple("_MemoryBIO", ["bio", "char_ptr"])
_OpenSSLError = collections.namedtuple("_OpenSSLError",
["code", "lib", "func", "reason"])
@utils.register_interface(CipherBackend)
@utils.register_interface(CMACBackend)
@utils.register_interface(DERSerializationBackend)
@utils.register_interface(DSABackend)
@utils.register_interface(EllipticCurveBackend)
@utils.register_interface(HashBackend)
@utils.register_interface(HMACBackend)
@utils.register_interface(PBKDF2HMACBackend)
@utils.register_interface(RSABackend)
@utils.register_interface(PEMSerializationBackend)
@utils.register_interface(X509Backend)
class Backend(object):
"""
OpenSSL API binding interfaces.
"""
name = "openssl"
def __init__(self):
self._binding = Binding()
self._ffi = self._binding.ffi
self._lib = self._binding.lib
self._binding.init_static_locks()
# adds all ciphers/digests for EVP
self._lib.OpenSSL_add_all_algorithms()
# registers available SSL/TLS ciphers and digests
self._lib.SSL_library_init()
# loads error strings for libcrypto and libssl functions
self._lib.SSL_load_error_strings()
self._cipher_registry = {}
self._register_default_ciphers()
self.activate_osrandom_engine()
def activate_builtin_random(self):
# Obtain a new structural reference.
e = self._lib.ENGINE_get_default_RAND()
if e != self._ffi.NULL:
self._lib.ENGINE_unregister_RAND(e)
# Reset the RNG to use the new engine.
self._lib.RAND_cleanup()
# decrement the structural reference from get_default_RAND
res = self._lib.ENGINE_finish(e)
assert res == 1
def activate_osrandom_engine(self):
# Unregister and free the current engine.
self.activate_builtin_random()
# Fetches an engine by id and returns it. This creates a structural
# reference.
e = self._lib.ENGINE_by_id(self._lib.Cryptography_osrandom_engine_id)
assert e != self._ffi.NULL
# Initialize the engine for use. This adds a functional reference.
res = self._lib.ENGINE_init(e)
assert res == 1
# Set the engine as the default RAND provider.
res = self._lib.ENGINE_set_default_RAND(e)
assert res == 1
# Decrement the structural ref incremented by ENGINE_by_id.
res = self._lib.ENGINE_free(e)
assert res == 1
# Decrement the functional ref incremented by ENGINE_init.
res = self._lib.ENGINE_finish(e)
assert res == 1
# Reset the RNG to use the new engine.
self._lib.RAND_cleanup()
def openssl_version_text(self):
"""
Friendly string name of the loaded OpenSSL library. This is not
necessarily the same version as it was compiled against.
Example: OpenSSL 1.0.1e 11 Feb 2013
"""
return self._ffi.string(
self._lib.SSLeay_version(self._lib.SSLEAY_VERSION)
).decode("ascii")
def create_hmac_ctx(self, key, algorithm):
return _HMACContext(self, key, algorithm)
def hash_supported(self, algorithm):
digest = self._lib.EVP_get_digestbyname(algorithm.name.encode("ascii"))
return digest != self._ffi.NULL
def hmac_supported(self, algorithm):
return self.hash_supported(algorithm)
def create_hash_ctx(self, algorithm):
return _HashContext(self, algorithm)
def cipher_supported(self, cipher, mode):
if self._evp_cipher_supported(cipher, mode):
return True
elif isinstance(mode, CTR) and isinstance(cipher, AES):
return True
else:
return False
def _evp_cipher_supported(self, cipher, mode):
try:
adapter = self._cipher_registry[type(cipher), type(mode)]
except KeyError:
return False
evp_cipher = adapter(self, cipher, mode)
return self._ffi.NULL != evp_cipher
def register_cipher_adapter(self, cipher_cls, mode_cls, adapter):
if (cipher_cls, mode_cls) in self._cipher_registry:
raise ValueError("Duplicate registration for: {0} {1}.".format(
cipher_cls, mode_cls)
)
self._cipher_registry[cipher_cls, mode_cls] = adapter
def _register_default_ciphers(self):
for mode_cls in [CBC, CTR, ECB, OFB, CFB, CFB8]:
self.register_cipher_adapter(
AES,
mode_cls,
GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}")
)
for mode_cls in [CBC, CTR, ECB, OFB, CFB]:
self.register_cipher_adapter(
Camellia,
mode_cls,
GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}")
)
for mode_cls in [CBC, CFB, CFB8, OFB]:
self.register_cipher_adapter(
TripleDES,
mode_cls,
GetCipherByName("des-ede3-{mode.name}")
)
self.register_cipher_adapter(
TripleDES,
ECB,
GetCipherByName("des-ede3")
)
for mode_cls in [CBC, CFB, OFB, ECB]:
self.register_cipher_adapter(
Blowfish,
mode_cls,
GetCipherByName("bf-{mode.name}")
)
for mode_cls in [CBC, CFB, OFB, ECB]:
self.register_cipher_adapter(
SEED,
mode_cls,
GetCipherByName("seed-{mode.name}")
)
for cipher_cls, mode_cls in itertools.product(
[CAST5, IDEA],
[CBC, OFB, CFB, ECB],
):
self.register_cipher_adapter(
cipher_cls,
mode_cls,
GetCipherByName("{cipher.name}-{mode.name}")
)
self.register_cipher_adapter(
ARC4,
type(None),
GetCipherByName("rc4")
)
self.register_cipher_adapter(
AES,
GCM,
GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}")
)
def create_symmetric_encryption_ctx(self, cipher, mode):
if (isinstance(mode, CTR) and isinstance(cipher, AES) and
not self._evp_cipher_supported(cipher, mode)):
# This is needed to provide support for AES CTR mode in OpenSSL
# 0.9.8. It can be removed when we drop 0.9.8 support (RHEL 5
# extended life ends 2020).
return _AESCTRCipherContext(self, cipher, mode)
else:
return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT)
def create_symmetric_decryption_ctx(self, cipher, mode):
if (isinstance(mode, CTR) and isinstance(cipher, AES) and
not self._evp_cipher_supported(cipher, mode)):
# This is needed to provide support for AES CTR mode in OpenSSL
# 0.9.8. It can be removed when we drop 0.9.8 support (RHEL 5
# extended life ends 2020).
return _AESCTRCipherContext(self, cipher, mode)
else:
return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT)
def pbkdf2_hmac_supported(self, algorithm):
if self._lib.Cryptography_HAS_PBKDF2_HMAC:
return self.hmac_supported(algorithm)
else:
# OpenSSL < 1.0.0 has an explicit PBKDF2-HMAC-SHA1 function,
# so if the PBKDF2_HMAC function is missing we only support
# SHA1 via PBKDF2_HMAC_SHA1.
return isinstance(algorithm, hashes.SHA1)
def derive_pbkdf2_hmac(self, algorithm, length, salt, iterations,
key_material):
buf = self._ffi.new("char[]", length)
if self._lib.Cryptography_HAS_PBKDF2_HMAC:
evp_md = self._lib.EVP_get_digestbyname(
algorithm.name.encode("ascii"))
assert evp_md != self._ffi.NULL
res = self._lib.PKCS5_PBKDF2_HMAC(
key_material,
len(key_material),
salt,
len(salt),
iterations,
evp_md,
length,
buf
)
assert res == 1
else:
if not isinstance(algorithm, hashes.SHA1):
raise UnsupportedAlgorithm(
"This version of OpenSSL only supports PBKDF2HMAC with "
"SHA1.",
_Reasons.UNSUPPORTED_HASH
)
res = self._lib.PKCS5_PBKDF2_HMAC_SHA1(
key_material,
len(key_material),
salt,
len(salt),
iterations,
length,
buf
)
assert res == 1
return self._ffi.buffer(buf)[:]
def _err_string(self, code):
err_buf = self._ffi.new("char[]", 256)
self._lib.ERR_error_string_n(code, err_buf, 256)
return self._ffi.string(err_buf, 256)[:]
def _consume_errors(self):
errors = []
while True:
code = self._lib.ERR_get_error()
if code == 0:
break
lib = self._lib.ERR_GET_LIB(code)
func = self._lib.ERR_GET_FUNC(code)
reason = self._lib.ERR_GET_REASON(code)
errors.append(_OpenSSLError(code, lib, func, reason))
return errors
def _unknown_error(self, error):
return InternalError(
"Unknown error code {0} from OpenSSL, "
"you should probably file a bug. {1}.".format(
error.code, self._err_string(error.code)
)
)
def _bn_to_int(self, bn):
assert bn != self._ffi.NULL
if six.PY3:
# Python 3 has constant time from_bytes, so use that.
bn_num_bytes = (self._lib.BN_num_bits(bn) + 7) // 8
bin_ptr = self._ffi.new("unsigned char[]", bn_num_bytes)
bin_len = self._lib.BN_bn2bin(bn, bin_ptr)
# A zero length means the BN has value 0
assert bin_len >= 0
assert bin_ptr != self._ffi.NULL
return int.from_bytes(self._ffi.buffer(bin_ptr)[:bin_len], "big")
else:
# Under Python 2 the best we can do is hex()
hex_cdata = self._lib.BN_bn2hex(bn)
assert hex_cdata != self._ffi.NULL
hex_str = self._ffi.string(hex_cdata)
self._lib.OPENSSL_free(hex_cdata)
return int(hex_str, 16)
def _int_to_bn(self, num, bn=None):
"""
Converts a python integer to a BIGNUM. The returned BIGNUM will not
be garbage collected (to support adding them to structs that take
ownership of the object). Be sure to register it for GC if it will
be discarded after use.
"""
assert bn is None or bn != self._ffi.NULL
if bn is None:
bn = self._ffi.NULL
if six.PY3:
# Python 3 has constant time to_bytes, so use that.
binary = num.to_bytes(int(num.bit_length() / 8.0 + 1), "big")
bn_ptr = self._lib.BN_bin2bn(binary, len(binary), bn)
assert bn_ptr != self._ffi.NULL
return bn_ptr
else:
# Under Python 2 the best we can do is hex()
hex_num = hex(num).rstrip("L").lstrip("0x").encode("ascii") or b"0"
bn_ptr = self._ffi.new("BIGNUM **")
bn_ptr[0] = bn
res = self._lib.BN_hex2bn(bn_ptr, hex_num)
assert res != 0
assert bn_ptr[0] != self._ffi.NULL
return bn_ptr[0]
def generate_rsa_private_key(self, public_exponent, key_size):
rsa._verify_rsa_parameters(public_exponent, key_size)
rsa_cdata = self._lib.RSA_new()
assert rsa_cdata != self._ffi.NULL
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
bn = self._int_to_bn(public_exponent)
bn = self._ffi.gc(bn, self._lib.BN_free)
res = self._lib.RSA_generate_key_ex(
rsa_cdata, key_size, bn, self._ffi.NULL
)
assert res == 1
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPrivateKey(self, rsa_cdata, evp_pkey)
def generate_rsa_parameters_supported(self, public_exponent, key_size):
return (public_exponent >= 3 and public_exponent & 1 != 0 and
key_size >= 512)
def load_rsa_private_numbers(self, numbers):
rsa._check_private_key_components(
numbers.p,
numbers.q,
numbers.d,
numbers.dmp1,
numbers.dmq1,
numbers.iqmp,
numbers.public_numbers.e,
numbers.public_numbers.n
)
rsa_cdata = self._lib.RSA_new()
assert rsa_cdata != self._ffi.NULL
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
rsa_cdata.p = self._int_to_bn(numbers.p)
rsa_cdata.q = self._int_to_bn(numbers.q)
rsa_cdata.d = self._int_to_bn(numbers.d)
rsa_cdata.dmp1 = self._int_to_bn(numbers.dmp1)
rsa_cdata.dmq1 = self._int_to_bn(numbers.dmq1)
rsa_cdata.iqmp = self._int_to_bn(numbers.iqmp)
rsa_cdata.e = self._int_to_bn(numbers.public_numbers.e)
rsa_cdata.n = self._int_to_bn(numbers.public_numbers.n)
res = self._lib.RSA_blinding_on(rsa_cdata, self._ffi.NULL)
assert res == 1
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPrivateKey(self, rsa_cdata, evp_pkey)
def load_rsa_public_numbers(self, numbers):
rsa._check_public_key_components(numbers.e, numbers.n)
rsa_cdata = self._lib.RSA_new()
assert rsa_cdata != self._ffi.NULL
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
rsa_cdata.e = self._int_to_bn(numbers.e)
rsa_cdata.n = self._int_to_bn(numbers.n)
res = self._lib.RSA_blinding_on(rsa_cdata, self._ffi.NULL)
assert res == 1
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPublicKey(self, rsa_cdata, evp_pkey)
def _rsa_cdata_to_evp_pkey(self, rsa_cdata):
evp_pkey = self._lib.EVP_PKEY_new()
assert evp_pkey != self._ffi.NULL
evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
res = self._lib.EVP_PKEY_set1_RSA(evp_pkey, rsa_cdata)
assert res == 1
return evp_pkey
def _bytes_to_bio(self, data):
"""
Return a _MemoryBIO namedtuple of (BIO, char*).
The char* is the storage for the BIO and it must stay alive until the
BIO is finished with.
"""
data_char_p = self._ffi.new("char[]", data)
bio = self._lib.BIO_new_mem_buf(
data_char_p, len(data)
)
assert bio != self._ffi.NULL
return _MemoryBIO(self._ffi.gc(bio, self._lib.BIO_free), data_char_p)
def _create_mem_bio(self):
"""
Creates an empty memory BIO.
"""
bio_method = self._lib.BIO_s_mem()
assert bio_method != self._ffi.NULL
bio = self._lib.BIO_new(bio_method)
assert bio != self._ffi.NULL
bio = self._ffi.gc(bio, self._lib.BIO_free)
return bio
def _read_mem_bio(self, bio):
"""
Reads a memory BIO. This only works on memory BIOs.
"""
buf = self._ffi.new("char **")
buf_len = self._lib.BIO_get_mem_data(bio, buf)
assert buf_len > 0
assert buf[0] != self._ffi.NULL
bio_data = self._ffi.buffer(buf[0], buf_len)[:]
return bio_data
def _evp_pkey_to_private_key(self, evp_pkey):
"""
Return the appropriate type of PrivateKey given an evp_pkey cdata
pointer.
"""
key_type = evp_pkey.type
if key_type == self._lib.EVP_PKEY_RSA:
rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
assert rsa_cdata != self._ffi.NULL
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
return _RSAPrivateKey(self, rsa_cdata, evp_pkey)
elif key_type == self._lib.EVP_PKEY_DSA:
dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey)
assert dsa_cdata != self._ffi.NULL
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
return _DSAPrivateKey(self, dsa_cdata, evp_pkey)
elif (self._lib.Cryptography_HAS_EC == 1 and
key_type == self._lib.EVP_PKEY_EC):
ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey)
assert ec_cdata != self._ffi.NULL
ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)
else:
raise UnsupportedAlgorithm("Unsupported key type.")
def _evp_pkey_to_public_key(self, evp_pkey):
"""
Return the appropriate type of PublicKey given an evp_pkey cdata
pointer.
"""
key_type = evp_pkey.type
if key_type == self._lib.EVP_PKEY_RSA:
rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
assert rsa_cdata != self._ffi.NULL
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
return _RSAPublicKey(self, rsa_cdata, evp_pkey)
elif key_type == self._lib.EVP_PKEY_DSA:
dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey)
assert dsa_cdata != self._ffi.NULL
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
return _DSAPublicKey(self, dsa_cdata, evp_pkey)
elif (self._lib.Cryptography_HAS_EC == 1 and
key_type == self._lib.EVP_PKEY_EC):
ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey)
assert ec_cdata != self._ffi.NULL
ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey)
else:
raise UnsupportedAlgorithm("Unsupported key type.")
def _pem_password_cb(self, password):
"""
Generate a pem_password_cb function pointer that copied the password to
OpenSSL as required and returns the number of bytes copied.
typedef int pem_password_cb(char *buf, int size,
int rwflag, void *userdata);
Useful for decrypting PKCS8 files and so on.
Returns a tuple of (cdata function pointer, callback function).
"""
def pem_password_cb(buf, size, writing, userdata):
pem_password_cb.called += 1
if not password:
pem_password_cb.exception = TypeError(
"Password was not given but private key is encrypted."
)
return 0
elif len(password) < size:
pw_buf = self._ffi.buffer(buf, size)
pw_buf[:len(password)] = password
return len(password)
else:
pem_password_cb.exception = ValueError(
"Passwords longer than {0} bytes are not supported "
"by this backend.".format(size - 1)
)
return 0
pem_password_cb.called = 0
pem_password_cb.exception = None
return (
self._ffi.callback("int (char *, int, int, void *)",
pem_password_cb),
pem_password_cb
)
def _mgf1_hash_supported(self, algorithm):
if self._lib.Cryptography_HAS_MGF1_MD:
return self.hash_supported(algorithm)
else:
return isinstance(algorithm, hashes.SHA1)
def rsa_padding_supported(self, padding):
if isinstance(padding, PKCS1v15):
return True
elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1):
return self._mgf1_hash_supported(padding._mgf._algorithm)
elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1):
return isinstance(padding._mgf._algorithm, hashes.SHA1)
else:
return False
def generate_dsa_parameters(self, key_size):
if key_size not in (1024, 2048, 3072):
raise ValueError(
"Key size must be 1024 or 2048 or 3072 bits.")
if (self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f and
key_size > 1024):
raise ValueError(
"Key size must be 1024 because OpenSSL < 1.0.0 doesn't "
"support larger key sizes.")
ctx = self._lib.DSA_new()
assert ctx != self._ffi.NULL
ctx = self._ffi.gc(ctx, self._lib.DSA_free)
res = self._lib.DSA_generate_parameters_ex(
ctx, key_size, self._ffi.NULL, 0,
self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
)
assert res == 1
return _DSAParameters(self, ctx)
def generate_dsa_private_key(self, parameters):
ctx = self._lib.DSA_new()
assert ctx != self._ffi.NULL
ctx = self._ffi.gc(ctx, self._lib.DSA_free)
ctx.p = self._lib.BN_dup(parameters._dsa_cdata.p)
ctx.q = self._lib.BN_dup(parameters._dsa_cdata.q)
ctx.g = self._lib.BN_dup(parameters._dsa_cdata.g)
self._lib.DSA_generate_key(ctx)
evp_pkey = self._dsa_cdata_to_evp_pkey(ctx)
return _DSAPrivateKey(self, ctx, evp_pkey)
def generate_dsa_private_key_and_parameters(self, key_size):
parameters = self.generate_dsa_parameters(key_size)
return self.generate_dsa_private_key(parameters)
def load_dsa_private_numbers(self, numbers):
dsa._check_dsa_private_numbers(numbers)
parameter_numbers = numbers.public_numbers.parameter_numbers
dsa_cdata = self._lib.DSA_new()
assert dsa_cdata != self._ffi.NULL
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
dsa_cdata.p = self._int_to_bn(parameter_numbers.p)
dsa_cdata.q = self._int_to_bn(parameter_numbers.q)
dsa_cdata.g = self._int_to_bn(parameter_numbers.g)
dsa_cdata.pub_key = self._int_to_bn(numbers.public_numbers.y)
dsa_cdata.priv_key = self._int_to_bn(numbers.x)
evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata)
return _DSAPrivateKey(self, dsa_cdata, evp_pkey)
def load_dsa_public_numbers(self, numbers):
dsa._check_dsa_parameters(numbers.parameter_numbers)
dsa_cdata = self._lib.DSA_new()
assert dsa_cdata != self._ffi.NULL
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
dsa_cdata.p = self._int_to_bn(numbers.parameter_numbers.p)
dsa_cdata.q = self._int_to_bn(numbers.parameter_numbers.q)
dsa_cdata.g = self._int_to_bn(numbers.parameter_numbers.g)
dsa_cdata.pub_key = self._int_to_bn(numbers.y)
evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata)
return _DSAPublicKey(self, dsa_cdata, evp_pkey)
def load_dsa_parameter_numbers(self, numbers):
dsa._check_dsa_parameters(numbers)
dsa_cdata = self._lib.DSA_new()
assert dsa_cdata != self._ffi.NULL
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
dsa_cdata.p = self._int_to_bn(numbers.p)
dsa_cdata.q = self._int_to_bn(numbers.q)
dsa_cdata.g = self._int_to_bn(numbers.g)
return _DSAParameters(self, dsa_cdata)
def _dsa_cdata_to_evp_pkey(self, dsa_cdata):
evp_pkey = self._lib.EVP_PKEY_new()
assert evp_pkey != self._ffi.NULL
evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
res = self._lib.EVP_PKEY_set1_DSA(evp_pkey, dsa_cdata)
assert res == 1
return evp_pkey
def dsa_hash_supported(self, algorithm):
if self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f:
return isinstance(algorithm, hashes.SHA1)
else:
return self.hash_supported(algorithm)
def dsa_parameters_supported(self, p, q, g):
if self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f:
return utils.bit_length(p) <= 1024 and utils.bit_length(q) <= 160
else:
return True
def cmac_algorithm_supported(self, algorithm):
return (
self._lib.Cryptography_HAS_CMAC == 1 and
self.cipher_supported(
algorithm, CBC(b"\x00" * algorithm.block_size)
)
)
def create_cmac_ctx(self, algorithm):
return _CMACContext(self, algorithm)
def load_pem_private_key(self, data, password):
return self._load_key(
self._lib.PEM_read_bio_PrivateKey,
self._evp_pkey_to_private_key,
data,
password,
)
def load_pem_public_key(self, data):
mem_bio = self._bytes_to_bio(data)
evp_pkey = self._lib.PEM_read_bio_PUBKEY(
mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
)
if evp_pkey != self._ffi.NULL:
evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
return self._evp_pkey_to_public_key(evp_pkey)
else:
# It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still
# need to check to see if it is a pure PKCS1 RSA public key (not
# embedded in a subjectPublicKeyInfo)
self._consume_errors()
res = self._lib.BIO_reset(mem_bio.bio)
assert res == 1
rsa_cdata = self._lib.PEM_read_bio_RSAPublicKey(
mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
)
if rsa_cdata != self._ffi.NULL:
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPublicKey(self, rsa_cdata, evp_pkey)
else:
self._handle_key_loading_error()
def load_der_private_key(self, data, password):
# OpenSSL has a function called d2i_AutoPrivateKey that can simplify
# this. Unfortunately it doesn't properly support PKCS8 on OpenSSL
# 0.9.8 so we can't use it. Instead we sequentially try to load it 3
# different ways. First we'll try to load it as a traditional key
bio_data = self._bytes_to_bio(data)
key = self._evp_pkey_from_der_traditional_key(bio_data, password)
if not key:
# Okay so it's not a traditional key. Let's try
# PKCS8 unencrypted. OpenSSL 0.9.8 can't load unencrypted
# PKCS8 keys using d2i_PKCS8PrivateKey_bio so we do this instead.
# Reset the memory BIO so we can read the data again.
res = self._lib.BIO_reset(bio_data.bio)
assert res == 1
key = self._evp_pkey_from_der_unencrypted_pkcs8(bio_data, password)
if key:
return self._evp_pkey_to_private_key(key)
else:
# Finally we try to load it with the method that handles encrypted
# PKCS8 properly.
return self._load_key(
self._lib.d2i_PKCS8PrivateKey_bio,
self._evp_pkey_to_private_key,
data,
password,
)
def _evp_pkey_from_der_traditional_key(self, bio_data, password):
key = self._lib.d2i_PrivateKey_bio(bio_data.bio, self._ffi.NULL)
if key != self._ffi.NULL:
key = self._ffi.gc(key, self._lib.EVP_PKEY_free)
if password is not None:
raise TypeError(
"Password was given but private key is not encrypted."
)
return key
else:
self._consume_errors()
return None
def _evp_pkey_from_der_unencrypted_pkcs8(self, bio_data, password):
info = self._lib.d2i_PKCS8_PRIV_KEY_INFO_bio(
bio_data.bio, self._ffi.NULL
)
info = self._ffi.gc(info, self._lib.PKCS8_PRIV_KEY_INFO_free)
if info != self._ffi.NULL:
key = self._lib.EVP_PKCS82PKEY(info)
assert key != self._ffi.NULL
key = self._ffi.gc(key, self._lib.EVP_PKEY_free)
if password is not None:
raise TypeError(
"Password was given but private key is not encrypted."
)
return key
else:
self._consume_errors()
return None
def load_der_public_key(self, data):
mem_bio = self._bytes_to_bio(data)
evp_pkey = self._lib.d2i_PUBKEY_bio(mem_bio.bio, self._ffi.NULL)
if evp_pkey != self._ffi.NULL:
evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
return self._evp_pkey_to_public_key(evp_pkey)
else:
# It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still
# need to check to see if it is a pure PKCS1 RSA public key (not
# embedded in a subjectPublicKeyInfo)
self._consume_errors()
res = self._lib.BIO_reset(mem_bio.bio)
assert res == 1
rsa_cdata = self._lib.d2i_RSAPublicKey_bio(
mem_bio.bio, self._ffi.NULL
)
if rsa_cdata != self._ffi.NULL:
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPublicKey(self, rsa_cdata, evp_pkey)
else:
self._handle_key_loading_error()
def load_pem_x509_certificate(self, data):
mem_bio = self._bytes_to_bio(data)
x509 = self._lib.PEM_read_bio_X509(
mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
)
if x509 == self._ffi.NULL:
self._consume_errors()
raise ValueError("Unable to load certificate")
x509 = self._ffi.gc(x509, self._lib.X509_free)
return _Certificate(self, x509)
def load_der_x509_certificate(self, data):
mem_bio = self._bytes_to_bio(data)
x509 = self._lib.d2i_X509_bio(mem_bio.bio, self._ffi.NULL)
if x509 == self._ffi.NULL:
self._consume_errors()
raise ValueError("Unable to load certificate")
x509 = self._ffi.gc(x509, self._lib.X509_free)
return _Certificate(self, x509)
def load_pem_x509_csr(self, data):
mem_bio = self._bytes_to_bio(data)
x509_req = self._lib.PEM_read_bio_X509_REQ(
mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
)
if x509_req == self._ffi.NULL:
self._consume_errors()
raise ValueError("Unable to load request")
x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free)
return _CertificateSigningRequest(self, x509_req)
def load_der_x509_csr(self, data):
mem_bio = self._bytes_to_bio(data)
x509_req = self._lib.d2i_X509_REQ_bio(mem_bio.bio, self._ffi.NULL)
if x509_req == self._ffi.NULL:
self._consume_errors()
raise ValueError("Unable to load request")
x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free)
return _CertificateSigningRequest(self, x509_req)
def _load_key(self, openssl_read_func, convert_func, data, password):
mem_bio = self._bytes_to_bio(data)
password_callback, password_func = self._pem_password_cb(password)
evp_pkey = openssl_read_func(
mem_bio.bio,
self._ffi.NULL,
password_callback,
self._ffi.NULL
)
if evp_pkey == self._ffi.NULL:
if password_func.exception is not None:
errors = self._consume_errors()
assert errors
raise password_func.exception
else:
self._handle_key_loading_error()
evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
if password is not None and password_func.called == 0:
raise TypeError(
"Password was given but private key is not encrypted.")
assert (
(password is not None and password_func.called == 1) or
password is None
)
return convert_func(evp_pkey)
def _handle_key_loading_error(self):
errors = self._consume_errors()
if not errors:
raise ValueError("Could not unserialize key data.")
elif errors[0][1:] in (
(
self._lib.ERR_LIB_EVP,
self._lib.EVP_F_EVP_DECRYPTFINAL_EX,
self._lib.EVP_R_BAD_DECRYPT
),
(
self._lib.ERR_LIB_PKCS12,
self._lib.PKCS12_F_PKCS12_PBE_CRYPT,
self._lib.PKCS12_R_PKCS12_CIPHERFINAL_ERROR,
)
):
raise ValueError("Bad decrypt. Incorrect password?")
elif errors[0][1:] in (
(
self._lib.ERR_LIB_PEM,
self._lib.PEM_F_PEM_GET_EVP_CIPHER_INFO,
self._lib.PEM_R_UNSUPPORTED_ENCRYPTION
),
(
self._lib.ERR_LIB_EVP,
self._lib.EVP_F_EVP_PBE_CIPHERINIT,
self._lib.EVP_R_UNKNOWN_PBE_ALGORITHM
)
):
raise UnsupportedAlgorithm(
"PEM data is encrypted with an unsupported cipher",
_Reasons.UNSUPPORTED_CIPHER
)
elif any(
error[1:] == (
self._lib.ERR_LIB_EVP,
self._lib.EVP_F_EVP_PKCS82PKEY,
self._lib.EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM
)
for error in errors
):
raise UnsupportedAlgorithm(
"Unsupported public key algorithm.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
)
else:
assert errors[0][1] in (
self._lib.ERR_LIB_EVP,
self._lib.ERR_LIB_PEM,
self._lib.ERR_LIB_ASN1,
)
raise ValueError("Could not unserialize key data.")
def elliptic_curve_supported(self, curve):
if self._lib.Cryptography_HAS_EC != 1:
return False
try:
curve_nid = self._elliptic_curve_to_nid(curve)
except UnsupportedAlgorithm:
curve_nid = self._lib.NID_undef
ctx = self._lib.EC_GROUP_new_by_curve_name(curve_nid)
if ctx == self._ffi.NULL:
errors = self._consume_errors()
assert (
curve_nid == self._lib.NID_undef or
errors[0][1:] == (
self._lib.ERR_LIB_EC,
self._lib.EC_F_EC_GROUP_NEW_BY_CURVE_NAME,
self._lib.EC_R_UNKNOWN_GROUP
)
)
return False
else:
assert curve_nid != self._lib.NID_undef
self._lib.EC_GROUP_free(ctx)
return True
def elliptic_curve_signature_algorithm_supported(
self, signature_algorithm, curve
):
if self._lib.Cryptography_HAS_EC != 1:
return False
# We only support ECDSA right now.
if not isinstance(signature_algorithm, ec.ECDSA):
return False
# Before 0.9.8m OpenSSL can't cope with digests longer than the curve.
if (
self._lib.OPENSSL_VERSION_NUMBER < 0x009080df and
curve.key_size < signature_algorithm.algorithm.digest_size * 8
):
return False
return self.elliptic_curve_supported(curve)
def generate_elliptic_curve_private_key(self, curve):
"""
Generate a new private key on the named curve.
"""
if self.elliptic_curve_supported(curve):
curve_nid = self._elliptic_curve_to_nid(curve)
ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid)
assert ec_cdata != self._ffi.NULL
ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
res = self._lib.EC_KEY_generate_key(ec_cdata)
assert res == 1
res = self._lib.EC_KEY_check_key(ec_cdata)
assert res == 1
evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata)
return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)
else:
raise UnsupportedAlgorithm(
"Backend object does not support {0}.".format(curve.name),
_Reasons.UNSUPPORTED_ELLIPTIC_CURVE
)
def load_elliptic_curve_private_numbers(self, numbers):
public = numbers.public_numbers
curve_nid = self._elliptic_curve_to_nid(public.curve)
ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid)
assert ec_cdata != self._ffi.NULL
ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
ec_cdata = self._ec_key_set_public_key_affine_coordinates(
ec_cdata, public.x, public.y)
res = self._lib.EC_KEY_set_private_key(
ec_cdata, self._int_to_bn(numbers.private_value))
assert res == 1
evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata)
return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)
def load_elliptic_curve_public_numbers(self, numbers):
curve_nid = self._elliptic_curve_to_nid(numbers.curve)
ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid)
assert ec_cdata != self._ffi.NULL
ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
ec_cdata = self._ec_key_set_public_key_affine_coordinates(
ec_cdata, numbers.x, numbers.y)
evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata)
return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey)
def _ec_cdata_to_evp_pkey(self, ec_cdata):
evp_pkey = self._lib.EVP_PKEY_new()
assert evp_pkey != self._ffi.NULL
evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
res = self._lib.EVP_PKEY_set1_EC_KEY(evp_pkey, ec_cdata)
assert res == 1
def _elliptic_curve_to_nid(self, curve):
"""
Get the NID for a curve name.
"""
curve_aliases = {
"secp192r1": "prime192v1",
"secp256r1": "prime256v1"
}
curve_name = curve_aliases.get(curve.name, curve.name)
curve_nid = self._lib.OBJ_sn2nid(curve_name.encode())
if curve_nid == self._lib.NID_undef:
raise UnsupportedAlgorithm(
"{0} is not a supported elliptic curve".format(curve.name),
_Reasons.UNSUPPORTED_ELLIPTIC_CURVE
)
return curve_nid
@contextmanager
def _tmp_bn_ctx(self):
bn_ctx = self._lib.BN_CTX_new()
assert bn_ctx != self._ffi.NULL
bn_ctx = self._ffi.gc(bn_ctx, self._lib.BN_CTX_free)
self._lib.BN_CTX_start(bn_ctx)
try:
yield bn_ctx
finally:
self._lib.BN_CTX_end(bn_ctx)
def _ec_key_determine_group_get_set_funcs(self, ctx):
"""
Given an EC_KEY determine the group and what methods are required to
get/set point coordinates.
"""
assert ctx != self._ffi.NULL
nid_two_field = self._lib.OBJ_sn2nid(b"characteristic-two-field")
assert nid_two_field != self._lib.NID_undef
group = self._lib.EC_KEY_get0_group(ctx)
assert group != self._ffi.NULL
method = self._lib.EC_GROUP_method_of(group)
assert method != self._ffi.NULL
nid = self._lib.EC_METHOD_get_field_type(method)
assert nid != self._lib.NID_undef
if nid == nid_two_field and self._lib.Cryptography_HAS_EC2M:
set_func = self._lib.EC_POINT_set_affine_coordinates_GF2m
get_func = self._lib.EC_POINT_get_affine_coordinates_GF2m
else:
set_func = self._lib.EC_POINT_set_affine_coordinates_GFp
get_func = self._lib.EC_POINT_get_affine_coordinates_GFp
assert set_func and get_func
return set_func, get_func, group
def _ec_key_set_public_key_affine_coordinates(self, ctx, x, y):
"""
This is a port of EC_KEY_set_public_key_affine_coordinates that was
added in 1.0.1.
Sets the public key point in the EC_KEY context to the affine x and y
values.
"""
if x < 0 or y < 0:
raise ValueError(
"Invalid EC key. Both x and y must be non-negative."
)
set_func, get_func, group = (
self._ec_key_determine_group_get_set_funcs(ctx)
)
point = self._lib.EC_POINT_new(group)
assert point != self._ffi.NULL
point = self._ffi.gc(point, self._lib.EC_POINT_free)
bn_x = self._int_to_bn(x)
bn_y = self._int_to_bn(y)
with self._tmp_bn_ctx() as bn_ctx:
check_x = self._lib.BN_CTX_get(bn_ctx)
check_y = self._lib.BN_CTX_get(bn_ctx)
res = set_func(group, point, bn_x, bn_y, bn_ctx)
assert res == 1
res = get_func(group, point, check_x, check_y, bn_ctx)
assert res == 1
res = self._lib.BN_cmp(bn_x, check_x)
assert res == 0
res = self._lib.BN_cmp(bn_y, check_y)
assert res == 0
res = self._lib.EC_KEY_set_public_key(ctx, point)
assert res == 1
res = self._lib.EC_KEY_check_key(ctx)
if res != 1:
self._consume_errors()
raise ValueError("Invalid EC key.")
return ctx
def _private_key_bytes(self, encoding, format, encryption_algorithm,
evp_pkey, cdata):
if not isinstance(encoding, serialization.Encoding):
raise TypeError("encoding must be an item from the Encoding enum")
if not isinstance(format, serialization.PrivateFormat):
raise TypeError(
"format must be an item from the PrivateFormat enum"
)
if not isinstance(encryption_algorithm,
serialization.KeySerializationEncryption):
raise TypeError(
"Encryption algorithm must be a KeySerializationEncryption "
"instance"
)
if isinstance(encryption_algorithm, serialization.NoEncryption):
password = b""
passlen = 0
evp_cipher = self._ffi.NULL
elif isinstance(encryption_algorithm,
serialization.BestAvailableEncryption):
# This is a curated value that we will update over time.
evp_cipher = self._lib.EVP_get_cipherbyname(
b"aes-256-cbc"
)
password = encryption_algorithm.password
passlen = len(password)
if passlen > 1023:
raise ValueError(
"Passwords longer than 1023 bytes are not supported by "
"this backend"
)
else:
raise ValueError("Unsupported encryption type")
if encoding is serialization.Encoding.PEM:
if format is serialization.PrivateFormat.PKCS8:
write_bio = self._lib.PEM_write_bio_PKCS8PrivateKey
key = evp_pkey
elif format is serialization.PrivateFormat.TraditionalOpenSSL:
if evp_pkey.type == self._lib.EVP_PKEY_RSA:
write_bio = self._lib.PEM_write_bio_RSAPrivateKey
elif evp_pkey.type == self._lib.EVP_PKEY_DSA:
write_bio = self._lib.PEM_write_bio_DSAPrivateKey
elif (self._lib.Cryptography_HAS_EC == 1 and
evp_pkey.type == self._lib.EVP_PKEY_EC):
write_bio = self._lib.PEM_write_bio_ECPrivateKey
key = cdata
elif encoding is serialization.Encoding.DER:
if format is serialization.PrivateFormat.TraditionalOpenSSL:
if not isinstance(
encryption_algorithm, serialization.NoEncryption
):
raise ValueError(
"Encryption is not supported for DER encoded "
"traditional OpenSSL keys"
)
return self._private_key_bytes_traditional_der(
evp_pkey.type, cdata
)
elif format is serialization.PrivateFormat.PKCS8:
write_bio = self._lib.i2d_PKCS8PrivateKey_bio
key = evp_pkey
bio = self._create_mem_bio()
res = write_bio(
bio,
key,
evp_cipher,
password,
passlen,
self._ffi.NULL,
self._ffi.NULL
)
assert res == 1
return self._read_mem_bio(bio)
def _private_key_bytes_traditional_der(self, key_type, cdata):
if key_type == self._lib.EVP_PKEY_RSA:
write_bio = self._lib.i2d_RSAPrivateKey_bio
elif (self._lib.Cryptography_HAS_EC == 1 and
key_type == self._lib.EVP_PKEY_EC):
write_bio = self._lib.i2d_ECPrivateKey_bio
elif key_type == self._lib.EVP_PKEY_DSA:
write_bio = self._lib.i2d_DSAPrivateKey_bio
bio = self._create_mem_bio()
res = write_bio(bio, cdata)
assert res == 1
return self._read_mem_bio(bio)
def _public_key_bytes(self, encoding, format, evp_pkey, cdata):
if not isinstance(encoding, serialization.Encoding):
raise TypeError("encoding must be an item from the Encoding enum")
if not isinstance(format, serialization.PublicFormat):
raise TypeError(
"format must be an item from the PublicFormat enum"
)
if format is serialization.PublicFormat.SubjectPublicKeyInfo:
if encoding is serialization.Encoding.PEM:
write_bio = self._lib.PEM_write_bio_PUBKEY
elif encoding is serialization.Encoding.DER:
write_bio = self._lib.i2d_PUBKEY_bio
key = evp_pkey
elif format is serialization.PublicFormat.PKCS1:
# Only RSA is supported here.
assert evp_pkey.type == self._lib.EVP_PKEY_RSA
if encoding is serialization.Encoding.PEM:
write_bio = self._lib.PEM_write_bio_RSAPublicKey
elif encoding is serialization.Encoding.DER:
write_bio = self._lib.i2d_RSAPublicKey_bio
key = cdata
bio = self._create_mem_bio()
res = write_bio(bio, key)
assert res == 1
return self._read_mem_bio(bio)
class GetCipherByName(object):
def __init__(self, fmt):
self._fmt = fmt
def __call__(self, backend, cipher, mode):
cipher_name = self._fmt.format(cipher=cipher, mode=mode).lower()
return backend._lib.EVP_get_cipherbyname(cipher_name.encode("ascii"))
backend = Backend()
|
sholsapp/cryptography
|
src/cryptography/hazmat/backends/openssl/backend.py
|
Python
|
bsd-3-clause
| 49,028 |
$(function(){
function openPanel(){
require(['panel']);
$('#admin_link').hide();
}
if($.cookie('grass_panel')){
openPanel();
}
$('#admin_link').on('click', function(e){
e.preventDefault();
openPanel();
});
});
require.config({
baseUrl: 'media/scripts',
paths: {
// 'doT': 'vendor/dot',
'riotjs': 'vendor/riot+compiler',
'panel': 'admin/panel',
'text': 'vendor/text'
},
shim: {
riotjs: {
exports: 'riot'
}
}
});
var riot;
function loadCss(url) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
|
grnrbt/grass
|
web/media/scripts/link.js
|
JavaScript
|
bsd-3-clause
| 781 |
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\widgets\ActiveForm;
use yii\bootstrap\Modal;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $searchModel app\modules\fct\models\FctSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'ผู้ป่วยในระบบ FCT';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="fct-index">
<!-- <h1><?= Html::encode($this->title) ?></h1>-->
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<!-- <p>
<?= Html::a('Create Fct', ['create'], ['class' => 'btn btn-success']) ?>
</p>-->
<div class="panel panel-success">
<div class="panel-heading"> รายชื่อผู้ป่วย</div>
<div class="panel-body">
<?php Pjax::begin(['id' => 'fct_id']); ?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'formatter' => ['class' => 'yii\i18n\Formatter', 'nullDisplay' => '-'],
'striped' => false,
'hover' => true,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
//'fcttype_id',
//'pass',
//'colour_id',
'senddate',
'cid',
//'hn',
// 'an',
'ptname',
//'birthday',
[
'attribute' => 'sex',
'format' => 'html',
'value' => function($model, $key, $index, $column) {
return $model->sex == 1 ? "<span style=\"color:green;\">ชาย</span>" : "<span style=\"color:red;\">หญิง</span>";
}
],
// 'ptage',
// 'diage',
// 'pps',
// 'pain',
// 'painnote',
// 'cc',
// 'pi',
// 'bt',
// 'pr',
// 'rr',
// 'bp',
// 'drugallergy',
// 'admit',
// 'dc',
// 'or',
// 'ordate',
// 'disease',
// 'receive',
'address',
// 'ptcate',
// 'hossub',
// 'tra',
// 'retng',
// 'retfo',
// 'colobag',
// 'lesion',
// 'lesioncare',
// 'recov',
// 'recovcare',
// 'oxygen',
// 'lr01',
// 'lr02',
// 'lr03',
// 'lr04',
// 'lr05',
// 'lr06',
// 'lr07',
// 'lr08',
// 'lr09',
// 'lr10',
// 'lrl01',
// 'lrl02',
// 'lrl03',
// 'lrl04',
// 'lrl05',
// 'lrl06',
// 'lrl07',
// 'lrl08',
// 'lr',
// 'lrl09',
// 'lrl10',
// 'lrl11',
// 'lrl12',
// 'lrl13',
// 'other',
// 'appdate',
// 'doctorapp',
// 'appdate2',
// 'doctorapp2',
// 'appdate3',
// 'doctorapp3',
// 'windpipe',
// 'insulin',
// 'equip',
// 'depart',
// 'hosin',
// 'officer',
// 'confirm',
// 'confirmfct',
//'tmbpart',
'phone',
//'bloodgrp',
// [
// 'class' => 'kartik\grid\BooleanColumn',
// 'attribute' => 'send',
// ],
// [
// 'class' => 'kartik\grid\BooleanColumn',
// 'attribute' => 'okcase',
// ],
[
'class' => 'yii\grid\ActionColumn',
'options' => ['style' => 'width:100px;'],
'template' => '<div class="btn-group btn-group-sm" role="group" aria-label="...">{update}</div>',
'buttons' => [
// 'view'=>function($url,$model,$key){
// return Html::a('<i class="glyphicon glyphicon-search"></i>',$url,['class'=>'btn btn-default']);
// },
'update' => function($url, $model, $key) {
return Html::a('<i class="glyphicon glyphicon-pencil"></i> ', ['/fct/fcthhc/update', 'id' => $model->id], [
'class' => 'activity-update-link btn btn-info',
'title' => 'บันทึก',
// 'data-toggle' => 'modal',
// 'data-target' => '#activity-modal',
// 'data-id' => $key,
// 'data-pjax' => '0',
]);
},
//
// 'delete'=>function($url,$model,$key){
// return Html::a('<i class="glyphicon glyphicon-trash"></i>', $url,[
// 'title' => Yii::t('yii', 'Delete'),
// 'data-confirm' => Yii::t('yii', 'คุณต้องการลบไฟล์นี้?'),
// 'data-method' => 'post',
// 'data-pjax' => '0',
// 'class'=>'btn btn-default'
// ]);
// }
]
],
],
]);
?>
<?php Pjax::end() ?>
</div>
</div>
</div>
<?php
Modal::begin([
'id' => 'activity-modal',
'header' => '<h4 class="modal-title"></h4>',
'size' => 'modal-lg',
'footer' => '<a href="#" class="btn btn-primary" data-dismiss="modal">ปิด</a>',
]);
Modal::end();
?>
<?php $this->registerJs('
function init_click_handlers(){
$(".activity-update-link").click(function(e) {
var fID = $(this).closest("tr").data("key");
$.get(
"?r=fct/fcthhc/update",
{
fct_id: fID
},
function (data)
{
$("#activity-modal").find(".modal-body").html(data);
$(".modal-body").html(data);
$(".modal-title").html("รับผู้ป่วยที่มีความเสี่ยงเข้าระบบ");
$("#activity-modal").modal("show");
}
);
});
}
init_click_handlers(); //first run
$("#fct_id").on("pjax:success", function() {
init_click_handlers(); //reactivate links in grid after pjax update
});'); ?>
|
inamjung/fct
|
modules/fct/views/fct/indexcaseok.php
|
PHP
|
bsd-3-clause
| 8,182 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RobotCode2014.commands.manipulator;
import RobotCode2014.commands.CommandBase;
/**
*
* @author me
*/
public class PitchAccelerationCommand extends CommandBase {
public PitchAccelerationCommand() {
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
manipPitch.updatePitchSpeed();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
HarkerRobo/robocode14
|
src/RobotCode2014/commands/manipulator/PitchAccelerationCommand.java
|
Java
|
bsd-3-clause
| 1,076 |
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\DI;
use Nette;
use Nette\Utils\Validators;
use Nette\Utils\Strings;
use Nette\PhpGenerator\Helpers as PhpHelpers;
use ReflectionClass;
/**
* Basic container builder.
*/
class ContainerBuilder extends Nette\Object
{
const THIS_SERVICE = 'self',
THIS_CONTAINER = 'container';
/** @var array */
public $parameters = array();
/** @var string */
private $className = 'Container';
/** @var ServiceDefinition[] */
private $definitions = array();
/** @var array of alias => service */
private $aliases = array();
/** @var array for auto-wiring */
private $classes;
/** @var string[] of classes excluded from auto-wiring */
private $excludedClasses = array();
/** @var array of file names */
private $dependencies = array();
/** @var Nette\PhpGenerator\ClassType[] */
private $generatedClasses = array();
/** @var string */
/*private in 5.4*/public $currentService;
/**
* Adds new service definition.
* @param string
* @return ServiceDefinition
*/
public function addDefinition($name, ServiceDefinition $definition = NULL)
{
if (!is_string($name) || !$name) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($name)));
}
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
if (isset($this->definitions[$name])) {
throw new Nette\InvalidStateException("Service '$name' has already been added.");
}
return $this->definitions[$name] = $definition ?: new ServiceDefinition;
}
/**
* Removes the specified service definition.
* @param string
* @return void
*/
public function removeDefinition($name)
{
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
unset($this->definitions[$name]);
if ($this->classes) {
foreach ($this->classes as & $tmp) {
foreach ($tmp as & $names) {
$names = array_values(array_diff($names, array($name)));
}
}
}
}
/**
* Gets the service definition.
* @param string
* @return ServiceDefinition
*/
public function getDefinition($name)
{
$service = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
if (!isset($this->definitions[$service])) {
throw new MissingServiceException("Service '$name' not found.");
}
return $this->definitions[$service];
}
/**
* Gets all service definitions.
* @return ServiceDefinition[]
*/
public function getDefinitions()
{
return $this->definitions;
}
/**
* Does the service definition or alias exist?
* @param string
* @return bool
*/
public function hasDefinition($name)
{
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
return isset($this->definitions[$name]);
}
/**
* @param string
* @param string
*/
public function addAlias($alias, $service)
{
if (!is_string($alias) || !$alias) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Alias name must be a non-empty string, %s given.', gettype($alias)));
} elseif (!is_string($service) || !$service) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($service)));
} elseif (isset($this->aliases[$alias])) {
throw new Nette\InvalidStateException("Alias '$alias' has already been added.");
} elseif (isset($this->definitions[$alias])) {
throw new Nette\InvalidStateException("Service '$alias' has already been added.");
}
$this->aliases[$alias] = $service;
}
/**
* Removes the specified alias.
* @return void
*/
public function removeAlias($alias)
{
unset($this->aliases[$alias]);
}
/**
* Gets all service aliases.
* @return array
*/
public function getAliases()
{
return $this->aliases;
}
/**
* @return self
*/
public function setClassName($name)
{
$this->className = (string) $name;
return $this;
}
/**
* @return string
*/
public function getClassName()
{
return $this->className;
}
/********************* class resolving ****************d*g**/
/**
* Resolves service name by type.
* @param string class or interface
* @return string|NULL service name or NULL
* @throws ServiceCreationException
*/
public function getByType($class)
{
$class = ltrim($class, '\\');
if ($this->currentService !== NULL) {
$curClass = $this->definitions[$this->currentService]->getClass();
if ($curClass === $class || is_subclass_of($curClass, $class)) {
return $this->currentService;
}
}
if (empty($this->classes[$class][TRUE])) {
self::checkCase($class);
return;
} elseif (count($this->classes[$class][TRUE]) === 1) {
return $this->classes[$class][TRUE][0];
} else {
throw new ServiceCreationException("Multiple services of type $class found: " . implode(', ', $this->classes[$class][TRUE]));
}
}
/**
* Gets the service names and definitions of the specified type.
* @param string
* @return ServiceDefinition[]
*/
public function findByType($class)
{
$class = ltrim($class, '\\');
self::checkCase($class);
$found = array();
if (!empty($this->classes[$class])) {
foreach (call_user_func_array('array_merge', $this->classes[$class]) as $name) {
$found[$name] = $this->definitions[$name];
}
}
return $found;
}
/**
* Gets the service objects of the specified tag.
* @param string
* @return array of [service name => tag attributes]
*/
public function findByTag($tag)
{
$found = array();
foreach ($this->definitions as $name => $def) {
if (($tmp = $def->getTag($tag)) !== NULL) {
$found[$name] = $tmp;
}
}
return $found;
}
/**
* Creates a list of arguments using autowiring.
* @return array
*/
public function autowireArguments($class, $method, array $arguments)
{
$rc = new ReflectionClass($class);
if (!$rc->hasMethod($method)) {
if (!Nette\Utils\Arrays::isList($arguments)) {
throw new ServiceCreationException("Unable to pass specified arguments to $class::$method().");
}
return $arguments;
}
$rm = $rc->getMethod($method);
if (!$rm->isPublic()) {
throw new ServiceCreationException("$class::$method() is not callable.");
}
$this->addDependency($rm->getFileName());
return Helpers::autowireArguments($rm, $arguments, $this);
}
/**
* Generates $dependencies, $classes and normalizes class names.
* @return array
* @internal
*/
public function prepareClassList()
{
unset($this->definitions[self::THIS_CONTAINER]);
$this->addDefinition(self::THIS_CONTAINER)->setClass('Nette\DI\Container');
$this->classes = FALSE;
foreach ($this->definitions as $name => $def) {
// prepare generated factories
if ($def->getImplement()) {
$this->resolveImplement($def, $name);
}
if ($def->isDynamic()) {
if (!$def->getClass()) {
throw new ServiceCreationException("Class is missing in definition of service '$name'.");
}
$def->setFactory(NULL);
continue;
}
// complete class-factory pairs
if (!$def->getEntity()) {
if (!$def->getClass()) {
throw new ServiceCreationException("Class and factory are missing in definition of service '$name'.");
}
$def->setFactory($def->getClass(), ($factory = $def->getFactory()) ? $factory->arguments : array());
}
// auto-disable autowiring for aliases
if (($alias = $this->getServiceName($def->getFactory()->getEntity())) &&
(!$def->getImplement() || (!Strings::contains($alias, '\\') && $this->definitions[$alias]->getImplement()))
) {
$def->setAutowired(FALSE);
}
}
// resolve and check classes
foreach ($this->definitions as $name => $def) {
$this->resolveServiceClass($name);
}
// build auto-wiring list
$excludedClasses = array();
foreach ($this->excludedClasses as $class) {
self::checkCase($class);
$excludedClasses += class_parents($class) + class_implements($class) + array($class => $class);
}
$this->classes = array();
foreach ($this->definitions as $name => $def) {
if ($class = $def->getImplement() ?: $def->getClass()) {
foreach (class_parents($class) + class_implements($class) + array($class) as $parent) {
$this->classes[$parent][$def->isAutowired() && empty($excludedClasses[$parent])][] = (string) $name;
}
}
}
foreach ($this->classes as $class => $foo) {
$rc = new ReflectionClass($class);
$this->addDependency($rc->getFileName());
}
}
private function resolveImplement(ServiceDefinition $def, $name)
{
$interface = $def->getImplement();
if (!interface_exists($interface)) {
throw new ServiceCreationException("Interface $interface used in service '$name' not found.");
}
self::checkCase($interface);
$rc = new ReflectionClass($interface);
$method = $rc->hasMethod('create')
? $rc->getMethod('create')
: ($rc->hasMethod('get') ? $rc->getMethod('get') : NULL);
if (count($rc->getMethods()) !== 1 || !$method || $method->isStatic()) {
throw new ServiceCreationException("Interface $interface used in service '$name' must have just one non-static method create() or get().");
}
$def->setImplementType($methodName = $rc->hasMethod('create') ? 'create' : 'get');
if (!$def->getClass() && !$def->getEntity()) {
$returnType = PhpReflection::getReturnType($method);
if (!$returnType) {
throw new ServiceCreationException("Method $interface::$methodName() used in service '$name' has no @return annotation.");
} elseif (!class_exists($returnType)) {
throw new ServiceCreationException("Check a @return annotation of the $interface::$methodName() method used in service '$name', class '$returnType' cannot be found.");
}
$def->setClass($returnType);
}
if ($methodName === 'get') {
if ($method->getParameters()) {
throw new ServiceCreationException("Method $interface::get() used in service '$name' must have no arguments.");
}
if (!$def->getEntity()) {
$def->setFactory('@\\' . ltrim($def->getClass(), '\\'));
} elseif (!$this->getServiceName($def->getFactory()->getEntity())) {
throw new ServiceCreationException("Invalid factory in service '$name' definition.");
}
}
if (!$def->parameters) {
$ctorParams = array();
if (!$def->getEntity()) {
$def->setFactory($def->getClass(), $def->getFactory() ? $def->getFactory()->arguments : array());
}
if (($class = $this->resolveEntityClass($def->getFactory(), array($name => 1)))
&& ($rc = new ReflectionClass($class)) && ($ctor = $rc->getConstructor())
) {
foreach ($ctor->getParameters() as $param) {
$ctorParams[$param->getName()] = $param;
}
}
foreach ($method->getParameters() as $param) {
$hint = PhpReflection::getParameterType($param);
if (isset($ctorParams[$param->getName()])) {
$arg = $ctorParams[$param->getName()];
if ($hint !== PhpReflection::getParameterType($arg)) {
throw new ServiceCreationException("Type hint for \${$param->getName()} in $interface::$methodName() doesn't match type hint in $class constructor.");
}
$def->getFactory()->arguments[$arg->getPosition()] = self::literal('$' . $arg->getName());
} elseif (!$def->getSetup()) {
$hint = Nette\Utils\ObjectMixin::getSuggestion(array_keys($ctorParams), $param->getName());
throw new ServiceCreationException("Unused parameter \${$param->getName()} when implementing method $interface::$methodName()" . ($hint ? ", did you mean \${$hint}?" : '.'));
}
$paramDef = $hint . ' ' . $param->getName();
if ($param->isOptional()) {
$def->parameters[$paramDef] = $param->getDefaultValue();
} else {
$def->parameters[] = $paramDef;
}
}
}
}
/** @return string|NULL */
private function resolveServiceClass($name, $recursive = array())
{
if (isset($recursive[$name])) {
throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.', implode(', ', array_keys($recursive))));
}
$recursive[$name] = TRUE;
$def = $this->definitions[$name];
$class = $def->getFactory() ? $this->resolveEntityClass($def->getFactory()->getEntity(), $recursive) : NULL; // call always to check entities
if ($class = $def->getClass() ?: $class) {
$def->setClass($class);
if (!class_exists($class) && !interface_exists($class)) {
throw new ServiceCreationException("Type $class used in service '$name' not found or is not class or interface.");
}
self::checkCase($class);
} elseif ($def->isAutowired()) {
trigger_error("Type of service '$name' is unknown.", E_USER_NOTICE);
}
return $class;
}
/** @return string|NULL */
private function resolveEntityClass($entity, $recursive = array())
{
$entity = $this->normalizeEntity($entity instanceof Statement ? $entity->getEntity() : $entity);
if (is_array($entity)) {
if (($service = $this->getServiceName($entity[0])) || $entity[0] instanceof Statement) {
$entity[0] = $this->resolveEntityClass($entity[0], $recursive);
if (!$entity[0]) {
return;
} elseif (isset($this->definitions[$service]) && $this->definitions[$service]->getImplement()) { // @Implement::create
return $entity[1] === 'create' ? $this->resolveServiceClass($service, $recursive) : NULL;
}
}
try {
$reflection = Nette\Utils\Callback::toReflection($entity[0] === '' ? $entity[1] : $entity);
$refClass = $reflection instanceof \ReflectionMethod ? $reflection->getDeclaringClass() : NULL;
} catch (\ReflectionException $e) {
}
if (isset($e) || ($refClass && (!$reflection->isPublic()
|| (PHP_VERSION_ID >= 50400 && $refClass->isTrait() && !$reflection->isStatic())
))) {
$name = array_slice(array_keys($recursive), -1);
throw new ServiceCreationException(sprintf("Factory '%s' used in service '%s' is not callable.", Nette\Utils\Callback::toString($entity), $name[0]));
}
return PhpReflection::getReturnType($reflection);
} elseif ($service = $this->getServiceName($entity)) { // alias or factory
if (Strings::contains($service, '\\')) { // @\Class
return ltrim($service, '\\');
}
return $this->definitions[$service]->getImplement() ?: $this->resolveServiceClass($service, $recursive);
} elseif (is_string($entity)) {
if (!class_exists($entity) || !($rc = new ReflectionClass($entity)) || !$rc->isInstantiable()) {
$name = array_slice(array_keys($recursive), -1);
throw new ServiceCreationException("Class $entity used in service '$name[0]' not found or is not instantiable.");
}
return ltrim($entity, '\\');
}
}
private function checkCase($class)
{
if ((class_exists($class) || interface_exists($class)) && ($rc = new ReflectionClass($class)) && $class !== $rc->getName()) {
throw new ServiceCreationException("Case mismatch on class name '$class', correct name is '{$rc->getName()}'.");
}
}
/**
* @param string[]
* @return self
*/
public function addExcludedClasses(array $classes)
{
$this->excludedClasses = array_merge($this->excludedClasses, $classes);
return $this;
}
/**
* Adds a file to the list of dependencies.
* @return self
* @internal
*/
public function addDependency($file)
{
$this->dependencies[$file] = TRUE;
return $this;
}
/**
* Returns the list of dependent files.
* @return array
*/
public function getDependencies()
{
unset($this->dependencies[FALSE]);
return array_keys($this->dependencies);
}
/********************* code generator ****************d*g**/
/**
* Generates PHP classes. First class is the container.
* @return Nette\PhpGenerator\ClassType[]
*/
public function generateClasses($className = NULL, $parentName = NULL)
{
$this->prepareClassList();
$this->generatedClasses = array();
$this->className = $className ?: $this->className;
$containerClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType($this->className);
$containerClass->setExtends($parentName ?: 'Nette\DI\Container');
$containerClass->addMethod('__construct')
->addBody('parent::__construct(?);', array($this->parameters));
$definitions = $this->definitions;
ksort($definitions);
$meta = $containerClass->addProperty('meta')
->setVisibility('protected')
->setValue(array(Container::TYPES => $this->classes));
foreach ($definitions as $name => $def) {
$meta->value[Container::SERVICES][$name] = $def->getClass() ?: NULL;
foreach ($def->getTags() as $tag => $value) {
$meta->value[Container::TAGS][$tag][$name] = $value;
}
}
foreach ($definitions as $name => $def) {
try {
$name = (string) $name;
$methodName = Container::getMethodName($name);
if (!PhpHelpers::isIdentifier($methodName)) {
throw new ServiceCreationException('Name contains invalid characters.');
}
$containerClass->addMethod($methodName)
->addComment('@return ' . ($def->getImplement() ?: $def->getClass()))
->setBody($name === self::THIS_CONTAINER ? 'return $this;' : $this->generateService($name))
->setParameters($def->getImplement() ? array() : $this->convertParameters($def->parameters));
} catch (\Exception $e) {
throw new ServiceCreationException("Service '$name': " . $e->getMessage(), NULL, $e);
}
}
$aliases = $this->aliases;
ksort($aliases);
$meta->value[Container::ALIASES] = $aliases;
return $this->generatedClasses;
}
/**
* Generates body of service method.
* @return string
*/
private function generateService($name)
{
$this->currentService = NULL;
$def = $this->definitions[$name];
if ($def->isDynamic()) {
return PhpHelpers::formatArgs('throw new Nette\\DI\\ServiceCreationException(?);',
array("Unable to create dynamic service '$name', it must be added using addService()")
);
}
$entity = $def->getFactory()->getEntity();
$serviceRef = $this->getServiceName($entity);
$factory = $serviceRef && !$def->getFactory()->arguments && !$def->getSetup() && $def->getImplementType() !== 'create'
? new Statement(array('@' . self::THIS_CONTAINER, 'getService'), array($serviceRef))
: $def->getFactory();
$code = '$service = ' . $this->formatStatement($factory) . ";\n";
$this->currentService = $name;
if (($class = $def->getClass()) && !$serviceRef && $class !== $entity
&& !(is_string($entity) && preg_match('#^[\w\\\\]+\z#', $entity) && is_subclass_of($entity, $class))
) {
$code .= PhpHelpers::formatArgs("if (!\$service instanceof $class) {\n"
. "\tthrow new Nette\\UnexpectedValueException(?);\n}\n",
array("Unable to create service '$name', value returned by factory is not $class type.")
);
}
foreach ($def->getSetup() as $setup) {
if (is_string($setup->getEntity()) && strpbrk($setup->getEntity(), ':@?\\') === FALSE) { // auto-prepend @self
$setup->setEntity(array('@self', $setup->getEntity()));
}
$code .= $this->formatStatement($setup) . ";\n";
}
$this->currentService = NULL;
$code .= 'return $service;';
if (!$def->getImplement()) {
return $code;
}
$factoryClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType;
$factoryClass->setName(str_replace(array('\\', '.'), '_', "{$this->className}_{$def->getImplement()}Impl_{$name}"))
->addImplement($def->getImplement())
->setFinal(TRUE);
$factoryClass->addProperty('container')
->setVisibility('private');
$factoryClass->addMethod('__construct')
->addBody('$this->container = $container;')
->addParameter('container')
->setTypeHint($this->className);
$factoryClass->addMethod($def->getImplementType())
->setParameters($this->convertParameters($def->parameters))
->setBody(str_replace('$this', '$this->container', $code))
->setReturnType(PHP_VERSION_ID >= 70000 ? $def->getClass() : NULL);
return "return new {$factoryClass->getName()}(\$this);";
}
/**
* Converts parameters from ServiceDefinition to PhpGenerator.
* @return Nette\PhpGenerator\Parameter[]
*/
private function convertParameters(array $parameters)
{
$res = array();
foreach ($parameters as $k => $v) {
$tmp = explode(' ', is_int($k) ? $v : $k);
$param = $res[] = new Nette\PhpGenerator\Parameter;
$param->setName(end($tmp));
if (!is_int($k)) {
$param = $param->setOptional(TRUE)->setDefaultValue($v);
}
if (isset($tmp[1])) {
$param->setTypeHint($tmp[0]);
}
}
return $res;
}
/**
* Formats PHP code for class instantiating, function calling or property setting in PHP.
* @return string
* @internal
*/
public function formatStatement(Statement $statement)
{
$entity = $this->normalizeEntity($statement->getEntity());
$arguments = $statement->arguments;
if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal
return $this->formatPhp($entity, $arguments);
} elseif ($service = $this->getServiceName($entity)) { // factory calling
$params = array();
foreach ($this->definitions[$service]->parameters as $k => $v) {
$params[] = preg_replace('#\w+\z#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
}
$rm = new \ReflectionFunction(create_function(implode(', ', $params), ''));
$arguments = Helpers::autowireArguments($rm, $arguments, $this);
return $this->formatPhp('$this->?(?*)', array(Container::getMethodName($service), $arguments));
} elseif ($entity === 'not') { // operator
return $this->formatPhp('!?', array($arguments[0]));
} elseif (is_string($entity)) { // class name
$rc = new ReflectionClass($entity);
if ($constructor = $rc->getConstructor()) {
$this->addDependency($constructor->getFileName());
$arguments = Helpers::autowireArguments($constructor, $arguments, $this);
} elseif ($arguments) {
throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor.");
}
return $this->formatPhp("new $entity" . ($arguments ? '(?*)' : ''), array($arguments));
} elseif (!Nette\Utils\Arrays::isList($entity) || count($entity) !== 2) {
throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.', PhpHelpers::dump($entity)));
} elseif (!preg_match('#^\$?' . PhpHelpers::PHP_IDENT . '\z#', $entity[1])) {
throw new ServiceCreationException("Expected function, method or property name, '$entity[1]' given.");
} elseif ($entity[0] === '') { // globalFunc
return $this->formatPhp("$entity[1](?*)", array($arguments));
} elseif ($entity[0] instanceof Statement) {
$inner = $this->formatPhp('?', array($entity[0]));
if (substr($inner, 0, 4) === 'new ') {
$inner = PHP_VERSION_ID < 50400 ? "current(array($inner))" : "($inner)";
}
return $this->formatPhp("$inner->?(?*)", array($entity[1], $arguments));
} elseif (Strings::contains($entity[1], '$')) { // property setter
Validators::assert($arguments, 'list:1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'");
if ($this->getServiceName($entity[0])) {
return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0]));
} else {
return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0]));
}
} elseif ($service = $this->getServiceName($entity[0])) { // service method
$class = $this->definitions[$service]->getImplement();
if (!$class || !method_exists($class, $entity[1])) {
$class = $this->definitions[$service]->getClass();
}
if ($class) {
$arguments = $this->autowireArguments($class, $entity[1], $arguments);
}
return $this->formatPhp('?->?(?*)', array($entity[0], $entity[1], $arguments));
} else { // static method
$arguments = $this->autowireArguments($entity[0], $entity[1], $arguments);
return $this->formatPhp("$entity[0]::$entity[1](?*)", array($arguments));
}
}
/**
* Formats PHP statement.
* @return string
* @internal
*/
public function formatPhp($statement, $args)
{
$that = $this;
array_walk_recursive($args, function (& $val) use ($that) {
if ($val instanceof Statement) {
$val = ContainerBuilder::literal($that->formatStatement($val));
} elseif ($val === $that) {
$val = ContainerBuilder::literal('$this');
} elseif ($val instanceof ServiceDefinition) {
$val = '@' . current(array_keys($that->getDefinitions(), $val, TRUE));
}
if (!is_string($val)) {
return;
} elseif (substr($val, 0, 2) === '@@') {
$val = substr($val, 1);
} elseif (substr($val, 0, 1) === '@' && strlen($val) > 1) {
$pair = explode('::', $val, 2);
$name = $that->getServiceName($pair[0]);
if (isset($pair[1]) && preg_match('#^[A-Z][A-Z0-9_]*\z#', $pair[1], $m)) {
$val = $that->getDefinition($name)->getClass() . '::' . $pair[1];
} else {
if ($name === ContainerBuilder::THIS_CONTAINER) {
$val = '$this';
} elseif ($name === $that->currentService) {
$val = '$service';
} else {
$val = $that->formatStatement(new Statement(array('@' . ContainerBuilder::THIS_CONTAINER, 'getService'), array($name)));
}
$val .= (isset($pair[1]) ? PhpHelpers::formatArgs('->?', array($pair[1])) : '');
}
$val = ContainerBuilder::literal($val);
}
});
return PhpHelpers::formatArgs($statement, $args);
}
/**
* Expands %placeholders% in strings.
* @return mixed
* @deprecated
*/
public function expand($value)
{
return Helpers::expand($value, $this->parameters);
}
/**
* @return Nette\PhpGenerator\PhpLiteral
*/
public static function literal($phpCode)
{
return new Nette\PhpGenerator\PhpLiteral($phpCode);
}
/** @internal */
public function normalizeEntity($entity)
{
if (is_string($entity) && Strings::contains($entity, '::') && !Strings::contains($entity, '?')) { // Class::method -> [Class, method]
$entity = explode('::', $entity);
}
if (is_array($entity) && $entity[0] instanceof ServiceDefinition) { // [ServiceDefinition, ...] -> [@serviceName, ...]
$entity[0] = '@' . current(array_keys($this->definitions, $entity[0], TRUE));
} elseif ($entity instanceof ServiceDefinition) { // ServiceDefinition -> @serviceName
$entity = '@' . current(array_keys($this->definitions, $entity, TRUE));
} elseif (is_array($entity) && $entity[0] === $this) { // [$this, ...] -> [@container, ...]
$entity[0] = '@' . self::THIS_CONTAINER;
}
return $entity; // Class, @service, [Class, member], [@service, member], [, globalFunc], Statement
}
/**
* Converts @service or @\Class -> service name and checks its existence.
* @return string of FALSE, if argument is not service name
* @internal
*/
public function getServiceName($arg)
{
$arg = $this->normalizeEntity($arg);
if (!is_string($arg) || !preg_match('#^@[\w\\\\.].*\z#', $arg)) {
return FALSE;
}
$service = substr($arg, 1);
if ($service === self::THIS_SERVICE) {
$service = $this->currentService;
}
if (Strings::contains($service, '\\')) {
if ($this->classes === FALSE) { // may be disabled by prepareClassList
return $service;
}
$res = $this->getByType($service);
if (!$res) {
throw new ServiceCreationException("Reference to missing service of type $service.");
}
return $res;
}
$service = isset($this->aliases[$service]) ? $this->aliases[$service] : $service;
if (!isset($this->definitions[$service])) {
throw new ServiceCreationException("Reference to missing service '$service'.");
}
return $service;
}
}
|
kivi8/ars-poetica
|
vendor/nette/di/src/DI/ContainerBuilder.php
|
PHP
|
bsd-3-clause
| 27,588 |
/**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
package org.cagrid.gaards.dorian.federation;
import gov.nih.nci.cagrid.common.Utils;
import java.util.Arrays;
public class ReportUtils {
public static String generateReport(TrustedIdP original, TrustedIdP updated) {
StringBuffer sb = new StringBuffer();
sb.append("The following changes were made to the Trusted IdP, " + original.getName() + " (" + original.getId()
+ "): \n");
int count = 0;
if ((Utils.clean(updated.getDisplayName()) != null)
&& (!updated.getDisplayName().equals(original.getDisplayName()))) {
count = count + 1;
sb.append(count + ". Display Name changed from " + original.getDisplayName() + " to "
+ updated.getDisplayName() + ".\n");
}
if ((Utils.clean(updated.getUserPolicyClass()) != null)
&& (!updated.getUserPolicyClass().equals(original.getUserPolicyClass()))) {
count = count + 1;
sb.append(count + ". User policy changed from " + original.getUserPolicyClass() + " to "
+ updated.getUserPolicyClass() + ".\n");
}
if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) {
count = count + 1;
sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to "
+ updated.getStatus().getValue() + ".\n");
}
if ((Utils.clean(updated.getIdPCertificate()) != null)
&& (!updated.getIdPCertificate().equals(original.getIdPCertificate()))) {
count = count + 1;
sb.append(count + ". Signing certificate changed.\n");
}
if (updated.getAuthenticationServiceURL() == null) {
updated.setAuthenticationServiceURL("");
}
if (!updated.getAuthenticationServiceURL().equals(original.getAuthenticationServiceURL())) {
count = count + 1;
sb.append(count + ". Authentication Service URL changed from " + original.getAuthenticationServiceURL()
+ " to " + updated.getAuthenticationServiceURL() + ".\n");
}
if (updated.getAuthenticationServiceIdentity() == null) {
updated.setAuthenticationServiceIdentity("");
}
if (!updated.getAuthenticationServiceIdentity().equals(original.getAuthenticationServiceIdentity())) {
count = count + 1;
sb.append(count + ". Authentication Service Identity changed from "
+ original.getAuthenticationServiceIdentity() + " to " + updated.getAuthenticationServiceIdentity()
+ ".\n");
}
if ((updated.getUserIdAttributeDescriptor() != null)
&& (!updated.getUserIdAttributeDescriptor().equals(original.getUserIdAttributeDescriptor()))) {
count = count + 1;
sb.append(count + ". User Id Attribute changed from "
+ original.getUserIdAttributeDescriptor().getNamespaceURI() + ":"
+ original.getUserIdAttributeDescriptor().getName() + " to "
+ updated.getUserIdAttributeDescriptor().getNamespaceURI() + ":"
+ updated.getUserIdAttributeDescriptor().getName() + ".\n");
}
if ((updated.getFirstNameAttributeDescriptor() != null)
&& (!updated.getFirstNameAttributeDescriptor().equals(original.getFirstNameAttributeDescriptor()))) {
count = count + 1;
sb.append(count + ". First Name Attribute changed from "
+ original.getFirstNameAttributeDescriptor().getNamespaceURI() + ":"
+ original.getFirstNameAttributeDescriptor().getName() + " to "
+ updated.getFirstNameAttributeDescriptor().getNamespaceURI() + ":"
+ updated.getFirstNameAttributeDescriptor().getName() + ".\n");
}
if ((updated.getLastNameAttributeDescriptor() != null)
&& (!updated.getLastNameAttributeDescriptor().equals(original.getLastNameAttributeDescriptor()))) {
count = count + 1;
sb.append(count + ". Last Name Attribute changed from "
+ original.getLastNameAttributeDescriptor().getNamespaceURI() + ":"
+ original.getLastNameAttributeDescriptor().getName() + " to "
+ updated.getLastNameAttributeDescriptor().getNamespaceURI() + ":"
+ updated.getLastNameAttributeDescriptor().getName() + ".\n");
}
if ((updated.getEmailAttributeDescriptor() != null)
&& (!updated.getEmailAttributeDescriptor().equals(original.getEmailAttributeDescriptor()))) {
count = count + 1;
sb.append(count + ". Email Attribute changed from "
+ original.getEmailAttributeDescriptor().getNamespaceURI() + ":"
+ original.getEmailAttributeDescriptor().getName() + " to "
+ updated.getEmailAttributeDescriptor().getNamespaceURI() + ":"
+ updated.getEmailAttributeDescriptor().getName() + ".\n");
}
if (!Arrays.equals(original.getAuthenticationMethod(), updated.getAuthenticationMethod())) {
count = count + 1;
sb.append(count + ". Authentication methods changed from (");
boolean first = true;
if (original.getAuthenticationMethod() != null) {
for (int i = 0; i < original.getAuthenticationMethod().length; i++) {
if (!first) {
sb.append(", ");
}
sb.append(original.getAuthenticationMethod(i));
first = false;
}
}
sb.append(") to (");
first = true;
if (updated.getAuthenticationMethod() != null) {
for (int i = 0; i < updated.getAuthenticationMethod().length; i++) {
if (!first) {
sb.append(", ");
}
sb.append(updated.getAuthenticationMethod(i));
first = false;
}
}
sb.append(").");
}
return sb.toString();
}
public static String generateReport(GridUser original, GridUser updated) {
StringBuffer sb = new StringBuffer();
sb.append("The following changes were made to the Grid user, " + original.getGridId() + ": \n");
int count = 0;
if ((updated.getFirstName() != null) && (!updated.getFirstName().equals(original.getFirstName()))) {
count = count + 1;
sb.append(count + ". First Name changed from " + original.getFirstName() + " to " + updated.getFirstName()
+ ".\n");
}
if ((updated.getLastName() != null) && (!updated.getLastName().equals(original.getLastName()))) {
count = count + 1;
sb.append(count + ". Last Name changed from " + original.getLastName() + " to " + updated.getLastName()
+ ".\n");
}
if ((updated.getEmail() != null) && (!updated.getEmail().equals(original.getEmail()))) {
count = count + 1;
sb.append(count + ". Email changed from " + original.getEmail() + " to " + updated.getEmail() + ".\n");
}
if ((updated.getUserStatus() != null) && (!updated.getUserStatus().equals(original.getUserStatus()))) {
count = count + 1;
sb.append(count + ". Status changed from " + original.getUserStatus().getValue() + " to "
+ updated.getUserStatus().getValue() + ".\n");
}
return sb.toString();
}
public static String generateReport(HostCertificateRecord original, HostCertificateRecord updated) {
StringBuffer sb = new StringBuffer();
sb.append("The following changes were made to the host certificate, " + original.getHost() + "("
+ original.getId() + "): \n");
int count = 0;
if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) {
count = count + 1;
sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to "
+ updated.getStatus().getValue() + ".\n");
}
if ((updated.getOwner() != null) && (!updated.getOwner().equals(original.getOwner()))) {
count = count + 1;
sb.append(count + ". Owner changed from " + original.getOwner() + " to " + updated.getOwner() + ".\n");
}
return sb.toString();
}
public static String generateReport(UserCertificateRecord original, UserCertificateRecord updated) {
StringBuffer sb = new StringBuffer();
sb.append("The following changes were made to the user certificate, " + original.getSerialNumber() + ": \n");
int count = 0;
if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) {
count = count + 1;
sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to "
+ updated.getStatus().getValue() + ".\n");
}
if ((updated.getNotes() != null) && (!updated.getNotes().equals(original.getNotes()))) {
count = count + 1;
sb.append(count + ". Notes updated.\n");
}
return sb.toString();
}
}
|
NCIP/cagrid-core
|
caGrid/projects/dorian/src/org/cagrid/gaards/dorian/federation/ReportUtils.java
|
Java
|
bsd-3-clause
| 9,870 |
//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for inline asm statements.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ExprCXX.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
using namespace clang;
using namespace sema;
/// Remove the upper-level LValueToRValue cast from an expression.
static void removeLValueToRValueCast(Expr *E) {
Expr *Parent = E;
Expr *ExprUnderCast = nullptr;
SmallVector<Expr *, 8> ParentsToUpdate;
while (true) {
ParentsToUpdate.push_back(Parent);
if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) {
Parent = ParenE->getSubExpr();
continue;
}
Expr *Child = nullptr;
CastExpr *ParentCast = dyn_cast<CastExpr>(Parent);
if (ParentCast)
Child = ParentCast->getSubExpr();
else
return;
if (auto *CastE = dyn_cast<CastExpr>(Child))
if (CastE->getCastKind() == CK_LValueToRValue) {
ExprUnderCast = CastE->getSubExpr();
// LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
ParentCast->setSubExpr(ExprUnderCast);
break;
}
Parent = Child;
}
// Update parent expressions to have same ValueType as the underlying.
assert(ExprUnderCast &&
"Should be reachable only if LValueToRValue cast was found!");
auto ValueKind = ExprUnderCast->getValueKind();
for (Expr *E : ParentsToUpdate)
E->setValueKind(ValueKind);
}
/// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
/// and fix the argument with removing LValueToRValue cast from the expression.
static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
Sema &S) {
if (!S.getLangOpts().HeinousExtensions) {
S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue)
<< BadArgument->getSourceRange();
} else {
S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue)
<< BadArgument->getSourceRange();
}
removeLValueToRValueCast(BadArgument);
}
/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
/// ignore "noop" casts in places where an lvalue is required by an inline asm.
/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
/// provide a strong guidance to not use it.
///
/// This method checks to see if the argument is an acceptable l-value and
/// returns false if it is a case we can handle.
static bool CheckAsmLValue(Expr *E, Sema &S) {
// Type dependent expressions will be checked during instantiation.
if (E->isTypeDependent())
return false;
if (E->isLValue())
return false; // Cool, this is an lvalue.
// Okay, this is not an lvalue, but perhaps it is the result of a cast that we
// are supposed to allow.
const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
if (E != E2 && E2->isLValue()) {
emitAndFixInvalidAsmCastLValue(E2, E, S);
// Accept, even if we emitted an error diagnostic.
return false;
}
// None of the above, just randomly invalid non-lvalue.
return true;
}
/// isOperandMentioned - Return true if the specified operand # is mentioned
/// anywhere in the decomposed asm string.
static bool
isOperandMentioned(unsigned OpNo,
ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
if (!Piece.isOperand())
continue;
// If this is a reference to the input and if the input was the smaller
// one, then we have to reject this asm.
if (Piece.getOperandNo() == OpNo)
return true;
}
return false;
}
static bool CheckNakedParmReference(Expr *E, Sema &S) {
FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
if (!Func)
return false;
if (!Func->hasAttr<NakedAttr>())
return false;
SmallVector<Expr*, 4> WorkList;
WorkList.push_back(E);
while (WorkList.size()) {
Expr *E = WorkList.pop_back_val();
if (isa<CXXThisExpr>(E)) {
S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref);
S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
return true;
}
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
if (isa<ParmVarDecl>(DRE->getDecl())) {
S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref);
S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
return true;
}
}
for (Stmt *Child : E->children()) {
if (Expr *E = dyn_cast_or_null<Expr>(Child))
WorkList.push_back(E);
}
}
return false;
}
/// Returns true if given expression is not compatible with inline
/// assembly's memory constraint; false otherwise.
static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
TargetInfo::ConstraintInfo &Info,
bool is_input_expr) {
enum {
ExprBitfield = 0,
ExprVectorElt,
ExprGlobalRegVar,
ExprSafeType
} EType = ExprSafeType;
// Bitfields, vector elements and global register variables are not
// compatible.
if (E->refersToBitField())
EType = ExprBitfield;
else if (E->refersToVectorElement())
EType = ExprVectorElt;
else if (E->refersToGlobalRegisterVar())
EType = ExprGlobalRegVar;
if (EType != ExprSafeType) {
S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint)
<< EType << is_input_expr << Info.getConstraintStr()
<< E->getSourceRange();
return true;
}
return false;
}
// Extracting the register name from the Expression value,
// if there is no register name to extract, returns ""
static StringRef extractRegisterName(const Expr *Expression,
const TargetInfo &Target) {
Expression = Expression->IgnoreImpCasts();
if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) {
// Handle cases where the expression is a variable
const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl());
if (Variable && Variable->getStorageClass() == SC_Register) {
if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
if (Target.isValidGCCRegisterName(Attr->getLabel()))
return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true);
}
}
return "";
}
// Checks if there is a conflict between the input and output lists with the
// clobbers list. If there's a conflict, returns the location of the
// conflicted clobber, else returns nullptr
static SourceLocation
getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints,
StringLiteral **Clobbers, int NumClobbers,
unsigned NumLabels,
const TargetInfo &Target, ASTContext &Cont) {
llvm::StringSet<> InOutVars;
// Collect all the input and output registers from the extended asm
// statement in order to check for conflicts with the clobber list
for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) {
StringRef Constraint = Constraints[i]->getString();
StringRef InOutReg = Target.getConstraintRegister(
Constraint, extractRegisterName(Exprs[i], Target));
if (InOutReg != "")
InOutVars.insert(InOutReg);
}
// Check for each item in the clobber list if it conflicts with the input
// or output
for (int i = 0; i < NumClobbers; ++i) {
StringRef Clobber = Clobbers[i]->getString();
// We only check registers, therefore we don't check cc and memory
// clobbers
if (Clobber == "cc" || Clobber == "memory")
continue;
Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
// Go over the output's registers we collected
if (InOutVars.count(Clobber))
return Clobbers[i]->getBeginLoc();
}
return SourceLocation();
}
StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg constraints, MultiExprArg Exprs,
Expr *asmString, MultiExprArg clobbers,
unsigned NumLabels,
SourceLocation RParenLoc) {
unsigned NumClobbers = clobbers.size();
StringLiteral **Constraints =
reinterpret_cast<StringLiteral**>(constraints.data());
StringLiteral *AsmString = cast<StringLiteral>(asmString);
StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
// The parser verifies that there is a string literal here.
assert(AsmString->isAscii());
FunctionDecl *FD = dyn_cast<FunctionDecl>(getCurLexicalContext());
llvm::StringMap<bool> FeatureMap;
Context.getFunctionFeatureMap(FeatureMap, FD);
for (unsigned i = 0; i != NumOutputs; i++) {
StringLiteral *Literal = Constraints[i];
assert(Literal->isAscii());
StringRef OutputName;
if (Names[i])
OutputName = Names[i]->getName();
TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
targetDiag(Literal->getBeginLoc(),
diag::err_asm_invalid_output_constraint)
<< Info.getConstraintStr();
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(), AsmString,
NumClobbers, Clobbers, NumLabels, RParenLoc);
}
ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
if (ER.isInvalid())
return StmtError();
Exprs[i] = ER.get();
// Check that the output exprs are valid lvalues.
Expr *OutputExpr = Exprs[i];
// Referring to parameters is not allowed in naked functions.
if (CheckNakedParmReference(OutputExpr, *this))
return StmtError();
// Check that the output expression is compatible with memory constraint.
if (Info.allowsMemory() &&
checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
return StmtError();
OutputConstraintInfos.push_back(Info);
// If this is dependent, just continue.
if (OutputExpr->isTypeDependent())
continue;
Expr::isModifiableLvalueResult IsLV =
OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
switch (IsLV) {
case Expr::MLV_Valid:
// Cool, this is an lvalue.
break;
case Expr::MLV_ArrayType:
// This is OK too.
break;
case Expr::MLV_LValueCast: {
const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this);
// Accept, even if we emitted an error diagnostic.
break;
}
case Expr::MLV_IncompleteType:
case Expr::MLV_IncompleteVoidType:
if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(),
diag::err_dereference_incomplete_type))
return StmtError();
LLVM_FALLTHROUGH;
default:
return StmtError(Diag(OutputExpr->getBeginLoc(),
diag::err_asm_invalid_lvalue_in_output)
<< OutputExpr->getSourceRange());
}
unsigned Size = Context.getTypeSize(OutputExpr->getType());
if (!Context.getTargetInfo().validateOutputSize(
FeatureMap, Literal->getString(), Size)) {
targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size)
<< Info.getConstraintStr();
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(), AsmString,
NumClobbers, Clobbers, NumLabels, RParenLoc);
}
}
SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
StringLiteral *Literal = Constraints[i];
assert(Literal->isAscii());
StringRef InputName;
if (Names[i])
InputName = Names[i]->getName();
TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
Info)) {
targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint)
<< Info.getConstraintStr();
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(), AsmString,
NumClobbers, Clobbers, NumLabels, RParenLoc);
}
ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
if (ER.isInvalid())
return StmtError();
Exprs[i] = ER.get();
Expr *InputExpr = Exprs[i];
// Referring to parameters is not allowed in naked functions.
if (CheckNakedParmReference(InputExpr, *this))
return StmtError();
// Check that the input expression is compatible with memory constraint.
if (Info.allowsMemory() &&
checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
return StmtError();
// Only allow void types for memory constraints.
if (Info.allowsMemory() && !Info.allowsRegister()) {
if (CheckAsmLValue(InputExpr, *this))
return StmtError(Diag(InputExpr->getBeginLoc(),
diag::err_asm_invalid_lvalue_in_input)
<< Info.getConstraintStr()
<< InputExpr->getSourceRange());
} else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
if (!InputExpr->isValueDependent()) {
Expr::EvalResult EVResult;
if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) {
// For compatibility with GCC, we also allow pointers that would be
// integral constant expressions if they were cast to int.
llvm::APSInt IntResult;
if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
Context))
if (!Info.isValidAsmImmediate(IntResult))
return StmtError(Diag(InputExpr->getBeginLoc(),
diag::err_invalid_asm_value_for_constraint)
<< IntResult.toString(10)
<< Info.getConstraintStr()
<< InputExpr->getSourceRange());
}
}
} else {
ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
if (Result.isInvalid())
return StmtError();
Exprs[i] = Result.get();
}
if (Info.allowsRegister()) {
if (InputExpr->getType()->isVoidType()) {
return StmtError(
Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
<< InputExpr->getType() << Info.getConstraintStr()
<< InputExpr->getSourceRange());
}
}
InputConstraintInfos.push_back(Info);
const Type *Ty = Exprs[i]->getType().getTypePtr();
if (Ty->isDependentType())
continue;
if (!Ty->isVoidType() || !Info.allowsMemory())
if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
diag::err_dereference_incomplete_type))
return StmtError();
unsigned Size = Context.getTypeSize(Ty);
if (!Context.getTargetInfo().validateInputSize(FeatureMap,
Literal->getString(), Size))
return StmtResult(
targetDiag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size)
<< Info.getConstraintStr());
}
// Check that the clobbers are valid.
for (unsigned i = 0; i != NumClobbers; i++) {
StringLiteral *Literal = Clobbers[i];
assert(Literal->isAscii());
StringRef Clobber = Literal->getString();
if (!Context.getTargetInfo().isValidClobber(Clobber)) {
targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name)
<< Clobber;
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(), AsmString,
NumClobbers, Clobbers, NumLabels, RParenLoc);
}
}
GCCAsmStmt *NS =
new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(),
AsmString, NumClobbers, Clobbers, NumLabels,
RParenLoc);
// Validate the asm string, ensuring it makes sense given the operands we
// have.
SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
unsigned DiagOffs;
if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
<< AsmString->getSourceRange();
return NS;
}
// Validate constraints and modifiers.
for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
if (!Piece.isOperand()) continue;
// Look for the correct constraint index.
unsigned ConstraintIdx = Piece.getOperandNo();
unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
// Labels are the last in the Exprs list.
if (NS->isAsmGoto() && ConstraintIdx >= NumOperands)
continue;
// Look for the (ConstraintIdx - NumOperands + 1)th constraint with
// modifier '+'.
if (ConstraintIdx >= NumOperands) {
unsigned I = 0, E = NS->getNumOutputs();
for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
ConstraintIdx = I;
break;
}
assert(I != E && "Invalid operand number should have been caught in "
" AnalyzeAsmString");
}
// Now that we have the right indexes go ahead and check.
StringLiteral *Literal = Constraints[ConstraintIdx];
const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
if (Ty->isDependentType() || Ty->isIncompleteType())
continue;
unsigned Size = Context.getTypeSize(Ty);
std::string SuggestedModifier;
if (!Context.getTargetInfo().validateConstraintModifier(
Literal->getString(), Piece.getModifier(), Size,
SuggestedModifier)) {
targetDiag(Exprs[ConstraintIdx]->getBeginLoc(),
diag::warn_asm_mismatched_size_modifier);
if (!SuggestedModifier.empty()) {
auto B = targetDiag(Piece.getRange().getBegin(),
diag::note_asm_missing_constraint_modifier)
<< SuggestedModifier;
SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier);
}
}
}
// Validate tied input operands for type mismatches.
unsigned NumAlternatives = ~0U;
for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
StringRef ConstraintStr = Info.getConstraintStr();
unsigned AltCount = ConstraintStr.count(',') + 1;
if (NumAlternatives == ~0U) {
NumAlternatives = AltCount;
} else if (NumAlternatives != AltCount) {
targetDiag(NS->getOutputExpr(i)->getBeginLoc(),
diag::err_asm_unexpected_constraint_alternatives)
<< NumAlternatives << AltCount;
return NS;
}
}
SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
~0U);
for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
StringRef ConstraintStr = Info.getConstraintStr();
unsigned AltCount = ConstraintStr.count(',') + 1;
if (NumAlternatives == ~0U) {
NumAlternatives = AltCount;
} else if (NumAlternatives != AltCount) {
targetDiag(NS->getInputExpr(i)->getBeginLoc(),
diag::err_asm_unexpected_constraint_alternatives)
<< NumAlternatives << AltCount;
return NS;
}
// If this is a tied constraint, verify that the output and input have
// either exactly the same type, or that they are int/ptr operands with the
// same size (int/long, int*/long, are ok etc).
if (!Info.hasTiedOperand()) continue;
unsigned TiedTo = Info.getTiedOperand();
unsigned InputOpNo = i+NumOutputs;
Expr *OutputExpr = Exprs[TiedTo];
Expr *InputExpr = Exprs[InputOpNo];
// Make sure no more than one input constraint matches each output.
assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
if (InputMatchedToOutput[TiedTo] != ~0U) {
targetDiag(NS->getInputExpr(i)->getBeginLoc(),
diag::err_asm_input_duplicate_match)
<< TiedTo;
targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
diag::note_asm_input_duplicate_first)
<< TiedTo;
return NS;
}
InputMatchedToOutput[TiedTo] = i;
if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
continue;
QualType InTy = InputExpr->getType();
QualType OutTy = OutputExpr->getType();
if (Context.hasSameType(InTy, OutTy))
continue; // All types can be tied to themselves.
// Decide if the input and output are in the same domain (integer/ptr or
// floating point.
enum AsmDomain {
AD_Int, AD_FP, AD_Other
} InputDomain, OutputDomain;
if (InTy->isIntegerType() || InTy->isPointerType())
InputDomain = AD_Int;
else if (InTy->isRealFloatingType())
InputDomain = AD_FP;
else
InputDomain = AD_Other;
if (OutTy->isIntegerType() || OutTy->isPointerType())
OutputDomain = AD_Int;
else if (OutTy->isRealFloatingType())
OutputDomain = AD_FP;
else
OutputDomain = AD_Other;
// They are ok if they are the same size and in the same domain. This
// allows tying things like:
// void* to int*
// void* to int if they are the same size.
// double to long double if they are the same size.
//
uint64_t OutSize = Context.getTypeSize(OutTy);
uint64_t InSize = Context.getTypeSize(InTy);
if (OutSize == InSize && InputDomain == OutputDomain &&
InputDomain != AD_Other)
continue;
// If the smaller input/output operand is not mentioned in the asm string,
// then we can promote the smaller one to a larger input and the asm string
// won't notice.
bool SmallerValueMentioned = false;
// If this is a reference to the input and if the input was the smaller
// one, then we have to reject this asm.
if (isOperandMentioned(InputOpNo, Pieces)) {
// This is a use in the asm string of the smaller operand. Since we
// codegen this by promoting to a wider value, the asm will get printed
// "wrong".
SmallerValueMentioned |= InSize < OutSize;
}
if (isOperandMentioned(TiedTo, Pieces)) {
// If this is a reference to the output, and if the output is the larger
// value, then it's ok because we'll promote the input to the larger type.
SmallerValueMentioned |= OutSize < InSize;
}
// If the smaller value wasn't mentioned in the asm string, and if the
// output was a register, just extend the shorter one to the size of the
// larger one.
if (!SmallerValueMentioned && InputDomain != AD_Other &&
OutputConstraintInfos[TiedTo].allowsRegister())
continue;
// Either both of the operands were mentioned or the smaller one was
// mentioned. One more special case that we'll allow: if the tied input is
// integer, unmentioned, and is a constant, then we'll allow truncating it
// down to the size of the destination.
if (InputDomain == AD_Int && OutputDomain == AD_Int &&
!isOperandMentioned(InputOpNo, Pieces) &&
InputExpr->isEvaluatable(Context)) {
CastKind castKind =
(OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Exprs[InputOpNo] = InputExpr;
NS->setInputExpr(i, InputExpr);
continue;
}
targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
<< InTy << OutTy << OutputExpr->getSourceRange()
<< InputExpr->getSourceRange();
return NS;
}
// Check for conflicts between clobber list and input or output lists
SourceLocation ConstraintLoc =
getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
NumLabels,
Context.getTargetInfo(), Context);
if (ConstraintLoc.isValid())
targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
// Check for duplicate asm operand name between input, output and label lists.
typedef std::pair<StringRef , Expr *> NamedOperand;
SmallVector<NamedOperand, 4> NamedOperandList;
for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
if (Names[i])
NamedOperandList.emplace_back(
std::make_pair(Names[i]->getName(), Exprs[i]));
// Sort NamedOperandList.
std::stable_sort(NamedOperandList.begin(), NamedOperandList.end(),
[](const NamedOperand &LHS, const NamedOperand &RHS) {
return LHS.first < RHS.first;
});
// Find adjacent duplicate operand.
SmallVector<NamedOperand, 4>::iterator Found =
std::adjacent_find(begin(NamedOperandList), end(NamedOperandList),
[](const NamedOperand &LHS, const NamedOperand &RHS) {
return LHS.first == RHS.first;
});
if (Found != NamedOperandList.end()) {
Diag((Found + 1)->second->getBeginLoc(),
diag::error_duplicate_asm_operand_name)
<< (Found + 1)->first;
Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name)
<< Found->first;
return StmtError();
}
if (NS->isAsmGoto())
setFunctionHasBranchIntoScope();
return NS;
}
void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
llvm::InlineAsmIdentifierInfo &Info) {
QualType T = Res->getType();
Expr::EvalResult Eval;
if (T->isFunctionType() || T->isDependentType())
return Info.setLabel(Res);
if (Res->isRValue()) {
bool IsEnum = isa<clang::EnumType>(T);
if (DeclRefExpr *DRE = dyn_cast<clang::DeclRefExpr>(Res))
if (DRE->getDecl()->getKind() == Decl::EnumConstant)
IsEnum = true;
if (IsEnum && Res->EvaluateAsRValue(Eval, Context))
return Info.setEnum(Eval.Val.getInt().getSExtValue());
return Info.setLabel(Res);
}
unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
unsigned Type = Size;
if (const auto *ATy = Context.getAsArrayType(T))
Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
bool IsGlobalLV = false;
if (Res->EvaluateAsLValue(Eval, Context))
IsGlobalLV = Eval.isGlobalLValue();
Info.setVar(Res, IsGlobalLV, Size, Type);
}
ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
bool IsUnevaluatedContext) {
if (IsUnevaluatedContext)
PushExpressionEvaluationContext(
ExpressionEvaluationContext::UnevaluatedAbstract,
ReuseLambdaContextDecl);
ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
/*trailing lparen*/ false,
/*is & operand*/ false,
/*CorrectionCandidateCallback=*/nullptr,
/*IsInlineAsmIdentifier=*/ true);
if (IsUnevaluatedContext)
PopExpressionEvaluationContext();
if (!Result.isUsable()) return Result;
Result = CheckPlaceholderExpr(Result.get());
if (!Result.isUsable()) return Result;
// Referring to parameters is not allowed in naked functions.
if (CheckNakedParmReference(Result.get(), *this))
return ExprError();
QualType T = Result.get()->getType();
if (T->isDependentType()) {
return Result;
}
// Any sort of function type is fine.
if (T->isFunctionType()) {
return Result;
}
// Otherwise, it needs to be a complete type.
if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
return ExprError();
}
return Result;
}
bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc) {
Offset = 0;
SmallVector<StringRef, 2> Members;
Member.split(Members, ".");
NamedDecl *FoundDecl = nullptr;
// MS InlineAsm uses 'this' as a base
if (getLangOpts().CPlusPlus && Base.equals("this")) {
if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
FoundDecl = PT->getPointeeType()->getAsTagDecl();
} else {
LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
LookupOrdinaryName);
if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
FoundDecl = BaseResult.getFoundDecl();
}
if (!FoundDecl)
return true;
for (StringRef NextMember : Members) {
const RecordType *RT = nullptr;
if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
RT = VD->getType()->getAs<RecordType>();
else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
// MS InlineAsm often uses struct pointer aliases as a base
QualType QT = TD->getUnderlyingType();
if (const auto *PT = QT->getAs<PointerType>())
QT = PT->getPointeeType();
RT = QT->getAs<RecordType>();
} else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
RT = TD->getTypeForDecl()->getAs<RecordType>();
else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
RT = TD->getType()->getAs<RecordType>();
if (!RT)
return true;
if (RequireCompleteType(AsmLoc, QualType(RT, 0),
diag::err_asm_incomplete_type))
return true;
LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
SourceLocation(), LookupMemberName);
if (!LookupQualifiedName(FieldResult, RT->getDecl()))
return true;
if (!FieldResult.isSingleResult())
return true;
FoundDecl = FieldResult.getFoundDecl();
// FIXME: Handle IndirectFieldDecl?
FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
if (!FD)
return true;
const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
unsigned i = FD->getFieldIndex();
CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
Offset += (unsigned)Result.getQuantity();
}
return false;
}
ExprResult
Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
SourceLocation AsmLoc) {
QualType T = E->getType();
if (T->isDependentType()) {
DeclarationNameInfo NameInfo;
NameInfo.setLoc(AsmLoc);
NameInfo.setName(&Context.Idents.get(Member));
return CXXDependentScopeMemberExpr::Create(
Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
SourceLocation(),
/*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
}
const RecordType *RT = T->getAs<RecordType>();
// FIXME: Diagnose this as field access into a scalar type.
if (!RT)
return ExprResult();
LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
LookupMemberName);
if (!LookupQualifiedName(FieldResult, RT->getDecl()))
return ExprResult();
// Only normal and indirect field results will work.
ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
if (!FD)
FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
if (!FD)
return ExprResult();
// Make an Expr to thread through OpDecl.
ExprResult Result = BuildMemberReferenceExpr(
E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
return Result;
}
StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc) {
bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
setFunctionHasBranchProtectedScope();
MSAsmStmt *NS =
new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
/*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
Constraints, Exprs, AsmString,
Clobbers, EndLoc);
return NS;
}
LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate) {
LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
Location);
if (Label->isMSAsmLabel()) {
// If we have previously created this label implicitly, mark it as used.
Label->markUsed(Context);
} else {
// Otherwise, insert it, but only resolve it if we have seen the label itself.
std::string InternalName;
llvm::raw_string_ostream OS(InternalName);
// Create an internal name for the label. The name should not be a valid
// mangled name, and should be unique. We use a dot to make the name an
// invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
// unique label is generated each time this blob is emitted, even after
// inlining or LTO.
OS << "__MSASMLABEL_.${:uid}__";
for (char C : ExternalLabelName) {
OS << C;
// We escape '$' in asm strings by replacing it with "$$"
if (C == '$')
OS << '$';
}
Label->setMSAsmLabel(OS.str());
}
if (AlwaysCreate) {
// The label might have been created implicitly from a previously encountered
// goto statement. So, for both newly created and looked up labels, we mark
// them as resolved.
Label->setMSAsmLabelResolved();
}
// Adjust their location for being able to generate accurate diagnostics.
Label->setLocation(Location);
return Label;
}
|
endlessm/chromium-browser
|
third_party/llvm/clang/lib/Sema/SemaStmtAsm.cpp
|
C++
|
bsd-3-clause
| 36,063 |
/**
* Copyright (c) 2009-2016, rultor.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. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* SPI, tests.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 1.28
*/
package com.rultor.spi;
|
dalifreire/rultor
|
src/test/java/com/rultor/spi/package-info.java
|
Java
|
bsd-3-clause
| 1,692 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/privacy/dlp/v2beta1/dlp.proto
package com.google.privacy.dlp.v2beta1;
/**
* <pre>
* Description of the information type (infoType).
* </pre>
*
* Protobuf type {@code google.privacy.dlp.v2beta1.InfoTypeDescription}
*/
public final class InfoTypeDescription extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.privacy.dlp.v2beta1.InfoTypeDescription)
InfoTypeDescriptionOrBuilder {
private static final long serialVersionUID = 0L;
// Use InfoTypeDescription.newBuilder() to construct.
private InfoTypeDescription(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private InfoTypeDescription() {
name_ = "";
displayName_ = "";
categories_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private InfoTypeDescription(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
displayName_ = s;
break;
}
case 26: {
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
categories_ = new java.util.ArrayList<com.google.privacy.dlp.v2beta1.CategoryDescription>();
mutable_bitField0_ |= 0x00000004;
}
categories_.add(
input.readMessage(com.google.privacy.dlp.v2beta1.CategoryDescription.parser(), extensionRegistry));
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
categories_ = java.util.Collections.unmodifiableList(categories_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.privacy.dlp.v2beta1.InfoTypeDescription.class, com.google.privacy.dlp.v2beta1.InfoTypeDescription.Builder.class);
}
private int bitField0_;
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
* <pre>
* Internal name of the infoType.
* </pre>
*
* <code>string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <pre>
* Internal name of the infoType.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DISPLAY_NAME_FIELD_NUMBER = 2;
private volatile java.lang.Object displayName_;
/**
* <pre>
* Human readable form of the infoType name.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
}
}
/**
* <pre>
* Human readable form of the infoType name.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public com.google.protobuf.ByteString
getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CATEGORIES_FIELD_NUMBER = 3;
private java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> categories_;
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> getCategoriesList() {
return categories_;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public java.util.List<? extends com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder>
getCategoriesOrBuilderList() {
return categories_;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public int getCategoriesCount() {
return categories_.size();
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public com.google.privacy.dlp.v2beta1.CategoryDescription getCategories(int index) {
return categories_.get(index);
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder getCategoriesOrBuilder(
int index) {
return categories_.get(index);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (!getDisplayNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, displayName_);
}
for (int i = 0; i < categories_.size(); i++) {
output.writeMessage(3, categories_.get(i));
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!getDisplayNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, displayName_);
}
for (int i = 0; i < categories_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(3, categories_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.privacy.dlp.v2beta1.InfoTypeDescription)) {
return super.equals(obj);
}
com.google.privacy.dlp.v2beta1.InfoTypeDescription other = (com.google.privacy.dlp.v2beta1.InfoTypeDescription) obj;
boolean result = true;
result = result && getName()
.equals(other.getName());
result = result && getDisplayName()
.equals(other.getDisplayName());
result = result && getCategoriesList()
.equals(other.getCategoriesList());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDisplayName().hashCode();
if (getCategoriesCount() > 0) {
hash = (37 * hash) + CATEGORIES_FIELD_NUMBER;
hash = (53 * hash) + getCategoriesList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.privacy.dlp.v2beta1.InfoTypeDescription prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Description of the information type (infoType).
* </pre>
*
* Protobuf type {@code google.privacy.dlp.v2beta1.InfoTypeDescription}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.privacy.dlp.v2beta1.InfoTypeDescription)
com.google.privacy.dlp.v2beta1.InfoTypeDescriptionOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.privacy.dlp.v2beta1.InfoTypeDescription.class, com.google.privacy.dlp.v2beta1.InfoTypeDescription.Builder.class);
}
// Construct using com.google.privacy.dlp.v2beta1.InfoTypeDescription.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getCategoriesFieldBuilder();
}
}
public Builder clear() {
super.clear();
name_ = "";
displayName_ = "";
if (categoriesBuilder_ == null) {
categories_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
} else {
categoriesBuilder_.clear();
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor;
}
public com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstanceForType() {
return com.google.privacy.dlp.v2beta1.InfoTypeDescription.getDefaultInstance();
}
public com.google.privacy.dlp.v2beta1.InfoTypeDescription build() {
com.google.privacy.dlp.v2beta1.InfoTypeDescription result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.privacy.dlp.v2beta1.InfoTypeDescription buildPartial() {
com.google.privacy.dlp.v2beta1.InfoTypeDescription result = new com.google.privacy.dlp.v2beta1.InfoTypeDescription(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
result.name_ = name_;
result.displayName_ = displayName_;
if (categoriesBuilder_ == null) {
if (((bitField0_ & 0x00000004) == 0x00000004)) {
categories_ = java.util.Collections.unmodifiableList(categories_);
bitField0_ = (bitField0_ & ~0x00000004);
}
result.categories_ = categories_;
} else {
result.categories_ = categoriesBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.privacy.dlp.v2beta1.InfoTypeDescription) {
return mergeFrom((com.google.privacy.dlp.v2beta1.InfoTypeDescription)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.privacy.dlp.v2beta1.InfoTypeDescription other) {
if (other == com.google.privacy.dlp.v2beta1.InfoTypeDescription.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (!other.getDisplayName().isEmpty()) {
displayName_ = other.displayName_;
onChanged();
}
if (categoriesBuilder_ == null) {
if (!other.categories_.isEmpty()) {
if (categories_.isEmpty()) {
categories_ = other.categories_;
bitField0_ = (bitField0_ & ~0x00000004);
} else {
ensureCategoriesIsMutable();
categories_.addAll(other.categories_);
}
onChanged();
}
} else {
if (!other.categories_.isEmpty()) {
if (categoriesBuilder_.isEmpty()) {
categoriesBuilder_.dispose();
categoriesBuilder_ = null;
categories_ = other.categories_;
bitField0_ = (bitField0_ & ~0x00000004);
categoriesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getCategoriesFieldBuilder() : null;
} else {
categoriesBuilder_.addAllMessages(other.categories_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.privacy.dlp.v2beta1.InfoTypeDescription parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.privacy.dlp.v2beta1.InfoTypeDescription) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
* <pre>
* Internal name of the infoType.
* </pre>
*
* <code>string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Internal name of the infoType.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Internal name of the infoType.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <pre>
* Internal name of the infoType.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <pre>
* Internal name of the infoType.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private java.lang.Object displayName_ = "";
/**
* <pre>
* Human readable form of the infoType name.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Human readable form of the infoType name.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public com.google.protobuf.ByteString
getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Human readable form of the infoType name.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public Builder setDisplayName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
displayName_ = value;
onChanged();
return this;
}
/**
* <pre>
* Human readable form of the infoType name.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public Builder clearDisplayName() {
displayName_ = getDefaultInstance().getDisplayName();
onChanged();
return this;
}
/**
* <pre>
* Human readable form of the infoType name.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public Builder setDisplayNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
displayName_ = value;
onChanged();
return this;
}
private java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> categories_ =
java.util.Collections.emptyList();
private void ensureCategoriesIsMutable() {
if (!((bitField0_ & 0x00000004) == 0x00000004)) {
categories_ = new java.util.ArrayList<com.google.privacy.dlp.v2beta1.CategoryDescription>(categories_);
bitField0_ |= 0x00000004;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> categoriesBuilder_;
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> getCategoriesList() {
if (categoriesBuilder_ == null) {
return java.util.Collections.unmodifiableList(categories_);
} else {
return categoriesBuilder_.getMessageList();
}
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public int getCategoriesCount() {
if (categoriesBuilder_ == null) {
return categories_.size();
} else {
return categoriesBuilder_.getCount();
}
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public com.google.privacy.dlp.v2beta1.CategoryDescription getCategories(int index) {
if (categoriesBuilder_ == null) {
return categories_.get(index);
} else {
return categoriesBuilder_.getMessage(index);
}
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder setCategories(
int index, com.google.privacy.dlp.v2beta1.CategoryDescription value) {
if (categoriesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCategoriesIsMutable();
categories_.set(index, value);
onChanged();
} else {
categoriesBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder setCategories(
int index, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) {
if (categoriesBuilder_ == null) {
ensureCategoriesIsMutable();
categories_.set(index, builderForValue.build());
onChanged();
} else {
categoriesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder addCategories(com.google.privacy.dlp.v2beta1.CategoryDescription value) {
if (categoriesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCategoriesIsMutable();
categories_.add(value);
onChanged();
} else {
categoriesBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder addCategories(
int index, com.google.privacy.dlp.v2beta1.CategoryDescription value) {
if (categoriesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCategoriesIsMutable();
categories_.add(index, value);
onChanged();
} else {
categoriesBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder addCategories(
com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) {
if (categoriesBuilder_ == null) {
ensureCategoriesIsMutable();
categories_.add(builderForValue.build());
onChanged();
} else {
categoriesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder addCategories(
int index, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) {
if (categoriesBuilder_ == null) {
ensureCategoriesIsMutable();
categories_.add(index, builderForValue.build());
onChanged();
} else {
categoriesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder addAllCategories(
java.lang.Iterable<? extends com.google.privacy.dlp.v2beta1.CategoryDescription> values) {
if (categoriesBuilder_ == null) {
ensureCategoriesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, categories_);
onChanged();
} else {
categoriesBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder clearCategories() {
if (categoriesBuilder_ == null) {
categories_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
} else {
categoriesBuilder_.clear();
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public Builder removeCategories(int index) {
if (categoriesBuilder_ == null) {
ensureCategoriesIsMutable();
categories_.remove(index);
onChanged();
} else {
categoriesBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder getCategoriesBuilder(
int index) {
return getCategoriesFieldBuilder().getBuilder(index);
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder getCategoriesOrBuilder(
int index) {
if (categoriesBuilder_ == null) {
return categories_.get(index); } else {
return categoriesBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public java.util.List<? extends com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder>
getCategoriesOrBuilderList() {
if (categoriesBuilder_ != null) {
return categoriesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(categories_);
}
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder addCategoriesBuilder() {
return getCategoriesFieldBuilder().addBuilder(
com.google.privacy.dlp.v2beta1.CategoryDescription.getDefaultInstance());
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder addCategoriesBuilder(
int index) {
return getCategoriesFieldBuilder().addBuilder(
index, com.google.privacy.dlp.v2beta1.CategoryDescription.getDefaultInstance());
}
/**
* <pre>
* List of categories this infoType belongs to.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code>
*/
public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription.Builder>
getCategoriesBuilderList() {
return getCategoriesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder>
getCategoriesFieldBuilder() {
if (categoriesBuilder_ == null) {
categoriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder>(
categories_,
((bitField0_ & 0x00000004) == 0x00000004),
getParentForChildren(),
isClean());
categories_ = null;
}
return categoriesBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.privacy.dlp.v2beta1.InfoTypeDescription)
}
// @@protoc_insertion_point(class_scope:google.privacy.dlp.v2beta1.InfoTypeDescription)
private static final com.google.privacy.dlp.v2beta1.InfoTypeDescription DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.privacy.dlp.v2beta1.InfoTypeDescription();
}
public static com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<InfoTypeDescription>
PARSER = new com.google.protobuf.AbstractParser<InfoTypeDescription>() {
public InfoTypeDescription parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new InfoTypeDescription(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<InfoTypeDescription> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<InfoTypeDescription> getParserForType() {
return PARSER;
}
public com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
pongad/api-client-staging
|
generated/java/proto-google-cloud-dlp-v2beta1/src/main/java/com/google/privacy/dlp/v2beta1/InfoTypeDescription.java
|
Java
|
bsd-3-clause
| 37,925 |
// 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 "media/filters/vpx_video_decoder.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/sys_byteorder.h"
#include "base/trace_event/trace_event.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/decoder_buffer.h"
#include "media/base/limits.h"
#include "media/base/media_switches.h"
#include "media/base/video_aspect_ratio.h"
#include "media/filters/frame_buffer_pool.h"
#include "third_party/libvpx/source/libvpx/vpx/vp8dx.h"
#include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h"
#include "third_party/libvpx/source/libvpx/vpx/vpx_frame_buffer.h"
#include "third_party/libyuv/include/libyuv/convert.h"
#include "third_party/libyuv/include/libyuv/planar_functions.h"
namespace media {
// Returns the number of threads.
static int GetVpxVideoDecoderThreadCount(const VideoDecoderConfig& config) {
// vp8a doesn't really need more threads.
int desired_threads = limits::kMinVideoDecodeThreads;
// For VP9 decoding increase the number of decode threads to equal the
// maximum number of tiles possible for higher resolution streams.
if (config.codec() == VideoCodec::kVP9) {
const int width = config.coded_size().width();
if (width >= 3840)
desired_threads = 16;
else if (width >= 2560)
desired_threads = 8;
else if (width >= 1280)
desired_threads = 4;
}
return VideoDecoder::GetRecommendedThreadCount(desired_threads);
}
static std::unique_ptr<vpx_codec_ctx> InitializeVpxContext(
const VideoDecoderConfig& config) {
auto context = std::make_unique<vpx_codec_ctx>();
vpx_codec_dec_cfg_t vpx_config = {0};
vpx_config.w = config.coded_size().width();
vpx_config.h = config.coded_size().height();
vpx_config.threads = GetVpxVideoDecoderThreadCount(config);
vpx_codec_err_t status = vpx_codec_dec_init(context.get(),
config.codec() == VideoCodec::kVP9
? vpx_codec_vp9_dx()
: vpx_codec_vp8_dx(),
&vpx_config, 0 /* flags */);
if (status == VPX_CODEC_OK)
return context;
DLOG(ERROR) << "vpx_codec_dec_init() failed: "
<< vpx_codec_error(context.get());
return nullptr;
}
static int32_t GetVP9FrameBuffer(void* user_priv,
size_t min_size,
vpx_codec_frame_buffer* fb) {
DCHECK(user_priv);
DCHECK(fb);
FrameBufferPool* pool = static_cast<FrameBufferPool*>(user_priv);
fb->data = pool->GetFrameBuffer(min_size, &fb->priv);
fb->size = min_size;
return fb->data ? 0 : VPX_CODEC_MEM_ERROR;
}
static int32_t ReleaseVP9FrameBuffer(void* user_priv,
vpx_codec_frame_buffer* fb) {
DCHECK(user_priv);
DCHECK(fb);
if (!fb->priv)
return -1;
FrameBufferPool* pool = static_cast<FrameBufferPool*>(user_priv);
pool->ReleaseFrameBuffer(fb->priv);
return 0;
}
// static
SupportedVideoDecoderConfigs VpxVideoDecoder::SupportedConfigs() {
SupportedVideoDecoderConfigs supported_configs;
supported_configs.emplace_back(/*profile_min=*/VP8PROFILE_ANY,
/*profile_max=*/VP8PROFILE_ANY,
/*coded_size_min=*/kDefaultSwDecodeSizeMin,
/*coded_size_max=*/kDefaultSwDecodeSizeMax,
/*allow_encrypted=*/false,
/*require_encrypted=*/false);
supported_configs.emplace_back(/*profile_min=*/VP9PROFILE_PROFILE0,
/*profile_max=*/VP9PROFILE_PROFILE2,
/*coded_size_min=*/kDefaultSwDecodeSizeMin,
/*coded_size_max=*/kDefaultSwDecodeSizeMax,
/*allow_encrypted=*/false,
/*require_encrypted=*/false);
return supported_configs;
}
VpxVideoDecoder::VpxVideoDecoder(OffloadState offload_state)
: bind_callbacks_(offload_state == OffloadState::kNormal) {
DETACH_FROM_SEQUENCE(sequence_checker_);
}
VpxVideoDecoder::~VpxVideoDecoder() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CloseDecoder();
}
VideoDecoderType VpxVideoDecoder::GetDecoderType() const {
return VideoDecoderType::kVpx;
}
void VpxVideoDecoder::Initialize(const VideoDecoderConfig& config,
bool /* low_delay */,
CdmContext* /* cdm_context */,
InitCB init_cb,
const OutputCB& output_cb,
const WaitingCB& /* waiting_cb */) {
DVLOG(1) << __func__ << ": " << config.AsHumanReadableString();
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(config.IsValidConfig());
CloseDecoder();
InitCB bound_init_cb = bind_callbacks_ ? BindToCurrentLoop(std::move(init_cb))
: std::move(init_cb);
if (config.is_encrypted()) {
std::move(bound_init_cb).Run(StatusCode::kEncryptedContentUnsupported);
return;
}
if (!ConfigureDecoder(config)) {
std::move(bound_init_cb).Run(StatusCode::kDecoderFailedInitialization);
return;
}
// Success!
config_ = config;
state_ = DecoderState::kNormal;
output_cb_ = output_cb;
std::move(bound_init_cb).Run(OkStatus());
}
void VpxVideoDecoder::Decode(scoped_refptr<DecoderBuffer> buffer,
DecodeCB decode_cb) {
DVLOG(3) << __func__ << ": " << buffer->AsHumanReadableString();
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(buffer);
DCHECK(decode_cb);
DCHECK_NE(state_, DecoderState::kUninitialized)
<< "Called Decode() before successful Initialize()";
DecodeCB bound_decode_cb = bind_callbacks_
? BindToCurrentLoop(std::move(decode_cb))
: std::move(decode_cb);
if (state_ == DecoderState::kError) {
std::move(bound_decode_cb).Run(DecodeStatus::DECODE_ERROR);
return;
}
if (state_ == DecoderState::kDecodeFinished) {
std::move(bound_decode_cb).Run(DecodeStatus::OK);
return;
}
if (state_ == DecoderState::kNormal && buffer->end_of_stream()) {
state_ = DecoderState::kDecodeFinished;
std::move(bound_decode_cb).Run(DecodeStatus::OK);
return;
}
scoped_refptr<VideoFrame> video_frame;
if (!VpxDecode(buffer.get(), &video_frame)) {
state_ = DecoderState::kError;
std::move(bound_decode_cb).Run(DecodeStatus::DECODE_ERROR);
return;
}
// We might get a successful VpxDecode but not a frame if only a partial
// decode happened.
if (video_frame) {
video_frame->metadata().power_efficient = false;
output_cb_.Run(video_frame);
}
// VideoDecoderShim expects |decode_cb| call after |output_cb_|.
std::move(bound_decode_cb).Run(DecodeStatus::OK);
}
void VpxVideoDecoder::Reset(base::OnceClosure reset_cb) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
state_ = DecoderState::kNormal;
if (bind_callbacks_)
BindToCurrentLoop(std::move(reset_cb)).Run();
else
std::move(reset_cb).Run();
// Allow Initialize() to be called on another thread now.
DETACH_FROM_SEQUENCE(sequence_checker_);
}
bool VpxVideoDecoder::ConfigureDecoder(const VideoDecoderConfig& config) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (config.codec() != VideoCodec::kVP8 && config.codec() != VideoCodec::kVP9)
return false;
#if BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS)
// When enabled, ffmpeg handles VP8 that doesn't have alpha, and
// VpxVideoDecoder will handle VP8 with alpha. FFvp8 is being deprecated.
// See http://crbug.com/992235.
if (base::FeatureList::IsEnabled(kFFmpegDecodeOpaqueVP8) &&
config.codec() == VideoCodec::kVP8 &&
config.alpha_mode() == VideoDecoderConfig::AlphaMode::kIsOpaque) {
return false;
}
#endif
DCHECK(!vpx_codec_);
vpx_codec_ = InitializeVpxContext(config);
if (!vpx_codec_)
return false;
// Configure VP9 to decode on our buffers to skip a data copy on
// decoding. For YV12A-VP9, we use our buffers for the Y, U and V planes and
// copy the A plane.
if (config.codec() == VideoCodec::kVP9) {
DCHECK(vpx_codec_get_caps(vpx_codec_->iface) &
VPX_CODEC_CAP_EXTERNAL_FRAME_BUFFER);
DCHECK(!memory_pool_);
memory_pool_ = new FrameBufferPool();
if (vpx_codec_set_frame_buffer_functions(
vpx_codec_.get(), &GetVP9FrameBuffer, &ReleaseVP9FrameBuffer,
memory_pool_.get())) {
DLOG(ERROR) << "Failed to configure external buffers. "
<< vpx_codec_error(vpx_codec_.get());
return false;
}
vpx_codec_err_t status =
vpx_codec_control(vpx_codec_.get(), VP9D_SET_LOOP_FILTER_OPT, 1);
if (status != VPX_CODEC_OK) {
DLOG(ERROR) << "Failed to enable VP9D_SET_LOOP_FILTER_OPT. "
<< vpx_codec_error(vpx_codec_.get());
return false;
}
}
if (config.alpha_mode() == VideoDecoderConfig::AlphaMode::kIsOpaque)
return true;
DCHECK(!vpx_codec_alpha_);
vpx_codec_alpha_ = InitializeVpxContext(config);
return !!vpx_codec_alpha_;
}
void VpxVideoDecoder::CloseDecoder() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Note: The vpx_codec_destroy() calls below don't release the memory
// allocated for vpx_codec_ctx, they just release internal allocations, so we
// still need std::unique_ptr to release the structure memory.
if (vpx_codec_)
vpx_codec_destroy(vpx_codec_.get());
if (vpx_codec_alpha_)
vpx_codec_destroy(vpx_codec_alpha_.get());
vpx_codec_.reset();
vpx_codec_alpha_.reset();
if (memory_pool_) {
memory_pool_->Shutdown();
memory_pool_ = nullptr;
}
}
void VpxVideoDecoder::Detach() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!bind_callbacks_);
CloseDecoder();
DETACH_FROM_SEQUENCE(sequence_checker_);
}
bool VpxVideoDecoder::VpxDecode(const DecoderBuffer* buffer,
scoped_refptr<VideoFrame>* video_frame) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(video_frame);
DCHECK(!buffer->end_of_stream());
{
TRACE_EVENT1("media", "vpx_codec_decode", "buffer",
buffer->AsHumanReadableString());
vpx_codec_err_t status =
vpx_codec_decode(vpx_codec_.get(), buffer->data(), buffer->data_size(),
nullptr /* user_priv */, 0 /* deadline */);
if (status != VPX_CODEC_OK) {
DLOG(ERROR) << "vpx_codec_decode() error: "
<< vpx_codec_err_to_string(status);
return false;
}
}
// Gets pointer to decoded data.
vpx_codec_iter_t iter = NULL;
const vpx_image_t* vpx_image = vpx_codec_get_frame(vpx_codec_.get(), &iter);
if (!vpx_image) {
*video_frame = nullptr;
return true;
}
const vpx_image_t* vpx_image_alpha = nullptr;
const auto alpha_decode_status =
DecodeAlphaPlane(vpx_image, &vpx_image_alpha, buffer);
if (alpha_decode_status == kAlphaPlaneError) {
return false;
} else if (alpha_decode_status == kNoAlphaPlaneData) {
*video_frame = nullptr;
return true;
}
if (!CopyVpxImageToVideoFrame(vpx_image, vpx_image_alpha, video_frame))
return false;
if (vpx_image_alpha && config_.codec() == VideoCodec::kVP8) {
libyuv::CopyPlane(vpx_image_alpha->planes[VPX_PLANE_Y],
vpx_image_alpha->stride[VPX_PLANE_Y],
(*video_frame)->visible_data(VideoFrame::kAPlane),
(*video_frame)->stride(VideoFrame::kAPlane),
(*video_frame)->visible_rect().width(),
(*video_frame)->visible_rect().height());
}
(*video_frame)->set_timestamp(buffer->timestamp());
(*video_frame)->set_hdr_metadata(config_.hdr_metadata());
// Prefer the color space from the config if available. It generally comes
// from the color tag which is more expressive than the vp8 and vp9 bitstream.
if (config_.color_space_info().IsSpecified()) {
(*video_frame)
->set_color_space(config_.color_space_info().ToGfxColorSpace());
return true;
}
auto primaries = gfx::ColorSpace::PrimaryID::INVALID;
auto transfer = gfx::ColorSpace::TransferID::INVALID;
auto matrix = gfx::ColorSpace::MatrixID::INVALID;
auto range = vpx_image->range == VPX_CR_FULL_RANGE
? gfx::ColorSpace::RangeID::FULL
: gfx::ColorSpace::RangeID::LIMITED;
switch (vpx_image->cs) {
case VPX_CS_BT_601:
case VPX_CS_SMPTE_170:
primaries = gfx::ColorSpace::PrimaryID::SMPTE170M;
transfer = gfx::ColorSpace::TransferID::SMPTE170M;
matrix = gfx::ColorSpace::MatrixID::SMPTE170M;
break;
case VPX_CS_SMPTE_240:
primaries = gfx::ColorSpace::PrimaryID::SMPTE240M;
transfer = gfx::ColorSpace::TransferID::SMPTE240M;
matrix = gfx::ColorSpace::MatrixID::SMPTE240M;
break;
case VPX_CS_BT_709:
primaries = gfx::ColorSpace::PrimaryID::BT709;
transfer = gfx::ColorSpace::TransferID::BT709;
matrix = gfx::ColorSpace::MatrixID::BT709;
break;
case VPX_CS_BT_2020:
primaries = gfx::ColorSpace::PrimaryID::BT2020;
if (vpx_image->bit_depth >= 12)
transfer = gfx::ColorSpace::TransferID::BT2020_12;
else if (vpx_image->bit_depth >= 10)
transfer = gfx::ColorSpace::TransferID::BT2020_10;
else
transfer = gfx::ColorSpace::TransferID::BT709;
matrix = gfx::ColorSpace::MatrixID::BT2020_NCL; // is this right?
break;
case VPX_CS_SRGB:
primaries = gfx::ColorSpace::PrimaryID::BT709;
transfer = gfx::ColorSpace::TransferID::IEC61966_2_1;
matrix = gfx::ColorSpace::MatrixID::GBR;
break;
default:
break;
}
// TODO(ccameron): Set a color space even for unspecified values.
if (primaries != gfx::ColorSpace::PrimaryID::INVALID) {
(*video_frame)
->set_color_space(gfx::ColorSpace(primaries, transfer, matrix, range));
}
return true;
}
VpxVideoDecoder::AlphaDecodeStatus VpxVideoDecoder::DecodeAlphaPlane(
const struct vpx_image* vpx_image,
const struct vpx_image** vpx_image_alpha,
const DecoderBuffer* buffer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!vpx_codec_alpha_ || buffer->side_data_size() < 8) {
return kAlphaPlaneProcessed;
}
// First 8 bytes of side data is |side_data_id| in big endian.
const uint64_t side_data_id = base::NetToHost64(
*(reinterpret_cast<const uint64_t*>(buffer->side_data())));
if (side_data_id != 1) {
return kAlphaPlaneProcessed;
}
// Try and decode buffer->side_data() minus the first 8 bytes as a full
// frame.
{
TRACE_EVENT1("media", "vpx_codec_decode_alpha", "buffer",
buffer->AsHumanReadableString());
vpx_codec_err_t status =
vpx_codec_decode(vpx_codec_alpha_.get(), buffer->side_data() + 8,
buffer->side_data_size() - 8, nullptr /* user_priv */,
0 /* deadline */);
if (status != VPX_CODEC_OK) {
DLOG(ERROR) << "vpx_codec_decode() failed for the alpha: "
<< vpx_codec_error(vpx_codec_.get());
return kAlphaPlaneError;
}
}
vpx_codec_iter_t iter_alpha = NULL;
*vpx_image_alpha = vpx_codec_get_frame(vpx_codec_alpha_.get(), &iter_alpha);
if (!(*vpx_image_alpha)) {
return kNoAlphaPlaneData;
}
if ((*vpx_image_alpha)->d_h != vpx_image->d_h ||
(*vpx_image_alpha)->d_w != vpx_image->d_w) {
DLOG(ERROR) << "The alpha plane dimensions are not the same as the "
"image dimensions.";
return kAlphaPlaneError;
}
return kAlphaPlaneProcessed;
}
bool VpxVideoDecoder::CopyVpxImageToVideoFrame(
const struct vpx_image* vpx_image,
const struct vpx_image* vpx_image_alpha,
scoped_refptr<VideoFrame>* video_frame) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(vpx_image);
VideoPixelFormat codec_format;
switch (vpx_image->fmt) {
case VPX_IMG_FMT_I420:
codec_format = vpx_image_alpha ? PIXEL_FORMAT_I420A : PIXEL_FORMAT_I420;
break;
case VPX_IMG_FMT_I422:
codec_format = PIXEL_FORMAT_I422;
break;
case VPX_IMG_FMT_I444:
codec_format = PIXEL_FORMAT_I444;
break;
case VPX_IMG_FMT_I42016:
switch (vpx_image->bit_depth) {
case 10:
codec_format = PIXEL_FORMAT_YUV420P10;
break;
case 12:
codec_format = PIXEL_FORMAT_YUV420P12;
break;
default:
DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth;
return false;
}
break;
case VPX_IMG_FMT_I42216:
switch (vpx_image->bit_depth) {
case 10:
codec_format = PIXEL_FORMAT_YUV422P10;
break;
case 12:
codec_format = PIXEL_FORMAT_YUV422P12;
break;
default:
DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth;
return false;
}
break;
case VPX_IMG_FMT_I44416:
switch (vpx_image->bit_depth) {
case 10:
codec_format = PIXEL_FORMAT_YUV444P10;
break;
case 12:
codec_format = PIXEL_FORMAT_YUV444P12;
break;
default:
DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth;
return false;
}
break;
default:
DLOG(ERROR) << "Unsupported pixel format: " << vpx_image->fmt;
return false;
}
// The mixed |w|/|d_h| in |coded_size| is intentional. Setting the correct
// coded width is necessary to allow coalesced memory access, which may avoid
// frame copies. Setting the correct coded height however does not have any
// benefit, and only risk copying too much data.
const gfx::Size coded_size(vpx_image->w, vpx_image->d_h);
const gfx::Size visible_size(vpx_image->d_w, vpx_image->d_h);
// Compute natural size by scaling visible size by *pixel* aspect ratio. Note
// that we could instead use vpx_image r_w and r_h, but doing so would allow
// pixel aspect ratio to change on a per-frame basis which would make
// vpx_video_decoder inconsistent with decoders where changes to
// pixel aspect ratio are not surfaced (e.g. Android MediaCodec).
const gfx::Size natural_size =
config_.aspect_ratio().GetNaturalSize(gfx::Rect(visible_size));
if (memory_pool_) {
DCHECK_EQ(VideoCodec::kVP9, config_.codec());
if (vpx_image_alpha) {
size_t alpha_plane_size =
vpx_image_alpha->stride[VPX_PLANE_Y] * vpx_image_alpha->d_h;
uint8_t* alpha_plane = memory_pool_->AllocateAlphaPlaneForFrameBuffer(
alpha_plane_size, vpx_image->fb_priv);
if (!alpha_plane) // In case of OOM, abort copy.
return false;
libyuv::CopyPlane(vpx_image_alpha->planes[VPX_PLANE_Y],
vpx_image_alpha->stride[VPX_PLANE_Y], alpha_plane,
vpx_image_alpha->stride[VPX_PLANE_Y],
vpx_image_alpha->d_w, vpx_image_alpha->d_h);
*video_frame = VideoFrame::WrapExternalYuvaData(
codec_format, coded_size, gfx::Rect(visible_size), natural_size,
vpx_image->stride[VPX_PLANE_Y], vpx_image->stride[VPX_PLANE_U],
vpx_image->stride[VPX_PLANE_V], vpx_image_alpha->stride[VPX_PLANE_Y],
vpx_image->planes[VPX_PLANE_Y], vpx_image->planes[VPX_PLANE_U],
vpx_image->planes[VPX_PLANE_V], alpha_plane, kNoTimestamp);
} else {
*video_frame = VideoFrame::WrapExternalYuvData(
codec_format, coded_size, gfx::Rect(visible_size), natural_size,
vpx_image->stride[VPX_PLANE_Y], vpx_image->stride[VPX_PLANE_U],
vpx_image->stride[VPX_PLANE_V], vpx_image->planes[VPX_PLANE_Y],
vpx_image->planes[VPX_PLANE_U], vpx_image->planes[VPX_PLANE_V],
kNoTimestamp);
}
if (!(*video_frame))
return false;
video_frame->get()->AddDestructionObserver(
memory_pool_->CreateFrameCallback(vpx_image->fb_priv));
return true;
}
*video_frame = frame_pool_.CreateFrame(codec_format, visible_size,
gfx::Rect(visible_size), natural_size,
kNoTimestamp);
if (!(*video_frame))
return false;
for (int plane = 0; plane < 3; plane++) {
libyuv::CopyPlane(
vpx_image->planes[plane], vpx_image->stride[plane],
(*video_frame)->visible_data(plane), (*video_frame)->stride(plane),
(*video_frame)->row_bytes(plane), (*video_frame)->rows(plane));
}
return true;
}
} // namespace media
|
nwjs/chromium.src
|
media/filters/vpx_video_decoder.cc
|
C++
|
bsd-3-clause
| 21,197 |
"""Workflow for uploading many many many log files at once."""
from __future__ import absolute_import
import os
from os.path import isfile, getsize
import logging
import re
import luigi
import psycopg2
import pandas as pd
# import sqlalchemy
try:
from .pylog_parse import LogFile
except:
from pylog_parse import LogFile
logger = logging.getLogger(__name__)
class LogTask(luigi.Task):
"""Base task for log workflow."""
path = luigi.Parameter()
logtype = luigi.Parameter()
_conf = luigi.configuration.get_config()
_conf.reload()
_password = _conf.get('postgres', 'password')
_host = _conf.get('postgres', 'host')
_port = _conf.get('postgres', 'port')
_database = _conf.get('pylog', 'database')
_user = _conf.get('postgres', 'user')
_url = """postgresql://{u}:{p}@{h}:{port}/{db}""".format(u=_user,
p=_password,
h=_host,
port=_port,
db=_database)
@property
def url(self):
"""Postgresql url property."""
return self._url
def folder_size(path):
"""Return size of folder at path."""
return sum(getsize(f) for f in os.listdir('.') if isfile(f))
def list_directory_files(path, folders=False):
"""Yield all filenames in a path."""
for f in os.listdir(path):
if f[0] == '.':
continue
current_path = os.path.join(path, f)
if folders is False:
if os.path.isfile(current_path):
if os.path.getsize(current_path) != 0:
yield current_path
else:
file_ext = os.path.splitext(f)[1]
if file_ext == '' or file_ext == '/':
yield current_path
def get_subfolders(path):
for f in list_directory_files(path, folders=True):
file_ext = os.path.splitext(f)[1]
if file_ext == ''or file_ext == '/':
yield f
def get_sublogs(path):
for f in list_directory_files(path):
file_ext = os.path.splitext(f)[1]
if file_ext == '.log':
yield f
class CheckLogPath(luigi.ExternalTask):
path = luigi.Parameter()
def output(self):
return luigi.LocalTarget(path=self.path)
class UploadLogs(LogTask):
def requires(self):
return CheckLogPath(path=self.path)
def output(self):
groups = re.search(r'2015.(\d{2}).(\d{2})', self.path).groups()
csv = '/home/ubuntu/elb2/2015-{m}-{d}.csv'.format(m=groups[0],
d=groups[1])
return luigi.LocalTarget(path=csv)
def run(self):
conn = psycopg2.connect(self.url)
log = LogFile(path=self.path, log_type=self.logtype)
cursor = conn.cursor()
cursor.close()
log.to_csv(self.output().path, con=conn, copy=True)
if os.path.exists(self.output().path):
df = pd.DataFrame({'length': log.length}, index=[0])
os.remove(self.output().path)
df.to_csv(self.output().path, index=False) # Only keep head of csv
class LogPaths(LogTask):
def requires(self):
log_files = [f for f in get_sublogs(self.path)]
subfolders = [f for f in get_subfolders(self.path)]
logger.debug('Path: {p}'.format(p=self.path))
logger.debug('Subfolders: {s}'.format(s=subfolders))
logger.debug('Subfiles: {f}'.format(f=log_files))
for fold in subfolders:
sub = [f for f in get_subfolders(fold)]
files = [f for f in get_sublogs(fold)]
if len(sub) > 0:
logger.info('Subfolders of {f}: {s}'.format(f=fold, s=sub))
yield LogPaths(path=fold, logtype=self.logtype)
elif len(files) > 0:
yield UploadLogs(path=fold, logtype=self.logtype)
for f in log_files:
yield UploadLogs(path=f, logtype=self.logtype)
def run(self):
total_length = 0
for f in self.input():
total_length = total_length + pd.read_csv(f.path()).iloc[0][0]
logger.info('AllFilesLength: {l}'.format(l=total_length))
if __name__ == '__main__':
luigi.run()
|
sethmenghi/pylog_parse
|
pylog_parse/workflow.py
|
Python
|
bsd-3-clause
| 4,335 |
namespace NHibernate.ZMQLogPublisher
{
using System.Collections.Concurrent;
using System.Collections.Generic;
using ZMQ;
public class SocketManager
{
private readonly Context context;
private ConcurrentDictionary<string, Socket> sockets;
private object synclock = new object();
private bool terminated;
public SocketManager()
{
this.context = new Context(1);
this.sockets = new ConcurrentDictionary<string, Socket>();
}
public bool Terminated
{
get
{
return this.terminated;
}
}
public Context Context
{
get
{
return this.context;
}
}
public Socket CreateSocketForKey(string loggerKey, SocketType socketType)
{
return this.sockets.GetOrAdd(
loggerKey,
key =>
{
var socket = this.Context.Socket(socketType);
this.sockets.TryAdd(loggerKey, socket);
return socket;
});
}
public void Terminate()
{
this.terminated = true;
foreach (var socket in sockets.Values)
{
lock (this.synclock)
{
socket.Dispose();
}
}
sockets.Clear();
this.Context.Dispose();
}
}
}
|
seif/NHibernate.ZMQLogPublisher
|
src/NHibernate.ZMQLogPublisher/SocketManager.cs
|
C#
|
bsd-3-clause
| 1,545 |
/**
* @decription mock file config
*
* 该文件实现路由的配置,在没有test准备好的情况下可以直接走这个mock数据
* key: 为要匹配的路由
* value: 为对应的参数配置
* method: get或者post,router的方法
* filename: 对应的mock文件
*/
module.exports = {
'/api/realtime': {
method: "post",
filename: "realtime.js"
}
};
|
changfuguo/vuejs-boilerplate
|
server/config/route.js
|
JavaScript
|
bsd-3-clause
| 383 |
using System;
using SevenDigital.Messaging.MessageReceiving;
namespace SevenDigital.Messaging
{
/// <summary>
/// A receiver node source that can produce competitive or co-operative consumers
/// </summary>
public interface IReceiver
{
/// <summary>
/// Map handlers to a listener on a named endpoint.
/// All other listeners on this endpoint will compete for messages
/// (i.e. only one listener will get a given message)
/// </summary>
IReceiverNode TakeFrom(Endpoint endpoint, Action<IMessageBinding> bindings);
/// <summary>
/// Map handlers to a listener on a unique endpoint.
/// All listeners mapped this way will receive all messages.
/// </summary>
IReceiverNode Listen(Action<IMessageBinding> bindings);
}
/// <summary>
/// Interface for binding message types to handlers
/// </summary>
public interface IMessageBinding: IBinding
{
/// <summary>
/// Handle a message type. Must complete With<>() to bind to a handler.
/// </summary>
IHandlerBinding<TMessage> Handle<TMessage>() where TMessage:IMessage;
}
/// <summary>
/// Interface for binding message types to handlers
/// </summary>
public interface IHandlerBinding<TMessage>where TMessage:IMessage
{
/// <summary>
/// Bind a handler to the selected message
/// </summary>
IMessageBinding With<THandler>() where THandler : IHandle<TMessage>;
}
/// <summary>
/// Control methods for IReceiver.
/// Seperated to simplify receiver interface.
/// </summary>
public interface IReceiverControl: IDisposable
{
/// <summary>
/// Close all receiver nodes that have been created
/// </summary>
void Shutdown();
/// <summary>
/// Unregister a node from the shutdown list
/// </summary>
void Remove(IReceiverNode node);
/// <summary>
/// Set maximum concurrent handlers per receiver node
/// </summary>
void SetConcurrentHandlers(int max);
/// <summary>
/// Set purging policy. If true, all waiting messages are DELETED when a handler is registered.
/// This setting is meant for integration tests.
/// Default is false.
/// </summary>
bool PurgeOnConnect { get; set; }
/// <summary>
/// Set cleanup policy. If true, all endpoints generated in integration mode
/// are deleted when the receiver is disposed.
/// Default is false.
/// </summary>
bool DeleteIntegrationEndpointsOnShutdown { get; set; }
}
}
|
i-e-b/SevenDigital.Messaging
|
src/SevenDigital.Messaging/IReceiver.cs
|
C#
|
bsd-3-clause
| 2,465 |
<?php
namespace Base\Form\Hydrator;
use Zend\Stdlib\Hydrator\HydratorInterface;
use Base\Constants as C;
class User implements HydratorInterface {
public function extract($object) {
$filter = function($value) {
return !(($value === null) || ($value === ''));
};
$data = array(
'user_id' => $object->getUserId(),
'username' => $object->getUserName(),
'email' => $object->getEmail(),
'display_name' => $object->getDisplayName(),
'password' => $object->getPassword(),
'state' => $object->getState(),
);
$result = array_filter($data, $filter);
// var_dump(__METHOD__, 'EXT_OBJ', $object, 'EXT_RES', $result);
return $result;
}
public function hydrate(array $data, $object) {
(!isset($data['user_id']) || $this->isEmpty($data['user_id'])) ? : $object->setUserId($data['user_id']);
(!isset($data['username']) || $this->isEmpty($data['username'])) ? : $object->setUserName($data['username']);
(!isset($data['email']) || $this->isEmpty($data['email'])) ? : $object->setEmail($data['email']);
(!isset($data['display_name']) || $this->isEmpty($data['display_name'])) ? : $object->setDisplayName($data['display_name']);
(!isset($data['password']) || $this->isEmpty($data['password'])) ? : $object->setPassword($data['password']);
(!isset($data['state']) || $this->isEmpty($data['state'])) ? : $object->setState($data['state']);
// var_dump(__METHOD__, 'HYD_SRCDATA', $data, 'HYD_RES', $object);
return $object;
}
private function isEmpty($value) {
return (($value === null) || ($value === ''));
}
}
|
fhsctv/ctv2base
|
module/Base/src/Base/Form/Hydrator/User.php
|
PHP
|
bsd-3-clause
| 1,947 |
import os
from setuptools import setup, find_packages
setup(
name='django-scrape',
version='0.1',
author='Luke Hodkinson',
author_email='furious.luke@gmail.com',
maintainer='Luke Hodkinson',
maintainer_email='furious.luke@gmail.com',
url='https://github.com/furious-luke/django-scrape',
description='A django application for easier web scraping.',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
classifiers = [
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
license='BSD',
packages=find_packages(),
include_package_data=True,
package_data={'': ['*.txt', '*.js', '*.html', '*.*']},
install_requires=['setuptools'],
zip_safe=False,
)
|
furious-luke/django-scrape
|
setup.py
|
Python
|
bsd-3-clause
| 990 |
<?php
return [
'adminEmail' => 'shockedbear@shockedbear.myjino.ru',
];
|
shockedbear/board
|
frontend/config/params.php
|
PHP
|
bsd-3-clause
| 75 |
from __future__ import absolute_import
import base64
import json
import unittest
import urllib
import urllib2
import urlparse
from celery.exceptions import RetryTaskError
from mock import MagicMock as Mock
import mock
from . import tasks
from .conf import settings as mp_settings
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
patcher = mock.patch('urllib2.urlopen')
self.addCleanup(patcher.stop)
self.mock_urlopen = patcher.start()
self.mock_urlopen.return_value.read.return_value = '1'
# Setup token for mixpanel
mp_settings.MIXPANEL_API_TOKEN = 'testmixpanel'
@staticmethod
def assertDictEqual(a, b):
assert a == b, "Dicts are not equal.\nExpected: %s\nActual: %s" % (
json.dumps(b, indent=3, sort_keys=True),
json.dumps(a, indent=3, sort_keys=True))
def _test_any(self, task, *args, **kwargs):
result = kwargs.pop('result', True)
server = kwargs.pop('server', mp_settings.MIXPANEL_API_SERVER)
endpoint = kwargs.pop('endpoint', mp_settings.MIXPANEL_TRACKING_ENDPOINT)
data = kwargs.pop('data', {})
actual = task(*args, **kwargs)
self.assertTrue(self.mock_urlopen.called)
self.assertEqual(actual, result)
url = self.mock_urlopen.call_args[0][0]
scheme, netloc, path, params, querystr, frag = urlparse.urlparse(url)
query = urlparse.parse_qs(querystr, keep_blank_values=True, strict_parsing=True)
self.assertEqual(netloc, server)
self.assertEqual(path, endpoint)
self.assertEqual(query.keys(), ['data'])
datastr = base64.b64decode(query['data'][0])
actual = json.loads(datastr)
self.assertDictEqual(actual, data)
class EventTrackerTest(TestCase):
def _test_event(self, *args, **kwargs):
return self._test_any(tasks.event_tracker, *args, **kwargs)
def test_event(self):
self._test_event('clicked button',
data={
"event": "clicked button",
"properties": { "token": "testmixpanel" },
},
)
def test_event_props(self):
self._test_event('User logged in',
properties={
"distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0",
"partner": True,
"userid": 456,
"code": "double oh 7",
},
data={
"event": "User logged in",
"properties": {
"distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0",
"partner": True,
"userid": 456,
"code": "double oh 7",
"token": "testmixpanel",
},
},
)
def test_event_token(self):
self._test_event('Override token',
token="footoken",
data={
"event": "Override token",
"properties": { "token": "footoken" },
},
)
class PeopleTrackerTest(TestCase):
def _test_people(self, *args, **kwargs):
kwargs.setdefault('endpoint', mp_settings.MIXPANEL_PEOPLE_TRACKING_ENDPOINT)
return self._test_any(tasks.people_tracker, *args, **kwargs)
def test_validation(self):
self.assertRaises(tasks.InvalidPeopleProperties,
tasks.people_tracker, 'foo')
self.assertRaises(tasks.InvalidPeopleProperties,
tasks.people_tracker, 'foo', set={1:2}, add={3:4})
result = tasks.people_tracker('foo', set={1:2})
self.assertEqual(result, True)
result = tasks.people_tracker('foo', add={3:4})
self.assertEqual(result, True)
def test_people_set(self):
self._test_people('c9533b5b-d69e-479a-ae5f-42dd7a9752a0',
set={
"$first_name": "Aron",
},
data={
"$distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0",
"$token": "testmixpanel",
"$set": {
"$first_name": "Aron",
},
})
def test_people_add(self):
self._test_people('c9533b5b-d69e-479a-ae5f-42dd7a9752a0',
add={
"visits": 1,
},
data={
"$distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0",
"$token": "testmixpanel",
"$add": {
"visits": 1,
},
})
def test_people_token(self):
self._test_people('c9533b5b-d69e-479a-ae5f-42dd7a9752a0',
token="footoken",
set={
"$first_name": "Aron",
},
data={
"$distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0",
"$token": "footoken",
"$set": {
"$first_name": "Aron",
},
})
def test_people_extra(self):
self._test_people('c9533b5b-d69e-479a-ae5f-42dd7a9752a0',
set={
"$first_name": "Aron",
},
extra={
"$ignore_time": True,
},
data={
"$distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0",
"$token": "testmixpanel",
"$ignore_time": True,
"$set": {
"$first_name": "Aron",
},
})
class FunnelTrackerTest(TestCase):
def _test_funnel(self, *args, **kwargs):
return self._test_any(tasks.funnel_event_tracker, *args, **kwargs)
def test_validation(self):
funnel = 'test_funnel'
step = 'test_step'
goal = 'test_goal'
# Missing distinct_id
properties = {}
self.assertRaises(tasks.InvalidFunnelProperties,
tasks.funnel_event_tracker,
funnel, step, goal, properties)
# With distinct_id
properties = {
'distinct_id': 'c9533b5b-d69e-479a-ae5f-42dd7a9752a0',
}
result = tasks.funnel_event_tracker(funnel, step, goal, properties)
self.assertEqual(result, True)
def test_funnel(self):
funnel = 'test_funnel'
step = 'test_step'
goal = 'test_goal'
self._test_funnel(funnel, step, goal,
properties={
'distinct_id': 'c9533b5b-d69e-479a-ae5f-42dd7a9752a0',
},
data={
"event": "mp_funnel",
"properties": {
"distinct_id": "c9533b5b-d69e-479a-ae5f-42dd7a9752a0",
"funnel": "test_funnel",
"goal": "test_goal",
"step": "test_step",
"token": "testmixpanel"
},
},
)
class FailuresTestCase(TestCase):
def test_failed_request(self):
self.mock_urlopen.side_effect = urllib2.URLError("You're doing it wrong")
# This wants to test RetryTaskError, but that isn't available with
# CELERY_ALWAYS_EAGER
self.assertRaises(tasks.FailedEventRequest, # RetryTaskError
tasks.event_tracker,
'event_foo')
def test_failed_response(self):
self.mock_urlopen.return_value.read.return_value = '0'
result = tasks.event_tracker('event_foo')
self.assertEqual(result, False)
|
bss/mixpanel-celery
|
mixpanel/tests.py
|
Python
|
bsd-3-clause
| 7,560 |
/*================================================================================
Copyright (c) 2009 VMware, Inc. 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 VMware, Inc. 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 VMWARE, INC. 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.
================================================================================*/
package com.vmware.vim25;
/**
@author Steve Jin (sjin@vmware.com)
*/
public enum DiagnosticManagerLogCreator
{
vpxd ("vpxd"),
vpxa ("vpxa"),
hostd ("hostd"),
serverd ("serverd"),
install ("install"),
vpxClient ("vpxClient"),
recordLog ("recordLog");
private final String val;
private DiagnosticManagerLogCreator(String val)
{
this.val = val;
}
}
|
mikem2005/vijava
|
src/com/vmware/vim25/DiagnosticManagerLogCreator.java
|
Java
|
bsd-3-clause
| 2,018 |
//*********************************************************************************************************************
// EthernetIfaceDO.java
//
// Copyright 2014 ELECTRIC POWER RESEARCH INSTITUTE, INC. All rights reserved.
//
// PT2 ("this software") is licensed under BSD 3-Clause license.
//
// 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 Electric Power Research Institute, Inc. (“EPRI”) 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 EPRI 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.
//
//
//*********************************************************************************************************************
//
// Code Modification History:
// -------------------------------------------------------------------------------------------------------------------
// 11/20/2012 - Tam T. Do, Southwest Research Institute (SwRI)
// Generated original version of source code.
// 10/22/2014 - Tam T. Do, Southwest Research Institute (SwRI)
// Added DNP3 software capabilities.
//*********************************************************************************************************************
//
package org.epri.pt2.DO;
import javax.persistence.Entity;
import org.epri.pt2.InterfaceType;
/**
* Implements the ethernet interface data object.
*
* @author tdo
*
*/
@Entity
public class EthernetIfaceDO extends AbstractIfaceDO {
public EthernetIfaceDO() {
super(InterfaceType.Ethernet);
}
public int compareTo(AbstractIfaceDO o) {
return getId() - o.getId();
}
}
|
epri-dev/PT2
|
src/main/java/org/epri/pt2/DO/EthernetIfaceDO.java
|
Java
|
bsd-3-clause
| 2,820 |
package sodium;
class LazyCell<A> extends Cell<A> {
LazyCell(final Stream<A> event, final Lazy<A> lazyInitValue) {
super(event, null);
this.lazyInitValue = lazyInitValue;
}
@Override
A sampleNoTrans()
{
if (value == null && lazyInitValue != null) {
value = lazyInitValue.get();
lazyInitValue = null;
}
return value;
}
}
|
kevintvh/sodium
|
java/src/sodium/LazyCell.java
|
Java
|
bsd-3-clause
| 411 |
// Copyright 2018 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/ash/policy/reporting/arc_app_install_event_logger.h"
#include <stdint.h>
#include <algorithm>
#include <iterator>
#include "ash/components/arc/arc_prefs.h"
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/task/post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/ash/arc/arc_util.h"
#include "chrome/browser/ash/arc/policy/arc_policy_util.h"
#include "chrome/browser/ash/policy/reporting/install_event_logger_base.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/policy_constants.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
namespace em = enterprise_management;
namespace policy {
namespace {
constexpr int kNonComplianceReasonAppNotInstalled = 5;
std::set<std::string> GetRequestedPackagesFromPolicy(
const policy::PolicyMap& policy) {
const base::Value* const arc_enabled = policy.GetValue(key::kArcEnabled);
if (!arc_enabled || !arc_enabled->is_bool() || !arc_enabled->GetBool()) {
return {};
}
const base::Value* const arc_policy = policy.GetValue(key::kArcPolicy);
if (!arc_policy || !arc_policy->is_string()) {
return {};
}
return arc::policy_util::GetRequestedPackagesFromArcPolicy(
arc_policy->GetString());
}
} // namespace
ArcAppInstallEventLogger::ArcAppInstallEventLogger(Delegate* delegate,
Profile* profile)
: InstallEventLoggerBase(profile), delegate_(delegate) {
if (!arc::IsArcAllowedForProfile(profile_)) {
AddForSetOfApps(GetPackagesFromPref(arc::prefs::kArcPushInstallAppsPending),
CreateEvent(em::AppInstallReportLogEvent::CANCELED));
Clear(profile_);
return;
}
policy::PolicyService* const policy_service =
profile_->GetProfilePolicyConnector()->policy_service();
EvaluatePolicy(policy_service->GetPolicies(policy::PolicyNamespace(
policy::POLICY_DOMAIN_CHROME, std::string())),
true /* initial */);
observing_ = true;
arc::ArcPolicyBridge* bridge =
arc::ArcPolicyBridge::GetForBrowserContext(profile_);
bridge->AddObserver(this);
policy_service->AddObserver(policy::POLICY_DOMAIN_CHROME, this);
}
ArcAppInstallEventLogger::~ArcAppInstallEventLogger() {
if (log_collector_) {
log_collector_->OnLogout();
}
if (observing_) {
arc::ArcPolicyBridge::GetForBrowserContext(profile_)->RemoveObserver(this);
profile_->GetProfilePolicyConnector()->policy_service()->RemoveObserver(
policy::POLICY_DOMAIN_CHROME, this);
}
}
// static
void ArcAppInstallEventLogger::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterListPref(arc::prefs::kArcPushInstallAppsRequested);
registry->RegisterListPref(arc::prefs::kArcPushInstallAppsPending);
}
// static
void ArcAppInstallEventLogger::Clear(Profile* profile) {
profile->GetPrefs()->ClearPref(arc::prefs::kArcPushInstallAppsRequested);
profile->GetPrefs()->ClearPref(arc::prefs::kArcPushInstallAppsPending);
}
void ArcAppInstallEventLogger::AddForAllPackages(
std::unique_ptr<em::AppInstallReportLogEvent> event) {
EnsureTimestampSet(event.get());
AddForSetOfApps(GetPackagesFromPref(arc::prefs::kArcPushInstallAppsPending),
std::move(event));
}
void ArcAppInstallEventLogger::Add(
const std::string& package,
bool gather_disk_space_info,
std::unique_ptr<em::AppInstallReportLogEvent> event) {
AddEvent(package, gather_disk_space_info, event);
}
void ArcAppInstallEventLogger::OnPolicyUpdated(
const policy::PolicyNamespace& ns,
const policy::PolicyMap& previous,
const policy::PolicyMap& current) {
EvaluatePolicy(current, false /* initial */);
}
void ArcAppInstallEventLogger::OnPolicySent(const std::string& policy) {
requested_in_arc_ =
arc::policy_util::GetRequestedPackagesFromArcPolicy(policy);
}
void ArcAppInstallEventLogger::OnComplianceReportReceived(
const base::Value* compliance_report) {
const base::Value* const details = compliance_report->FindKeyOfType(
"nonComplianceDetails", base::Value::Type::LIST);
if (!details) {
return;
}
const std::set<std::string> previous_pending =
GetPackagesFromPref(arc::prefs::kArcPushInstallAppsPending);
std::set<std::string> pending_in_arc;
for (const auto& detail : details->GetList()) {
const base::Value* const reason =
detail.FindKeyOfType("nonComplianceReason", base::Value::Type::INTEGER);
if (!reason || reason->GetInt() != kNonComplianceReasonAppNotInstalled) {
continue;
}
const base::Value* const app_name =
detail.FindKeyOfType("packageName", base::Value::Type::STRING);
if (!app_name || app_name->GetString().empty()) {
continue;
}
pending_in_arc.insert(app_name->GetString());
}
const std::set<std::string> current_pending = GetDifference(
previous_pending, GetDifference(requested_in_arc_, pending_in_arc));
const std::set<std::string> removed =
GetDifference(previous_pending, current_pending);
AddForSetOfAppsWithDiskSpaceInfo(
removed, CreateEvent(em::AppInstallReportLogEvent::SUCCESS));
if (removed.empty()) {
return;
}
SetPref(arc::prefs::kArcPushInstallAppsPending, current_pending);
if (!current_pending.empty()) {
UpdateCollector(current_pending);
} else {
StopCollector();
}
}
std::set<std::string> ArcAppInstallEventLogger::GetPackagesFromPref(
const std::string& pref_name) const {
std::set<std::string> packages;
for (const auto& package :
profile_->GetPrefs()->GetList(pref_name)->GetList()) {
if (!package.is_string()) {
continue;
}
packages.insert(package.GetString());
}
return packages;
}
void ArcAppInstallEventLogger::SetPref(const std::string& pref_name,
const std::set<std::string>& packages) {
base::Value value(base::Value::Type::LIST);
for (const std::string& package : packages) {
value.Append(package);
}
profile_->GetPrefs()->Set(pref_name, value);
}
void ArcAppInstallEventLogger::UpdateCollector(
const std::set<std::string>& pending) {
if (!log_collector_) {
log_collector_ = std::make_unique<ArcAppInstallEventLogCollector>(
this, profile_, pending);
} else {
log_collector_->OnPendingPackagesChanged(pending);
}
}
void ArcAppInstallEventLogger::StopCollector() {
log_collector_.reset();
}
void ArcAppInstallEventLogger::EvaluatePolicy(const policy::PolicyMap& policy,
bool initial) {
const std::set<std::string> previous_requested =
GetPackagesFromPref(arc::prefs::kArcPushInstallAppsRequested);
const std::set<std::string> previous_pending =
GetPackagesFromPref(arc::prefs::kArcPushInstallAppsPending);
const std::set<std::string> current_requested =
GetRequestedPackagesFromPolicy(policy);
const std::set<std::string> added =
GetDifference(current_requested, previous_requested);
const std::set<std::string> removed =
GetDifference(previous_pending, current_requested);
AddForSetOfAppsWithDiskSpaceInfo(
added, CreateEvent(em::AppInstallReportLogEvent::SERVER_REQUEST));
AddForSetOfApps(removed, CreateEvent(em::AppInstallReportLogEvent::CANCELED));
const std::set<std::string> current_pending = GetDifference(
current_requested, GetDifference(previous_requested, previous_pending));
SetPref(arc::prefs::kArcPushInstallAppsRequested, current_requested);
SetPref(arc::prefs::kArcPushInstallAppsPending, current_pending);
if (!current_pending.empty()) {
UpdateCollector(current_pending);
if (initial) {
log_collector_->OnLogin();
}
} else {
StopCollector();
}
}
void ArcAppInstallEventLogger::AddForSetOfApps(
const std::set<std::string>& packages,
std::unique_ptr<em::AppInstallReportLogEvent> event) {
delegate_->GetAndroidId(
base::BindOnce(&ArcAppInstallEventLogger::OnGetAndroidId,
weak_factory_.GetWeakPtr(), packages, std::move(event)));
}
void ArcAppInstallEventLogger::OnGetAndroidId(
const std::set<std::string>& packages,
std::unique_ptr<em::AppInstallReportLogEvent> event,
bool ok,
int64_t android_id) {
if (ok) {
event->set_android_id(android_id);
}
delegate_->Add(packages, *event);
}
} // namespace policy
|
ric2b/Vivaldi-browser
|
chromium/chrome/browser/ash/policy/reporting/arc_app_install_event_logger.cc
|
C++
|
bsd-3-clause
| 8,972 |
<?php
namespace CLIFramework\Component\Table;
use CLIFramework\Ansi\Colors;
class CellAttribute {
const ALIGN_RIGHT = 1;
const ALIGN_LEFT = 2;
const ALIGN_CENTER = 3;
const WRAP = 1;
const CLIP = 2;
const ELLIPSIS = 3;
protected $alignment = 2;
protected $formatter;
protected $textOverflow = CellAttribute::WRAP;
protected $backgroundColor;
protected $foregroundColor;
/*
protected $style;
public function __construct(TableStyle $style)
{
$this->style = $style;
}
public function setStyle(TableStyle $style)
{
$this->style = $style;
}
*/
public function setAlignment($alignment)
{
$this->alignment = $alignment;
}
public function setFormatter($formatter)
{
$this->formatter = $formatter;
}
public function getFormatter()
{
return $this->formatter;
}
public function setTextOverflow($overflowType)
{
$this->textOverflow = $overflowType;
}
/**
* The default cell text formatter
*/
public function format($cell) {
if ($this->formatter) {
return call_user_func($this->formatter, $cell);
}
return $cell;
}
public function setBackgroundColor($color) {
$this->backgroundColor = $color;
}
public function setForegroundColor($color) {
$this->foregroundColor = $color;
}
public function getForegroundColor()
{
return $this->foregroundColor; // TODO: fallback to table style
}
public function getBackgroundColor()
{
return $this->backgroundColor; // TODO: fallback to table style
}
/**
* When inserting rows, we pre-explode the lines to extra rows from Table
* hence this method is separated for pre-processing..
*/
public function handleTextOverflow($cell, $maxWidth)
{
$lines = explode("\n",$cell);
if ($this->textOverflow == self::WRAP) {
$maxLineWidth = max(array_map('mb_strlen', $lines));
if ($maxLineWidth > $maxWidth) {
$cell = wordwrap($cell, $maxWidth, "\n");
// Re-explode the lines
$lines = explode("\n",$cell);
}
} elseif ($this->textOverflow == self::ELLIPSIS) {
if (mb_strlen($lines[0]) > $maxWidth) {
$lines = array(mb_substr($lines[0], 0, $maxWidth - 2) . '..');
}
} elseif ($this->textOverflow == self::CLIP) {
if (mb_strlen($lines[0]) > $maxWidth) {
$lines = array(mb_substr($lines[0], 0, $maxWidth));
}
}
return $lines;
}
public function renderCell($cell, $width, $style)
{
$out = '';
$out .= str_repeat($style->cellPaddingChar, $style->cellPadding);
/*
if ($this->backgroundColor || $this->foregroundColor) {
$decoratedCell = Colors::decorate($cell, $this->foregroundColor, $this->backgroundColor);
$width += mb_strlen($decoratedCell) - mb_strlen($cell);
$cell = $decoratedCell;
}
*/
if ($this->alignment === CellAttribute::ALIGN_LEFT) {
$out .= str_pad($cell, $width, ' '); // default alignment = LEFT
} elseif ($this->alignment === CellAttribute::ALIGN_RIGHT) {
$out .= str_pad($cell, $width, ' ', STR_PAD_LEFT);
} elseif ($this->alignment === CellAttribute::ALIGN_CENTER) {
$out .= str_pad($cell, $width, ' ', STR_PAD_BOTH);
} else {
$out .= str_pad($cell, $width, ' '); // default alignment
}
$out .= str_repeat($style->cellPaddingChar, $style->cellPadding);
if ($this->backgroundColor || $this->foregroundColor) {
return Colors::decorate($out, $this->foregroundColor, $this->backgroundColor);
}
return $out;
}
}
|
marcioAlmada/CLIFramework
|
src/CLIFramework/Component/Table/CellAttribute.php
|
PHP
|
bsd-3-clause
| 3,942 |
/****************************************************************************
* Copyright (c) 2012-2020 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
/*!
* \file DTK_DOFMap.hpp
* \brief Degree-of-freedom map.
*/
//---------------------------------------------------------------------------//
#ifndef DTK_DOFMAP_HPP
#define DTK_DOFMAP_HPP
#include <Kokkos_Core.hpp>
#include <Kokkos_DynRankView.hpp>
namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
* \class DOFMap.
*
* \brief Trivially-copyable degree-of-freedom map.
*
* \tparam ViewProperties Properties of the contained Kokkos views.
*/
template <class... ViewProperties>
class DOFMap
{
public:
//! View Traits.
using ViewTraits = typename Kokkos::ViewTraits<int, ViewProperties...>;
//! Globally-unique ids for dofs represented on this process. These may or
//! may not be locally owned but every dof for every object defined on
//! this process must be available in this list. This list is of rank-1
//! and of length equal to the number of degrees of freedom on the local
//! MPI rank. Dimensions: (dof)
Kokkos::View<GlobalOrdinal *, ViewProperties...> global_dof_ids;
//! For every object of the given type in the object list give the local
//! dof ids for that object. The local dof ids correspond to the index of
//! the entry in the global dof id view. This view can be either rank-1 or
//! rank-2
//!
//! If this view is defined as rank-1 it represents unstructured rank-2
//! data. It should be sized as (total sum of the number of dofs defined on
//! each object) or the total sum of the entries in the dof_per_object
//! view. Consider the \f$n^th\f$ dof of object \f$i\f$ to be \f$d^i_n\f$
//! which is
//! equal to the local index of the corresponding node in the nodes
//! view. Two objects, the first with 5 dofs and the second with 4 would
//! then be defined via this view as: \f$(d^1_1, d^1_2, d^1_3, d^1_4, d^1_5,
//! d^2_1, d^2_2, d^2_3, d^2_4 )\f$ with the dofs_per_object view reading
//! \f$(5, 4)\f$. Dimensions: (object * dof).
//!
//! If this view is rank-2, then it represents a fixed number of dofs per
//! object. The ordering of the dofs for each object should be the same as
//! the case of rank-1 input. Dimensions: (object, dof).
Kokkos::DynRankView<LocalOrdinal, ViewProperties...> object_dof_ids;
//! The number of degrees of freedom on each object. This view is only
//! necessary if the object_dof_ids array is rank-1. This view is rank-1
//! and of length of the number of objects of the given type in the
//! list. Dimensions: (object).
Kokkos::View<unsigned *, ViewProperties...> dofs_per_object;
};
//---------------------------------------------------------------------------//
} // namespace DataTransferKit
//---------------------------------------------------------------------------//
#endif // end DTK_DOFMAP_HPP
//---------------------------------------------------------------------------//
// end DTK_DOFMap.hpp
//---------------------------------------------------------------------------//
|
Rombur/DataTransferKit
|
packages/Interface/src/DTK_DOFMap.hpp
|
C++
|
bsd-3-clause
| 3,843 |
//
// Copyright 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// capture_gles3_params.cpp:
// Pointer parameter capture functions for the OpenGL ES 3.0 entry points.
#include "libANGLE/capture_gles_2_0_autogen.h"
#include "libANGLE/capture_gles_3_0_autogen.h"
using namespace angle;
namespace gl
{
void CaptureClearBufferfv_value(const State &glState,
bool isCallValid,
GLenum buffer,
GLint drawbuffer,
const GLfloat *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureClearBufferiv_value(const State &glState,
bool isCallValid,
GLenum buffer,
GLint drawbuffer,
const GLint *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureClearBufferuiv_value(const State &glState,
bool isCallValid,
GLenum buffer,
GLint drawbuffer,
const GLuint *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureCompressedTexImage3D_data(const State &glState,
bool isCallValid,
TextureTarget targetPacked,
GLint level,
GLenum internalformat,
GLsizei width,
GLsizei height,
GLsizei depth,
GLint border,
GLsizei imageSize,
const void *data,
ParamCapture *paramCapture)
{
if (glState.getTargetBuffer(gl::BufferBinding::PixelUnpack))
{
return;
}
if (!data)
{
return;
}
CaptureMemory(data, imageSize, paramCapture);
}
void CaptureCompressedTexSubImage3D_data(const State &glState,
bool isCallValid,
TextureTarget targetPacked,
GLint level,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLsizei width,
GLsizei height,
GLsizei depth,
GLenum format,
GLsizei imageSize,
const void *data,
ParamCapture *paramCapture)
{
CaptureCompressedTexImage3D_data(glState, isCallValid, targetPacked, level, 0, width, height,
depth, 0, imageSize, data, paramCapture);
}
void CaptureDeleteQueries_idsPacked(const State &glState,
bool isCallValid,
GLsizei n,
const QueryID *ids,
ParamCapture *paramCapture)
{
CaptureMemory(ids, sizeof(QueryID) * n, paramCapture);
}
void CaptureDeleteSamplers_samplersPacked(const State &glState,
bool isCallValid,
GLsizei count,
const SamplerID *samplers,
ParamCapture *paramCapture)
{
CaptureMemory(samplers, sizeof(SamplerID) * count, paramCapture);
}
void CaptureDeleteTransformFeedbacks_idsPacked(const State &glState,
bool isCallValid,
GLsizei n,
const TransformFeedbackID *ids,
ParamCapture *paramCapture)
{
CaptureMemory(ids, sizeof(TransformFeedbackID) * n, paramCapture);
}
void CaptureDeleteVertexArrays_arraysPacked(const State &glState,
bool isCallValid,
GLsizei n,
const VertexArrayID *arrays,
ParamCapture *paramCapture)
{
CaptureMemory(arrays, sizeof(VertexArrayID) * n, paramCapture);
}
void CaptureDrawBuffers_bufs(const State &glState,
bool isCallValid,
GLsizei n,
const GLenum *bufs,
ParamCapture *paramCapture)
{
CaptureMemory(bufs, sizeof(GLenum) * n, paramCapture);
}
void CaptureDrawElementsInstanced_indices(const State &glState,
bool isCallValid,
PrimitiveMode modePacked,
GLsizei count,
DrawElementsType typePacked,
const void *indices,
GLsizei instancecount,
ParamCapture *paramCapture)
{
CaptureDrawElements_indices(glState, isCallValid, modePacked, count, typePacked, indices,
paramCapture);
}
void CaptureDrawRangeElements_indices(const State &glState,
bool isCallValid,
PrimitiveMode modePacked,
GLuint start,
GLuint end,
GLsizei count,
DrawElementsType typePacked,
const void *indices,
ParamCapture *paramCapture)
{
CaptureDrawElements_indices(glState, isCallValid, modePacked, count, typePacked, indices,
paramCapture);
}
void CaptureGenQueries_idsPacked(const State &glState,
bool isCallValid,
GLsizei n,
QueryID *ids,
ParamCapture *paramCapture)
{
CaptureGenHandles(n, ids, paramCapture);
}
void CaptureGenSamplers_samplersPacked(const State &glState,
bool isCallValid,
GLsizei count,
SamplerID *samplers,
ParamCapture *paramCapture)
{
CaptureGenHandles(count, samplers, paramCapture);
}
void CaptureGenTransformFeedbacks_idsPacked(const State &glState,
bool isCallValid,
GLsizei n,
TransformFeedbackID *ids,
ParamCapture *paramCapture)
{
CaptureGenHandles(n, ids, paramCapture);
}
void CaptureGenVertexArrays_arraysPacked(const State &glState,
bool isCallValid,
GLsizei n,
VertexArrayID *arrays,
ParamCapture *paramCapture)
{
CaptureGenHandles(n, arrays, paramCapture);
}
void CaptureGetActiveUniformBlockName_length(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLuint uniformBlockIndex,
GLsizei bufSize,
GLsizei *length,
GLchar *uniformBlockName,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetActiveUniformBlockName_uniformBlockName(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLuint uniformBlockIndex,
GLsizei bufSize,
GLsizei *length,
GLchar *uniformBlockName,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetActiveUniformBlockiv_params(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLuint uniformBlockIndex,
GLenum pname,
GLint *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetActiveUniformsiv_uniformIndices(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLsizei uniformCount,
const GLuint *uniformIndices,
GLenum pname,
GLint *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetActiveUniformsiv_params(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLsizei uniformCount,
const GLuint *uniformIndices,
GLenum pname,
GLint *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetBufferParameteri64v_params(const State &glState,
bool isCallValid,
BufferBinding targetPacked,
GLenum pname,
GLint64 *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetBufferPointerv_params(const State &glState,
bool isCallValid,
BufferBinding targetPacked,
GLenum pname,
void **params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetFragDataLocation_name(const State &glState,
bool isCallValid,
ShaderProgramID program,
const GLchar *name,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetInteger64i_v_data(const State &glState,
bool isCallValid,
GLenum target,
GLuint index,
GLint64 *data,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetInteger64v_data(const State &glState,
bool isCallValid,
GLenum pname,
GLint64 *data,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetIntegeri_v_data(const State &glState,
bool isCallValid,
GLenum target,
GLuint index,
GLint *data,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetInternalformativ_params(const State &glState,
bool isCallValid,
GLenum target,
GLenum internalformat,
GLenum pname,
GLsizei bufSize,
GLint *params,
ParamCapture *paramCapture)
{
// From the OpenGL ES 3.0 spec:
//
// The information retrieved will be written to memory addressed by the pointer specified in
// params.
//
// No more than bufSize integers will be written to this memory.
//
// If pname is GL_NUM_SAMPLE_COUNTS, the number of sample counts that would be returned by
// querying GL_SAMPLES will be returned in params.
//
// If pname is GL_SAMPLES, the sample counts supported for internalformat and target are written
// into params in descending numeric order. Only positive values are returned.
//
// Querying GL_SAMPLES with bufSize of one will return just the maximum supported number of
// samples for this format.
if (bufSize == 0)
return;
if (params)
{
// For GL_NUM_SAMPLE_COUNTS, only one value is returned
// For GL_SAMPLES, two values will be returned, unless bufSize limits it to one
uint32_t paramCount = (pname == GL_SAMPLES && bufSize > 1) ? 2 : 1;
paramCapture->readBufferSizeBytes = sizeof(GLint) * paramCount;
}
}
void CaptureGetProgramBinary_length(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLsizei bufSize,
GLsizei *length,
GLenum *binaryFormat,
void *binary,
ParamCapture *paramCapture)
{
if (length)
{
paramCapture->readBufferSizeBytes = sizeof(GLsizei);
}
}
void CaptureGetProgramBinary_binaryFormat(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLsizei bufSize,
GLsizei *length,
GLenum *binaryFormat,
void *binary,
ParamCapture *paramCapture)
{
paramCapture->readBufferSizeBytes = sizeof(GLenum);
}
void CaptureGetProgramBinary_binary(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLsizei bufSize,
GLsizei *length,
GLenum *binaryFormat,
void *binary,
ParamCapture *paramCapture)
{
// If we have length, then actual binarySize was written there
// Otherwise, we don't know how many bytes were written
if (!length)
{
UNIMPLEMENTED();
return;
}
GLsizei binarySize = *length;
if (binarySize > bufSize)
{
// This is a GL error, but clamp it anyway
binarySize = bufSize;
}
paramCapture->readBufferSizeBytes = binarySize;
}
void CaptureGetQueryObjectuiv_params(const State &glState,
bool isCallValid,
QueryID id,
GLenum pname,
GLuint *params,
ParamCapture *paramCapture)
{
// This only returns one value
paramCapture->readBufferSizeBytes = sizeof(GLint);
}
void CaptureGetQueryiv_params(const State &glState,
bool isCallValid,
QueryType targetPacked,
GLenum pname,
GLint *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetSamplerParameterfv_params(const State &glState,
bool isCallValid,
SamplerID sampler,
GLenum pname,
GLfloat *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetSamplerParameteriv_params(const State &glState,
bool isCallValid,
SamplerID sampler,
GLenum pname,
GLint *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetSynciv_length(const State &glState,
bool isCallValid,
GLsync sync,
GLenum pname,
GLsizei bufSize,
GLsizei *length,
GLint *values,
ParamCapture *paramCapture)
{
if (length)
{
paramCapture->readBufferSizeBytes = sizeof(GLsizei);
}
}
void CaptureGetSynciv_values(const State &glState,
bool isCallValid,
GLsync sync,
GLenum pname,
GLsizei bufSize,
GLsizei *length,
GLint *values,
ParamCapture *paramCapture)
{
// Spec: On success, GetSynciv replaces up to bufSize integers in values with the corresponding
// property values of the object being queried. The actual number of integers replaced is
// returned in *length.If length is NULL, no length is returned.
if (bufSize == 0)
return;
if (values)
{
paramCapture->readBufferSizeBytes = sizeof(GLint) * bufSize;
}
}
void CaptureGetTransformFeedbackVarying_length(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLsizei *size,
GLenum *type,
GLchar *name,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetTransformFeedbackVarying_size(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLsizei *size,
GLenum *type,
GLchar *name,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetTransformFeedbackVarying_type(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLsizei *size,
GLenum *type,
GLchar *name,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetTransformFeedbackVarying_name(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLsizei *size,
GLenum *type,
GLchar *name,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetUniformBlockIndex_uniformBlockName(const State &glState,
bool isCallValid,
ShaderProgramID program,
const GLchar *uniformBlockName,
ParamCapture *paramCapture)
{
CaptureString(uniformBlockName, paramCapture);
}
void CaptureGetUniformIndices_uniformNames(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLsizei uniformCount,
const GLchar *const *uniformNames,
GLuint *uniformIndices,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetUniformIndices_uniformIndices(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLsizei uniformCount,
const GLchar *const *uniformNames,
GLuint *uniformIndices,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetUniformuiv_params(const State &glState,
bool isCallValid,
ShaderProgramID program,
UniformLocation location,
GLuint *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetVertexAttribIiv_params(const State &glState,
bool isCallValid,
GLuint index,
GLenum pname,
GLint *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureGetVertexAttribIuiv_params(const State &glState,
bool isCallValid,
GLuint index,
GLenum pname,
GLuint *params,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureInvalidateFramebuffer_attachments(const State &glState,
bool isCallValid,
GLenum target,
GLsizei numAttachments,
const GLenum *attachments,
ParamCapture *paramCapture)
{
CaptureMemory(attachments, sizeof(GLenum) * numAttachments, paramCapture);
paramCapture->value.voidConstPointerVal = paramCapture->data[0].data();
}
void CaptureInvalidateSubFramebuffer_attachments(const State &glState,
bool isCallValid,
GLenum target,
GLsizei numAttachments,
const GLenum *attachments,
GLint x,
GLint y,
GLsizei width,
GLsizei height,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureProgramBinary_binary(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLenum binaryFormat,
const void *binary,
GLsizei length,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureSamplerParameterfv_param(const State &glState,
bool isCallValid,
SamplerID sampler,
GLenum pname,
const GLfloat *param,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureSamplerParameteriv_param(const State &glState,
bool isCallValid,
SamplerID sampler,
GLenum pname,
const GLint *param,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureTexImage3D_pixels(const State &glState,
bool isCallValid,
TextureTarget targetPacked,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLsizei depth,
GLint border,
GLenum format,
GLenum type,
const void *pixels,
ParamCapture *paramCapture)
{
if (glState.getTargetBuffer(gl::BufferBinding::PixelUnpack))
{
return;
}
if (!pixels)
{
return;
}
const gl::InternalFormat &internalFormatInfo = gl::GetInternalFormatInfo(format, type);
const gl::PixelUnpackState &unpack = glState.getUnpackState();
const Extents size(width, height, depth);
GLuint endByte = 0;
bool unpackSize =
internalFormatInfo.computePackUnpackEndByte(type, size, unpack, true, &endByte);
ASSERT(unpackSize);
CaptureMemory(pixels, static_cast<size_t>(endByte), paramCapture);
}
void CaptureTexSubImage3D_pixels(const State &glState,
bool isCallValid,
TextureTarget targetPacked,
GLint level,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLsizei width,
GLsizei height,
GLsizei depth,
GLenum format,
GLenum type,
const void *pixels,
ParamCapture *paramCapture)
{
CaptureTexImage3D_pixels(glState, isCallValid, targetPacked, level, 0, width, height, depth, 0,
format, type, pixels, paramCapture);
}
void CaptureTransformFeedbackVaryings_varyings(const State &glState,
bool isCallValid,
ShaderProgramID program,
GLsizei count,
const GLchar *const *varyings,
GLenum bufferMode,
ParamCapture *paramCapture)
{
for (GLsizei index = 0; index < count; ++index)
{
CaptureString(varyings[index], paramCapture);
}
}
void CaptureUniform1uiv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
const GLuint *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniform2uiv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
const GLuint *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniform3uiv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
const GLuint *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniform4uiv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
const GLuint *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniformMatrix2x3fv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
GLboolean transpose,
const GLfloat *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniformMatrix2x4fv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
GLboolean transpose,
const GLfloat *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniformMatrix3x2fv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
GLboolean transpose,
const GLfloat *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniformMatrix3x4fv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
GLboolean transpose,
const GLfloat *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniformMatrix4x2fv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
GLboolean transpose,
const GLfloat *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureUniformMatrix4x3fv_value(const State &glState,
bool isCallValid,
UniformLocation location,
GLsizei count,
GLboolean transpose,
const GLfloat *value,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureVertexAttribI4iv_v(const State &glState,
bool isCallValid,
GLuint index,
const GLint *v,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureVertexAttribI4uiv_v(const State &glState,
bool isCallValid,
GLuint index,
const GLuint *v,
ParamCapture *paramCapture)
{
UNIMPLEMENTED();
}
void CaptureVertexAttribIPointer_pointer(const State &glState,
bool isCallValid,
GLuint index,
GLint size,
VertexAttribType typePacked,
GLsizei stride,
const void *pointer,
ParamCapture *paramCapture)
{
CaptureVertexAttribPointer_pointer(glState, isCallValid, index, size, typePacked, false, stride,
pointer, paramCapture);
}
} // namespace gl
|
endlessm/chromium-browser
|
third_party/angle/src/libANGLE/capture_gles_3_0_params.cpp
|
C++
|
bsd-3-clause
| 34,588 |
<?php
// # Cancel Invoice Sample
// This sample code demonstrate how you can cancel
// an invoice.
/** @var Invoice $invoice */
$invoice = require 'SendInvoice.php';
use PayPal\Api\Invoice;
use PayPal\Api\CancelNotification;
try {
// ### Cancel Notification Object
// This would send a notification to both merchant as well
// the payer about the cancellation. The information of
// merchant and payer is retrieved from the invoice details
$notify = new CancelNotification();
$notify
->setSubject("Past due")
->setNote("Canceling invoice")
->setSendToMerchant(true)
->setSendToPayer(true);
// ### Cancel Invoice
// Cancel invoice object by calling the
// static `cancel` method
// on the Invoice class by passing a valid
// notification object
// (See bootstrap.php for more on `ApiContext`)
$cancelStatus = $invoice->cancel($notify, $apiContext);
} catch (Exception $ex) {
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printError("Cancel Invoice", "Invoice", null, $notify, $ex);
exit(1);
}
// NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY
ResultPrinter::printResult("Cancel Invoice", "Invoice", $invoice->getId(), $notify, null);
|
frankpaul142/aurasur
|
vendor/paypal/rest-api-sdk-php/sample/invoice/CancelInvoice.php
|
PHP
|
bsd-3-clause
| 1,327 |
<?php
/**
* AutomaticUpload.php
*
* PHP version 5.4+
*
* @author Philippe Gaultier <pgaultier@sweelix.net>
* @copyright 2010-2014 Sweelix
* @license http://www.sweelix.net/license license
* @version 1.0.3
* @link http://www.sweelix.net
* @category behaviors
* @package sweelix.yii2.plupload.behaviors
*/
namespace sweelix\yii2\plupload\behaviors;
use sweelix\yii2\plupload\components\UploadedFile;
use yii\base\Behavior;
use yii\base\InvalidParamException;
use yii\validators\FileValidator;
use yii\db\ActiveRecord;
use yii\helpers\Json;
use yii\helpers\Html;
use Yii;
use Exception;
/**
* This UploadedFile handle automagically the upload process in
* models
*
* @author Philippe Gaultier <pgaultier@sweelix.net>
* @copyright 2010-2014 Sweelix
* @license http://www.sweelix.net/license license
* @version 1.0.3
* @link http://www.sweelix.net
* @category behaviors
* @package sweelix.yii2.plupload.behaviors
* @since 1.0.0
*/
class AutomaticUpload extends Behavior
{
/**
* @var array handled attributes
*/
public $attributes=[];
/**
* @var string define locale for sanitize (it would probably be better to use Yii::$app locale)
*/
public static $sanitizeLocale = 'fr_FR.UTF8';
/**
* @var callable function used to serialize attributes. default to json
*/
public $serializeCallback;
/**
* @var callable function used to unserialize attributes. default to json
*/
public $unserializeCallback;
/**
* @var boolean check if we must wayt for afterInsert to save the files
*/
protected $modelShouldBeSaved = false;
/**
* @var boolean check if we are "re-saving" data in afterSave (when we recompute the path)
*/
protected $modelIsUpdating = false;
/**
* List of tracked events
*
* @return array
* @since 1.0.0
*/
public function events()
{
return [
// ActiveRecord::EVENT_INIT => 'afterInit',
ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
];
}
/**
* Serialize file attribute when multifile upload is active
*
* @param string $attribute the attribute name
*
* @return void
* @since 1.0.0
*/
protected function serializeAttribute($attribute)
{
if ($this->isMultifile($attribute) === true) {
if (is_callable($this->serializeCallback) === true) {
$this->owner->{$attribute} = call_user_func([$this, 'serializeCallback'], $this->owner->{$attribute});
} else {
$data = $this->owner->{$attribute};
if (is_array($data) === true) {
$data = array_filter($data, function($el) { return (empty($el) === false); });
}
$this->owner->{$attribute} = Json::encode($data);
}
} else {
$realData = $this->owner->{$attribute};
if (is_array($realData) === true) {
$realData = array_pop($realData);
}
$this->owner->{$attribute} = $realData;
}
}
/**
* Unserialize file attribute when multifile upload is active
*
* @param string $attribute the attribute name
*
* @return void
* @since 1.0.0
*/
protected function unserializeAttribute($attribute)
{
if (self::isMultifile($attribute) === true) {
if (is_callable($this->unserializeCallback) === true) {
$attributeContent = call_user_func([$this, 'unserializeCallback'], $this->owner->{$attribute});
} else {
try {
$attributeContent = Json::decode($this->owner->{$attribute});
} catch (InvalidParamException $e) {
$attributeContent = [];
}
}
if ((is_array($attributeContent) === false) && (empty($attributeContent) === false)) {
$attributeContent = [$attributeContent];
}
$this->owner->{$attribute} = $attributeContent;
}
}
/**
* Clean up file name
*
* @param string $name file name to sanitize
*
* @return string
* @since 1.0.0
*/
public static function sanitize($name)
{
// we can sanitize file a litlle better anyway, this should tdo the trick with all noob users
setlocale(LC_ALL, self::$sanitizeLocale);
$name = iconv('utf-8', 'ASCII//TRANSLIT//IGNORE', $name);
setlocale(LC_ALL, 0);
return preg_replace('/([^a-z0-9\._\-])+/iu', '-', $name);
}
/**
* Check if current attribute support multifile
*
* @param string $attribute check if file attribute support multifile
*
* @return boolean
* @since 1.0.0
*/
public function isMultifile($attribute)
{
$config = $this->getValidatorConfig($attribute);
return $config['multiFile'];
}
/**
* Get max file size allowed for the attribute
*
* @param string $attribute the source attribute
*
* @return integer
* @since 1.0.1
*/
public function getMaxFileSize($attribute)
{
$config = $this->getValidatorConfig($attribute);
return (int)$config['maxFileSize'];
}
/**
* Get file extensions allowed for the attribute
*
* @param string $attribute the source attribute
*
* @return string
* @since 1.0.1
*/
public function getFileExtensions($attribute)
{
$config = $this->getValidatorConfig($attribute);
return $config['allowedExtensions'];
}
/**
* @var array lazy loaded file information
*/
private static $validatorConfig = [];
/**
* Retrieve the validator configuration
*
* @param string $attribute attribute which is validated
*
* @return array
* @since 1.0.1
*/
protected function getValidatorConfig($attribute)
{
if (isset(self::$validatorConfig[$attribute]) === false) {
self::$validatorConfig[$attribute] = false;
$config = [
'multiFile' => false,
'maxFileSize' => 0,
'allowedExtensions' => null,
];
foreach ($this->owner->getActiveValidators($attribute) as $validator) {
if ($validator instanceof FileValidator) {
// we can set all the parameters
if ($validator->maxFiles > 1) {
// multi add brackets
$config['multiFile'] = true;
}
if (empty($validator->extensions) === false) {
$config['allowedExtensions'] = implode(',', $validator->extensions);
}
if (($validator->maxSize !== null) && ($validator->maxSize > 0)) {
$config['maxFileSize'] = $validator->maxSize;
}
// we should not have multiple file validators for the same file
break;
}
}
self::$validatorConfig[$attribute] = $config;
}
return self::$validatorConfig[$attribute];
}
/**
* Perform file save before insert if we can
* If not, we delay the file processing on after insert
*
* @return void
* @since 1.0.0
*/
public function beforeInsert()
{
foreach ($this->attributes as $attribute => $config) {
if ($this->shouldExpandAliasPath($attribute) === true) {
$this->modelShouldBeSaved = true;
break;
}
}
if ($this->modelShouldBeSaved === false) {
$this->beforeUpdate();
} else {
foreach ($this->attributes as $attribute => $config) {
$this->serializeAttribute($attribute);
}
}
}
/**
* Perform file save after insert if we need to recompute the path
*
* @return void
* @since 1.0.0
*/
public function afterInsert()
{
if ($this->modelShouldBeSaved === true) {
// avoid to save everything twice
$this->modelShouldBeSaved = false;
foreach ($this->attributes as $attribute => $config) {
$this->unserializeAttribute($attribute);
}
$this->beforeUpdate();
$attributes = array_keys($this->attributes);
$sAttributes = [];
foreach ($attributes as $attribute) {
$sAttributes[$attribute] = $this->owner->{$attribute};
}
if (empty($sAttributes) === false) {
$condition = $this->owner->getPrimaryKey(true);
$modelClass = get_class($this->owner);
$command = $modelClass::getDb()->createCommand();
$command->update($modelClass::tableName(), $sAttributes, $condition);
$command->execute();
}
foreach ($this->attributes as $attribute => $config) {
$this->unserializeAttribute($attribute);
}
}
}
/**
* Unserialize attributes
*
* @return void
* @since 1.0.0
*/
public function afterFind()
{
foreach ($this->attributes as $attribute => $config) {
$this->unserializeAttribute($attribute);
}
}
/**
* Remove useless data from the properties and return a clean array
*
* @param array $propertyData property files
*
* @return array
* @since 1.0.0
*/
protected function cleanUpProperty($propertyData)
{
$propertyData = array_map(function ($el) {
return trim($el);
}, $propertyData);
return array_filter($propertyData);
}
/**
* Like insert but we will never need to recompute the key
*
* @return void
* @since 1.0.0
*/
public function beforeUpdate()
{
foreach ($this->attributes as $attribute => $config) {
$aliasPath = $this->getAliasPath($attribute, true);
if (is_array($this->owner->{$attribute}) === false) {
if (empty($this->owner->{$attribute}) === false) {
$this->owner->{$attribute} = [$this->owner->{$attribute}];
} else {
$this->owner->{$attribute} = [];
}
}
// clean up attributes
$this->owner->{$attribute} = $this->cleanUpProperty($this->owner->{$attribute});
$selectedFiles = $this->owner->{$attribute};
$savedFiles = [];
$attributeName = Html::getInputName($this->owner, $attribute);
$uploadedFiles = UploadedFile::getInstancesByName($attributeName);
foreach ($uploadedFiles as $instance) {
if (in_array($instance->name, $selectedFiles) === true) {
$fileName = static::sanitize($instance->name);
if (empty($instance->tempName) === true) {
// image was uploaded earlier
// we should probably check if image is always available
$savedFiles[] = $fileName;
} else {
$targetFile = Yii::getAlias($aliasPath.'/'.$fileName);
$targetPath = pathinfo($targetFile, PATHINFO_DIRNAME);
if (is_dir($targetPath) === false) {
if (mkdir($targetPath, 0755, true) === false) {
throw new Exception('Unable to create path : "'.$targetPath.'"');
}
}
if ($instance->saveAs($targetFile) === true) {
//TODO: saved files must be removed - correct place would be in UploadedFile
$savedFiles[] = $fileName;
}
}
}
}
$this->owner->{$attribute} = $savedFiles;
$this->serializeAttribute($attribute);
}
}
/**
* Should only reset attributes as expected
*
* @return void
* @since 1.0.0
*/
public function afterUpdate()
{
// UploadedFile::reset();
if ($this->modelIsUpdating === false) {
foreach ($this->attributes as $attribute => $config) {
$this->unserializeAttribute($attribute);
}
}
}
/**
* Check if attibute is handled automagically
*
* @param string $attribute attribute to check
*
* @return boolean
* @since 1.0.0
*/
public function isAutomatic($attribute)
{
return array_key_exists($attribute, $this->attributes);
}
/**
* Return current file(s) attribute with the(ir) full path
*
* @param string $attribute attribute to retrieve
* @param boolean $expanded should we expand parameters if they are used in the path
*
* @return mixed
* @since 1.0.0
*/
public function getAsFilePath($attribute, $expanded = false)
{
if (($this->isMultifile($attribute) === true)
&& (is_array($this->owner->{$attribute}) === true)
&& (empty($this->owner->{$attribute}) === false)) {
return array_map(function ($el) use ($attribute, $expanded) {
return Yii::getAlias($this->getAliasPath($attribute, $expanded).'/'.$el);
}, $this->owner->{$attribute});
} elseif (empty($this->owner->{$attribute}) === false) {
return Yii::getAlias($this->getAliasPath($attribute, $expanded).'/'.$this->owner->{$attribute});
} else {
return null;
}
}
/**
* Return current file(s) attribute with the(ir) full url
*
* @param string $attribute attribute to retrieve
* @param boolean $expanded should we expand parameters if they are used in the url
*
* @return mixed
* @since 1.0.0
*/
public function getAsFileUrl($attribute, $expanded = false)
{
if (($this->isMultifile($attribute) === true) && (is_array($this->owner->{$attribute}) === true)) {
return array_map(function ($el) use ($attribute, $expanded) {
return Yii::getAlias($this->getAliasUrl($attribute, $expanded).'/'.$el);
}, $this->owner->{$attribute});
} elseif (empty($this->owner->{$attribute}) === false) {
return Yii::getAlias($this->getAliasUrl($attribute, $expanded).'/'.$this->owner->{$attribute});
} else {
return null;
}
}
/**
* Get Alias path for selected attribute
*
* @param string $attribute name of selected attribute
* @param boolean $expand should we expand the alias path with model values
*
* @return string
* @since 1.0.0
*/
public function getAliasPath($attribute, $expand = false)
{
if (isset($this->attributes[$attribute]['basePath']) === true) {
$basePath = $this->attributes[$attribute]['basePath'];
if ($expand === true) {
$expansionVars = $this->getAliasPathExpansionVars($attribute);
if (empty($expansionVars) === false) {
$basePath = str_replace(array_keys($expansionVars), array_values($expansionVars), $basePath);
}
}
return $basePath;
} else {
return '@webroot';
}
}
/**
* Check if current path should be expanded
*
* @param string $attribute attribute to check
*
* @return boolean
* @since 1.0.0
*/
public function shouldExpandAliasPath($attribute)
{
$aliasPath = $this->getAliasPath($attribute);
return (preg_match_all('/{([^}]+)}/', $aliasPath)>0);
}
/**
* Get variables used for path expansion
*
* @param string $attribute attribute to check
*
* @return mixed
* @since 1.0.0
*/
public function getAliasPathExpansionVars($attribute)
{
$expansionVars = [];
$aliasPath = $this->getAliasPath($attribute);
if ($aliasPath !== null) {
$nbMatches = preg_match_all('/{([^}]+)}/', $aliasPath, $matches);
if ($nbMatches > 0) {
foreach ($matches[1] as $expandAttribute) {
$expansionVars['{'.$expandAttribute.'}'] = $this->owner->{$expandAttribute};
}
}
}
return (empty($expansionVars) === true)?null:$expansionVars;
}
/**
* Get Alias URL for selected attribute
*
* @param string $attribute name of selected attribute
* @param boolean $expand should we expand the alias url with model values
*
* @return string
* @since 1.0.0
*/
public function getAliasUrl($attribute, $expand = false)
{
if (isset($this->attributes[$attribute]['baseUrl']) === true) {
$baseUrl = $this->attributes[$attribute]['baseUrl'];
if ($expand === true) {
$expansionVars = $this->getAliasUrlExpansionVars($attribute);
if (empty($expansionVars) === false) {
$baseUrl = str_replace(array_keys($expansionVars), array_values($expansionVars), $baseUrl);
}
}
return $baseUrl;
} else {
return '@web';
}
}
/**
* Check if current URL should be expanded
*
* @param string $attribute attribute to check
*
* @return boolean
* @since 1.0.0
*/
public function shouldExpandAliasUrl($attribute)
{
$aliasUrl = $this->getAliasUrl($attribute);
return (preg_match_all('/{([^}]+)}/', $aliasUrl)>0);
}
/**
* Get variables used for URL expansion
*
* @param string $attribute attribute to check
*
* @return mixed
* @since 1.0.0
*/
public function getAliasUrlExpansionVars($attribute)
{
$expansionVars = [];
$aliasUrl = $this->getAliasUrl($attribute);
if ($aliasUrl !== null) {
$nbMatches = preg_match_all('/{([^}]+)}/', $aliasUrl, $matches);
if ($nbMatches > 0) {
foreach ($matches[1] as $expandAttribute) {
$expansionVars['{'.$expandAttribute.'}'] = $this->owner->{$expandAttribute};
}
}
}
return (empty($expansionVars) === true)?null:$expansionVars;
}
}
|
pgaultier/sweelix-yii2-plupload
|
src/behaviors/AutomaticUpload.php
|
PHP
|
bsd-3-clause
| 19,061 |
<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
use common\models\User;
/**
* Activation reset request form
*/
class ActivationCodeResetRequestForm extends Model {
// Init Public Constants
const STATUS_SUCCESS = 100;
const STATUS_ERROR_ACCOUNT_ALREADY_ACTIVATED = 200;
const STATUS_ERROR_ACCOUNT_NOT_FOUND = 300;
const STATUS_ERROR_MAIL_NOT_SENT = 400;
// Init Public Variables
public $email;
/**
* @inheritdoc
*/
public function rules() {
return [
[
'email',
'trim'
],
[
'email',
'required'
],
[
'email',
'email'
],
[
'email',
'exist',
'targetClass' => '\common\models\User',
'filter' => [
'status' => User::STATUS_ACTIVE
],
'message' => 'There is no user with such email.'
]
];
}
/**
* Sends an email with a link, for resetting the password.
*
* @return bool whether the email was send
*/
public function sendEmail() {
/* @var $user User */
$user = User::findOne ( [
'status' => User::STATUS_ACTIVE,
'email' => $this->email
] );
if (! $user) {
return self::STATUS_ERROR_ACCOUNT_NOT_FOUND;
}
if (! $user->ActivationDateTime == null) {
return self::STATUS_ERROR_ACCOUNT_ALREADY_ACTIVATED;
}
// Send an Email
if (Yii::$app->mailer->compose ( "accountActivation", [
'model' => $user
] )->setTo ( array (
$user->email => $user->FirstName
) )->setFrom ( array (
Yii::$app->params ['adminEmail'] => 'Custom Reminder Administrator'
) )->setSubject ( 'Account Activation Required for ' . $user->FirstName )->send () == true) {
return self::STATUS_SUCCESS;
} else {
return self::STATUS_ERROR_MAIL_NOT_SENT;
}
}
}
|
microdisk/customre_website
|
frontend/models/ActivationCodeResetRequestForm.php
|
PHP
|
bsd-3-clause
| 1,755 |
package org.sana.android.fragment;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import org.sana.R;
import org.sana.android.activity.ObserverList;
import org.sana.android.content.Uris;
import org.sana.android.content.core.ObserverWrapper;
import org.sana.android.provider.Observers;
import org.sana.android.util.PhoneUtil;
import org.sana.core.Observer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import static android.telephony.PhoneNumberUtils.formatNumberToE164;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link ModelSelectedListener}
* interface.
*/
public class ObserverListFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private ModelSelectedListener<Observer> mListener = null;
private ObserverCursorAdapter mAdapter = null;
private Uri mUri = Observers.CONTENT_URI;
// static final String[] mProjection = null;
public static final String TAG = ObserverListFragment.class.getName();
static ObserverList observerList = new ObserverList();
static final String[] mProjection = new String[] {
Observers.Contract._ID,
Observers.Contract.FIRST_NAME,
Observers.Contract.LAST_NAME,
Observers.Contract.PHONE_NUMBER,
Observers.Contract.LOCATIONS
};
// static final String mSelect = Observers.Contract.ROLE +" = '"+ observerList.getUser() +"'";
static final String userSelect = Observers.Contract.ROLE +" = 'vht'";
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ObserverListFragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static ObserverListFragment newInstance(int columnCount) {
ObserverListFragment fragment = new ObserverListFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
// args.putString("user", observerListuser);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_observer_list, container, false);
// TODO Anything else related to the view that needs to happen here
// Toast.makeText(ObserverListFragment.this.getContext(), ""+mSelect, Toast.LENGTH_SHORT).show();
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// userSelect = Observers.Contract.ROLE +" = 'midwife'";
// final String mSelect = Observers.Contract.ROLE +" = '"+ observerList.getUser() +"'";
if (context instanceof ModelSelectedListener) {
mListener = (ModelSelectedListener<Observer>) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement ModelSelectedListener<Observer>");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// TODO initialize mAdapter
mAdapter = new ObserverCursorAdapter(getActivity(), null, 0);
setListAdapter(mAdapter);
LoaderManager.enableDebugLogging(true);
getActivity().getSupportLoaderManager().initLoader(Uris.OBSERVER_DIR, null, this);
// set the list item click listener
getListView().setOnItemClickListener(this);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String user = Observers.Contract.ROLE +" = '"+ getActivity().getIntent().getStringExtra("user") +"'";
CursorLoader loader = new CursorLoader(getActivity(),
mUri,
null,//mProjection,
//mSelect
user, null, null);
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null){
((TextView)getListView().getEmptyView()).setText(getString(R.string.msg_drivers_vht));
}
if(cursor != null){
if(cursor.getCount() == 0) {
((TextView)getListView().getEmptyView()).setText(getString(R.string.msg_drivers_vht));
} else{
((ObserverCursorAdapter) this.getListAdapter()).swapCursor(cursor);
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
((ObserverCursorAdapter)this.getListAdapter()).swapCursor(null);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Implement click to call functionality
Object number = view.getTag();
if(number != null){
try {
PhoneUtil.call(getActivity(), String.valueOf(number));
} catch(Exception e){
Toast.makeText(getActivity(), R.string.error_unable_to_call,
Toast.LENGTH_LONG);
}
} else {
if (mListener != null) {
mListener.onModelSelected((Observer)mAdapter.getItem(position));
}
}
}
public static class ObserverCursorAdapter extends CursorAdapter{
protected Map<Integer, Observer> mHolders = new HashMap<>();
public ObserverCursorAdapter(Context context, Cursor c, int resId) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View child = inflater.inflate(R.layout.list_item_observer, parent, false);
return child;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ObserverWrapper wrapper = new ObserverWrapper(cursor);
if(wrapper == null || wrapper.isBeforeFirst() || cursor.getCount() == 0)
return;
Observer obj = (Observer) wrapper.getObject();
view.setTag(obj.getPhoneNumber());
// TODO fill in any fields etc
setText(view, R.id.first_name, obj.getFirstName());
setText(view, R.id.last_name, obj.getLastName());
setText(view, R.id.phone_number, obj.getPhoneNumber());
mHolders.put(cursor.getPosition(), obj);
Log.v(TAG,",.,.,.<><><><><><.,.,.,.<><><><>"+obj.getFirstName());
}
public Object getItem(int position){
return mHolders.get(position);
}
protected void setText(View root, int resId, String text){
TextView child = (TextView) root.findViewById(resId);
child.setText(text);
}
}
}
|
UNFPAInnovation/GetIn_Mobile
|
app/src/main/java/org/sana/android/fragment/ObserverListFragment.java
|
Java
|
bsd-3-clause
| 8,088 |
#include "Ht.h"
#include "PersObk.h"
void
CPersObk::PersObk()
{
if (PR_htValid) {
switch (PR_htInst) {
case OBK_PUSH:
{
if (P_loopCnt == 0) {
HtContinue(OBK_RTN);
break;
}
if (SendHostDataBusy()) {
HtRetry();
break;
}
uint64_t data = (uint64_t)((uint64_t)P_pau << 56);
data |= (uint64_t)((uint64_t)P_loopCnt);
#ifndef _HTV
if (!(P_loopCnt % 10000))
fprintf(stderr, "%d loopCnt = %d\n",
(int)P_pau, (int)P_loopCnt);
#endif
SendHostData(data);
P_loopCnt -= 1;
HtContinue(OBK_PUSH);
}
break;
case OBK_RTN:
{
if (SendReturnBusy_htmain()) {
HtRetry();
break;
}
SendReturn_htmain();
}
break;
default:
assert(0);
}
}
}
|
TonyBrewer/OpenHT
|
tests/obk/src_pers/PersObk_src.cpp
|
C++
|
bsd-3-clause
| 716 |
/*================================================================================
Copyright (c) 2009 VMware, Inc. 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 VMware, Inc. 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 VMWARE, INC. 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.
================================================================================*/
package com.vmware.vim25;
/**
@author Steve Jin (sjin@vmware.com)
*/
public class CannotAddHostWithFTVmAsStandalone extends HostConnectFault
{
}
|
mikem2005/vijava
|
src/com/vmware/vim25/CannotAddHostWithFTVmAsStandalone.java
|
Java
|
bsd-3-clause
| 1,790 |
package de.fraunhofer.fokus.movepla.portlets;
/*
* #%L
* govapps_data
* $Id: E_Stati.java 566 2014-11-13 15:22:01Z sma $
* %%
* Copyright (C) 2013 - 2014 Fraunhofer FOKUS / CC ÖFIT
* %%
* Copyright (c) 2,013, Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT
* 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) All advertising materials mentioning features or use of this software must
* display the following acknowledgement:
* This product includes software developed by Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT.
*
* 4) Neither the name of the organization 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 COPYRIGHT HOLDER ''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
* Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT
* 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.
* #L%
*/
public enum E_Stati {
APPLICATION_STATUS_SUBMITTED("APPLICATION_STATUS_SUBMITTED", 1),
APPLICATION_STATUS_DELETED("APPLICATION_STATUS_DELETED", 2),
APPLICATION_STATUS_RESUBMITTED("APPLICATION_STATUS_RESUBMITTED", 3),
APPLICATION_STATUS_VERIFIED_AND_RESUBMITTED("APPLICATION_STATUS_VERIFIED_AND_RESUBMITTED", -3),
APPLICATION_STATUS_REJECTED("APPLICATION_STATUS_REJECTED", -1),
APPLICATION_STATUS_VERIFIED("APPLICATION_STATUS_VERIFIED", 4),
APPLICATION_STATUS_CERTIFIED("APPLICATION_STATUS_CERTIFIED", 5),
APPLICATION_STATUS_OLD_VERIFIED("APPLICATION_STATUS_OLD_VERIFIED", 6);
private String m_strStatus;
private int m_intStatus;
private E_Stati(String strStatus, int intStatus) {
m_strStatus = strStatus;
m_intStatus = intStatus;
}
public String getStrStatus() {
return m_strStatus;
}
public int getIntStatus() {
return m_intStatus;
}
}
|
fraunhoferfokus/govapps
|
data-portlet/src/main/java/de/fraunhofer/fokus/movepla/portlets/E_Stati.java
|
Java
|
bsd-3-clause
| 2,939 |
package com.hitler.common.model.menu;
import java.io.Serializable;
import java.util.Collection;
/**
* 导航栏菜单vo
* @author Kylin
* 2015-10-10 上午9:44:27
*/
public class NavMenu implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
/**
* 显示内容
*/
public String text;
/**
* 图标
*/
public String icon;
/**
* 子节点
*/
public Collection<? extends Serializable> children;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Collection<? extends Serializable> getChildren() {
return children;
}
public void setChildren(Collection<? extends Serializable> children) {
this.children = children;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((text == null) ? 0 : text.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NavMenu other = (NavMenu) obj;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
return true;
}
}
|
onsoul/ha-db
|
saas-mycat/saas/src/main/java/com/hitler/common/model/menu/NavMenu.java
|
Java
|
bsd-3-clause
| 1,481 |
package net.meisen.dissertation.performance.indexes;
/**
* Helper interface to provide different data generators
*
* @author pmeisen
*
*/
public interface IDataGenerator {
/**
* Creates a generated {@code Object} the time of generation should be equal
* for each object.
*
* @return a generated object
*/
public Object generateData();
}
|
pmeisen/dis-timeintervaldataanalyzer
|
test/net/meisen/dissertation/performance/indexes/IDataGenerator.java
|
Java
|
bsd-3-clause
| 359 |
// Copyright 2015-present 650 Industries. All rights reserved.
package abi41_0_0.expo.modules.analytics.segment;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.Nullable;
import com.segment.analytics.Analytics;
import com.segment.analytics.Options;
import com.segment.analytics.Properties;
import com.segment.analytics.Traits;
import com.segment.analytics.android.integrations.firebase.FirebaseIntegration;
import java.util.HashMap;
import java.util.Map;
import abi41_0_0.org.unimodules.core.ExportedModule;
import abi41_0_0.org.unimodules.core.ModuleRegistry;
import abi41_0_0.org.unimodules.core.Promise;
import abi41_0_0.org.unimodules.core.interfaces.ExpoMethod;
import abi41_0_0.org.unimodules.interfaces.constants.ConstantsInterface;
public class SegmentModule extends ExportedModule {
private static final String NAME = "ExponentSegment";
private static final String ENABLED_PREFERENCE_KEY = "enabled";
private static final String TAG = SegmentModule.class.getSimpleName();
private static int sCurrentTag = 0;
private Context mContext;
private Analytics mClient;
private ConstantsInterface mConstants;
// We have to keep track of `enabled` on our own.
// Since we have to change tag every time (see commit 083f051), Segment may or may not properly apply
// remembered preference to the instance. The module in a standalone app would start disabled
// (settings = { 0 => disabled }, tag = 0) but after OTA update it would reload with
// (settings = { 0 => disabled }, tag = 1) and segment would become enabled if the app does not
// disable it on start.
private SharedPreferences mSharedPreferences;
public SegmentModule(Context context) {
super(context);
mContext = context;
mSharedPreferences = mContext.getSharedPreferences(NAME, Context.MODE_PRIVATE);
}
private static Traits readableMapToTraits(Map<String, Object> properties) {
Traits traits = new Traits();
for (String key : properties.keySet()) {
Object value = properties.get(key);
if (value instanceof Map) {
traits.put(key, coalesceAnonymousMapToJsonObject((Map) value));
} else {
traits.put(key, value);
}
}
return traits;
}
private static Map<String, Object> coalesceAnonymousMapToJsonObject(Map map) {
Map<String, Object> validObject = new HashMap<>();
for (Object key : map.keySet()) {
if (key instanceof String) {
Object value = map.get(key);
if (value instanceof Map) {
validObject.put((String) key, coalesceAnonymousMapToJsonObject((Map) value));
} else {
validObject.put((String) key, value);
}
}
}
return validObject;
}
private static Options readableMapToOptions(Map<String, Object> properties) {
Options options = new Options();
if (properties != null) {
for (Map.Entry<String, Object> entry : properties.entrySet()) {
String keyName = entry.getKey();
if (keyName.equals("context") && entry.getValue() != null) {
Map<String, Object> contexts = (Map) entry.getValue();
for (Map.Entry<String, Object> context : contexts.entrySet()) {
options.putContext(context.getKey(), context.getValue());
}
} else if (keyName.equals("integrations") && entry.getValue() != null) {
options = addIntegrationsToOptions(options, (Map) entry.getValue());
}
}
}
return options;
}
private static Options addIntegrationsToOptions(Options options, Map<String,Object> integrations) {
for (Map.Entry<String, Object> integration : integrations.entrySet()) {
String integrationKey = integration.getKey();
if (integration.getValue() instanceof Map) {
Map integrationOptions = (Map) integration.getValue();
if (integrationOptions.get("enabled") instanceof Boolean) {
boolean enabled = (Boolean) integrationOptions.get("enabled");
options.setIntegration(integrationKey, enabled);
} else if (integrationOptions.get("enabled") instanceof String) {
String enabled = (String) integrationOptions.get("enabled");
options.setIntegration(integrationKey, Boolean.valueOf(enabled));
}
if (integrationOptions.get("options") instanceof Map) {
Map<String, Object> jsonOptions = coalesceAnonymousMapToJsonObject((Map) integrationOptions.get("options"));
options.setIntegrationOptions(integrationKey, jsonOptions);
}
}
}
return options;
}
private static Properties readableMapToProperties(Map<String, Object> properties) {
Properties result = new Properties();
for (String key : properties.keySet()) {
Object value = properties.get(key);
if (value instanceof Map) {
result.put(key, coalesceAnonymousMapToJsonObject((Map) value));
} else {
result.put(key, value);
}
}
return result;
}
@Override
public String getName() {
return NAME;
}
@ExpoMethod
public void initialize(final String writeKey, Promise promise) {
Analytics.Builder builder = new Analytics.Builder(mContext, writeKey);
builder.tag(Integer.toString(sCurrentTag++));
builder.use(FirebaseIntegration.FACTORY);
mClient = builder.build();
mClient.optOut(!getEnabledPreferenceValue());
promise.resolve(null);
}
@ExpoMethod
public void identify(final String userId, Promise promise) {
if (mClient != null) {
mClient.identify(userId);
}
promise.resolve(null);
}
@ExpoMethod
public void identifyWithTraits(final String userId, final Map<String, Object> properties, @Nullable final Map<String, Object> options, Promise promise) {
if (mClient != null) {
mClient.identify(userId, readableMapToTraits(properties), readableMapToOptions(options));
}
promise.resolve(null);
}
@ExpoMethod
public void track(final String eventName, Promise promise) {
if (mClient != null) {
mClient.track(eventName);
}
promise.resolve(null);
}
@ExpoMethod
public void trackWithProperties(final String eventName, final Map<String, Object> properties, @Nullable final Map<String, Object> options, Promise promise) {
if (mClient != null) {
mClient.track(eventName, readableMapToProperties(properties), readableMapToOptions(options));
}
promise.resolve(null);
}
@ExpoMethod
public void alias(final String newId, final Map<String, Object> options, Promise promise) {
Analytics client = mClient;
if (client != null) {
client.alias(newId, readableMapToOptions(options));
promise.resolve(null);
} else {
promise.reject("E_NO_SEG", "Segment instance has not been initialized yet, have you tried calling Segment.initialize prior to calling Segment.alias?");
}
}
@ExpoMethod
public void group(final String groupId, Promise promise) {
if (mClient != null) {
mClient.group(groupId);
}
promise.resolve(null);
}
@ExpoMethod
public void groupWithTraits(final String groupId, final Map<String, Object> properties, @Nullable final Map<String, Object> options, Promise promise) {
if (mClient != null) {
mClient.group(groupId, readableMapToTraits(properties), readableMapToOptions(options));
}
promise.resolve(null);
}
@ExpoMethod
public void screen(final String screenName, Promise promise) {
if (mClient != null) {
mClient.screen(screenName);
}
promise.resolve(null);
}
@ExpoMethod
public void screenWithProperties(final String screenName, final Map<String, Object> properties, @Nullable final Map<String, Object> options, Promise promise) {
if (mClient != null) {
mClient.screen(null, screenName, readableMapToProperties(properties), readableMapToOptions(options));
}
promise.resolve(null);
}
@ExpoMethod
public void flush(Promise promise) {
if (mClient != null) {
mClient.flush();
}
promise.resolve(null);
}
@ExpoMethod
public void reset(Promise promise) {
if (mClient != null) {
mClient.reset();
}
promise.resolve(null);
}
@ExpoMethod
public void getEnabledAsync(final Promise promise) {
promise.resolve(getEnabledPreferenceValue());
}
@ExpoMethod
public void setEnabledAsync(final boolean enabled, final Promise promise) {
if (mConstants.getAppOwnership().equals("expo")) {
promise.reject("E_UNSUPPORTED", "Setting Segment's `enabled` is not supported in Expo Go.");
return;
}
mSharedPreferences.edit().putBoolean(ENABLED_PREFERENCE_KEY, enabled).apply();
if (mClient != null) {
mClient.optOut(!enabled);
}
promise.resolve(null);
}
@Override
public void onCreate(ModuleRegistry moduleRegistry) {
mConstants = null;
if (moduleRegistry != null) {
mConstants = moduleRegistry.getModule(ConstantsInterface.class);
}
}
private boolean getEnabledPreferenceValue() {
return mSharedPreferences.getBoolean(ENABLED_PREFERENCE_KEY, true);
}
}
|
exponent/exponent
|
android/versioned-abis/expoview-abi41_0_0/src/main/java/abi41_0_0/expo/modules/analytics/segment/SegmentModule.java
|
Java
|
bsd-3-clause
| 9,079 |
// 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 "third_party/blink/renderer/platform/graphics/dark_mode_color_classifier.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/dark_mode_settings.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/skia/include/core/SkColor.h"
namespace blink {
namespace {
Color GetColorWithBrightness(int target_brightness) {
CHECK_GE(target_brightness, 0);
CHECK_LE(target_brightness, 256);
return Color(target_brightness, target_brightness, target_brightness);
}
TEST(DarkModeColorClassifierTest, ApplyFilterToDarkTextOnly) {
DarkModeSettings settings;
settings.mode = DarkModeInversionAlgorithm::kSimpleInvertForTesting;
settings.text_brightness_threshold = 200;
auto classifier = DarkModeColorClassifier::MakeTextColorClassifier(settings);
// Verify that the following are inverted:
// * black text
// * text darker than the text brightness threshold
// and the following are not inverted:
// * white text
// * text brighter than the text brightness threshold
// * text at the brightness threshold
EXPECT_EQ(DarkModeClassification::kApplyFilter,
classifier->ShouldInvertColor(GetColorWithBrightness(
settings.text_brightness_threshold - 5)));
EXPECT_EQ(DarkModeClassification::kApplyFilter,
classifier->ShouldInvertColor(Color::kBlack));
EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter,
classifier->ShouldInvertColor(Color::kWhite));
EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter,
classifier->ShouldInvertColor(GetColorWithBrightness(
settings.text_brightness_threshold + 5)));
EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter,
classifier->ShouldInvertColor(
GetColorWithBrightness(settings.text_brightness_threshold)));
}
TEST(DarkModeColorClassifierTest, ApplyFilterToLightBackgroundElementsOnly) {
DarkModeSettings settings;
settings.mode = DarkModeInversionAlgorithm::kSimpleInvertForTesting;
settings.background_brightness_threshold = 200;
auto classifier =
DarkModeColorClassifier::MakeBackgroundColorClassifier(settings);
EXPECT_EQ(DarkModeClassification::kApplyFilter,
classifier->ShouldInvertColor(Color::kWhite));
EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter,
classifier->ShouldInvertColor(Color::kBlack));
EXPECT_EQ(DarkModeClassification::kApplyFilter,
classifier->ShouldInvertColor(GetColorWithBrightness(
settings.background_brightness_threshold + 5)));
EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter,
classifier->ShouldInvertColor(GetColorWithBrightness(
settings.background_brightness_threshold)));
EXPECT_EQ(DarkModeClassification::kDoNotApplyFilter,
classifier->ShouldInvertColor(GetColorWithBrightness(
settings.background_brightness_threshold - 5)));
}
} // namespace
} // namespace blink
|
endlessm/chromium-browser
|
third_party/blink/renderer/platform/graphics/dark_mode_color_classifier_test.cc
|
C++
|
bsd-3-clause
| 3,260 |
/*
* Copyright (C) 2012 Adobe Systems Incorporated. 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 HOLDER "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 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 "third_party/blink/renderer/core/css/basic_shape_functions.h"
#include "third_party/blink/renderer/core/css/css_basic_shape_values.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
#include "third_party/blink/renderer/core/css/css_ray_value.h"
#include "third_party/blink/renderer/core/css/css_value_pair.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
#include "third_party/blink/renderer/core/style/basic_shapes.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/style_ray.h"
namespace blink {
static StyleRay::RaySize KeywordToRaySize(CSSValueID id) {
switch (id) {
case CSSValueID::kClosestSide:
return StyleRay::RaySize::kClosestSide;
case CSSValueID::kClosestCorner:
return StyleRay::RaySize::kClosestCorner;
case CSSValueID::kFarthestSide:
return StyleRay::RaySize::kFarthestSide;
case CSSValueID::kFarthestCorner:
return StyleRay::RaySize::kFarthestCorner;
case CSSValueID::kSides:
return StyleRay::RaySize::kSides;
default:
NOTREACHED();
return StyleRay::RaySize::kClosestSide;
}
}
static CSSValueID RaySizeToKeyword(StyleRay::RaySize size) {
switch (size) {
case StyleRay::RaySize::kClosestSide:
return CSSValueID::kClosestSide;
case StyleRay::RaySize::kClosestCorner:
return CSSValueID::kClosestCorner;
case StyleRay::RaySize::kFarthestSide:
return CSSValueID::kFarthestSide;
case StyleRay::RaySize::kFarthestCorner:
return CSSValueID::kFarthestCorner;
case StyleRay::RaySize::kSides:
return CSSValueID::kSides;
}
NOTREACHED();
return CSSValueID::kInvalid;
}
static CSSValue* ValueForCenterCoordinate(
const ComputedStyle& style,
const BasicShapeCenterCoordinate& center,
EBoxOrient orientation) {
if (center.GetDirection() == BasicShapeCenterCoordinate::kTopLeft)
return CSSValue::Create(center.length(), style.EffectiveZoom());
CSSValueID keyword = orientation == EBoxOrient::kHorizontal
? CSSValueID::kRight
: CSSValueID::kBottom;
return MakeGarbageCollected<CSSValuePair>(
CSSIdentifierValue::Create(keyword),
CSSValue::Create(center.length(), style.EffectiveZoom()),
CSSValuePair::kDropIdenticalValues);
}
static CSSValuePair* ValueForLengthSize(const LengthSize& length_size,
const ComputedStyle& style) {
return MakeGarbageCollected<CSSValuePair>(
CSSValue::Create(length_size.Width(), style.EffectiveZoom()),
CSSValue::Create(length_size.Height(), style.EffectiveZoom()),
CSSValuePair::kKeepIdenticalValues);
}
static CSSValue* BasicShapeRadiusToCSSValue(const ComputedStyle& style,
const BasicShapeRadius& radius) {
switch (radius.GetType()) {
case BasicShapeRadius::kValue:
return CSSValue::Create(radius.Value(), style.EffectiveZoom());
case BasicShapeRadius::kClosestSide:
return CSSIdentifierValue::Create(CSSValueID::kClosestSide);
case BasicShapeRadius::kFarthestSide:
return CSSIdentifierValue::Create(CSSValueID::kFarthestSide);
}
NOTREACHED();
return nullptr;
}
CSSValue* ValueForBasicShape(const ComputedStyle& style,
const BasicShape* basic_shape) {
switch (basic_shape->GetType()) {
case BasicShape::kStyleRayType: {
const StyleRay& ray = To<StyleRay>(*basic_shape);
return MakeGarbageCollected<cssvalue::CSSRayValue>(
*CSSNumericLiteralValue::Create(
ray.Angle(), CSSPrimitiveValue::UnitType::kDegrees),
*CSSIdentifierValue::Create(RaySizeToKeyword(ray.Size())),
(ray.Contain() ? CSSIdentifierValue::Create(CSSValueID::kContain)
: nullptr));
}
case BasicShape::kStylePathType:
return To<StylePath>(basic_shape)->ComputedCSSValue();
case BasicShape::kBasicShapeCircleType: {
const BasicShapeCircle* circle = To<BasicShapeCircle>(basic_shape);
cssvalue::CSSBasicShapeCircleValue* circle_value =
MakeGarbageCollected<cssvalue::CSSBasicShapeCircleValue>();
circle_value->SetCenterX(ValueForCenterCoordinate(
style, circle->CenterX(), EBoxOrient::kHorizontal));
circle_value->SetCenterY(ValueForCenterCoordinate(
style, circle->CenterY(), EBoxOrient::kVertical));
circle_value->SetRadius(
BasicShapeRadiusToCSSValue(style, circle->Radius()));
return circle_value;
}
case BasicShape::kBasicShapeEllipseType: {
const BasicShapeEllipse* ellipse = To<BasicShapeEllipse>(basic_shape);
auto* ellipse_value =
MakeGarbageCollected<cssvalue::CSSBasicShapeEllipseValue>();
ellipse_value->SetCenterX(ValueForCenterCoordinate(
style, ellipse->CenterX(), EBoxOrient::kHorizontal));
ellipse_value->SetCenterY(ValueForCenterCoordinate(
style, ellipse->CenterY(), EBoxOrient::kVertical));
ellipse_value->SetRadiusX(
BasicShapeRadiusToCSSValue(style, ellipse->RadiusX()));
ellipse_value->SetRadiusY(
BasicShapeRadiusToCSSValue(style, ellipse->RadiusY()));
return ellipse_value;
}
case BasicShape::kBasicShapePolygonType: {
const BasicShapePolygon* polygon = To<BasicShapePolygon>(basic_shape);
auto* polygon_value =
MakeGarbageCollected<cssvalue::CSSBasicShapePolygonValue>();
polygon_value->SetWindRule(polygon->GetWindRule());
const Vector<Length>& values = polygon->Values();
for (unsigned i = 0; i < values.size(); i += 2) {
polygon_value->AppendPoint(
CSSPrimitiveValue::CreateFromLength(values.at(i),
style.EffectiveZoom()),
CSSPrimitiveValue::CreateFromLength(values.at(i + 1),
style.EffectiveZoom()));
}
return polygon_value;
}
case BasicShape::kBasicShapeInsetType: {
const BasicShapeInset* inset = To<BasicShapeInset>(basic_shape);
auto* inset_value =
MakeGarbageCollected<cssvalue::CSSBasicShapeInsetValue>();
inset_value->SetTop(CSSPrimitiveValue::CreateFromLength(
inset->Top(), style.EffectiveZoom()));
inset_value->SetRight(CSSPrimitiveValue::CreateFromLength(
inset->Right(), style.EffectiveZoom()));
inset_value->SetBottom(CSSPrimitiveValue::CreateFromLength(
inset->Bottom(), style.EffectiveZoom()));
inset_value->SetLeft(CSSPrimitiveValue::CreateFromLength(
inset->Left(), style.EffectiveZoom()));
inset_value->SetTopLeftRadius(
ValueForLengthSize(inset->TopLeftRadius(), style));
inset_value->SetTopRightRadius(
ValueForLengthSize(inset->TopRightRadius(), style));
inset_value->SetBottomRightRadius(
ValueForLengthSize(inset->BottomRightRadius(), style));
inset_value->SetBottomLeftRadius(
ValueForLengthSize(inset->BottomLeftRadius(), style));
return inset_value;
}
default:
return nullptr;
}
}
static Length ConvertToLength(const StyleResolverState& state,
const CSSPrimitiveValue* value) {
if (!value)
return Length::Fixed(0);
return value->ConvertToLength(state.CssToLengthConversionData());
}
static LengthSize ConvertToLengthSize(const StyleResolverState& state,
const CSSValuePair* value) {
if (!value)
return LengthSize(Length::Fixed(0), Length::Fixed(0));
return LengthSize(
ConvertToLength(state, &To<CSSPrimitiveValue>(value->First())),
ConvertToLength(state, &To<CSSPrimitiveValue>(value->Second())));
}
static BasicShapeCenterCoordinate ConvertToCenterCoordinate(
const StyleResolverState& state,
CSSValue* value) {
BasicShapeCenterCoordinate::Direction direction;
Length offset = Length::Fixed(0);
CSSValueID keyword = CSSValueID::kTop;
if (!value) {
keyword = CSSValueID::kCenter;
} else if (auto* identifier_value = DynamicTo<CSSIdentifierValue>(value)) {
keyword = identifier_value->GetValueID();
} else if (auto* value_pair = DynamicTo<CSSValuePair>(value)) {
keyword = To<CSSIdentifierValue>(value_pair->First()).GetValueID();
offset =
ConvertToLength(state, &To<CSSPrimitiveValue>(value_pair->Second()));
} else {
offset = ConvertToLength(state, To<CSSPrimitiveValue>(value));
}
switch (keyword) {
case CSSValueID::kTop:
case CSSValueID::kLeft:
direction = BasicShapeCenterCoordinate::kTopLeft;
break;
case CSSValueID::kRight:
case CSSValueID::kBottom:
direction = BasicShapeCenterCoordinate::kBottomRight;
break;
case CSSValueID::kCenter:
direction = BasicShapeCenterCoordinate::kTopLeft;
offset = Length::Percent(50);
break;
default:
NOTREACHED();
direction = BasicShapeCenterCoordinate::kTopLeft;
break;
}
return BasicShapeCenterCoordinate(direction, offset);
}
static BasicShapeRadius CssValueToBasicShapeRadius(
const StyleResolverState& state,
const CSSValue* radius) {
if (!radius)
return BasicShapeRadius(BasicShapeRadius::kClosestSide);
if (auto* radius_identifier_value = DynamicTo<CSSIdentifierValue>(radius)) {
switch (radius_identifier_value->GetValueID()) {
case CSSValueID::kClosestSide:
return BasicShapeRadius(BasicShapeRadius::kClosestSide);
case CSSValueID::kFarthestSide:
return BasicShapeRadius(BasicShapeRadius::kFarthestSide);
default:
NOTREACHED();
break;
}
}
return BasicShapeRadius(
ConvertToLength(state, To<CSSPrimitiveValue>(radius)));
}
scoped_refptr<BasicShape> BasicShapeForValue(
const StyleResolverState& state,
const CSSValue& basic_shape_value) {
scoped_refptr<BasicShape> basic_shape;
if (IsA<cssvalue::CSSBasicShapeCircleValue>(basic_shape_value)) {
const auto& circle_value =
To<cssvalue::CSSBasicShapeCircleValue>(basic_shape_value);
scoped_refptr<BasicShapeCircle> circle = BasicShapeCircle::Create();
circle->SetCenterX(
ConvertToCenterCoordinate(state, circle_value.CenterX()));
circle->SetCenterY(
ConvertToCenterCoordinate(state, circle_value.CenterY()));
circle->SetRadius(CssValueToBasicShapeRadius(state, circle_value.Radius()));
basic_shape = std::move(circle);
} else if (IsA<cssvalue::CSSBasicShapeEllipseValue>(basic_shape_value)) {
const auto& ellipse_value =
To<cssvalue::CSSBasicShapeEllipseValue>(basic_shape_value);
scoped_refptr<BasicShapeEllipse> ellipse = BasicShapeEllipse::Create();
ellipse->SetCenterX(
ConvertToCenterCoordinate(state, ellipse_value.CenterX()));
ellipse->SetCenterY(
ConvertToCenterCoordinate(state, ellipse_value.CenterY()));
ellipse->SetRadiusX(
CssValueToBasicShapeRadius(state, ellipse_value.RadiusX()));
ellipse->SetRadiusY(
CssValueToBasicShapeRadius(state, ellipse_value.RadiusY()));
basic_shape = std::move(ellipse);
} else if (IsA<cssvalue::CSSBasicShapePolygonValue>(basic_shape_value)) {
const cssvalue::CSSBasicShapePolygonValue& polygon_value =
To<cssvalue::CSSBasicShapePolygonValue>(basic_shape_value);
scoped_refptr<BasicShapePolygon> polygon = BasicShapePolygon::Create();
polygon->SetWindRule(polygon_value.GetWindRule());
const HeapVector<Member<CSSPrimitiveValue>>& values =
polygon_value.Values();
for (unsigned i = 0; i < values.size(); i += 2)
polygon->AppendPoint(ConvertToLength(state, values.at(i).Get()),
ConvertToLength(state, values.at(i + 1).Get()));
basic_shape = std::move(polygon);
} else if (IsA<cssvalue::CSSBasicShapeInsetValue>(basic_shape_value)) {
const cssvalue::CSSBasicShapeInsetValue& rect_value =
To<cssvalue::CSSBasicShapeInsetValue>(basic_shape_value);
scoped_refptr<BasicShapeInset> rect = BasicShapeInset::Create();
rect->SetTop(ConvertToLength(state, rect_value.Top()));
rect->SetRight(ConvertToLength(state, rect_value.Right()));
rect->SetBottom(ConvertToLength(state, rect_value.Bottom()));
rect->SetLeft(ConvertToLength(state, rect_value.Left()));
rect->SetTopLeftRadius(
ConvertToLengthSize(state, rect_value.TopLeftRadius()));
rect->SetTopRightRadius(
ConvertToLengthSize(state, rect_value.TopRightRadius()));
rect->SetBottomRightRadius(
ConvertToLengthSize(state, rect_value.BottomRightRadius()));
rect->SetBottomLeftRadius(
ConvertToLengthSize(state, rect_value.BottomLeftRadius()));
basic_shape = std::move(rect);
} else if (const auto* ray_value =
DynamicTo<cssvalue::CSSRayValue>(basic_shape_value)) {
float angle = ray_value->Angle().ComputeDegrees();
StyleRay::RaySize size = KeywordToRaySize(ray_value->Size().GetValueID());
bool contain = !!ray_value->Contain();
basic_shape = StyleRay::Create(angle, size, contain);
} else {
NOTREACHED();
}
return basic_shape;
}
FloatPoint FloatPointForCenterCoordinate(
const BasicShapeCenterCoordinate& center_x,
const BasicShapeCenterCoordinate& center_y,
FloatSize box_size) {
float x = FloatValueForLength(center_x.ComputedLength(), box_size.Width());
float y = FloatValueForLength(center_y.ComputedLength(), box_size.Height());
return FloatPoint(x, y);
}
} // namespace blink
|
endlessm/chromium-browser
|
third_party/blink/renderer/core/css/basic_shape_functions.cc
|
C++
|
bsd-3-clause
| 15,126 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# rfMHC documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import rfMHC
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'rfMHC'
copyright = u'2014, David Olivieri'
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = rfMHC.__version__
# The full version, including alpha/beta/rc tags.
release = rfMHC.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'rfMHCdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'rfMHC.tex',
u'rfMHC Documentation',
u'David Olivieri', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'rfMHC',
u'rfMHC Documentation',
[u'David Olivieri'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'rfMHC',
u'rfMHC Documentation',
u'David Olivieri',
'rfMHC',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
|
dnolivieri/rfMHC
|
docs/conf.py
|
Python
|
bsd-3-clause
| 8,369 |
class GameValidPolicy
include Wisper::Publisher
def initialize(game:)
@game = game
@errors = []
end
# Policy for determining if the game is valid
# The game is valid provided:
# 1) the game only ever has at most 1 criminal,
# 2) the game only ever has at most Game::NUMBER_OF_PLAYERS and,
# 3) if the game has Game::NUMBER_OF_PLAYERS, then the game has exactly 1 criminal
def valid?
check_player_count_is_valid
check_player_types_are_valid
publish(:fail, @errors) if @errors.any?
@errors.empty?
end
private
def check_player_count_is_valid
if @game.players.length > Game::NUMBER_OF_PLAYERS
@errors << "Game must have #{Game::NUMBER_OF_PLAYERS} or less players"
end
end
def check_player_types_are_valid
unless player_types_are_valid
@errors << 'Game may only have 1 criminal'
end
end
def player_types_are_valid
if @game.players.length < Game::NUMBER_OF_PLAYERS
!@game.players.many?(&:criminal?)
else
@game.players.one?(&:criminal?)
end
end
end
|
hjwylde/scotland-yard
|
app/policies/game_valid_policy.rb
|
Ruby
|
bsd-3-clause
| 1,062 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ABI40_0_0Props.h"
#include <folly/dynamic.h>
#include <ABI40_0_0React/core/propsConversions.h>
namespace ABI40_0_0facebook {
namespace ABI40_0_0React {
Props::Props(const Props &sourceProps, const RawProps &rawProps)
: nativeId(convertRawProp(rawProps, "nativeID", sourceProps.nativeId, {})),
revision(sourceProps.revision + 1)
#ifdef ANDROID
,
rawProps((folly::dynamic)rawProps)
#endif
{};
} // namespace ABI40_0_0React
} // namespace ABI40_0_0facebook
|
exponent/exponent
|
ios/versioned-react-native/ABI40_0_0/ReactNative/ReactCommon/fabric/core/shadownode/ABI40_0_0Props.cpp
|
C++
|
bsd-3-clause
| 689 |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\PagosPrestamos;
/**
* PagosPrestamosSearch represents the model behind the search form about `app\models\PagosPrestamos`.
*/
class PagosPrestamosSearch extends PagosPrestamos
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id_pagos', 'id_prestamo'], 'integer'],
[['capital', 'valor_cuota', 'interes', 'amortizacion'], 'number'],
[['fecha'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params,$id_prestamo)
{
$query = PagosPrestamos::find()->where('id_prestamo=:id');
$query->addParams([':id' => $id_prestamo]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'id_pagos' => $this->id_pagos,
'capital' => $this->capital,
'valor_cuota' => $this->valor_cuota,
'fecha' => $this->fecha,
'id_prestamo' => $this->id_prestamo,
'interes' => $this->interes,
'amortizacion' => $this->amortizacion,
]);
return $dataProvider;
}
}
|
oswen244/proserpaz
|
models/PagosPrestamosSearch.php
|
PHP
|
bsd-3-clause
| 1,662 |
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160130_212648_add_enrollment_to_student extends Migration
{
public function up()
{
$this->addColumn('student', 'enrollment_id', $this->string());
}
public function down()
{
echo "m160130_212648_add_enrollment_to_student cannot be reverted.\n";
return false;
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
|
RomarioLopezC/RobotSS
|
migrations/m160130_212648_add_enrollment_to_student.php
|
PHP
|
bsd-3-clause
| 538 |
$(document).ready(function(){
// Navigation
var body_class = document.body.className;
var hover_on_bg = "#c00";
var hover_on_co = "#fff";
var hover_off_bg = "#fff";
var hover_off_co = "#444";
var hover_delay = 200;
$("#navigation li a").removeClass("hover");
$("#navigation li").each(function(){
if (this.className == body_class) {
$('a', this).addClass("hover");
} else {
$(this).hover(function(){
$('a', this).stop().animate({ backgroundColor: hover_on_bg, color: hover_on_co }, hover_delay);
}, function(){
$('a', this).stop().animate({ backgroundColor: hover_off_bg, color: hover_off_co }, hover_delay);
});
$(this).focus(function(){
$('a', this).stop().animate({ backgroundColor: hover_on_bg, color: hover_on_co }, hover_delay);
}, function(){
$('a', this).stop().animate({ backgroundColor: hover_off_bg, color: hover_off_co }, hover_delay);
});
}
});
// About page first paragraph and clincher
$("body.about div#article p:first").addClass("first");
$("body.about div#article p:last").append("<span class=\"clincher\">■</span>");
});
// E-mail address DOM insertion
function email(email){
$("body.about div#article h4:eq(1)").before("<p><strong><a href=\"mailto:" + email + "\">" + email + "</a></strong></p>");
}
|
richardcornish/cyndiloza
|
cyndiloza/static/js/site.js
|
JavaScript
|
bsd-3-clause
| 1,360 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace vLogs.Objects.KeyValues
{
/// <summary>
/// Represents a collection of key/value pairs. This class cannot be inherited.
/// </summary>
public sealed class KeyValueCollection
: IList<KeyValuePair>
{
private KeyValuePair[] _arr;
int count = 0;
bool locked = false;
private void _Double()
{
var temp = _arr;
_arr = new KeyValuePair[temp.Length * 2];
Array.Copy(temp, _arr, temp.Length);
}
#region IList<KeyValuePair> Members
/// <summary>
/// Determines the index of a specific key/value pair in the collection.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">Thrown when the given item is null.</exception>
public int IndexOf(KeyValuePair item)
{
if (item == null)
throw new ArgumentNullException("item");
for (int i = 0; i < count; i++)
if (_arr[i] == item)
return i;
return -1;
}
/// <summary>
/// Inserts a key/value pair to the collection at the specified index.
/// </summary>
/// <param name="index"></param>
/// <param name="item"></param>
/// <exception cref="System.ArgumentNullException">Thrown when the given item is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown when the given index is negative or greater than the number of items in the collection.</exception>
/// <exception cref="System.InvalidOperationException">Thrown when the collection is locked (read-only).</exception>
public void Insert(int index, KeyValuePair item)
{
if (locked)
throw new InvalidOperationException("The collection is locked (read-only).");
if (index < 0 || index > count)
throw new ArgumentOutOfRangeException("index", "Given index must not be nagative or greater than the number of items in the collection.");
if (item == null)
throw new ArgumentNullException("item");
for (int i = 0; i < count; i++)
if (_arr[i].Key == item.Key)
throw new ArgumentException("A key/value pair with the key of the given item already exists in the collection.");
if (count == _arr.Length)
_Double();
for (int i = count; i > index; i--)
_arr[i] = _arr[i - 1];
_arr[index] = item;
count++;
}
/// <summary>
/// Removes the key/value pair at the specified index.
/// </summary>
/// <param name="index"></param>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown when the given index is negative or greater than or equal to the number of items in the collection.</exception>
/// <exception cref="System.InvalidOperationException">Thrown when the collection is locked (read-only).</exception>
public void RemoveAt(int index)
{
if (locked)
throw new InvalidOperationException("The collection is locked (read-only).");
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException("index", "Given index must be positive and less than the number of items in the collection.");
for (int i = index; i < count - 1; i++)
_arr[i] = _arr[i + 1];
_arr[count - 1] = null;
count--;
}
/// <summary>
/// Gets or sets the key/value pair at the specified index.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">Thrown when the given value is null.</exception>
/// <exception cref="System.IndexOutOfRangeException">Thrown when the given index is negative or greater than or equal to the number of items in the collection.</exception>
/// <exception cref="System.InvalidOperationException">Thrown when setting and the collection is locked (read-only).</exception>
public KeyValuePair this[int index]
{
get
{
if (index < 0 || index > count)
throw new IndexOutOfRangeException("Given index must be positive and less than the number of items in the collection.");
return _arr[index];
}
set
{
if (locked)
throw new InvalidOperationException("The collection is locked (read-only).");
if (index < 0 || index > count)
throw new IndexOutOfRangeException("Given index must be positive and less than the number of items in the collection.");
if (value == null)
throw new ArgumentNullException("value");
for (int i = 0; i < count; i++)
if (i != index && _arr[i].Key == value.Key)
throw new ArgumentException("A key/value pair with the key of the given item already exists in the collection.");
_arr[index] = value;
}
}
#endregion
#region ICollection<KeyValuePair> Members
/// <summary>
/// Adds a key/value pair to the collection.
/// </summary>
/// <param name="item"></param>
/// <exception cref="System.ArgumentNullException">Thrown when the given item is null.</exception>
/// <exception cref="System.InvalidOperationException">Thrown when the collection is locked (read-only).</exception>
public void Add(KeyValuePair item)
{
if (locked)
throw new InvalidOperationException("The collection is locked (read-only).");
if (item == null)
throw new ArgumentNullException("item");
for (int i = 0; i < count; i++)
if (_arr[i].Key == item.Key)
throw new ArgumentException("A key/value pair with the key of the given item already exists in the collection.");
if (count == _arr.Length)
_Double();
_arr[count] = item;
count++;
}
/// <summary>
/// Removes all key/value pairs from the collection.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown when the collection is locked (read-only).</exception>
public void Clear()
{
if (locked)
throw new InvalidOperationException("The collection is locked (read-only).");
for (int i = 0; i < count; i++)
_arr[i] = null;
count = 0;
}
/// <summary>
/// Determines whether the collection contains a specific key/value pair.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">Thrown when the given item is null.</exception>
public bool Contains(KeyValuePair item)
{
if (item == null)
throw new ArgumentNullException("item");
for (int i = 0; i < count; i++)
if (_arr[i] == item)
return true;
return false;
}
/// <summary>
/// Copies the elements of the collection to an <see cref="System.Array"/>, starting at a particular index.
/// </summary>
/// <param name="array"></param>
/// <param name="arrayIndex"></param>
/// <exception cref="System.ArgumentNullException">Thrown when the given array is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown when the given array index is negative or would not leave enough room to copy all the items in the collection to the destination array.</exception>
public void CopyTo(KeyValuePair[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0 || arrayIndex >= array.Length - count)
throw new ArgumentOutOfRangeException("arrayIndex", "Given index must be positive and must allow room for all pairs in the collection for copying.");
Array.Copy(_arr, 0, array, arrayIndex, count);
}
/// <summary>
/// Gets the number of elements contained in the collection.
/// </summary>
public int Count
{
get { return count; }
}
/// <summary>
/// Gets a value indicating whether the collection is read-only.
/// </summary>
public bool IsReadOnly
{
get { return locked; }
}
/// <summary>
/// Removes the specific key/value pair from the collection.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">Thrown when the given item is null.</exception>
/// <exception cref="System.InvalidOperationException">Thrown when the collection is locked (read-only).</exception>
public bool Remove(KeyValuePair item)
{
if (locked)
throw new InvalidOperationException("The collection is locked (read-only).");
for (int j = 0; j < count; j++)
if (_arr[j] == item)
{
for (int i = j; i < count - 1; i++)
_arr[i] = _arr[i + 1];
_arr[count - 1] = null;
count--;
return true;
}
return false;
}
#endregion
#region IEnumerable<KeyValuePair> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns></returns>
public IEnumerator<KeyValuePair> GetEnumerator()
{
for (int i = 0; i < count; i++)
yield return _arr[i];
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
for (int i = 0; i < count; i++)
yield return _arr[i];
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="vLogs.Objects.KeyValues.KeyValueCollection"/> class.
/// </summary>
public KeyValueCollection()
{
this._arr = new KeyValuePair[2];
}
/// <summary>
/// Initializes a new instance of the <see cref="vLogs.Objects.KeyValues.KeyValueCollection"/> class from the given enumeration of <see cref="vLogs.Objects.KeyValues.KeyValuePair"/>s and an optional indication whether the collection should be locked or not.
/// </summary>
/// <param name="kvps"></param>
/// <param name="locked">optional; True to lock the collection (making it read-only); otherwise false.</param>
/// <exception cref="System.ArgumentNullException">Thrown when the given enumeration is null.</exception>
/// <exception cref="System.ArgumentException">Thrown when the given enumeration contains two pairs with the same key.</exception>
public KeyValueCollection(IEnumerable<KeyValuePair> kvps, bool locked = false)
{
if (kvps == null)
throw new ArgumentNullException("kvps");
this._arr = kvps.ToArray();
this.count = this._arr.Length;
for (int i = 0; i < count; i++)
for (int j = 0; j < count; j++)
if (i != j && this._arr[i].Key == this._arr[j].Key)
throw new ArgumentException("The given enumeration of key/value pairs contains two pairs with the same key.");
if (count == 0)
this._arr = new KeyValuePair[2];
this.locked = locked;
}
/// <summary>
/// Initializes a new instance of the <see cref="vLogs.Objects.KeyValues.KeyValueCollection"/> class from the given enumeration of <see cref="vLogs.Objects.KeyValues.KeyValuePair"/>s and an optional indication whether the collection should be locked or not.
/// </summary>
/// <param name="locked">True to lock the collection (making it read-only); otherwise false.</param>
/// <param name="kvps"></param>
/// <exception cref="System.ArgumentNullException">Thrown when the given enumeration is null.</exception>
/// <exception cref="System.ArgumentException">Thrown when the given array contains two pairs with the same key.</exception>
public KeyValueCollection(bool locked, params KeyValuePair[] kvps)
{
if (kvps == null)
throw new ArgumentNullException("kvps");
for (int i = 0; i < kvps.Length; i++)
for (int j = 0; j < kvps.Length; j++)
if (i != j && kvps[i].Key == kvps[j].Key)
throw new ArgumentException("The given enumeration of key/value pairs contains two pairs with the same key.");
this.count = kvps.Length;
this._arr = new KeyValuePair[this.count];
if (this.count == 0)
this._arr = new KeyValuePair[2];
else
Array.Copy(kvps, this._arr, this.count);
this.locked = locked;
}
#endregion
/// <summary>
/// Locks the collection, making it read-only.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown when the collection is already locked (read-only).</exception>
public void Lock()
{
if (this.locked)
throw new InvalidOperationException("The collection is already locked.");
this.locked = true;
}
}
}
|
vercas/vLogs
|
vLogs/Objects/KeyValues/KeyValue Collection.cs
|
C#
|
bsd-3-clause
| 14,660 |
# frozen_string_literal: true
# rubocop:disable Metrics/BlockLength
require 'spec_helper'
describe JsonValidator do
describe :validate_each do
before do
run_migration do
create_table(:users, force: true) do |t|
t.text :data
end
end
spawn_model 'User' do
schema = '
{
"type": "object",
"properties": {
"city": { "type": "string" },
"country": { "type": "string" }
},
"required": ["country"]
}
'
serialize :data, JSON
validates :data, json: { schema: schema, message: ->(errors) { errors.map { |error| error['details'].to_a.flatten.join(' ') } } }
end
end
context 'with valid JSON data but schema errors' do
let(:user) { User.new(data: '{"city":"Quebec City"}') }
specify do
expect(user).not_to be_valid
expect(user.errors.full_messages).to eql(['Data missing_keys country'])
expect(user.data).to eql({ 'city' => 'Quebec City' })
expect(user.data_invalid_json).to be_nil
end
end
context 'with invalid JSON data' do
let(:data) { 'What? This is not JSON at all.' }
let(:user) { User.new(data: data) }
specify do
expect(user.data_invalid_json).to eql(data)
expect(user.data).to eql({})
end
end
end
describe :schema do
let(:validator) { JsonValidator.new(options) }
let(:options) { { attributes: [:foo], schema: schema_option } }
let(:schema) { validator.send(:schema, record) }
context 'with String schema' do
let(:schema_option) { double(:schema) }
let(:record) { double(:record) }
it { expect(schema).to eql(schema_option) }
end
context 'with Proc schema returning a Proc returning a Proc' do
let(:schema_option) { -> { dynamic_schema } }
let(:record) { record_class.new }
let(:record_class) do
Class.new do
def dynamic_schema
-> { another_dynamic_schema }
end
def another_dynamic_schema
-> { what_another_dynamic_schema }
end
def what_another_dynamic_schema
'yay'
end
end
end
it { expect(schema).to eql('yay') }
end
context 'with Symbol schema' do
let(:schema_option) { :dynamic_schema }
let(:record) { record_class.new }
let(:record_class) do
Class.new do
def dynamic_schema
'foo'
end
end
end
it { expect(schema).to eql('foo') }
end
end
describe :message do
let(:validator) { JsonValidator.new(options) }
let(:options) { { attributes: [:foo], message: message_option } }
let(:message) { validator.send(:message, errors) }
let(:errors) { %i[first_error second_error] }
context 'with Symbol message' do
let(:message_option) { :invalid_json }
it { expect(message).to eql([:invalid_json]) }
end
context 'with String value' do
let(:message_option) { ->(errors) { errors } }
it { expect(message).to eql(%i[first_error second_error]) }
end
end
end
# rubocop:enable Metrics/BlockLength
|
mirego/activerecord_json_validator
|
spec/json_validator_spec.rb
|
Ruby
|
bsd-3-clause
| 3,214 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/server/web_socket_encoder.h"
#include <vector>
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "net/base/io_buffer.h"
#include "net/websockets/websocket_deflate_parameters.h"
#include "net/websockets/websocket_extension.h"
#include "net/websockets/websocket_extension_parser.h"
namespace net {
const char WebSocketEncoder::kClientExtensions[] =
"Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits";
namespace {
const int kInflaterChunkSize = 16 * 1024;
// Constants for hybi-10 frame format.
typedef int OpCode;
const OpCode kOpCodeContinuation = 0x0;
const OpCode kOpCodeText = 0x1;
const OpCode kOpCodeBinary = 0x2;
const OpCode kOpCodeClose = 0x8;
const OpCode kOpCodePing = 0x9;
const OpCode kOpCodePong = 0xA;
const unsigned char kFinalBit = 0x80;
const unsigned char kReserved1Bit = 0x40;
const unsigned char kReserved2Bit = 0x20;
const unsigned char kReserved3Bit = 0x10;
const unsigned char kOpCodeMask = 0xF;
const unsigned char kMaskBit = 0x80;
const unsigned char kPayloadLengthMask = 0x7F;
const size_t kMaxSingleBytePayloadLength = 125;
const size_t kTwoBytePayloadLengthField = 126;
const size_t kEightBytePayloadLengthField = 127;
const size_t kMaskingKeyWidthInBytes = 4;
WebSocket::ParseResult DecodeFrameHybi17(const base::StringPiece& frame,
bool client_frame,
int* bytes_consumed,
std::string* output,
bool* compressed) {
size_t data_length = frame.length();
if (data_length < 2)
return WebSocket::FRAME_INCOMPLETE;
const char* buffer_begin = const_cast<char*>(frame.data());
const char* p = buffer_begin;
const char* buffer_end = p + data_length;
unsigned char first_byte = *p++;
unsigned char second_byte = *p++;
bool final = (first_byte & kFinalBit) != 0;
bool reserved1 = (first_byte & kReserved1Bit) != 0;
bool reserved2 = (first_byte & kReserved2Bit) != 0;
bool reserved3 = (first_byte & kReserved3Bit) != 0;
int op_code = first_byte & kOpCodeMask;
bool masked = (second_byte & kMaskBit) != 0;
*compressed = reserved1;
if (!final || reserved2 || reserved3)
return WebSocket::FRAME_ERROR; // Only compression extension is supported.
bool closed = false;
switch (op_code) {
case kOpCodeClose:
closed = true;
break;
case kOpCodeText:
break;
case kOpCodeBinary: // We don't support binary frames yet.
case kOpCodeContinuation: // We don't support binary frames yet.
case kOpCodePing: // We don't support binary frames yet.
case kOpCodePong: // We don't support binary frames yet.
default:
return WebSocket::FRAME_ERROR;
}
if (client_frame && !masked) // In Hybi-17 spec client MUST mask its frame.
return WebSocket::FRAME_ERROR;
uint64 payload_length64 = second_byte & kPayloadLengthMask;
if (payload_length64 > kMaxSingleBytePayloadLength) {
int extended_payload_length_size;
if (payload_length64 == kTwoBytePayloadLengthField)
extended_payload_length_size = 2;
else {
DCHECK(payload_length64 == kEightBytePayloadLengthField);
extended_payload_length_size = 8;
}
if (buffer_end - p < extended_payload_length_size)
return WebSocket::FRAME_INCOMPLETE;
payload_length64 = 0;
for (int i = 0; i < extended_payload_length_size; ++i) {
payload_length64 <<= 8;
payload_length64 |= static_cast<unsigned char>(*p++);
}
}
size_t actual_masking_key_length = masked ? kMaskingKeyWidthInBytes : 0;
static const uint64 max_payload_length = 0x7FFFFFFFFFFFFFFFull;
static size_t max_length = std::numeric_limits<size_t>::max();
if (payload_length64 > max_payload_length ||
payload_length64 + actual_masking_key_length > max_length) {
// WebSocket frame length too large.
return WebSocket::FRAME_ERROR;
}
size_t payload_length = static_cast<size_t>(payload_length64);
size_t total_length = actual_masking_key_length + payload_length;
if (static_cast<size_t>(buffer_end - p) < total_length)
return WebSocket::FRAME_INCOMPLETE;
if (masked) {
output->resize(payload_length);
const char* masking_key = p;
char* payload = const_cast<char*>(p + kMaskingKeyWidthInBytes);
for (size_t i = 0; i < payload_length; ++i) // Unmask the payload.
(*output)[i] = payload[i] ^ masking_key[i % kMaskingKeyWidthInBytes];
} else {
output->assign(p, p + payload_length);
}
size_t pos = p + actual_masking_key_length + payload_length - buffer_begin;
*bytes_consumed = pos;
return closed ? WebSocket::FRAME_CLOSE : WebSocket::FRAME_OK;
}
void EncodeFrameHybi17(const std::string& message,
int masking_key,
bool compressed,
std::string* output) {
std::vector<char> frame;
OpCode op_code = kOpCodeText;
size_t data_length = message.length();
int reserved1 = compressed ? kReserved1Bit : 0;
frame.push_back(kFinalBit | op_code | reserved1);
char mask_key_bit = masking_key != 0 ? kMaskBit : 0;
if (data_length <= kMaxSingleBytePayloadLength) {
frame.push_back(static_cast<char>(data_length) | mask_key_bit);
} else if (data_length <= 0xFFFF) {
frame.push_back(kTwoBytePayloadLengthField | mask_key_bit);
frame.push_back((data_length & 0xFF00) >> 8);
frame.push_back(data_length & 0xFF);
} else {
frame.push_back(kEightBytePayloadLengthField | mask_key_bit);
char extended_payload_length[8];
size_t remaining = data_length;
// Fill the length into extended_payload_length in the network byte order.
for (int i = 0; i < 8; ++i) {
extended_payload_length[7 - i] = remaining & 0xFF;
remaining >>= 8;
}
frame.insert(frame.end(), extended_payload_length,
extended_payload_length + 8);
DCHECK(!remaining);
}
const char* data = const_cast<char*>(message.data());
if (masking_key != 0) {
const char* mask_bytes = reinterpret_cast<char*>(&masking_key);
frame.insert(frame.end(), mask_bytes, mask_bytes + 4);
for (size_t i = 0; i < data_length; ++i) // Mask the payload.
frame.push_back(data[i] ^ mask_bytes[i % kMaskingKeyWidthInBytes]);
} else {
frame.insert(frame.end(), data, data + data_length);
}
*output = std::string(&frame[0], frame.size());
}
} // anonymous namespace
// static
scoped_ptr<WebSocketEncoder> WebSocketEncoder::CreateServer() {
return make_scoped_ptr(new WebSocketEncoder(FOR_SERVER, nullptr, nullptr));
}
// static
scoped_ptr<WebSocketEncoder> WebSocketEncoder::CreateServer(
const std::string& extensions,
WebSocketDeflateParameters* deflate_parameters) {
WebSocketExtensionParser parser;
if (!parser.Parse(extensions)) {
// Failed to parse Sec-WebSocket-Extensions header. We MUST fail the
// connection.
return nullptr;
}
for (const auto& extension : parser.extensions()) {
std::string failure_message;
WebSocketDeflateParameters offer;
if (!offer.Initialize(extension, &failure_message) ||
!offer.IsValidAsRequest(&failure_message)) {
// We decline unknown / malformed extensions.
continue;
}
WebSocketDeflateParameters response = offer;
if (offer.is_client_max_window_bits_specified() &&
!offer.has_client_max_window_bits_value()) {
// We need to choose one value for the response.
response.SetClientMaxWindowBits(15);
}
DCHECK(response.IsValidAsResponse());
DCHECK(offer.IsCompatibleWith(response));
auto deflater = make_scoped_ptr(
new WebSocketDeflater(response.server_context_take_over_mode()));
auto inflater = make_scoped_ptr(
new WebSocketInflater(kInflaterChunkSize, kInflaterChunkSize));
if (!deflater->Initialize(response.PermissiveServerMaxWindowBits()) ||
!inflater->Initialize(response.PermissiveClientMaxWindowBits())) {
// For some reason we cannot accept the parameters.
continue;
}
*deflate_parameters = response;
return make_scoped_ptr(
new WebSocketEncoder(FOR_SERVER, deflater.Pass(), inflater.Pass()));
}
// We cannot find an acceptable offer.
return make_scoped_ptr(new WebSocketEncoder(FOR_SERVER, nullptr, nullptr));
}
// static
scoped_ptr<WebSocketEncoder> WebSocketEncoder::CreateClient(
const std::string& response_extensions) {
// TODO(yhirano): Add a way to return an error.
WebSocketExtensionParser parser;
if (!parser.Parse(response_extensions)) {
// Parse error. Note that there are two cases here.
// 1) There is no Sec-WebSocket-Extensions header.
// 2) There is a malformed Sec-WebSocketExtensions header.
// We should return a deflate-disabled encoder for the former case and
// fail the connection for the latter case.
return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr));
}
if (parser.extensions().size() != 1) {
// Only permessage-deflate extension is supported.
// TODO (yhirano): Fail the connection.
return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr));
}
const auto& extension = parser.extensions()[0];
WebSocketDeflateParameters params;
std::string failure_message;
if (!params.Initialize(extension, &failure_message) ||
!params.IsValidAsResponse(&failure_message)) {
// TODO (yhirano): Fail the connection.
return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr));
}
auto deflater = make_scoped_ptr(
new WebSocketDeflater(params.client_context_take_over_mode()));
auto inflater = make_scoped_ptr(
new WebSocketInflater(kInflaterChunkSize, kInflaterChunkSize));
if (!deflater->Initialize(params.PermissiveClientMaxWindowBits()) ||
!inflater->Initialize(params.PermissiveServerMaxWindowBits())) {
// TODO (yhirano): Fail the connection.
return make_scoped_ptr(new WebSocketEncoder(FOR_CLIENT, nullptr, nullptr));
}
return make_scoped_ptr(
new WebSocketEncoder(FOR_CLIENT, deflater.Pass(), inflater.Pass()));
}
WebSocketEncoder::WebSocketEncoder(Type type,
scoped_ptr<WebSocketDeflater> deflater,
scoped_ptr<WebSocketInflater> inflater)
: type_(type), deflater_(deflater.Pass()), inflater_(inflater.Pass()) {}
WebSocketEncoder::~WebSocketEncoder() {}
WebSocket::ParseResult WebSocketEncoder::DecodeFrame(
const base::StringPiece& frame,
int* bytes_consumed,
std::string* output) {
bool compressed;
WebSocket::ParseResult result = DecodeFrameHybi17(
frame, type_ == FOR_SERVER, bytes_consumed, output, &compressed);
if (result == WebSocket::FRAME_OK && compressed) {
if (!Inflate(output))
result = WebSocket::FRAME_ERROR;
}
return result;
}
void WebSocketEncoder::EncodeFrame(const std::string& frame,
int masking_key,
std::string* output) {
std::string compressed;
if (Deflate(frame, &compressed))
EncodeFrameHybi17(compressed, masking_key, true, output);
else
EncodeFrameHybi17(frame, masking_key, false, output);
}
bool WebSocketEncoder::Inflate(std::string* message) {
if (!inflater_)
return false;
if (!inflater_->AddBytes(message->data(), message->length()))
return false;
if (!inflater_->Finish())
return false;
std::vector<char> output;
while (inflater_->CurrentOutputSize() > 0) {
scoped_refptr<IOBufferWithSize> chunk =
inflater_->GetOutput(inflater_->CurrentOutputSize());
if (!chunk.get())
return false;
output.insert(output.end(), chunk->data(), chunk->data() + chunk->size());
}
*message =
output.size() ? std::string(&output[0], output.size()) : std::string();
return true;
}
bool WebSocketEncoder::Deflate(const std::string& message,
std::string* output) {
if (!deflater_)
return false;
if (!deflater_->AddBytes(message.data(), message.length())) {
deflater_->Finish();
return false;
}
if (!deflater_->Finish())
return false;
scoped_refptr<IOBufferWithSize> buffer =
deflater_->GetOutput(deflater_->CurrentOutputSize());
if (!buffer.get())
return false;
*output = std::string(buffer->data(), buffer->size());
return true;
}
} // namespace net
|
Workday/OpenFrame
|
net/server/web_socket_encoder.cc
|
C++
|
bsd-3-clause
| 12,653 |
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <chrono>
#include <csignal>
#include <random>
#include <syslog.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem.hpp>
#include <osquery/config.h>
#include <osquery/core.h>
#include <osquery/events.h>
#include <osquery/extensions.h>
#include <osquery/flags.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/registry.h>
#include "osquery/core/watcher.h"
#include "osquery/database/db_handle.h"
#if defined(__linux__) || defined(__FreeBSD__)
#include <sys/resource.h>
#endif
#ifdef __linux__
#include <sys/syscall.h>
/*
* These are the io priority groups as implemented by CFQ. RT is the realtime
* class, it always gets premium service. BE is the best-effort scheduling
* class, the default for any process. IDLE is the idle scheduling class, it
* is only served when no one else is using the disk.
*/
enum {
IOPRIO_CLASS_NONE,
IOPRIO_CLASS_RT,
IOPRIO_CLASS_BE,
IOPRIO_CLASS_IDLE,
};
/*
* 8 best effort priority levels are supported
*/
#define IOPRIO_BE_NR (8)
enum {
IOPRIO_WHO_PROCESS = 1,
IOPRIO_WHO_PGRP,
IOPRIO_WHO_USER,
};
#endif
#define DESCRIPTION \
"osquery %s, your OS as a high-performance relational database\n"
#define EPILOG "\nosquery project page <https://osquery.io>.\n"
#define OPTIONS \
"\nosquery configuration options (set by config or CLI flags):\n\n"
#define OPTIONS_SHELL "\nosquery shell-only CLI flags:\n\n"
#define OPTIONS_CLI "osquery%s command line flags:\n\n"
#define USAGE "Usage: %s [OPTION]... %s\n\n"
#define CONFIG_ERROR \
"You are using default configurations for osqueryd for one or more of the " \
"following\n" \
"flags: pidfile, db_path.\n\n" \
"These options create files in /var/osquery but it looks like that path " \
"has not\n" \
"been created. Please consider explicitly defining those " \
"options as a different \n" \
"path. Additionally, review the \"using osqueryd\" wiki page:\n" \
" - https://osquery.readthedocs.org/en/latest/introduction/using-osqueryd/" \
"\n\n";
/// Seconds to alarm and quit for non-responsive event loops.
#define SIGNAL_ALARM_TIMEOUT 4
namespace fs = boost::filesystem;
namespace {
extern "C" {
static inline bool hasWorkerVariable() {
return (getenv("OSQUERY_WORKER") != nullptr);
}
volatile std::sig_atomic_t kHandledSignal{0};
void signalHandler(int signal) {
// Inform exit status of main threads blocked by service joins.
if (kHandledSignal == 0) {
kHandledSignal = signal;
}
// Handle signals based on a tri-state (worker, watcher, neither).
pid_t worker_pid = osquery::Watcher::getWorker();
bool is_watcher = worker_pid > 0;
if (signal == SIGHUP) {
if (!is_watcher || hasWorkerVariable()) {
// Reload configuration.
}
} else if (signal == SIGTERM || signal == SIGINT || signal == SIGABRT) {
// Time to stop, set an upper bound time constraint on how long threads
// have to terminate (join). Publishers may be in 20ms or similar sleeps.
alarm(SIGNAL_ALARM_TIMEOUT);
// Restore the default signal handler.
std::signal(signal, SIG_DFL);
// The watcher waits for the worker to die.
if (is_watcher) {
// Bind the fate of the worker to this watcher.
osquery::Watcher::bindFates();
} else {
// Otherwise the worker or non-watched process joins.
osquery::EventFactory::end(true);
// Re-raise the handled signal, which has since been restored to default.
raise(signal);
}
} else if (signal == SIGALRM) {
// Restore the default signal handler for SIGALRM.
std::signal(SIGALRM, SIG_DFL);
// Took too long to stop.
VLOG(1) << "Cannot stop event publisher threads";
raise((kHandledSignal != 0) ? kHandledSignal : SIGALRM);
}
if (is_watcher) {
// The signal should be proliferated through the process group.
// Otherwise the watcher could 'forward' the signal to workers and
// managed extension processes.
}
}
}
}
namespace osquery {
using chrono_clock = std::chrono::high_resolution_clock;
#ifndef __APPLE__
CLI_FLAG(bool, daemonize, false, "Run as daemon (osqueryd only)");
#endif
DECLARE_string(distributed_plugin);
DECLARE_bool(disable_distributed);
DECLARE_string(config_plugin);
DECLARE_bool(config_check);
DECLARE_bool(database_dump);
ToolType kToolType = OSQUERY_TOOL_UNKNOWN;
void printUsage(const std::string& binary, int tool) {
// Parse help options before gflags. Only display osquery-related options.
fprintf(stdout, DESCRIPTION, kVersion.c_str());
if (tool == OSQUERY_TOOL_SHELL) {
// The shell allows a caller to run a single SQL statement and exit.
fprintf(stdout, USAGE, binary.c_str(), "[SQL STATEMENT]");
} else {
fprintf(stdout, USAGE, binary.c_str(), "");
}
if (tool == OSQUERY_EXTENSION) {
fprintf(stdout, OPTIONS_CLI, " extension");
Flag::printFlags(false, true);
} else {
fprintf(stdout, OPTIONS_CLI, "");
Flag::printFlags(false, false, true);
fprintf(stdout, OPTIONS);
Flag::printFlags();
}
if (tool == OSQUERY_TOOL_SHELL) {
// Print shell flags.
fprintf(stdout, OPTIONS_SHELL);
Flag::printFlags(true);
}
fprintf(stdout, EPILOG);
}
Initializer::Initializer(int& argc, char**& argv, ToolType tool)
: argc_(&argc),
argv_(&argv),
tool_(tool),
binary_((tool == OSQUERY_TOOL_DAEMON) ? "osqueryd" : "osqueryi") {
std::srand(chrono_clock::now().time_since_epoch().count());
// Handled boost filesystem locale problems fixes in 1.56.
// See issue #1559 for the discussion and upstream boost patch.
try {
boost::filesystem::path::codecvt();
} catch (const std::runtime_error& e) {
setenv("LC_ALL", "C", 1);
}
// osquery implements a custom help/usage output.
for (int i = 1; i < *argc_; i++) {
auto help = std::string((*argv_)[i]);
if ((help == "--help" || help == "-help" || help == "--h" ||
help == "-h") &&
tool != OSQUERY_TOOL_TEST) {
printUsage(binary_, tool_);
::exit(0);
}
}
// To change the default config plugin, compile osquery with
// -DOSQUERY_DEFAULT_CONFIG_PLUGIN=<new_default_plugin>
#ifdef OSQUERY_DEFAULT_CONFIG_PLUGIN
FLAGS_config_plugin = STR(OSQUERY_DEFAULT_CONFIG_PLUGIN);
#endif
// To change the default logger plugin, compile osquery with
// -DOSQUERY_DEFAULT_LOGGER_PLUGIN=<new_default_plugin>
#ifdef OSQUERY_DEFAULT_LOGGER_PLUGIN
FLAGS_logger_plugin = STR(OSQUERY_DEFAULT_LOGGER_PLUGIN);
#endif
// Set version string from CMake build
GFLAGS_NAMESPACE::SetVersionString(kVersion.c_str());
// Let gflags parse the non-help options/flags.
GFLAGS_NAMESPACE::ParseCommandLineFlags(
argc_, argv_, (tool == OSQUERY_TOOL_SHELL));
// Set the tool type to allow runtime decisions based on daemon, shell, etc.
kToolType = tool;
if (tool == OSQUERY_TOOL_SHELL) {
// The shell is transient, rewrite config-loaded paths.
FLAGS_disable_logging = true;
// Get the caller's home dir for temporary storage/state management.
auto homedir = osqueryHomeDirectory();
if (osquery::pathExists(homedir).ok() ||
boost::filesystem::create_directory(homedir)) {
// Only apply user/shell-specific paths if not overridden by CLI flag.
if (Flag::isDefault("database_path")) {
osquery::FLAGS_database_path = homedir + "/shell.db";
}
if (Flag::isDefault("extensions_socket")) {
osquery::FLAGS_extensions_socket = homedir + "/shell.em";
}
}
}
// All tools handle the same set of signals.
// If a daemon process is a watchdog the signal is passed to the worker,
// unless the worker has not yet started.
std::signal(SIGTERM, signalHandler);
std::signal(SIGABRT, signalHandler);
std::signal(SIGINT, signalHandler);
std::signal(SIGHUP, signalHandler);
std::signal(SIGALRM, signalHandler);
// If the caller is checking configuration, disable the watchdog/worker.
if (FLAGS_config_check) {
FLAGS_disable_watchdog = true;
}
// Initialize the status and results logger.
initStatusLogger(binary_);
if (tool != OSQUERY_EXTENSION) {
if (isWorker()) {
VLOG(1) << "osquery worker initialized [watcher=" << getppid() << "]";
} else {
VLOG(1) << "osquery initialized [version=" << kVersion << "]";
}
} else {
VLOG(1) << "osquery extension initialized [sdk=" << kSDKVersion << "]";
}
}
void Initializer::initDaemon() {
if (FLAGS_config_check) {
// No need to daemonize, emit log lines, or create process mutexes.
return;
}
#ifndef __APPLE__
// OS X uses launchd to daemonize.
if (osquery::FLAGS_daemonize) {
if (daemon(0, 0) == -1) {
::exit(EXIT_FAILURE);
}
}
#endif
// Print the version to SYSLOG.
syslog(
LOG_NOTICE, "%s started [version=%s]", binary_.c_str(), kVersion.c_str());
// Check if /var/osquery exists
if ((Flag::isDefault("pidfile") || Flag::isDefault("database_path")) &&
!isDirectory("/var/osquery")) {
std::cerr << CONFIG_ERROR;
}
// Create a process mutex around the daemon.
auto pid_status = createPidFile();
if (!pid_status.ok()) {
LOG(ERROR) << binary_ << " initialize failed: " << pid_status.toString();
::exit(EXIT_FAILURE);
}
// Nice ourselves if using a watchdog and the level is not too permissive.
if (!FLAGS_disable_watchdog &&
FLAGS_watchdog_level >= WATCHDOG_LEVEL_DEFAULT &&
FLAGS_watchdog_level != WATCHDOG_LEVEL_DEBUG) {
// Set CPU scheduling I/O limits.
setpriority(PRIO_PGRP, 0, 10);
#ifdef __linux__
// Using: ioprio_set(IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE);
syscall(SYS_ioprio_set, IOPRIO_WHO_PGRP, 0, IOPRIO_CLASS_IDLE);
#elif defined(__APPLE__)
setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE);
#endif
}
}
void Initializer::initWatcher() {
// The watcher takes a list of paths to autoload extensions from.
osquery::loadExtensions();
// Add a watcher service thread to start/watch an optional worker and set
// of optional extensions in the autoload paths.
if (Watcher::hasManagedExtensions() || !FLAGS_disable_watchdog) {
Dispatcher::addService(std::make_shared<WatcherRunner>(
*argc_, *argv_, !FLAGS_disable_watchdog));
}
// If there are no autoloaded extensions, the watcher service will end,
// otherwise it will continue as a background thread and respawn them.
// If the watcher is also a worker watchdog it will do nothing but monitor
// the extensions and worker process.
if (!FLAGS_disable_watchdog) {
Dispatcher::joinServices();
// Execution should only reach this point if a signal was handled by the
// worker and watcher.
::exit((kHandledSignal > 0) ? 128 + kHandledSignal : EXIT_FAILURE);
}
}
void Initializer::initWorker(const std::string& name) {
// Clear worker's arguments.
size_t name_size = strlen((*argv_)[0]);
auto original_name = std::string((*argv_)[0]);
for (int i = 0; i < *argc_; i++) {
if ((*argv_)[i] != nullptr) {
memset((*argv_)[i], ' ', strlen((*argv_)[i]));
}
}
// Set the worker's process name.
if (name.size() < name_size) {
std::copy(name.begin(), name.end(), (*argv_)[0]);
(*argv_)[0][name.size()] = '\0';
} else {
std::copy(original_name.begin(), original_name.end(), (*argv_)[0]);
(*argv_)[0][original_name.size()] = '\0';
}
// Start a watcher watcher thread to exit the process if the watcher exits.
Dispatcher::addService(std::make_shared<WatcherWatcherRunner>(getppid()));
}
void Initializer::initWorkerWatcher(const std::string& name) {
if (isWorker()) {
initWorker(name);
} else {
// The watcher will forever monitor and spawn additional workers.
initWatcher();
}
}
bool Initializer::isWorker() { return hasWorkerVariable(); }
void Initializer::initActivePlugin(const std::string& type,
const std::string& name) {
// Use a delay, meaning the amount of milliseconds waited for extensions.
size_t delay = 0;
// The timeout is the maximum microseconds in seconds to wait for extensions.
size_t timeout = atoi(FLAGS_extensions_timeout.c_str()) * 1000000;
if (timeout < kExtensionInitializeLatencyUS * 10) {
timeout = kExtensionInitializeLatencyUS * 10;
}
while (!Registry::setActive(type, name)) {
if (!Watcher::hasManagedExtensions() || delay > timeout) {
LOG(ERROR) << "Active " << type << " plugin not found: " << name;
::exit(EXIT_CATASTROPHIC);
}
delay += kExtensionInitializeLatencyUS;
::usleep(kExtensionInitializeLatencyUS);
}
}
void Initializer::start() {
// Load registry/extension modules before extensions.
osquery::loadModules();
// Pre-extension manager initialization options checking.
if (FLAGS_config_check && !Watcher::hasManagedExtensions()) {
FLAGS_disable_extensions = true;
}
// A daemon must always have R/W access to the database.
DBHandle::setAllowOpen(true);
DBHandle::setRequireWrite(tool_ == OSQUERY_TOOL_DAEMON);
if (!DBHandle::checkDB()) {
LOG(ERROR) << RLOG(1629) << binary_
<< " initialize failed: Could not open RocksDB";
if (isWorker()) {
::exit(EXIT_CATASTROPHIC);
} else {
::exit(EXIT_FAILURE);
}
}
// Bind to an extensions socket and wait for registry additions.
osquery::startExtensionManager();
// Then set the config plugin, which uses a single/active plugin.
initActivePlugin("config", FLAGS_config_plugin);
// Run the setup for all lazy registries (tables, SQL).
Registry::setUp();
if (FLAGS_config_check) {
// The initiator requested an initialization and config check.
auto s = Config::getInstance().load();
if (!s.ok()) {
std::cerr << "Error reading config: " << s.toString() << "\n";
}
// A configuration check exits the application.
::exit(s.getCode());
}
if (FLAGS_database_dump) {
dumpDatabase();
::exit(EXIT_SUCCESS);
}
// Load the osquery config using the default/active config plugin.
auto s = Config::getInstance().load();
if (!s.ok()) {
auto message = "Error reading config: " + s.toString();
if (tool_ == OSQUERY_TOOL_DAEMON) {
LOG(WARNING) << message;
} else {
LOG(INFO) << message;
}
}
// Initialize the status and result plugin logger.
initActivePlugin("logger", FLAGS_logger_plugin);
initLogger(binary_);
// Initialize the distributed plugin, if necessary
if (!FLAGS_disable_distributed) {
if (Registry::exists("distributed", FLAGS_distributed_plugin)) {
initActivePlugin("distributed", FLAGS_distributed_plugin);
}
}
// Start event threads.
osquery::attachEvents();
EventFactory::delay();
}
void Initializer::shutdown() {
// End any event type run loops.
EventFactory::end();
// Hopefully release memory used by global string constructors in gflags.
GFLAGS_NAMESPACE::ShutDownCommandLineFlags();
}
}
|
mgoffin/osquery
|
osquery/core/init.cpp
|
C++
|
bsd-3-clause
| 15,563 |
// Copyright 2017 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.
package org.chromium.chrome.browser.offlinepages.prefetch;
import org.chromium.chrome.browser.preferences.ChromePreferenceKeys;
import org.chromium.chrome.browser.preferences.SharedPreferencesManager;
/**
* Preferences used to provide prefetch related notifications.
* - Having new pages: boolean indicating whether new pages have been saved or not
* - Notification timestamp: the last time a notification is shown
* - Offline counter: how many times the task ran and seen that we are offline
* - Ignored notification counter: how many times in a row we showed a notification without user
* reacting to it
*/
public class PrefetchPrefs {
/**
* Sets the flag to tell whether prefetch notifications are enabled in user settings.
*/
public static void setNotificationEnabled(boolean enabled) {
SharedPreferencesManager.getInstance().writeBoolean(
ChromePreferenceKeys.PREFETCH_NOTIFICATION_ENABLED, enabled);
}
/**
* Returns the flag to tell whether prefetch notifications are enabled in user settings.
*/
public static boolean getNotificationEnabled() {
return SharedPreferencesManager.getInstance().readBoolean(
ChromePreferenceKeys.PREFETCH_NOTIFICATION_ENABLED, true);
}
/**
* Sets the flag to tell whether new pages have been saved.
*/
public static void setHasNewPages(boolean hasNewPages) {
SharedPreferencesManager.getInstance().writeBoolean(
ChromePreferenceKeys.PREFETCH_HAS_NEW_PAGES, hasNewPages);
}
/**
* Returns the flag to tell whether new pages have been saved.
*/
public static boolean getHasNewPages() {
return SharedPreferencesManager.getInstance().readBoolean(
ChromePreferenceKeys.PREFETCH_HAS_NEW_PAGES, false);
}
/**
* Sets the last time a notification is shown, in milliseconds since the epoch.
*/
public static void setNotificationLastShownTime(long timeInMillis) {
SharedPreferencesManager.getInstance().writeLong(
ChromePreferenceKeys.PREFETCH_NOTIFICATION_TIME, timeInMillis);
}
/**
* Returns the last time a notification is shown, in milliseconds since the epoch.
*/
public static long getNotificationLastShownTime() {
return SharedPreferencesManager.getInstance().readLong(
ChromePreferenceKeys.PREFETCH_NOTIFICATION_TIME);
}
/**
* Sets the offline counter.
*/
public static void setOfflineCounter(int counter) {
SharedPreferencesManager.getInstance().writeInt(
ChromePreferenceKeys.PREFETCH_OFFLINE_COUNTER, counter);
}
/**
* Increments and returns the offline counter.
*/
public static int incrementOfflineCounter() {
return SharedPreferencesManager.getInstance().incrementInt(
ChromePreferenceKeys.PREFETCH_OFFLINE_COUNTER);
}
/**
* Sets the ignored notification counter.
*/
public static void setIgnoredNotificationCounter(int counter) {
SharedPreferencesManager.getInstance().writeInt(
ChromePreferenceKeys.PREFETCH_IGNORED_NOTIFICATION_COUNTER, counter);
}
/**
* Returns the ignored notification counter.
*/
public static int getIgnoredNotificationCounter() {
return SharedPreferencesManager.getInstance().readInt(
ChromePreferenceKeys.PREFETCH_IGNORED_NOTIFICATION_COUNTER);
}
/**
* Increments and returns the ignored notification counter.
*/
public static int incrementIgnoredNotificationCounter() {
return SharedPreferencesManager.getInstance().incrementInt(
ChromePreferenceKeys.PREFETCH_IGNORED_NOTIFICATION_COUNTER);
}
}
|
endlessm/chromium-browser
|
chrome/android/java/src/org/chromium/chrome/browser/offlinepages/prefetch/PrefetchPrefs.java
|
Java
|
bsd-3-clause
| 3,959 |
using System;
using System.Reflection;
using SD = System.Drawing;
using Eto.Forms;
using UIKit;
using Eto.Drawing;
namespace Eto.iOS.Forms.Controls
{
public class NumericUpDownHandler : IosControl<UITextField, NumericUpDown, NumericUpDown.ICallback>, NumericUpDown.IHandler
{
public NumericUpDownHandler()
{
Control = new UITextField();
}
protected override SizeF GetNaturalSize(SizeF availableSize)
{
return SizeF.Max(base.GetNaturalSize(availableSize), new SizeF(60, 0));
}
protected override void Initialize()
{
base.Initialize();
Control.KeyboardType = UIKeyboardType.NumberPad;
Control.ReturnKeyType = UIReturnKeyType.Done;
Control.BorderStyle = UITextBorderStyle.RoundedRect;
Control.ShouldReturn = (textField) =>
{
textField.ResignFirstResponder();
return true;
};
Control.EditingChanged += (sender, e) => Callback.OnValueChanged(Widget, EventArgs.Empty);
}
public bool ReadOnly
{
get;
set;
}
public double Value
{
get
{
double value;
if (double.TryParse(Control.Text, out value))
return value;
return 0;
}
set
{
Control.Text = value.ToString();
}
}
public double MinValue
{
get;
set;
}
public double MaxValue
{
get;
set;
}
public override Font Font
{
get { return base.Font; }
set
{
base.Font = value;
Control.Font = value.ToUI();
}
}
public double Increment
{
get;
set;
}
public int DecimalPlaces
{
get;
set;
}
public Color TextColor
{
get { return Control.TextColor.ToEto(); }
set { Control.TextColor = value.ToNSUI(); }
}
}
}
|
PowerOfCode/Eto
|
Source/Eto.iOS/Forms/Controls/NumericUpDownHandler.cs
|
C#
|
bsd-3-clause
| 1,650 |
<?php
namespace app\models;
class ClientWechatFanSearch extends \yii\base\Model
{
public $nickname;
public $mobile;
public $carrier;
public $province;
public $city;
public $create_time_start;
public $create_time_end;
public $gh_id;
public $office_id;
public $scene_pid;
public $searchStr;
public $page;
public function rules() {
return [
[[
'gh_id', 'nickname', 'mobile', 'carrier', 'province', 'city',
'create_time_start', 'create_time_end', 'office_id', 'searchStr',
'scene_pid','page',
], 'safe'],
];
}
public function search($params) {
$query = \app\models\MUser::find()
->join('INNER JOIN', 'wx_openid_bind_mobile', 'wx_openid_bind_mobile.gh_id = wx_user.gh_id and wx_openid_bind_mobile.openid = wx_user.openid')
->where(['wx_user.subscribe' => 1])
->orderBy(['wx_user.create_time' => SORT_DESC]);
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
if (!empty($this->page)) {
$dataProvider->pagination->page = $this->page;
}
if (!empty($this->searchStr)) {
$query->andWhere([
'or',
['like', 'wx_user.nickname', $this->searchStr],
['like', 'wx_openid_bind_mobile.mobile', $this->searchStr],
]);
}
$this->addCondition($query, 'nickname', true);
if (!empty($this->gh_id)) {
$query->andWhere(['wx_user.gh_id' => $this->gh_id]);
}
if (!empty($this->office_id)) {
$query->andWhere(['wx_user.belongto' => $this->office_id]);
}
$query->andFilterWhere(['like', 'wx_openid_bind_mobile.mobile', $this->mobile]);
if (trim($this->create_time_start) !== '')
{
$query->andWhere('date(wx_user.create_time)>=:create_time', [':create_time' => $this->create_time_start]);
}
if (trim($this->create_time_end) !== '')
{
$query->andWhere('date(wx_user.create_time)<=:create_time_2', [':create_time_2' => $this->create_time_end]);
}
return $dataProvider;
}
protected function addCondition($query, $attribute, $partialMatch = false)
{
if (($pos = strrpos($attribute, '.')) !== false) {
$modelAttribute = substr($attribute, $pos + 1);
} else {
$modelAttribute = $attribute;
}
$value = $this->$modelAttribute;
if (trim($value) === '') {
return;
}
if ($partialMatch) {
$query->andWhere(['like', $attribute, $value]);
} else {
$query->andWhere([$attribute => $value]);
}
}
}
|
yjhu/wowewe
|
models/ClientWechatFanSearch.php
|
PHP
|
bsd-3-clause
| 3,139 |
<?php
class AccesoController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view', 'vistaempresas','create', 'admin', 'update'),
'expression'=>'!$user->isGuest && Yii::app()->user->getState("nivel_acceso") == "Gerente"',
),
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index', 'vistaempresas','create', 'admin', 'view'),
'expression'=>'!$user->isGuest && Yii::app()->user->getState("nivel_acceso") == "Ventas"',
),
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index', 'admin', 'update', 'view', 'create', 'vistaempresas'),
'expression'=>'!$user->isGuest && Yii::app()->user->getState("persona") == "administrador"',
),
/*array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete', 'vistaempresas'),
'users'=>array('admin'),
),*/
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate($id)
{
$model=new Acceso;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Acceso']))
{
$model->attributes=$_POST['Acceso'];
if($model->save())
$this->redirect(array('personas/admin','id'=>$id));
}
$this->render('create',array(
'model'=>$model,
'id'=>$id,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Acceso']))
{
$model->attributes=$_POST['Acceso'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Acceso');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Acceso('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Acceso']))
$model->attributes=$_GET['Acceso'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer $id the ID of the model to be loaded
* @return Acceso the loaded model
* @throws CHttpException
*/
public function loadModel($id)
{
$model=Acceso::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param Acceso $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='acceso-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
|
ineps/inesa
|
inesa/protected/controllers/AccesoController.php
|
PHP
|
bsd-3-clause
| 5,110 |
// Code generated from gen/generic.rules; DO NOT EDIT.
// generated with: cd gen; go run *.go
package ssa
import "math"
import "cmd/compile/internal/types"
func rewriteValuegeneric(v *Value) bool {
switch v.Op {
case OpAdd16:
return rewriteValuegeneric_OpAdd16(v)
case OpAdd32:
return rewriteValuegeneric_OpAdd32(v)
case OpAdd32F:
return rewriteValuegeneric_OpAdd32F(v)
case OpAdd64:
return rewriteValuegeneric_OpAdd64(v)
case OpAdd64F:
return rewriteValuegeneric_OpAdd64F(v)
case OpAdd8:
return rewriteValuegeneric_OpAdd8(v)
case OpAddPtr:
return rewriteValuegeneric_OpAddPtr(v)
case OpAnd16:
return rewriteValuegeneric_OpAnd16(v)
case OpAnd32:
return rewriteValuegeneric_OpAnd32(v)
case OpAnd64:
return rewriteValuegeneric_OpAnd64(v)
case OpAnd8:
return rewriteValuegeneric_OpAnd8(v)
case OpAndB:
return rewriteValuegeneric_OpAndB(v)
case OpArraySelect:
return rewriteValuegeneric_OpArraySelect(v)
case OpCom16:
return rewriteValuegeneric_OpCom16(v)
case OpCom32:
return rewriteValuegeneric_OpCom32(v)
case OpCom64:
return rewriteValuegeneric_OpCom64(v)
case OpCom8:
return rewriteValuegeneric_OpCom8(v)
case OpConstInterface:
return rewriteValuegeneric_OpConstInterface(v)
case OpConstSlice:
return rewriteValuegeneric_OpConstSlice(v)
case OpConstString:
return rewriteValuegeneric_OpConstString(v)
case OpConvert:
return rewriteValuegeneric_OpConvert(v)
case OpCtz16:
return rewriteValuegeneric_OpCtz16(v)
case OpCtz32:
return rewriteValuegeneric_OpCtz32(v)
case OpCtz64:
return rewriteValuegeneric_OpCtz64(v)
case OpCtz8:
return rewriteValuegeneric_OpCtz8(v)
case OpCvt32Fto32:
return rewriteValuegeneric_OpCvt32Fto32(v)
case OpCvt32Fto64:
return rewriteValuegeneric_OpCvt32Fto64(v)
case OpCvt32Fto64F:
return rewriteValuegeneric_OpCvt32Fto64F(v)
case OpCvt32to32F:
return rewriteValuegeneric_OpCvt32to32F(v)
case OpCvt32to64F:
return rewriteValuegeneric_OpCvt32to64F(v)
case OpCvt64Fto32:
return rewriteValuegeneric_OpCvt64Fto32(v)
case OpCvt64Fto32F:
return rewriteValuegeneric_OpCvt64Fto32F(v)
case OpCvt64Fto64:
return rewriteValuegeneric_OpCvt64Fto64(v)
case OpCvt64to32F:
return rewriteValuegeneric_OpCvt64to32F(v)
case OpCvt64to64F:
return rewriteValuegeneric_OpCvt64to64F(v)
case OpCvtBoolToUint8:
return rewriteValuegeneric_OpCvtBoolToUint8(v)
case OpDiv16:
return rewriteValuegeneric_OpDiv16(v)
case OpDiv16u:
return rewriteValuegeneric_OpDiv16u(v)
case OpDiv32:
return rewriteValuegeneric_OpDiv32(v)
case OpDiv32F:
return rewriteValuegeneric_OpDiv32F(v)
case OpDiv32u:
return rewriteValuegeneric_OpDiv32u(v)
case OpDiv64:
return rewriteValuegeneric_OpDiv64(v)
case OpDiv64F:
return rewriteValuegeneric_OpDiv64F(v)
case OpDiv64u:
return rewriteValuegeneric_OpDiv64u(v)
case OpDiv8:
return rewriteValuegeneric_OpDiv8(v)
case OpDiv8u:
return rewriteValuegeneric_OpDiv8u(v)
case OpEq16:
return rewriteValuegeneric_OpEq16(v)
case OpEq32:
return rewriteValuegeneric_OpEq32(v)
case OpEq32F:
return rewriteValuegeneric_OpEq32F(v)
case OpEq64:
return rewriteValuegeneric_OpEq64(v)
case OpEq64F:
return rewriteValuegeneric_OpEq64F(v)
case OpEq8:
return rewriteValuegeneric_OpEq8(v)
case OpEqB:
return rewriteValuegeneric_OpEqB(v)
case OpEqInter:
return rewriteValuegeneric_OpEqInter(v)
case OpEqPtr:
return rewriteValuegeneric_OpEqPtr(v)
case OpEqSlice:
return rewriteValuegeneric_OpEqSlice(v)
case OpIMake:
return rewriteValuegeneric_OpIMake(v)
case OpInterCall:
return rewriteValuegeneric_OpInterCall(v)
case OpIsInBounds:
return rewriteValuegeneric_OpIsInBounds(v)
case OpIsNonNil:
return rewriteValuegeneric_OpIsNonNil(v)
case OpIsSliceInBounds:
return rewriteValuegeneric_OpIsSliceInBounds(v)
case OpLeq16:
return rewriteValuegeneric_OpLeq16(v)
case OpLeq16U:
return rewriteValuegeneric_OpLeq16U(v)
case OpLeq32:
return rewriteValuegeneric_OpLeq32(v)
case OpLeq32F:
return rewriteValuegeneric_OpLeq32F(v)
case OpLeq32U:
return rewriteValuegeneric_OpLeq32U(v)
case OpLeq64:
return rewriteValuegeneric_OpLeq64(v)
case OpLeq64F:
return rewriteValuegeneric_OpLeq64F(v)
case OpLeq64U:
return rewriteValuegeneric_OpLeq64U(v)
case OpLeq8:
return rewriteValuegeneric_OpLeq8(v)
case OpLeq8U:
return rewriteValuegeneric_OpLeq8U(v)
case OpLess16:
return rewriteValuegeneric_OpLess16(v)
case OpLess16U:
return rewriteValuegeneric_OpLess16U(v)
case OpLess32:
return rewriteValuegeneric_OpLess32(v)
case OpLess32F:
return rewriteValuegeneric_OpLess32F(v)
case OpLess32U:
return rewriteValuegeneric_OpLess32U(v)
case OpLess64:
return rewriteValuegeneric_OpLess64(v)
case OpLess64F:
return rewriteValuegeneric_OpLess64F(v)
case OpLess64U:
return rewriteValuegeneric_OpLess64U(v)
case OpLess8:
return rewriteValuegeneric_OpLess8(v)
case OpLess8U:
return rewriteValuegeneric_OpLess8U(v)
case OpLoad:
return rewriteValuegeneric_OpLoad(v)
case OpLsh16x16:
return rewriteValuegeneric_OpLsh16x16(v)
case OpLsh16x32:
return rewriteValuegeneric_OpLsh16x32(v)
case OpLsh16x64:
return rewriteValuegeneric_OpLsh16x64(v)
case OpLsh16x8:
return rewriteValuegeneric_OpLsh16x8(v)
case OpLsh32x16:
return rewriteValuegeneric_OpLsh32x16(v)
case OpLsh32x32:
return rewriteValuegeneric_OpLsh32x32(v)
case OpLsh32x64:
return rewriteValuegeneric_OpLsh32x64(v)
case OpLsh32x8:
return rewriteValuegeneric_OpLsh32x8(v)
case OpLsh64x16:
return rewriteValuegeneric_OpLsh64x16(v)
case OpLsh64x32:
return rewriteValuegeneric_OpLsh64x32(v)
case OpLsh64x64:
return rewriteValuegeneric_OpLsh64x64(v)
case OpLsh64x8:
return rewriteValuegeneric_OpLsh64x8(v)
case OpLsh8x16:
return rewriteValuegeneric_OpLsh8x16(v)
case OpLsh8x32:
return rewriteValuegeneric_OpLsh8x32(v)
case OpLsh8x64:
return rewriteValuegeneric_OpLsh8x64(v)
case OpLsh8x8:
return rewriteValuegeneric_OpLsh8x8(v)
case OpMod16:
return rewriteValuegeneric_OpMod16(v)
case OpMod16u:
return rewriteValuegeneric_OpMod16u(v)
case OpMod32:
return rewriteValuegeneric_OpMod32(v)
case OpMod32u:
return rewriteValuegeneric_OpMod32u(v)
case OpMod64:
return rewriteValuegeneric_OpMod64(v)
case OpMod64u:
return rewriteValuegeneric_OpMod64u(v)
case OpMod8:
return rewriteValuegeneric_OpMod8(v)
case OpMod8u:
return rewriteValuegeneric_OpMod8u(v)
case OpMove:
return rewriteValuegeneric_OpMove(v)
case OpMul16:
return rewriteValuegeneric_OpMul16(v)
case OpMul32:
return rewriteValuegeneric_OpMul32(v)
case OpMul32F:
return rewriteValuegeneric_OpMul32F(v)
case OpMul64:
return rewriteValuegeneric_OpMul64(v)
case OpMul64F:
return rewriteValuegeneric_OpMul64F(v)
case OpMul8:
return rewriteValuegeneric_OpMul8(v)
case OpNeg16:
return rewriteValuegeneric_OpNeg16(v)
case OpNeg32:
return rewriteValuegeneric_OpNeg32(v)
case OpNeg32F:
return rewriteValuegeneric_OpNeg32F(v)
case OpNeg64:
return rewriteValuegeneric_OpNeg64(v)
case OpNeg64F:
return rewriteValuegeneric_OpNeg64F(v)
case OpNeg8:
return rewriteValuegeneric_OpNeg8(v)
case OpNeq16:
return rewriteValuegeneric_OpNeq16(v)
case OpNeq32:
return rewriteValuegeneric_OpNeq32(v)
case OpNeq32F:
return rewriteValuegeneric_OpNeq32F(v)
case OpNeq64:
return rewriteValuegeneric_OpNeq64(v)
case OpNeq64F:
return rewriteValuegeneric_OpNeq64F(v)
case OpNeq8:
return rewriteValuegeneric_OpNeq8(v)
case OpNeqB:
return rewriteValuegeneric_OpNeqB(v)
case OpNeqInter:
return rewriteValuegeneric_OpNeqInter(v)
case OpNeqPtr:
return rewriteValuegeneric_OpNeqPtr(v)
case OpNeqSlice:
return rewriteValuegeneric_OpNeqSlice(v)
case OpNilCheck:
return rewriteValuegeneric_OpNilCheck(v)
case OpNot:
return rewriteValuegeneric_OpNot(v)
case OpOffPtr:
return rewriteValuegeneric_OpOffPtr(v)
case OpOr16:
return rewriteValuegeneric_OpOr16(v)
case OpOr32:
return rewriteValuegeneric_OpOr32(v)
case OpOr64:
return rewriteValuegeneric_OpOr64(v)
case OpOr8:
return rewriteValuegeneric_OpOr8(v)
case OpOrB:
return rewriteValuegeneric_OpOrB(v)
case OpPhi:
return rewriteValuegeneric_OpPhi(v)
case OpPtrIndex:
return rewriteValuegeneric_OpPtrIndex(v)
case OpRotateLeft16:
return rewriteValuegeneric_OpRotateLeft16(v)
case OpRotateLeft32:
return rewriteValuegeneric_OpRotateLeft32(v)
case OpRotateLeft64:
return rewriteValuegeneric_OpRotateLeft64(v)
case OpRotateLeft8:
return rewriteValuegeneric_OpRotateLeft8(v)
case OpRound32F:
return rewriteValuegeneric_OpRound32F(v)
case OpRound64F:
return rewriteValuegeneric_OpRound64F(v)
case OpRsh16Ux16:
return rewriteValuegeneric_OpRsh16Ux16(v)
case OpRsh16Ux32:
return rewriteValuegeneric_OpRsh16Ux32(v)
case OpRsh16Ux64:
return rewriteValuegeneric_OpRsh16Ux64(v)
case OpRsh16Ux8:
return rewriteValuegeneric_OpRsh16Ux8(v)
case OpRsh16x16:
return rewriteValuegeneric_OpRsh16x16(v)
case OpRsh16x32:
return rewriteValuegeneric_OpRsh16x32(v)
case OpRsh16x64:
return rewriteValuegeneric_OpRsh16x64(v)
case OpRsh16x8:
return rewriteValuegeneric_OpRsh16x8(v)
case OpRsh32Ux16:
return rewriteValuegeneric_OpRsh32Ux16(v)
case OpRsh32Ux32:
return rewriteValuegeneric_OpRsh32Ux32(v)
case OpRsh32Ux64:
return rewriteValuegeneric_OpRsh32Ux64(v)
case OpRsh32Ux8:
return rewriteValuegeneric_OpRsh32Ux8(v)
case OpRsh32x16:
return rewriteValuegeneric_OpRsh32x16(v)
case OpRsh32x32:
return rewriteValuegeneric_OpRsh32x32(v)
case OpRsh32x64:
return rewriteValuegeneric_OpRsh32x64(v)
case OpRsh32x8:
return rewriteValuegeneric_OpRsh32x8(v)
case OpRsh64Ux16:
return rewriteValuegeneric_OpRsh64Ux16(v)
case OpRsh64Ux32:
return rewriteValuegeneric_OpRsh64Ux32(v)
case OpRsh64Ux64:
return rewriteValuegeneric_OpRsh64Ux64(v)
case OpRsh64Ux8:
return rewriteValuegeneric_OpRsh64Ux8(v)
case OpRsh64x16:
return rewriteValuegeneric_OpRsh64x16(v)
case OpRsh64x32:
return rewriteValuegeneric_OpRsh64x32(v)
case OpRsh64x64:
return rewriteValuegeneric_OpRsh64x64(v)
case OpRsh64x8:
return rewriteValuegeneric_OpRsh64x8(v)
case OpRsh8Ux16:
return rewriteValuegeneric_OpRsh8Ux16(v)
case OpRsh8Ux32:
return rewriteValuegeneric_OpRsh8Ux32(v)
case OpRsh8Ux64:
return rewriteValuegeneric_OpRsh8Ux64(v)
case OpRsh8Ux8:
return rewriteValuegeneric_OpRsh8Ux8(v)
case OpRsh8x16:
return rewriteValuegeneric_OpRsh8x16(v)
case OpRsh8x32:
return rewriteValuegeneric_OpRsh8x32(v)
case OpRsh8x64:
return rewriteValuegeneric_OpRsh8x64(v)
case OpRsh8x8:
return rewriteValuegeneric_OpRsh8x8(v)
case OpSelect0:
return rewriteValuegeneric_OpSelect0(v)
case OpSelect1:
return rewriteValuegeneric_OpSelect1(v)
case OpSignExt16to32:
return rewriteValuegeneric_OpSignExt16to32(v)
case OpSignExt16to64:
return rewriteValuegeneric_OpSignExt16to64(v)
case OpSignExt32to64:
return rewriteValuegeneric_OpSignExt32to64(v)
case OpSignExt8to16:
return rewriteValuegeneric_OpSignExt8to16(v)
case OpSignExt8to32:
return rewriteValuegeneric_OpSignExt8to32(v)
case OpSignExt8to64:
return rewriteValuegeneric_OpSignExt8to64(v)
case OpSliceCap:
return rewriteValuegeneric_OpSliceCap(v)
case OpSliceLen:
return rewriteValuegeneric_OpSliceLen(v)
case OpSlicePtr:
return rewriteValuegeneric_OpSlicePtr(v)
case OpSlicemask:
return rewriteValuegeneric_OpSlicemask(v)
case OpSqrt:
return rewriteValuegeneric_OpSqrt(v)
case OpStaticCall:
return rewriteValuegeneric_OpStaticCall(v)
case OpStore:
return rewriteValuegeneric_OpStore(v)
case OpStringLen:
return rewriteValuegeneric_OpStringLen(v)
case OpStringPtr:
return rewriteValuegeneric_OpStringPtr(v)
case OpStructSelect:
return rewriteValuegeneric_OpStructSelect(v)
case OpSub16:
return rewriteValuegeneric_OpSub16(v)
case OpSub32:
return rewriteValuegeneric_OpSub32(v)
case OpSub32F:
return rewriteValuegeneric_OpSub32F(v)
case OpSub64:
return rewriteValuegeneric_OpSub64(v)
case OpSub64F:
return rewriteValuegeneric_OpSub64F(v)
case OpSub8:
return rewriteValuegeneric_OpSub8(v)
case OpTrunc16to8:
return rewriteValuegeneric_OpTrunc16to8(v)
case OpTrunc32to16:
return rewriteValuegeneric_OpTrunc32to16(v)
case OpTrunc32to8:
return rewriteValuegeneric_OpTrunc32to8(v)
case OpTrunc64to16:
return rewriteValuegeneric_OpTrunc64to16(v)
case OpTrunc64to32:
return rewriteValuegeneric_OpTrunc64to32(v)
case OpTrunc64to8:
return rewriteValuegeneric_OpTrunc64to8(v)
case OpXor16:
return rewriteValuegeneric_OpXor16(v)
case OpXor32:
return rewriteValuegeneric_OpXor32(v)
case OpXor64:
return rewriteValuegeneric_OpXor64(v)
case OpXor8:
return rewriteValuegeneric_OpXor8(v)
case OpZero:
return rewriteValuegeneric_OpZero(v)
case OpZeroExt16to32:
return rewriteValuegeneric_OpZeroExt16to32(v)
case OpZeroExt16to64:
return rewriteValuegeneric_OpZeroExt16to64(v)
case OpZeroExt32to64:
return rewriteValuegeneric_OpZeroExt32to64(v)
case OpZeroExt8to16:
return rewriteValuegeneric_OpZeroExt8to16(v)
case OpZeroExt8to32:
return rewriteValuegeneric_OpZeroExt8to32(v)
case OpZeroExt8to64:
return rewriteValuegeneric_OpZeroExt8to64(v)
}
return false
}
func rewriteValuegeneric_OpAdd16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Add16 (Const16 [c]) (Const16 [d]))
// result: (Const16 [c+d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c + d)
return true
}
break
}
// match: (Add16 <t> (Mul16 x y) (Mul16 x z))
// result: (Mul16 x (Add16 <t> y z))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpMul16 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if v_1.Op != OpMul16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i2 := 0; _i2 <= 1; _i2, v_1_0, v_1_1 = _i2+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
z := v_1_1
v.reset(OpMul16)
v0 := b.NewValue0(v.Pos, OpAdd16, t)
v0.AddArg2(y, z)
v.AddArg2(x, v0)
return true
}
}
}
break
}
// match: (Add16 (Const16 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Add16 (Const16 [1]) (Com16 x))
// result: (Neg16 x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 1 || v_1.Op != OpCom16 {
continue
}
x := v_1.Args[0]
v.reset(OpNeg16)
v.AddArg(x)
return true
}
break
}
// match: (Add16 (Add16 i:(Const16 <t>) z) x)
// cond: (z.Op != OpConst16 && x.Op != OpConst16)
// result: (Add16 i (Add16 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAdd16 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst16 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst16 && x.Op != OpConst16) {
continue
}
v.reset(OpAdd16)
v0 := b.NewValue0(v.Pos, OpAdd16, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Add16 (Sub16 i:(Const16 <t>) z) x)
// cond: (z.Op != OpConst16 && x.Op != OpConst16)
// result: (Add16 i (Sub16 <t> x z))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpSub16 {
continue
}
z := v_0.Args[1]
i := v_0.Args[0]
if i.Op != OpConst16 {
continue
}
t := i.Type
x := v_1
if !(z.Op != OpConst16 && x.Op != OpConst16) {
continue
}
v.reset(OpAdd16)
v0 := b.NewValue0(v.Pos, OpSub16, t)
v0.AddArg2(x, z)
v.AddArg2(i, v0)
return true
}
break
}
// match: (Add16 (Sub16 z i:(Const16 <t>)) x)
// cond: (z.Op != OpConst16 && x.Op != OpConst16)
// result: (Sub16 (Add16 <t> x z) i)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpSub16 {
continue
}
_ = v_0.Args[1]
z := v_0.Args[0]
i := v_0.Args[1]
if i.Op != OpConst16 {
continue
}
t := i.Type
x := v_1
if !(z.Op != OpConst16 && x.Op != OpConst16) {
continue
}
v.reset(OpSub16)
v0 := b.NewValue0(v.Pos, OpAdd16, t)
v0.AddArg2(x, z)
v.AddArg2(v0, i)
return true
}
break
}
// match: (Add16 (Const16 <t> [c]) (Add16 (Const16 <t> [d]) x))
// result: (Add16 (Const16 <t> [c+d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpAdd16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
continue
}
d := auxIntToInt16(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAdd16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Add16 (Const16 <t> [c]) (Sub16 (Const16 <t> [d]) x))
// result: (Sub16 (Const16 <t> [c+d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpSub16 {
continue
}
x := v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
continue
}
d := auxIntToInt16(v_1_0.AuxInt)
v.reset(OpSub16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
break
}
// match: (Add16 (Const16 <t> [c]) (Sub16 x (Const16 <t> [d])))
// result: (Add16 (Const16 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpSub16 {
continue
}
_ = v_1.Args[1]
x := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 || v_1_1.Type != t {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
v.reset(OpAdd16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpAdd32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Add32 (Const32 [c]) (Const32 [d]))
// result: (Const32 [c+d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c + d)
return true
}
break
}
// match: (Add32 <t> (Mul32 x y) (Mul32 x z))
// result: (Mul32 x (Add32 <t> y z))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpMul32 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i2 := 0; _i2 <= 1; _i2, v_1_0, v_1_1 = _i2+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
z := v_1_1
v.reset(OpMul32)
v0 := b.NewValue0(v.Pos, OpAdd32, t)
v0.AddArg2(y, z)
v.AddArg2(x, v0)
return true
}
}
}
break
}
// match: (Add32 (Const32 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Add32 (Const32 [1]) (Com32 x))
// result: (Neg32 x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 1 || v_1.Op != OpCom32 {
continue
}
x := v_1.Args[0]
v.reset(OpNeg32)
v.AddArg(x)
return true
}
break
}
// match: (Add32 (Add32 i:(Const32 <t>) z) x)
// cond: (z.Op != OpConst32 && x.Op != OpConst32)
// result: (Add32 i (Add32 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAdd32 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst32 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst32 && x.Op != OpConst32) {
continue
}
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpAdd32, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Add32 (Sub32 i:(Const32 <t>) z) x)
// cond: (z.Op != OpConst32 && x.Op != OpConst32)
// result: (Add32 i (Sub32 <t> x z))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpSub32 {
continue
}
z := v_0.Args[1]
i := v_0.Args[0]
if i.Op != OpConst32 {
continue
}
t := i.Type
x := v_1
if !(z.Op != OpConst32 && x.Op != OpConst32) {
continue
}
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpSub32, t)
v0.AddArg2(x, z)
v.AddArg2(i, v0)
return true
}
break
}
// match: (Add32 (Sub32 z i:(Const32 <t>)) x)
// cond: (z.Op != OpConst32 && x.Op != OpConst32)
// result: (Sub32 (Add32 <t> x z) i)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpSub32 {
continue
}
_ = v_0.Args[1]
z := v_0.Args[0]
i := v_0.Args[1]
if i.Op != OpConst32 {
continue
}
t := i.Type
x := v_1
if !(z.Op != OpConst32 && x.Op != OpConst32) {
continue
}
v.reset(OpSub32)
v0 := b.NewValue0(v.Pos, OpAdd32, t)
v0.AddArg2(x, z)
v.AddArg2(v0, i)
return true
}
break
}
// match: (Add32 (Const32 <t> [c]) (Add32 (Const32 <t> [d]) x))
// result: (Add32 (Const32 <t> [c+d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpAdd32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Add32 (Const32 <t> [c]) (Sub32 (Const32 <t> [d]) x))
// result: (Sub32 (Const32 <t> [c+d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpSub32 {
continue
}
x := v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
v.reset(OpSub32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
break
}
// match: (Add32 (Const32 <t> [c]) (Sub32 x (Const32 <t> [d])))
// result: (Add32 (Const32 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpSub32 {
continue
}
_ = v_1.Args[1]
x := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 || v_1_1.Type != t {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpAdd32F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Add32F (Const32F [c]) (Const32F [d]))
// cond: c+d == c+d
// result: (Const32F [c+d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32F {
continue
}
c := auxIntToFloat32(v_0.AuxInt)
if v_1.Op != OpConst32F {
continue
}
d := auxIntToFloat32(v_1.AuxInt)
if !(c+d == c+d) {
continue
}
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(c + d)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpAdd64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Add64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [c+d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c + d)
return true
}
break
}
// match: (Add64 <t> (Mul64 x y) (Mul64 x z))
// result: (Mul64 x (Add64 <t> y z))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpMul64 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if v_1.Op != OpMul64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i2 := 0; _i2 <= 1; _i2, v_1_0, v_1_1 = _i2+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
z := v_1_1
v.reset(OpMul64)
v0 := b.NewValue0(v.Pos, OpAdd64, t)
v0.AddArg2(y, z)
v.AddArg2(x, v0)
return true
}
}
}
break
}
// match: (Add64 (Const64 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Add64 (Const64 [1]) (Com64 x))
// result: (Neg64 x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 1 || v_1.Op != OpCom64 {
continue
}
x := v_1.Args[0]
v.reset(OpNeg64)
v.AddArg(x)
return true
}
break
}
// match: (Add64 (Add64 i:(Const64 <t>) z) x)
// cond: (z.Op != OpConst64 && x.Op != OpConst64)
// result: (Add64 i (Add64 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAdd64 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst64 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst64 && x.Op != OpConst64) {
continue
}
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpAdd64, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Add64 (Sub64 i:(Const64 <t>) z) x)
// cond: (z.Op != OpConst64 && x.Op != OpConst64)
// result: (Add64 i (Sub64 <t> x z))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpSub64 {
continue
}
z := v_0.Args[1]
i := v_0.Args[0]
if i.Op != OpConst64 {
continue
}
t := i.Type
x := v_1
if !(z.Op != OpConst64 && x.Op != OpConst64) {
continue
}
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpSub64, t)
v0.AddArg2(x, z)
v.AddArg2(i, v0)
return true
}
break
}
// match: (Add64 (Sub64 z i:(Const64 <t>)) x)
// cond: (z.Op != OpConst64 && x.Op != OpConst64)
// result: (Sub64 (Add64 <t> x z) i)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpSub64 {
continue
}
_ = v_0.Args[1]
z := v_0.Args[0]
i := v_0.Args[1]
if i.Op != OpConst64 {
continue
}
t := i.Type
x := v_1
if !(z.Op != OpConst64 && x.Op != OpConst64) {
continue
}
v.reset(OpSub64)
v0 := b.NewValue0(v.Pos, OpAdd64, t)
v0.AddArg2(x, z)
v.AddArg2(v0, i)
return true
}
break
}
// match: (Add64 (Const64 <t> [c]) (Add64 (Const64 <t> [d]) x))
// result: (Add64 (Const64 <t> [c+d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpAdd64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Add64 (Const64 <t> [c]) (Sub64 (Const64 <t> [d]) x))
// result: (Sub64 (Const64 <t> [c+d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpSub64 {
continue
}
x := v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
v.reset(OpSub64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
break
}
// match: (Add64 (Const64 <t> [c]) (Sub64 x (Const64 <t> [d])))
// result: (Add64 (Const64 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpSub64 {
continue
}
_ = v_1.Args[1]
x := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != t {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpAdd64F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Add64F (Const64F [c]) (Const64F [d]))
// cond: c+d == c+d
// result: (Const64F [c+d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64F {
continue
}
c := auxIntToFloat64(v_0.AuxInt)
if v_1.Op != OpConst64F {
continue
}
d := auxIntToFloat64(v_1.AuxInt)
if !(c+d == c+d) {
continue
}
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(c + d)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpAdd8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Add8 (Const8 [c]) (Const8 [d]))
// result: (Const8 [c+d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c + d)
return true
}
break
}
// match: (Add8 <t> (Mul8 x y) (Mul8 x z))
// result: (Mul8 x (Add8 <t> y z))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpMul8 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if v_1.Op != OpMul8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i2 := 0; _i2 <= 1; _i2, v_1_0, v_1_1 = _i2+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
z := v_1_1
v.reset(OpMul8)
v0 := b.NewValue0(v.Pos, OpAdd8, t)
v0.AddArg2(y, z)
v.AddArg2(x, v0)
return true
}
}
}
break
}
// match: (Add8 (Const8 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Add8 (Const8 [1]) (Com8 x))
// result: (Neg8 x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 1 || v_1.Op != OpCom8 {
continue
}
x := v_1.Args[0]
v.reset(OpNeg8)
v.AddArg(x)
return true
}
break
}
// match: (Add8 (Add8 i:(Const8 <t>) z) x)
// cond: (z.Op != OpConst8 && x.Op != OpConst8)
// result: (Add8 i (Add8 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAdd8 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst8 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst8 && x.Op != OpConst8) {
continue
}
v.reset(OpAdd8)
v0 := b.NewValue0(v.Pos, OpAdd8, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Add8 (Sub8 i:(Const8 <t>) z) x)
// cond: (z.Op != OpConst8 && x.Op != OpConst8)
// result: (Add8 i (Sub8 <t> x z))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpSub8 {
continue
}
z := v_0.Args[1]
i := v_0.Args[0]
if i.Op != OpConst8 {
continue
}
t := i.Type
x := v_1
if !(z.Op != OpConst8 && x.Op != OpConst8) {
continue
}
v.reset(OpAdd8)
v0 := b.NewValue0(v.Pos, OpSub8, t)
v0.AddArg2(x, z)
v.AddArg2(i, v0)
return true
}
break
}
// match: (Add8 (Sub8 z i:(Const8 <t>)) x)
// cond: (z.Op != OpConst8 && x.Op != OpConst8)
// result: (Sub8 (Add8 <t> x z) i)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpSub8 {
continue
}
_ = v_0.Args[1]
z := v_0.Args[0]
i := v_0.Args[1]
if i.Op != OpConst8 {
continue
}
t := i.Type
x := v_1
if !(z.Op != OpConst8 && x.Op != OpConst8) {
continue
}
v.reset(OpSub8)
v0 := b.NewValue0(v.Pos, OpAdd8, t)
v0.AddArg2(x, z)
v.AddArg2(v0, i)
return true
}
break
}
// match: (Add8 (Const8 <t> [c]) (Add8 (Const8 <t> [d]) x))
// result: (Add8 (Const8 <t> [c+d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpAdd8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
continue
}
d := auxIntToInt8(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAdd8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Add8 (Const8 <t> [c]) (Sub8 (Const8 <t> [d]) x))
// result: (Sub8 (Const8 <t> [c+d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpSub8 {
continue
}
x := v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
continue
}
d := auxIntToInt8(v_1_0.AuxInt)
v.reset(OpSub8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
break
}
// match: (Add8 (Const8 <t> [c]) (Sub8 x (Const8 <t> [d])))
// result: (Add8 (Const8 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpSub8 {
continue
}
_ = v_1.Args[1]
x := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 || v_1_1.Type != t {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
v.reset(OpAdd8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpAddPtr(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (AddPtr <t> x (Const64 [c]))
// result: (OffPtr <t> x [c])
for {
t := v.Type
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
v.reset(OpOffPtr)
v.Type = t
v.AuxInt = int64ToAuxInt(c)
v.AddArg(x)
return true
}
// match: (AddPtr <t> x (Const32 [c]))
// result: (OffPtr <t> x [int64(c)])
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpOffPtr)
v.Type = t
v.AuxInt = int64ToAuxInt(int64(c))
v.AddArg(x)
return true
}
return false
}
func rewriteValuegeneric_OpAnd16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (And16 (Const16 [c]) (Const16 [d]))
// result: (Const16 [c&d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c & d)
return true
}
break
}
// match: (And16 (Const16 [m]) (Rsh16Ux64 _ (Const64 [c])))
// cond: c >= int64(16-ntz16(m))
// result: (Const16 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
m := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpRsh16Ux64 {
continue
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= int64(16-ntz16(m))) {
continue
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
break
}
// match: (And16 (Const16 [m]) (Lsh16x64 _ (Const64 [c])))
// cond: c >= int64(16-nlz16(m))
// result: (Const16 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
m := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpLsh16x64 {
continue
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= int64(16-nlz16(m))) {
continue
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
break
}
// match: (And16 x x)
// result: x
for {
x := v_0
if x != v_1 {
break
}
v.copyOf(x)
return true
}
// match: (And16 (Const16 [-1]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != -1 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (And16 (Const16 [0]) _)
// result: (Const16 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
continue
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
break
}
// match: (And16 x (And16 x y))
// result: (And16 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpAnd16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.reset(OpAnd16)
v.AddArg2(x, y)
return true
}
}
break
}
// match: (And16 (And16 i:(Const16 <t>) z) x)
// cond: (z.Op != OpConst16 && x.Op != OpConst16)
// result: (And16 i (And16 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd16 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst16 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst16 && x.Op != OpConst16) {
continue
}
v.reset(OpAnd16)
v0 := b.NewValue0(v.Pos, OpAnd16, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (And16 (Const16 <t> [c]) (And16 (Const16 <t> [d]) x))
// result: (And16 (Const16 <t> [c&d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpAnd16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
continue
}
d := auxIntToInt16(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAnd16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c & d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpAnd32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (And32 (Const32 [c]) (Const32 [d]))
// result: (Const32 [c&d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c & d)
return true
}
break
}
// match: (And32 (Const32 [m]) (Rsh32Ux64 _ (Const64 [c])))
// cond: c >= int64(32-ntz32(m))
// result: (Const32 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpRsh32Ux64 {
continue
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= int64(32-ntz32(m))) {
continue
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
break
}
// match: (And32 (Const32 [m]) (Lsh32x64 _ (Const64 [c])))
// cond: c >= int64(32-nlz32(m))
// result: (Const32 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpLsh32x64 {
continue
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= int64(32-nlz32(m))) {
continue
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
break
}
// match: (And32 x x)
// result: x
for {
x := v_0
if x != v_1 {
break
}
v.copyOf(x)
return true
}
// match: (And32 (Const32 [-1]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != -1 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (And32 (Const32 [0]) _)
// result: (Const32 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
continue
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
break
}
// match: (And32 x (And32 x y))
// result: (And32 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpAnd32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.reset(OpAnd32)
v.AddArg2(x, y)
return true
}
}
break
}
// match: (And32 (And32 i:(Const32 <t>) z) x)
// cond: (z.Op != OpConst32 && x.Op != OpConst32)
// result: (And32 i (And32 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd32 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst32 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst32 && x.Op != OpConst32) {
continue
}
v.reset(OpAnd32)
v0 := b.NewValue0(v.Pos, OpAnd32, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (And32 (Const32 <t> [c]) (And32 (Const32 <t> [d]) x))
// result: (And32 (Const32 <t> [c&d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpAnd32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAnd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c & d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpAnd64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (And64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [c&d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c & d)
return true
}
break
}
// match: (And64 (Const64 [m]) (Rsh64Ux64 _ (Const64 [c])))
// cond: c >= int64(64-ntz64(m))
// result: (Const64 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpRsh64Ux64 {
continue
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= int64(64-ntz64(m))) {
continue
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
break
}
// match: (And64 (Const64 [m]) (Lsh64x64 _ (Const64 [c])))
// cond: c >= int64(64-nlz64(m))
// result: (Const64 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpLsh64x64 {
continue
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= int64(64-nlz64(m))) {
continue
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
break
}
// match: (And64 x x)
// result: x
for {
x := v_0
if x != v_1 {
break
}
v.copyOf(x)
return true
}
// match: (And64 (Const64 [-1]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != -1 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (And64 (Const64 [0]) _)
// result: (Const64 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
continue
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
break
}
// match: (And64 x (And64 x y))
// result: (And64 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpAnd64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.reset(OpAnd64)
v.AddArg2(x, y)
return true
}
}
break
}
// match: (And64 (And64 i:(Const64 <t>) z) x)
// cond: (z.Op != OpConst64 && x.Op != OpConst64)
// result: (And64 i (And64 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd64 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst64 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst64 && x.Op != OpConst64) {
continue
}
v.reset(OpAnd64)
v0 := b.NewValue0(v.Pos, OpAnd64, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (And64 (Const64 <t> [c]) (And64 (Const64 <t> [d]) x))
// result: (And64 (Const64 <t> [c&d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpAnd64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAnd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c & d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpAnd8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (And8 (Const8 [c]) (Const8 [d]))
// result: (Const8 [c&d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c & d)
return true
}
break
}
// match: (And8 (Const8 [m]) (Rsh8Ux64 _ (Const64 [c])))
// cond: c >= int64(8-ntz8(m))
// result: (Const8 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
m := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpRsh8Ux64 {
continue
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= int64(8-ntz8(m))) {
continue
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
break
}
// match: (And8 (Const8 [m]) (Lsh8x64 _ (Const64 [c])))
// cond: c >= int64(8-nlz8(m))
// result: (Const8 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
m := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpLsh8x64 {
continue
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= int64(8-nlz8(m))) {
continue
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
break
}
// match: (And8 x x)
// result: x
for {
x := v_0
if x != v_1 {
break
}
v.copyOf(x)
return true
}
// match: (And8 (Const8 [-1]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != -1 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (And8 (Const8 [0]) _)
// result: (Const8 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
continue
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
break
}
// match: (And8 x (And8 x y))
// result: (And8 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpAnd8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.reset(OpAnd8)
v.AddArg2(x, y)
return true
}
}
break
}
// match: (And8 (And8 i:(Const8 <t>) z) x)
// cond: (z.Op != OpConst8 && x.Op != OpConst8)
// result: (And8 i (And8 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd8 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst8 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst8 && x.Op != OpConst8) {
continue
}
v.reset(OpAnd8)
v0 := b.NewValue0(v.Pos, OpAnd8, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (And8 (Const8 <t> [c]) (And8 (Const8 <t> [d]) x))
// result: (And8 (Const8 <t> [c&d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpAnd8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
continue
}
d := auxIntToInt8(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAnd8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c & d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpAndB(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (AndB (Leq64 (Const64 [c]) x) (Less64 x (Const64 [d])))
// cond: d >= c
// result: (Less64U (Sub64 <x.Type> x (Const64 <x.Type> [c])) (Const64 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq64 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLess64 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(d >= c) {
continue
}
v.reset(OpLess64U)
v0 := b.NewValue0(v.Pos, OpSub64, x.Type)
v1 := b.NewValue0(v.Pos, OpConst64, x.Type)
v1.AuxInt = int64ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq64 (Const64 [c]) x) (Leq64 x (Const64 [d])))
// cond: d >= c
// result: (Leq64U (Sub64 <x.Type> x (Const64 <x.Type> [c])) (Const64 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq64 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLeq64 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(d >= c) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpSub64, x.Type)
v1 := b.NewValue0(v.Pos, OpConst64, x.Type)
v1.AuxInt = int64ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq32 (Const32 [c]) x) (Less32 x (Const32 [d])))
// cond: d >= c
// result: (Less32U (Sub32 <x.Type> x (Const32 <x.Type> [c])) (Const32 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq32 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLess32 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(d >= c) {
continue
}
v.reset(OpLess32U)
v0 := b.NewValue0(v.Pos, OpSub32, x.Type)
v1 := b.NewValue0(v.Pos, OpConst32, x.Type)
v1.AuxInt = int32ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq32 (Const32 [c]) x) (Leq32 x (Const32 [d])))
// cond: d >= c
// result: (Leq32U (Sub32 <x.Type> x (Const32 <x.Type> [c])) (Const32 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq32 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLeq32 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(d >= c) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpSub32, x.Type)
v1 := b.NewValue0(v.Pos, OpConst32, x.Type)
v1.AuxInt = int32ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq16 (Const16 [c]) x) (Less16 x (Const16 [d])))
// cond: d >= c
// result: (Less16U (Sub16 <x.Type> x (Const16 <x.Type> [c])) (Const16 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq16 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLess16 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(d >= c) {
continue
}
v.reset(OpLess16U)
v0 := b.NewValue0(v.Pos, OpSub16, x.Type)
v1 := b.NewValue0(v.Pos, OpConst16, x.Type)
v1.AuxInt = int16ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq16 (Const16 [c]) x) (Leq16 x (Const16 [d])))
// cond: d >= c
// result: (Leq16U (Sub16 <x.Type> x (Const16 <x.Type> [c])) (Const16 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq16 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLeq16 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(d >= c) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpSub16, x.Type)
v1 := b.NewValue0(v.Pos, OpConst16, x.Type)
v1.AuxInt = int16ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq8 (Const8 [c]) x) (Less8 x (Const8 [d])))
// cond: d >= c
// result: (Less8U (Sub8 <x.Type> x (Const8 <x.Type> [c])) (Const8 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq8 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLess8 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(d >= c) {
continue
}
v.reset(OpLess8U)
v0 := b.NewValue0(v.Pos, OpSub8, x.Type)
v1 := b.NewValue0(v.Pos, OpConst8, x.Type)
v1.AuxInt = int8ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq8 (Const8 [c]) x) (Leq8 x (Const8 [d])))
// cond: d >= c
// result: (Leq8U (Sub8 <x.Type> x (Const8 <x.Type> [c])) (Const8 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq8 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLeq8 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(d >= c) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpSub8, x.Type)
v1 := b.NewValue0(v.Pos, OpConst8, x.Type)
v1.AuxInt = int8ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less64 (Const64 [c]) x) (Less64 x (Const64 [d])))
// cond: d >= c+1 && c+1 > c
// result: (Less64U (Sub64 <x.Type> x (Const64 <x.Type> [c+1])) (Const64 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess64 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLess64 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(d >= c+1 && c+1 > c) {
continue
}
v.reset(OpLess64U)
v0 := b.NewValue0(v.Pos, OpSub64, x.Type)
v1 := b.NewValue0(v.Pos, OpConst64, x.Type)
v1.AuxInt = int64ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less64 (Const64 [c]) x) (Leq64 x (Const64 [d])))
// cond: d >= c+1 && c+1 > c
// result: (Leq64U (Sub64 <x.Type> x (Const64 <x.Type> [c+1])) (Const64 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess64 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLeq64 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(d >= c+1 && c+1 > c) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpSub64, x.Type)
v1 := b.NewValue0(v.Pos, OpConst64, x.Type)
v1.AuxInt = int64ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less32 (Const32 [c]) x) (Less32 x (Const32 [d])))
// cond: d >= c+1 && c+1 > c
// result: (Less32U (Sub32 <x.Type> x (Const32 <x.Type> [c+1])) (Const32 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess32 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLess32 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(d >= c+1 && c+1 > c) {
continue
}
v.reset(OpLess32U)
v0 := b.NewValue0(v.Pos, OpSub32, x.Type)
v1 := b.NewValue0(v.Pos, OpConst32, x.Type)
v1.AuxInt = int32ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less32 (Const32 [c]) x) (Leq32 x (Const32 [d])))
// cond: d >= c+1 && c+1 > c
// result: (Leq32U (Sub32 <x.Type> x (Const32 <x.Type> [c+1])) (Const32 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess32 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLeq32 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(d >= c+1 && c+1 > c) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpSub32, x.Type)
v1 := b.NewValue0(v.Pos, OpConst32, x.Type)
v1.AuxInt = int32ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less16 (Const16 [c]) x) (Less16 x (Const16 [d])))
// cond: d >= c+1 && c+1 > c
// result: (Less16U (Sub16 <x.Type> x (Const16 <x.Type> [c+1])) (Const16 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess16 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLess16 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(d >= c+1 && c+1 > c) {
continue
}
v.reset(OpLess16U)
v0 := b.NewValue0(v.Pos, OpSub16, x.Type)
v1 := b.NewValue0(v.Pos, OpConst16, x.Type)
v1.AuxInt = int16ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less16 (Const16 [c]) x) (Leq16 x (Const16 [d])))
// cond: d >= c+1 && c+1 > c
// result: (Leq16U (Sub16 <x.Type> x (Const16 <x.Type> [c+1])) (Const16 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess16 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLeq16 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(d >= c+1 && c+1 > c) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpSub16, x.Type)
v1 := b.NewValue0(v.Pos, OpConst16, x.Type)
v1.AuxInt = int16ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less8 (Const8 [c]) x) (Less8 x (Const8 [d])))
// cond: d >= c+1 && c+1 > c
// result: (Less8U (Sub8 <x.Type> x (Const8 <x.Type> [c+1])) (Const8 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess8 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLess8 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(d >= c+1 && c+1 > c) {
continue
}
v.reset(OpLess8U)
v0 := b.NewValue0(v.Pos, OpSub8, x.Type)
v1 := b.NewValue0(v.Pos, OpConst8, x.Type)
v1.AuxInt = int8ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less8 (Const8 [c]) x) (Leq8 x (Const8 [d])))
// cond: d >= c+1 && c+1 > c
// result: (Leq8U (Sub8 <x.Type> x (Const8 <x.Type> [c+1])) (Const8 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess8 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLeq8 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(d >= c+1 && c+1 > c) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpSub8, x.Type)
v1 := b.NewValue0(v.Pos, OpConst8, x.Type)
v1.AuxInt = int8ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq64U (Const64 [c]) x) (Less64U x (Const64 [d])))
// cond: uint64(d) >= uint64(c)
// result: (Less64U (Sub64 <x.Type> x (Const64 <x.Type> [c])) (Const64 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq64U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLess64U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(uint64(d) >= uint64(c)) {
continue
}
v.reset(OpLess64U)
v0 := b.NewValue0(v.Pos, OpSub64, x.Type)
v1 := b.NewValue0(v.Pos, OpConst64, x.Type)
v1.AuxInt = int64ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq64U (Const64 [c]) x) (Leq64U x (Const64 [d])))
// cond: uint64(d) >= uint64(c)
// result: (Leq64U (Sub64 <x.Type> x (Const64 <x.Type> [c])) (Const64 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq64U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLeq64U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(uint64(d) >= uint64(c)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpSub64, x.Type)
v1 := b.NewValue0(v.Pos, OpConst64, x.Type)
v1.AuxInt = int64ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq32U (Const32 [c]) x) (Less32U x (Const32 [d])))
// cond: uint32(d) >= uint32(c)
// result: (Less32U (Sub32 <x.Type> x (Const32 <x.Type> [c])) (Const32 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq32U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLess32U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(uint32(d) >= uint32(c)) {
continue
}
v.reset(OpLess32U)
v0 := b.NewValue0(v.Pos, OpSub32, x.Type)
v1 := b.NewValue0(v.Pos, OpConst32, x.Type)
v1.AuxInt = int32ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq32U (Const32 [c]) x) (Leq32U x (Const32 [d])))
// cond: uint32(d) >= uint32(c)
// result: (Leq32U (Sub32 <x.Type> x (Const32 <x.Type> [c])) (Const32 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq32U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLeq32U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(uint32(d) >= uint32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpSub32, x.Type)
v1 := b.NewValue0(v.Pos, OpConst32, x.Type)
v1.AuxInt = int32ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq16U (Const16 [c]) x) (Less16U x (Const16 [d])))
// cond: uint16(d) >= uint16(c)
// result: (Less16U (Sub16 <x.Type> x (Const16 <x.Type> [c])) (Const16 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq16U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLess16U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(uint16(d) >= uint16(c)) {
continue
}
v.reset(OpLess16U)
v0 := b.NewValue0(v.Pos, OpSub16, x.Type)
v1 := b.NewValue0(v.Pos, OpConst16, x.Type)
v1.AuxInt = int16ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq16U (Const16 [c]) x) (Leq16U x (Const16 [d])))
// cond: uint16(d) >= uint16(c)
// result: (Leq16U (Sub16 <x.Type> x (Const16 <x.Type> [c])) (Const16 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq16U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLeq16U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(uint16(d) >= uint16(c)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpSub16, x.Type)
v1 := b.NewValue0(v.Pos, OpConst16, x.Type)
v1.AuxInt = int16ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq8U (Const8 [c]) x) (Less8U x (Const8 [d])))
// cond: uint8(d) >= uint8(c)
// result: (Less8U (Sub8 <x.Type> x (Const8 <x.Type> [c])) (Const8 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq8U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLess8U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(uint8(d) >= uint8(c)) {
continue
}
v.reset(OpLess8U)
v0 := b.NewValue0(v.Pos, OpSub8, x.Type)
v1 := b.NewValue0(v.Pos, OpConst8, x.Type)
v1.AuxInt = int8ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Leq8U (Const8 [c]) x) (Leq8U x (Const8 [d])))
// cond: uint8(d) >= uint8(c)
// result: (Leq8U (Sub8 <x.Type> x (Const8 <x.Type> [c])) (Const8 <x.Type> [d-c]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq8U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLeq8U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(uint8(d) >= uint8(c)) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpSub8, x.Type)
v1 := b.NewValue0(v.Pos, OpConst8, x.Type)
v1.AuxInt = int8ToAuxInt(c)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d - c)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less64U (Const64 [c]) x) (Less64U x (Const64 [d])))
// cond: uint64(d) >= uint64(c+1) && uint64(c+1) > uint64(c)
// result: (Less64U (Sub64 <x.Type> x (Const64 <x.Type> [c+1])) (Const64 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess64U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLess64U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(uint64(d) >= uint64(c+1) && uint64(c+1) > uint64(c)) {
continue
}
v.reset(OpLess64U)
v0 := b.NewValue0(v.Pos, OpSub64, x.Type)
v1 := b.NewValue0(v.Pos, OpConst64, x.Type)
v1.AuxInt = int64ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less64U (Const64 [c]) x) (Leq64U x (Const64 [d])))
// cond: uint64(d) >= uint64(c+1) && uint64(c+1) > uint64(c)
// result: (Leq64U (Sub64 <x.Type> x (Const64 <x.Type> [c+1])) (Const64 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess64U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLeq64U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(uint64(d) >= uint64(c+1) && uint64(c+1) > uint64(c)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpSub64, x.Type)
v1 := b.NewValue0(v.Pos, OpConst64, x.Type)
v1.AuxInt = int64ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less32U (Const32 [c]) x) (Less32U x (Const32 [d])))
// cond: uint32(d) >= uint32(c+1) && uint32(c+1) > uint32(c)
// result: (Less32U (Sub32 <x.Type> x (Const32 <x.Type> [c+1])) (Const32 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess32U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLess32U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(uint32(d) >= uint32(c+1) && uint32(c+1) > uint32(c)) {
continue
}
v.reset(OpLess32U)
v0 := b.NewValue0(v.Pos, OpSub32, x.Type)
v1 := b.NewValue0(v.Pos, OpConst32, x.Type)
v1.AuxInt = int32ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less32U (Const32 [c]) x) (Leq32U x (Const32 [d])))
// cond: uint32(d) >= uint32(c+1) && uint32(c+1) > uint32(c)
// result: (Leq32U (Sub32 <x.Type> x (Const32 <x.Type> [c+1])) (Const32 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess32U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLeq32U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(uint32(d) >= uint32(c+1) && uint32(c+1) > uint32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpSub32, x.Type)
v1 := b.NewValue0(v.Pos, OpConst32, x.Type)
v1.AuxInt = int32ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less16U (Const16 [c]) x) (Less16U x (Const16 [d])))
// cond: uint16(d) >= uint16(c+1) && uint16(c+1) > uint16(c)
// result: (Less16U (Sub16 <x.Type> x (Const16 <x.Type> [c+1])) (Const16 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess16U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLess16U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(uint16(d) >= uint16(c+1) && uint16(c+1) > uint16(c)) {
continue
}
v.reset(OpLess16U)
v0 := b.NewValue0(v.Pos, OpSub16, x.Type)
v1 := b.NewValue0(v.Pos, OpConst16, x.Type)
v1.AuxInt = int16ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less16U (Const16 [c]) x) (Leq16U x (Const16 [d])))
// cond: uint16(d) >= uint16(c+1) && uint16(c+1) > uint16(c)
// result: (Leq16U (Sub16 <x.Type> x (Const16 <x.Type> [c+1])) (Const16 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess16U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLeq16U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(uint16(d) >= uint16(c+1) && uint16(c+1) > uint16(c)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpSub16, x.Type)
v1 := b.NewValue0(v.Pos, OpConst16, x.Type)
v1.AuxInt = int16ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less8U (Const8 [c]) x) (Less8U x (Const8 [d])))
// cond: uint8(d) >= uint8(c+1) && uint8(c+1) > uint8(c)
// result: (Less8U (Sub8 <x.Type> x (Const8 <x.Type> [c+1])) (Const8 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess8U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLess8U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(uint8(d) >= uint8(c+1) && uint8(c+1) > uint8(c)) {
continue
}
v.reset(OpLess8U)
v0 := b.NewValue0(v.Pos, OpSub8, x.Type)
v1 := b.NewValue0(v.Pos, OpConst8, x.Type)
v1.AuxInt = int8ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
// match: (AndB (Less8U (Const8 [c]) x) (Leq8U x (Const8 [d])))
// cond: uint8(d) >= uint8(c+1) && uint8(c+1) > uint8(c)
// result: (Leq8U (Sub8 <x.Type> x (Const8 <x.Type> [c+1])) (Const8 <x.Type> [d-c-1]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess8U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLeq8U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(uint8(d) >= uint8(c+1) && uint8(c+1) > uint8(c)) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpSub8, x.Type)
v1 := b.NewValue0(v.Pos, OpConst8, x.Type)
v1.AuxInt = int8ToAuxInt(c + 1)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d - c - 1)
v.AddArg2(v0, v2)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpArraySelect(v *Value) bool {
v_0 := v.Args[0]
// match: (ArraySelect (ArrayMake1 x))
// result: x
for {
if v_0.Op != OpArrayMake1 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (ArraySelect [0] (IData x))
// result: (IData x)
for {
if auxIntToInt64(v.AuxInt) != 0 || v_0.Op != OpIData {
break
}
x := v_0.Args[0]
v.reset(OpIData)
v.AddArg(x)
return true
}
return false
}
func rewriteValuegeneric_OpCom16(v *Value) bool {
v_0 := v.Args[0]
// match: (Com16 (Com16 x))
// result: x
for {
if v_0.Op != OpCom16 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Com16 (Const16 [c]))
// result: (Const16 [^c])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(^c)
return true
}
// match: (Com16 (Add16 (Const16 [-1]) x))
// result: (Neg16 x)
for {
if v_0.Op != OpAdd16 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst16 || auxIntToInt16(v_0_0.AuxInt) != -1 {
continue
}
x := v_0_1
v.reset(OpNeg16)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpCom32(v *Value) bool {
v_0 := v.Args[0]
// match: (Com32 (Com32 x))
// result: x
for {
if v_0.Op != OpCom32 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Com32 (Const32 [c]))
// result: (Const32 [^c])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(^c)
return true
}
// match: (Com32 (Add32 (Const32 [-1]) x))
// result: (Neg32 x)
for {
if v_0.Op != OpAdd32 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst32 || auxIntToInt32(v_0_0.AuxInt) != -1 {
continue
}
x := v_0_1
v.reset(OpNeg32)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpCom64(v *Value) bool {
v_0 := v.Args[0]
// match: (Com64 (Com64 x))
// result: x
for {
if v_0.Op != OpCom64 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Com64 (Const64 [c]))
// result: (Const64 [^c])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(^c)
return true
}
// match: (Com64 (Add64 (Const64 [-1]) x))
// result: (Neg64 x)
for {
if v_0.Op != OpAdd64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst64 || auxIntToInt64(v_0_0.AuxInt) != -1 {
continue
}
x := v_0_1
v.reset(OpNeg64)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpCom8(v *Value) bool {
v_0 := v.Args[0]
// match: (Com8 (Com8 x))
// result: x
for {
if v_0.Op != OpCom8 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Com8 (Const8 [c]))
// result: (Const8 [^c])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(^c)
return true
}
// match: (Com8 (Add8 (Const8 [-1]) x))
// result: (Neg8 x)
for {
if v_0.Op != OpAdd8 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst8 || auxIntToInt8(v_0_0.AuxInt) != -1 {
continue
}
x := v_0_1
v.reset(OpNeg8)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpConstInterface(v *Value) bool {
b := v.Block
typ := &b.Func.Config.Types
// match: (ConstInterface)
// result: (IMake (ConstNil <typ.Uintptr>) (ConstNil <typ.BytePtr>))
for {
v.reset(OpIMake)
v0 := b.NewValue0(v.Pos, OpConstNil, typ.Uintptr)
v1 := b.NewValue0(v.Pos, OpConstNil, typ.BytePtr)
v.AddArg2(v0, v1)
return true
}
}
func rewriteValuegeneric_OpConstSlice(v *Value) bool {
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (ConstSlice)
// cond: config.PtrSize == 4
// result: (SliceMake (ConstNil <v.Type.Elem().PtrTo()>) (Const32 <typ.Int> [0]) (Const32 <typ.Int> [0]))
for {
if !(config.PtrSize == 4) {
break
}
v.reset(OpSliceMake)
v0 := b.NewValue0(v.Pos, OpConstNil, v.Type.Elem().PtrTo())
v1 := b.NewValue0(v.Pos, OpConst32, typ.Int)
v1.AuxInt = int32ToAuxInt(0)
v.AddArg3(v0, v1, v1)
return true
}
// match: (ConstSlice)
// cond: config.PtrSize == 8
// result: (SliceMake (ConstNil <v.Type.Elem().PtrTo()>) (Const64 <typ.Int> [0]) (Const64 <typ.Int> [0]))
for {
if !(config.PtrSize == 8) {
break
}
v.reset(OpSliceMake)
v0 := b.NewValue0(v.Pos, OpConstNil, v.Type.Elem().PtrTo())
v1 := b.NewValue0(v.Pos, OpConst64, typ.Int)
v1.AuxInt = int64ToAuxInt(0)
v.AddArg3(v0, v1, v1)
return true
}
return false
}
func rewriteValuegeneric_OpConstString(v *Value) bool {
b := v.Block
config := b.Func.Config
fe := b.Func.fe
typ := &b.Func.Config.Types
// match: (ConstString {str})
// cond: config.PtrSize == 4 && str == ""
// result: (StringMake (ConstNil) (Const32 <typ.Int> [0]))
for {
str := auxToString(v.Aux)
if !(config.PtrSize == 4 && str == "") {
break
}
v.reset(OpStringMake)
v0 := b.NewValue0(v.Pos, OpConstNil, typ.BytePtr)
v1 := b.NewValue0(v.Pos, OpConst32, typ.Int)
v1.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v1)
return true
}
// match: (ConstString {str})
// cond: config.PtrSize == 8 && str == ""
// result: (StringMake (ConstNil) (Const64 <typ.Int> [0]))
for {
str := auxToString(v.Aux)
if !(config.PtrSize == 8 && str == "") {
break
}
v.reset(OpStringMake)
v0 := b.NewValue0(v.Pos, OpConstNil, typ.BytePtr)
v1 := b.NewValue0(v.Pos, OpConst64, typ.Int)
v1.AuxInt = int64ToAuxInt(0)
v.AddArg2(v0, v1)
return true
}
// match: (ConstString {str})
// cond: config.PtrSize == 4 && str != ""
// result: (StringMake (Addr <typ.BytePtr> {fe.StringData(str)} (SB)) (Const32 <typ.Int> [int32(len(str))]))
for {
str := auxToString(v.Aux)
if !(config.PtrSize == 4 && str != "") {
break
}
v.reset(OpStringMake)
v0 := b.NewValue0(v.Pos, OpAddr, typ.BytePtr)
v0.Aux = symToAux(fe.StringData(str))
v1 := b.NewValue0(v.Pos, OpSB, typ.Uintptr)
v0.AddArg(v1)
v2 := b.NewValue0(v.Pos, OpConst32, typ.Int)
v2.AuxInt = int32ToAuxInt(int32(len(str)))
v.AddArg2(v0, v2)
return true
}
// match: (ConstString {str})
// cond: config.PtrSize == 8 && str != ""
// result: (StringMake (Addr <typ.BytePtr> {fe.StringData(str)} (SB)) (Const64 <typ.Int> [int64(len(str))]))
for {
str := auxToString(v.Aux)
if !(config.PtrSize == 8 && str != "") {
break
}
v.reset(OpStringMake)
v0 := b.NewValue0(v.Pos, OpAddr, typ.BytePtr)
v0.Aux = symToAux(fe.StringData(str))
v1 := b.NewValue0(v.Pos, OpSB, typ.Uintptr)
v0.AddArg(v1)
v2 := b.NewValue0(v.Pos, OpConst64, typ.Int)
v2.AuxInt = int64ToAuxInt(int64(len(str)))
v.AddArg2(v0, v2)
return true
}
return false
}
func rewriteValuegeneric_OpConvert(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Convert (Add64 (Convert ptr mem) off) mem)
// result: (AddPtr ptr off)
for {
if v_0.Op != OpAdd64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConvert {
continue
}
mem := v_0_0.Args[1]
ptr := v_0_0.Args[0]
off := v_0_1
if mem != v_1 {
continue
}
v.reset(OpAddPtr)
v.AddArg2(ptr, off)
return true
}
break
}
// match: (Convert (Add32 (Convert ptr mem) off) mem)
// result: (AddPtr ptr off)
for {
if v_0.Op != OpAdd32 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConvert {
continue
}
mem := v_0_0.Args[1]
ptr := v_0_0.Args[0]
off := v_0_1
if mem != v_1 {
continue
}
v.reset(OpAddPtr)
v.AddArg2(ptr, off)
return true
}
break
}
// match: (Convert (Convert ptr mem) mem)
// result: ptr
for {
if v_0.Op != OpConvert {
break
}
mem := v_0.Args[1]
ptr := v_0.Args[0]
if mem != v_1 {
break
}
v.copyOf(ptr)
return true
}
return false
}
func rewriteValuegeneric_OpCtz16(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
// match: (Ctz16 (Const16 [c]))
// cond: config.PtrSize == 4
// result: (Const32 [int32(ntz16(c))])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if !(config.PtrSize == 4) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(ntz16(c)))
return true
}
// match: (Ctz16 (Const16 [c]))
// cond: config.PtrSize == 8
// result: (Const64 [int64(ntz16(c))])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if !(config.PtrSize == 8) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(ntz16(c)))
return true
}
return false
}
func rewriteValuegeneric_OpCtz32(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
// match: (Ctz32 (Const32 [c]))
// cond: config.PtrSize == 4
// result: (Const32 [int32(ntz32(c))])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if !(config.PtrSize == 4) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(ntz32(c)))
return true
}
// match: (Ctz32 (Const32 [c]))
// cond: config.PtrSize == 8
// result: (Const64 [int64(ntz32(c))])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if !(config.PtrSize == 8) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(ntz32(c)))
return true
}
return false
}
func rewriteValuegeneric_OpCtz64(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
// match: (Ctz64 (Const64 [c]))
// cond: config.PtrSize == 4
// result: (Const32 [int32(ntz64(c))])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if !(config.PtrSize == 4) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(ntz64(c)))
return true
}
// match: (Ctz64 (Const64 [c]))
// cond: config.PtrSize == 8
// result: (Const64 [int64(ntz64(c))])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if !(config.PtrSize == 8) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(ntz64(c)))
return true
}
return false
}
func rewriteValuegeneric_OpCtz8(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
// match: (Ctz8 (Const8 [c]))
// cond: config.PtrSize == 4
// result: (Const32 [int32(ntz8(c))])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if !(config.PtrSize == 4) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(ntz8(c)))
return true
}
// match: (Ctz8 (Const8 [c]))
// cond: config.PtrSize == 8
// result: (Const64 [int64(ntz8(c))])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if !(config.PtrSize == 8) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(ntz8(c)))
return true
}
return false
}
func rewriteValuegeneric_OpCvt32Fto32(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt32Fto32 (Const32F [c]))
// result: (Const32 [int32(c)])
for {
if v_0.Op != OpConst32F {
break
}
c := auxIntToFloat32(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt32Fto64(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt32Fto64 (Const32F [c]))
// result: (Const64 [int64(c)])
for {
if v_0.Op != OpConst32F {
break
}
c := auxIntToFloat32(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt32Fto64F(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt32Fto64F (Const32F [c]))
// result: (Const64F [float64(c)])
for {
if v_0.Op != OpConst32F {
break
}
c := auxIntToFloat32(v_0.AuxInt)
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(float64(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt32to32F(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt32to32F (Const32 [c]))
// result: (Const32F [float32(c)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(float32(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt32to64F(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt32to64F (Const32 [c]))
// result: (Const64F [float64(c)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(float64(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt64Fto32(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt64Fto32 (Const64F [c]))
// result: (Const32 [int32(c)])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt64Fto32F(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt64Fto32F (Const64F [c]))
// result: (Const32F [float32(c)])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(float32(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt64Fto64(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt64Fto64 (Const64F [c]))
// result: (Const64 [int64(c)])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt64to32F(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt64to32F (Const64 [c]))
// result: (Const32F [float32(c)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(float32(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvt64to64F(v *Value) bool {
v_0 := v.Args[0]
// match: (Cvt64to64F (Const64 [c]))
// result: (Const64F [float64(c)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(float64(c))
return true
}
return false
}
func rewriteValuegeneric_OpCvtBoolToUint8(v *Value) bool {
v_0 := v.Args[0]
// match: (CvtBoolToUint8 (ConstBool [false]))
// result: (Const8 [0])
for {
if v_0.Op != OpConstBool || auxIntToBool(v_0.AuxInt) != false {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (CvtBoolToUint8 (ConstBool [true]))
// result: (Const8 [1])
for {
if v_0.Op != OpConstBool || auxIntToBool(v_0.AuxInt) != true {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(1)
return true
}
return false
}
func rewriteValuegeneric_OpDiv16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Div16 (Const16 [c]) (Const16 [d]))
// cond: d != 0
// result: (Const16 [c/d])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c / d)
return true
}
// match: (Div16 n (Const16 [c]))
// cond: isNonNegative(n) && isPowerOfTwo16(c)
// result: (Rsh16Ux64 n (Const64 <typ.UInt64> [log16(c)]))
for {
n := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(isNonNegative(n) && isPowerOfTwo16(c)) {
break
}
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log16(c))
v.AddArg2(n, v0)
return true
}
// match: (Div16 <t> n (Const16 [c]))
// cond: c < 0 && c != -1<<15
// result: (Neg16 (Div16 <t> n (Const16 <t> [-c])))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(c < 0 && c != -1<<15) {
break
}
v.reset(OpNeg16)
v0 := b.NewValue0(v.Pos, OpDiv16, t)
v1 := b.NewValue0(v.Pos, OpConst16, t)
v1.AuxInt = int16ToAuxInt(-c)
v0.AddArg2(n, v1)
v.AddArg(v0)
return true
}
// match: (Div16 <t> x (Const16 [-1<<15]))
// result: (Rsh16Ux64 (And16 <t> x (Neg16 <t> x)) (Const64 <typ.UInt64> [15]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 || auxIntToInt16(v_1.AuxInt) != -1<<15 {
break
}
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpAnd16, t)
v1 := b.NewValue0(v.Pos, OpNeg16, t)
v1.AddArg(x)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(15)
v.AddArg2(v0, v2)
return true
}
// match: (Div16 <t> n (Const16 [c]))
// cond: isPowerOfTwo16(c)
// result: (Rsh16x64 (Add16 <t> n (Rsh16Ux64 <t> (Rsh16x64 <t> n (Const64 <typ.UInt64> [15])) (Const64 <typ.UInt64> [int64(16-log16(c))]))) (Const64 <typ.UInt64> [int64(log16(c))]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(isPowerOfTwo16(c)) {
break
}
v.reset(OpRsh16x64)
v0 := b.NewValue0(v.Pos, OpAdd16, t)
v1 := b.NewValue0(v.Pos, OpRsh16Ux64, t)
v2 := b.NewValue0(v.Pos, OpRsh16x64, t)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(15)
v2.AddArg2(n, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(16 - log16(c)))
v1.AddArg2(v2, v4)
v0.AddArg2(n, v1)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(int64(log16(c)))
v.AddArg2(v0, v5)
return true
}
// match: (Div16 <t> x (Const16 [c]))
// cond: smagicOK16(c)
// result: (Sub16 <t> (Rsh32x64 <t> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(smagic16(c).m)]) (SignExt16to32 x)) (Const64 <typ.UInt64> [16+smagic16(c).s])) (Rsh32x64 <t> (SignExt16to32 x) (Const64 <typ.UInt64> [31])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(smagicOK16(c)) {
break
}
v.reset(OpSub16)
v.Type = t
v0 := b.NewValue0(v.Pos, OpRsh32x64, t)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(smagic16(c).m))
v3 := b.NewValue0(v.Pos, OpSignExt16to32, typ.Int32)
v3.AddArg(x)
v1.AddArg2(v2, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(16 + smagic16(c).s)
v0.AddArg2(v1, v4)
v5 := b.NewValue0(v.Pos, OpRsh32x64, t)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(31)
v5.AddArg2(v3, v6)
v.AddArg2(v0, v5)
return true
}
return false
}
func rewriteValuegeneric_OpDiv16u(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (Div16u (Const16 [c]) (Const16 [d]))
// cond: d != 0
// result: (Const16 [int16(uint16(c)/uint16(d))])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(int16(uint16(c) / uint16(d)))
return true
}
// match: (Div16u n (Const16 [c]))
// cond: isPowerOfTwo16(c)
// result: (Rsh16Ux64 n (Const64 <typ.UInt64> [log16(c)]))
for {
n := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(isPowerOfTwo16(c)) {
break
}
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log16(c))
v.AddArg2(n, v0)
return true
}
// match: (Div16u x (Const16 [c]))
// cond: umagicOK16(c) && config.RegSize == 8
// result: (Trunc64to16 (Rsh64Ux64 <typ.UInt64> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(1<<16+umagic16(c).m)]) (ZeroExt16to64 x)) (Const64 <typ.UInt64> [16+umagic16(c).s])))
for {
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(umagicOK16(c) && config.RegSize == 8) {
break
}
v.reset(OpTrunc64to16)
v0 := b.NewValue0(v.Pos, OpRsh64Ux64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(1<<16 + umagic16(c).m))
v3 := b.NewValue0(v.Pos, OpZeroExt16to64, typ.UInt64)
v3.AddArg(x)
v1.AddArg2(v2, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(16 + umagic16(c).s)
v0.AddArg2(v1, v4)
v.AddArg(v0)
return true
}
// match: (Div16u x (Const16 [c]))
// cond: umagicOK16(c) && config.RegSize == 4 && umagic16(c).m&1 == 0
// result: (Trunc32to16 (Rsh32Ux64 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(1<<15+umagic16(c).m/2)]) (ZeroExt16to32 x)) (Const64 <typ.UInt64> [16+umagic16(c).s-1])))
for {
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(umagicOK16(c) && config.RegSize == 4 && umagic16(c).m&1 == 0) {
break
}
v.reset(OpTrunc32to16)
v0 := b.NewValue0(v.Pos, OpRsh32Ux64, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(1<<15 + umagic16(c).m/2))
v3 := b.NewValue0(v.Pos, OpZeroExt16to32, typ.UInt32)
v3.AddArg(x)
v1.AddArg2(v2, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(16 + umagic16(c).s - 1)
v0.AddArg2(v1, v4)
v.AddArg(v0)
return true
}
// match: (Div16u x (Const16 [c]))
// cond: umagicOK16(c) && config.RegSize == 4 && c&1 == 0
// result: (Trunc32to16 (Rsh32Ux64 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(1<<15+(umagic16(c).m+1)/2)]) (Rsh32Ux64 <typ.UInt32> (ZeroExt16to32 x) (Const64 <typ.UInt64> [1]))) (Const64 <typ.UInt64> [16+umagic16(c).s-2])))
for {
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(umagicOK16(c) && config.RegSize == 4 && c&1 == 0) {
break
}
v.reset(OpTrunc32to16)
v0 := b.NewValue0(v.Pos, OpRsh32Ux64, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(1<<15 + (umagic16(c).m+1)/2))
v3 := b.NewValue0(v.Pos, OpRsh32Ux64, typ.UInt32)
v4 := b.NewValue0(v.Pos, OpZeroExt16to32, typ.UInt32)
v4.AddArg(x)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(1)
v3.AddArg2(v4, v5)
v1.AddArg2(v2, v3)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(16 + umagic16(c).s - 2)
v0.AddArg2(v1, v6)
v.AddArg(v0)
return true
}
// match: (Div16u x (Const16 [c]))
// cond: umagicOK16(c) && config.RegSize == 4 && config.useAvg
// result: (Trunc32to16 (Rsh32Ux64 <typ.UInt32> (Avg32u (Lsh32x64 <typ.UInt32> (ZeroExt16to32 x) (Const64 <typ.UInt64> [16])) (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(umagic16(c).m)]) (ZeroExt16to32 x))) (Const64 <typ.UInt64> [16+umagic16(c).s-1])))
for {
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(umagicOK16(c) && config.RegSize == 4 && config.useAvg) {
break
}
v.reset(OpTrunc32to16)
v0 := b.NewValue0(v.Pos, OpRsh32Ux64, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpAvg32u, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpLsh32x64, typ.UInt32)
v3 := b.NewValue0(v.Pos, OpZeroExt16to32, typ.UInt32)
v3.AddArg(x)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(16)
v2.AddArg2(v3, v4)
v5 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v6 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v6.AuxInt = int32ToAuxInt(int32(umagic16(c).m))
v5.AddArg2(v6, v3)
v1.AddArg2(v2, v5)
v7 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v7.AuxInt = int64ToAuxInt(16 + umagic16(c).s - 1)
v0.AddArg2(v1, v7)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpDiv32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (Div32 (Const32 [c]) (Const32 [d]))
// cond: d != 0
// result: (Const32 [c/d])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c / d)
return true
}
// match: (Div32 n (Const32 [c]))
// cond: isNonNegative(n) && isPowerOfTwo32(c)
// result: (Rsh32Ux64 n (Const64 <typ.UInt64> [log32(c)]))
for {
n := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(isNonNegative(n) && isPowerOfTwo32(c)) {
break
}
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log32(c))
v.AddArg2(n, v0)
return true
}
// match: (Div32 <t> n (Const32 [c]))
// cond: c < 0 && c != -1<<31
// result: (Neg32 (Div32 <t> n (Const32 <t> [-c])))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(c < 0 && c != -1<<31) {
break
}
v.reset(OpNeg32)
v0 := b.NewValue0(v.Pos, OpDiv32, t)
v1 := b.NewValue0(v.Pos, OpConst32, t)
v1.AuxInt = int32ToAuxInt(-c)
v0.AddArg2(n, v1)
v.AddArg(v0)
return true
}
// match: (Div32 <t> x (Const32 [-1<<31]))
// result: (Rsh32Ux64 (And32 <t> x (Neg32 <t> x)) (Const64 <typ.UInt64> [31]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 || auxIntToInt32(v_1.AuxInt) != -1<<31 {
break
}
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpAnd32, t)
v1 := b.NewValue0(v.Pos, OpNeg32, t)
v1.AddArg(x)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(31)
v.AddArg2(v0, v2)
return true
}
// match: (Div32 <t> n (Const32 [c]))
// cond: isPowerOfTwo32(c)
// result: (Rsh32x64 (Add32 <t> n (Rsh32Ux64 <t> (Rsh32x64 <t> n (Const64 <typ.UInt64> [31])) (Const64 <typ.UInt64> [int64(32-log32(c))]))) (Const64 <typ.UInt64> [int64(log32(c))]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(isPowerOfTwo32(c)) {
break
}
v.reset(OpRsh32x64)
v0 := b.NewValue0(v.Pos, OpAdd32, t)
v1 := b.NewValue0(v.Pos, OpRsh32Ux64, t)
v2 := b.NewValue0(v.Pos, OpRsh32x64, t)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(31)
v2.AddArg2(n, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(32 - log32(c)))
v1.AddArg2(v2, v4)
v0.AddArg2(n, v1)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(int64(log32(c)))
v.AddArg2(v0, v5)
return true
}
// match: (Div32 <t> x (Const32 [c]))
// cond: smagicOK32(c) && config.RegSize == 8
// result: (Sub32 <t> (Rsh64x64 <t> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(smagic32(c).m)]) (SignExt32to64 x)) (Const64 <typ.UInt64> [32+smagic32(c).s])) (Rsh64x64 <t> (SignExt32to64 x) (Const64 <typ.UInt64> [63])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(smagicOK32(c) && config.RegSize == 8) {
break
}
v.reset(OpSub32)
v.Type = t
v0 := b.NewValue0(v.Pos, OpRsh64x64, t)
v1 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(smagic32(c).m))
v3 := b.NewValue0(v.Pos, OpSignExt32to64, typ.Int64)
v3.AddArg(x)
v1.AddArg2(v2, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(32 + smagic32(c).s)
v0.AddArg2(v1, v4)
v5 := b.NewValue0(v.Pos, OpRsh64x64, t)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(63)
v5.AddArg2(v3, v6)
v.AddArg2(v0, v5)
return true
}
// match: (Div32 <t> x (Const32 [c]))
// cond: smagicOK32(c) && config.RegSize == 4 && smagic32(c).m&1 == 0 && config.useHmul
// result: (Sub32 <t> (Rsh32x64 <t> (Hmul32 <t> (Const32 <typ.UInt32> [int32(smagic32(c).m/2)]) x) (Const64 <typ.UInt64> [smagic32(c).s-1])) (Rsh32x64 <t> x (Const64 <typ.UInt64> [31])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(smagicOK32(c) && config.RegSize == 4 && smagic32(c).m&1 == 0 && config.useHmul) {
break
}
v.reset(OpSub32)
v.Type = t
v0 := b.NewValue0(v.Pos, OpRsh32x64, t)
v1 := b.NewValue0(v.Pos, OpHmul32, t)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(smagic32(c).m / 2))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(smagic32(c).s - 1)
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpRsh32x64, t)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(31)
v4.AddArg2(x, v5)
v.AddArg2(v0, v4)
return true
}
// match: (Div32 <t> x (Const32 [c]))
// cond: smagicOK32(c) && config.RegSize == 4 && smagic32(c).m&1 != 0 && config.useHmul
// result: (Sub32 <t> (Rsh32x64 <t> (Add32 <t> (Hmul32 <t> (Const32 <typ.UInt32> [int32(smagic32(c).m)]) x) x) (Const64 <typ.UInt64> [smagic32(c).s])) (Rsh32x64 <t> x (Const64 <typ.UInt64> [31])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(smagicOK32(c) && config.RegSize == 4 && smagic32(c).m&1 != 0 && config.useHmul) {
break
}
v.reset(OpSub32)
v.Type = t
v0 := b.NewValue0(v.Pos, OpRsh32x64, t)
v1 := b.NewValue0(v.Pos, OpAdd32, t)
v2 := b.NewValue0(v.Pos, OpHmul32, t)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(smagic32(c).m))
v2.AddArg2(v3, x)
v1.AddArg2(v2, x)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(smagic32(c).s)
v0.AddArg2(v1, v4)
v5 := b.NewValue0(v.Pos, OpRsh32x64, t)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(31)
v5.AddArg2(x, v6)
v.AddArg2(v0, v5)
return true
}
return false
}
func rewriteValuegeneric_OpDiv32F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Div32F (Const32F [c]) (Const32F [d]))
// cond: c/d == c/d
// result: (Const32F [c/d])
for {
if v_0.Op != OpConst32F {
break
}
c := auxIntToFloat32(v_0.AuxInt)
if v_1.Op != OpConst32F {
break
}
d := auxIntToFloat32(v_1.AuxInt)
if !(c/d == c/d) {
break
}
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(c / d)
return true
}
// match: (Div32F x (Const32F <t> [c]))
// cond: reciprocalExact32(c)
// result: (Mul32F x (Const32F <t> [1/c]))
for {
x := v_0
if v_1.Op != OpConst32F {
break
}
t := v_1.Type
c := auxIntToFloat32(v_1.AuxInt)
if !(reciprocalExact32(c)) {
break
}
v.reset(OpMul32F)
v0 := b.NewValue0(v.Pos, OpConst32F, t)
v0.AuxInt = float32ToAuxInt(1 / c)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpDiv32u(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (Div32u (Const32 [c]) (Const32 [d]))
// cond: d != 0
// result: (Const32 [int32(uint32(c)/uint32(d))])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(uint32(c) / uint32(d)))
return true
}
// match: (Div32u n (Const32 [c]))
// cond: isPowerOfTwo32(c)
// result: (Rsh32Ux64 n (Const64 <typ.UInt64> [log32(c)]))
for {
n := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(isPowerOfTwo32(c)) {
break
}
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log32(c))
v.AddArg2(n, v0)
return true
}
// match: (Div32u x (Const32 [c]))
// cond: umagicOK32(c) && config.RegSize == 4 && umagic32(c).m&1 == 0 && config.useHmul
// result: (Rsh32Ux64 <typ.UInt32> (Hmul32u <typ.UInt32> (Const32 <typ.UInt32> [int32(1<<31+umagic32(c).m/2)]) x) (Const64 <typ.UInt64> [umagic32(c).s-1]))
for {
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(umagicOK32(c) && config.RegSize == 4 && umagic32(c).m&1 == 0 && config.useHmul) {
break
}
v.reset(OpRsh32Ux64)
v.Type = typ.UInt32
v0 := b.NewValue0(v.Pos, OpHmul32u, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v1.AuxInt = int32ToAuxInt(int32(1<<31 + umagic32(c).m/2))
v0.AddArg2(v1, x)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(umagic32(c).s - 1)
v.AddArg2(v0, v2)
return true
}
// match: (Div32u x (Const32 [c]))
// cond: umagicOK32(c) && config.RegSize == 4 && c&1 == 0 && config.useHmul
// result: (Rsh32Ux64 <typ.UInt32> (Hmul32u <typ.UInt32> (Const32 <typ.UInt32> [int32(1<<31+(umagic32(c).m+1)/2)]) (Rsh32Ux64 <typ.UInt32> x (Const64 <typ.UInt64> [1]))) (Const64 <typ.UInt64> [umagic32(c).s-2]))
for {
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(umagicOK32(c) && config.RegSize == 4 && c&1 == 0 && config.useHmul) {
break
}
v.reset(OpRsh32Ux64)
v.Type = typ.UInt32
v0 := b.NewValue0(v.Pos, OpHmul32u, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v1.AuxInt = int32ToAuxInt(int32(1<<31 + (umagic32(c).m+1)/2))
v2 := b.NewValue0(v.Pos, OpRsh32Ux64, typ.UInt32)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(1)
v2.AddArg2(x, v3)
v0.AddArg2(v1, v2)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(umagic32(c).s - 2)
v.AddArg2(v0, v4)
return true
}
// match: (Div32u x (Const32 [c]))
// cond: umagicOK32(c) && config.RegSize == 4 && config.useAvg && config.useHmul
// result: (Rsh32Ux64 <typ.UInt32> (Avg32u x (Hmul32u <typ.UInt32> (Const32 <typ.UInt32> [int32(umagic32(c).m)]) x)) (Const64 <typ.UInt64> [umagic32(c).s-1]))
for {
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(umagicOK32(c) && config.RegSize == 4 && config.useAvg && config.useHmul) {
break
}
v.reset(OpRsh32Ux64)
v.Type = typ.UInt32
v0 := b.NewValue0(v.Pos, OpAvg32u, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpHmul32u, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(umagic32(c).m))
v1.AddArg2(v2, x)
v0.AddArg2(x, v1)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(umagic32(c).s - 1)
v.AddArg2(v0, v3)
return true
}
// match: (Div32u x (Const32 [c]))
// cond: umagicOK32(c) && config.RegSize == 8 && umagic32(c).m&1 == 0
// result: (Trunc64to32 (Rsh64Ux64 <typ.UInt64> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(1<<31+umagic32(c).m/2)]) (ZeroExt32to64 x)) (Const64 <typ.UInt64> [32+umagic32(c).s-1])))
for {
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(umagicOK32(c) && config.RegSize == 8 && umagic32(c).m&1 == 0) {
break
}
v.reset(OpTrunc64to32)
v0 := b.NewValue0(v.Pos, OpRsh64Ux64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(1<<31 + umagic32(c).m/2))
v3 := b.NewValue0(v.Pos, OpZeroExt32to64, typ.UInt64)
v3.AddArg(x)
v1.AddArg2(v2, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(32 + umagic32(c).s - 1)
v0.AddArg2(v1, v4)
v.AddArg(v0)
return true
}
// match: (Div32u x (Const32 [c]))
// cond: umagicOK32(c) && config.RegSize == 8 && c&1 == 0
// result: (Trunc64to32 (Rsh64Ux64 <typ.UInt64> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(1<<31+(umagic32(c).m+1)/2)]) (Rsh64Ux64 <typ.UInt64> (ZeroExt32to64 x) (Const64 <typ.UInt64> [1]))) (Const64 <typ.UInt64> [32+umagic32(c).s-2])))
for {
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(umagicOK32(c) && config.RegSize == 8 && c&1 == 0) {
break
}
v.reset(OpTrunc64to32)
v0 := b.NewValue0(v.Pos, OpRsh64Ux64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(1<<31 + (umagic32(c).m+1)/2))
v3 := b.NewValue0(v.Pos, OpRsh64Ux64, typ.UInt64)
v4 := b.NewValue0(v.Pos, OpZeroExt32to64, typ.UInt64)
v4.AddArg(x)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(1)
v3.AddArg2(v4, v5)
v1.AddArg2(v2, v3)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(32 + umagic32(c).s - 2)
v0.AddArg2(v1, v6)
v.AddArg(v0)
return true
}
// match: (Div32u x (Const32 [c]))
// cond: umagicOK32(c) && config.RegSize == 8 && config.useAvg
// result: (Trunc64to32 (Rsh64Ux64 <typ.UInt64> (Avg64u (Lsh64x64 <typ.UInt64> (ZeroExt32to64 x) (Const64 <typ.UInt64> [32])) (Mul64 <typ.UInt64> (Const64 <typ.UInt32> [int64(umagic32(c).m)]) (ZeroExt32to64 x))) (Const64 <typ.UInt64> [32+umagic32(c).s-1])))
for {
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(umagicOK32(c) && config.RegSize == 8 && config.useAvg) {
break
}
v.reset(OpTrunc64to32)
v0 := b.NewValue0(v.Pos, OpRsh64Ux64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpAvg64u, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpLsh64x64, typ.UInt64)
v3 := b.NewValue0(v.Pos, OpZeroExt32to64, typ.UInt64)
v3.AddArg(x)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(32)
v2.AddArg2(v3, v4)
v5 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt32)
v6.AuxInt = int64ToAuxInt(int64(umagic32(c).m))
v5.AddArg2(v6, v3)
v1.AddArg2(v2, v5)
v7 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v7.AuxInt = int64ToAuxInt(32 + umagic32(c).s - 1)
v0.AddArg2(v1, v7)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpDiv64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (Div64 (Const64 [c]) (Const64 [d]))
// cond: d != 0
// result: (Const64 [c/d])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c / d)
return true
}
// match: (Div64 n (Const64 [c]))
// cond: isNonNegative(n) && isPowerOfTwo64(c)
// result: (Rsh64Ux64 n (Const64 <typ.UInt64> [log64(c)]))
for {
n := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(isNonNegative(n) && isPowerOfTwo64(c)) {
break
}
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log64(c))
v.AddArg2(n, v0)
return true
}
// match: (Div64 n (Const64 [-1<<63]))
// cond: isNonNegative(n)
// result: (Const64 [0])
for {
n := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != -1<<63 || !(isNonNegative(n)) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Div64 <t> n (Const64 [c]))
// cond: c < 0 && c != -1<<63
// result: (Neg64 (Div64 <t> n (Const64 <t> [-c])))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(c < 0 && c != -1<<63) {
break
}
v.reset(OpNeg64)
v0 := b.NewValue0(v.Pos, OpDiv64, t)
v1 := b.NewValue0(v.Pos, OpConst64, t)
v1.AuxInt = int64ToAuxInt(-c)
v0.AddArg2(n, v1)
v.AddArg(v0)
return true
}
// match: (Div64 <t> x (Const64 [-1<<63]))
// result: (Rsh64Ux64 (And64 <t> x (Neg64 <t> x)) (Const64 <typ.UInt64> [63]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != -1<<63 {
break
}
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpAnd64, t)
v1 := b.NewValue0(v.Pos, OpNeg64, t)
v1.AddArg(x)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(63)
v.AddArg2(v0, v2)
return true
}
// match: (Div64 <t> n (Const64 [c]))
// cond: isPowerOfTwo64(c)
// result: (Rsh64x64 (Add64 <t> n (Rsh64Ux64 <t> (Rsh64x64 <t> n (Const64 <typ.UInt64> [63])) (Const64 <typ.UInt64> [int64(64-log64(c))]))) (Const64 <typ.UInt64> [int64(log64(c))]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(isPowerOfTwo64(c)) {
break
}
v.reset(OpRsh64x64)
v0 := b.NewValue0(v.Pos, OpAdd64, t)
v1 := b.NewValue0(v.Pos, OpRsh64Ux64, t)
v2 := b.NewValue0(v.Pos, OpRsh64x64, t)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(63)
v2.AddArg2(n, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(64 - log64(c)))
v1.AddArg2(v2, v4)
v0.AddArg2(n, v1)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(int64(log64(c)))
v.AddArg2(v0, v5)
return true
}
// match: (Div64 <t> x (Const64 [c]))
// cond: smagicOK64(c) && smagic64(c).m&1 == 0 && config.useHmul
// result: (Sub64 <t> (Rsh64x64 <t> (Hmul64 <t> (Const64 <typ.UInt64> [int64(smagic64(c).m/2)]) x) (Const64 <typ.UInt64> [smagic64(c).s-1])) (Rsh64x64 <t> x (Const64 <typ.UInt64> [63])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(smagicOK64(c) && smagic64(c).m&1 == 0 && config.useHmul) {
break
}
v.reset(OpSub64)
v.Type = t
v0 := b.NewValue0(v.Pos, OpRsh64x64, t)
v1 := b.NewValue0(v.Pos, OpHmul64, t)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(smagic64(c).m / 2))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(smagic64(c).s - 1)
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpRsh64x64, t)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(63)
v4.AddArg2(x, v5)
v.AddArg2(v0, v4)
return true
}
// match: (Div64 <t> x (Const64 [c]))
// cond: smagicOK64(c) && smagic64(c).m&1 != 0 && config.useHmul
// result: (Sub64 <t> (Rsh64x64 <t> (Add64 <t> (Hmul64 <t> (Const64 <typ.UInt64> [int64(smagic64(c).m)]) x) x) (Const64 <typ.UInt64> [smagic64(c).s])) (Rsh64x64 <t> x (Const64 <typ.UInt64> [63])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(smagicOK64(c) && smagic64(c).m&1 != 0 && config.useHmul) {
break
}
v.reset(OpSub64)
v.Type = t
v0 := b.NewValue0(v.Pos, OpRsh64x64, t)
v1 := b.NewValue0(v.Pos, OpAdd64, t)
v2 := b.NewValue0(v.Pos, OpHmul64, t)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(int64(smagic64(c).m))
v2.AddArg2(v3, x)
v1.AddArg2(v2, x)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(smagic64(c).s)
v0.AddArg2(v1, v4)
v5 := b.NewValue0(v.Pos, OpRsh64x64, t)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(63)
v5.AddArg2(x, v6)
v.AddArg2(v0, v5)
return true
}
return false
}
func rewriteValuegeneric_OpDiv64F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Div64F (Const64F [c]) (Const64F [d]))
// cond: c/d == c/d
// result: (Const64F [c/d])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
if v_1.Op != OpConst64F {
break
}
d := auxIntToFloat64(v_1.AuxInt)
if !(c/d == c/d) {
break
}
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(c / d)
return true
}
// match: (Div64F x (Const64F <t> [c]))
// cond: reciprocalExact64(c)
// result: (Mul64F x (Const64F <t> [1/c]))
for {
x := v_0
if v_1.Op != OpConst64F {
break
}
t := v_1.Type
c := auxIntToFloat64(v_1.AuxInt)
if !(reciprocalExact64(c)) {
break
}
v.reset(OpMul64F)
v0 := b.NewValue0(v.Pos, OpConst64F, t)
v0.AuxInt = float64ToAuxInt(1 / c)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpDiv64u(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (Div64u (Const64 [c]) (Const64 [d]))
// cond: d != 0
// result: (Const64 [int64(uint64(c)/uint64(d))])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(uint64(c) / uint64(d)))
return true
}
// match: (Div64u n (Const64 [c]))
// cond: isPowerOfTwo64(c)
// result: (Rsh64Ux64 n (Const64 <typ.UInt64> [log64(c)]))
for {
n := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(isPowerOfTwo64(c)) {
break
}
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log64(c))
v.AddArg2(n, v0)
return true
}
// match: (Div64u n (Const64 [-1<<63]))
// result: (Rsh64Ux64 n (Const64 <typ.UInt64> [63]))
for {
n := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != -1<<63 {
break
}
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(63)
v.AddArg2(n, v0)
return true
}
// match: (Div64u x (Const64 [c]))
// cond: umagicOK64(c) && config.RegSize == 8 && umagic64(c).m&1 == 0 && config.useHmul
// result: (Rsh64Ux64 <typ.UInt64> (Hmul64u <typ.UInt64> (Const64 <typ.UInt64> [int64(1<<63+umagic64(c).m/2)]) x) (Const64 <typ.UInt64> [umagic64(c).s-1]))
for {
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(umagicOK64(c) && config.RegSize == 8 && umagic64(c).m&1 == 0 && config.useHmul) {
break
}
v.reset(OpRsh64Ux64)
v.Type = typ.UInt64
v0 := b.NewValue0(v.Pos, OpHmul64u, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v1.AuxInt = int64ToAuxInt(int64(1<<63 + umagic64(c).m/2))
v0.AddArg2(v1, x)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(umagic64(c).s - 1)
v.AddArg2(v0, v2)
return true
}
// match: (Div64u x (Const64 [c]))
// cond: umagicOK64(c) && config.RegSize == 8 && c&1 == 0 && config.useHmul
// result: (Rsh64Ux64 <typ.UInt64> (Hmul64u <typ.UInt64> (Const64 <typ.UInt64> [int64(1<<63+(umagic64(c).m+1)/2)]) (Rsh64Ux64 <typ.UInt64> x (Const64 <typ.UInt64> [1]))) (Const64 <typ.UInt64> [umagic64(c).s-2]))
for {
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(umagicOK64(c) && config.RegSize == 8 && c&1 == 0 && config.useHmul) {
break
}
v.reset(OpRsh64Ux64)
v.Type = typ.UInt64
v0 := b.NewValue0(v.Pos, OpHmul64u, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v1.AuxInt = int64ToAuxInt(int64(1<<63 + (umagic64(c).m+1)/2))
v2 := b.NewValue0(v.Pos, OpRsh64Ux64, typ.UInt64)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(1)
v2.AddArg2(x, v3)
v0.AddArg2(v1, v2)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(umagic64(c).s - 2)
v.AddArg2(v0, v4)
return true
}
// match: (Div64u x (Const64 [c]))
// cond: umagicOK64(c) && config.RegSize == 8 && config.useAvg && config.useHmul
// result: (Rsh64Ux64 <typ.UInt64> (Avg64u x (Hmul64u <typ.UInt64> (Const64 <typ.UInt64> [int64(umagic64(c).m)]) x)) (Const64 <typ.UInt64> [umagic64(c).s-1]))
for {
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(umagicOK64(c) && config.RegSize == 8 && config.useAvg && config.useHmul) {
break
}
v.reset(OpRsh64Ux64)
v.Type = typ.UInt64
v0 := b.NewValue0(v.Pos, OpAvg64u, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpHmul64u, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(umagic64(c).m))
v1.AddArg2(v2, x)
v0.AddArg2(x, v1)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(umagic64(c).s - 1)
v.AddArg2(v0, v3)
return true
}
return false
}
func rewriteValuegeneric_OpDiv8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Div8 (Const8 [c]) (Const8 [d]))
// cond: d != 0
// result: (Const8 [c/d])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c / d)
return true
}
// match: (Div8 n (Const8 [c]))
// cond: isNonNegative(n) && isPowerOfTwo8(c)
// result: (Rsh8Ux64 n (Const64 <typ.UInt64> [log8(c)]))
for {
n := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(isNonNegative(n) && isPowerOfTwo8(c)) {
break
}
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log8(c))
v.AddArg2(n, v0)
return true
}
// match: (Div8 <t> n (Const8 [c]))
// cond: c < 0 && c != -1<<7
// result: (Neg8 (Div8 <t> n (Const8 <t> [-c])))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(c < 0 && c != -1<<7) {
break
}
v.reset(OpNeg8)
v0 := b.NewValue0(v.Pos, OpDiv8, t)
v1 := b.NewValue0(v.Pos, OpConst8, t)
v1.AuxInt = int8ToAuxInt(-c)
v0.AddArg2(n, v1)
v.AddArg(v0)
return true
}
// match: (Div8 <t> x (Const8 [-1<<7 ]))
// result: (Rsh8Ux64 (And8 <t> x (Neg8 <t> x)) (Const64 <typ.UInt64> [7 ]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 || auxIntToInt8(v_1.AuxInt) != -1<<7 {
break
}
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpAnd8, t)
v1 := b.NewValue0(v.Pos, OpNeg8, t)
v1.AddArg(x)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(7)
v.AddArg2(v0, v2)
return true
}
// match: (Div8 <t> n (Const8 [c]))
// cond: isPowerOfTwo8(c)
// result: (Rsh8x64 (Add8 <t> n (Rsh8Ux64 <t> (Rsh8x64 <t> n (Const64 <typ.UInt64> [ 7])) (Const64 <typ.UInt64> [int64( 8-log8(c))]))) (Const64 <typ.UInt64> [int64(log8(c))]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(isPowerOfTwo8(c)) {
break
}
v.reset(OpRsh8x64)
v0 := b.NewValue0(v.Pos, OpAdd8, t)
v1 := b.NewValue0(v.Pos, OpRsh8Ux64, t)
v2 := b.NewValue0(v.Pos, OpRsh8x64, t)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(7)
v2.AddArg2(n, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(8 - log8(c)))
v1.AddArg2(v2, v4)
v0.AddArg2(n, v1)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(int64(log8(c)))
v.AddArg2(v0, v5)
return true
}
// match: (Div8 <t> x (Const8 [c]))
// cond: smagicOK8(c)
// result: (Sub8 <t> (Rsh32x64 <t> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(smagic8(c).m)]) (SignExt8to32 x)) (Const64 <typ.UInt64> [8+smagic8(c).s])) (Rsh32x64 <t> (SignExt8to32 x) (Const64 <typ.UInt64> [31])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(smagicOK8(c)) {
break
}
v.reset(OpSub8)
v.Type = t
v0 := b.NewValue0(v.Pos, OpRsh32x64, t)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(smagic8(c).m))
v3 := b.NewValue0(v.Pos, OpSignExt8to32, typ.Int32)
v3.AddArg(x)
v1.AddArg2(v2, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(8 + smagic8(c).s)
v0.AddArg2(v1, v4)
v5 := b.NewValue0(v.Pos, OpRsh32x64, t)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(31)
v5.AddArg2(v3, v6)
v.AddArg2(v0, v5)
return true
}
return false
}
func rewriteValuegeneric_OpDiv8u(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Div8u (Const8 [c]) (Const8 [d]))
// cond: d != 0
// result: (Const8 [int8(uint8(c)/uint8(d))])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(int8(uint8(c) / uint8(d)))
return true
}
// match: (Div8u n (Const8 [c]))
// cond: isPowerOfTwo8(c)
// result: (Rsh8Ux64 n (Const64 <typ.UInt64> [log8(c)]))
for {
n := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(isPowerOfTwo8(c)) {
break
}
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log8(c))
v.AddArg2(n, v0)
return true
}
// match: (Div8u x (Const8 [c]))
// cond: umagicOK8(c)
// result: (Trunc32to8 (Rsh32Ux64 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(1<<8+umagic8(c).m)]) (ZeroExt8to32 x)) (Const64 <typ.UInt64> [8+umagic8(c).s])))
for {
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(umagicOK8(c)) {
break
}
v.reset(OpTrunc32to8)
v0 := b.NewValue0(v.Pos, OpRsh32Ux64, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(1<<8 + umagic8(c).m))
v3 := b.NewValue0(v.Pos, OpZeroExt8to32, typ.UInt32)
v3.AddArg(x)
v1.AddArg2(v2, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(8 + umagic8(c).s)
v0.AddArg2(v1, v4)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpEq16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (Eq16 x x)
// result: (ConstBool [true])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (Eq16 (Const16 <t> [c]) (Add16 (Const16 <t> [d]) x))
// result: (Eq16 (Const16 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpAdd16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
continue
}
d := auxIntToInt16(v_1_0.AuxInt)
x := v_1_1
v.reset(OpEq16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Eq16 (Const16 [c]) (Const16 [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
// match: (Eq16 (Mod16u x (Const16 [c])) (Const16 [0]))
// cond: x.Op != OpConst16 && udivisibleOK16(c) && !hasSmallRotate(config)
// result: (Eq32 (Mod32u <typ.UInt32> (ZeroExt16to32 <typ.UInt32> x) (Const32 <typ.UInt32> [int32(uint16(c))])) (Const32 <typ.UInt32> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpMod16u {
continue
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_1.AuxInt)
if v_1.Op != OpConst16 || auxIntToInt16(v_1.AuxInt) != 0 || !(x.Op != OpConst16 && udivisibleOK16(c) && !hasSmallRotate(config)) {
continue
}
v.reset(OpEq32)
v0 := b.NewValue0(v.Pos, OpMod32u, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpZeroExt16to32, typ.UInt32)
v1.AddArg(x)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(uint16(c)))
v0.AddArg2(v1, v2)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v3)
return true
}
break
}
// match: (Eq16 (Mod16 x (Const16 [c])) (Const16 [0]))
// cond: x.Op != OpConst16 && sdivisibleOK16(c) && !hasSmallRotate(config)
// result: (Eq32 (Mod32 <typ.Int32> (SignExt16to32 <typ.Int32> x) (Const32 <typ.Int32> [int32(c)])) (Const32 <typ.Int32> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpMod16 {
continue
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_1.AuxInt)
if v_1.Op != OpConst16 || auxIntToInt16(v_1.AuxInt) != 0 || !(x.Op != OpConst16 && sdivisibleOK16(c) && !hasSmallRotate(config)) {
continue
}
v.reset(OpEq32)
v0 := b.NewValue0(v.Pos, OpMod32, typ.Int32)
v1 := b.NewValue0(v.Pos, OpSignExt16to32, typ.Int32)
v1.AddArg(x)
v2 := b.NewValue0(v.Pos, OpConst32, typ.Int32)
v2.AuxInt = int32ToAuxInt(int32(c))
v0.AddArg2(v1, v2)
v3 := b.NewValue0(v.Pos, OpConst32, typ.Int32)
v3.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v3)
return true
}
break
}
// match: (Eq16 x (Mul16 (Const16 [c]) (Trunc64to16 (Rsh64Ux64 mul:(Mul64 (Const64 [m]) (ZeroExt16to64 x)) (Const64 [s]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<16+umagic16(c).m) && s == 16+umagic16(c).s && x.Op != OpConst16 && udivisibleOK16(c)
// result: (Leq16U (RotateLeft16 <typ.UInt16> (Mul16 <typ.UInt16> (Const16 <typ.UInt16> [int16(udivisible16(c).m)]) x) (Const16 <typ.UInt16> [int16(16-udivisible16(c).k)]) ) (Const16 <typ.UInt16> [int16(udivisible16(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_1_0.AuxInt)
if v_1_1.Op != OpTrunc64to16 {
continue
}
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh64Ux64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul64 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if mul_1.Op != OpZeroExt16to64 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<16+umagic16(c).m) && s == 16+umagic16(c).s && x.Op != OpConst16 && udivisibleOK16(c)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpRotateLeft16, typ.UInt16)
v1 := b.NewValue0(v.Pos, OpMul16, typ.UInt16)
v2 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v2.AuxInt = int16ToAuxInt(int16(udivisible16(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v3.AuxInt = int16ToAuxInt(int16(16 - udivisible16(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v4.AuxInt = int16ToAuxInt(int16(udivisible16(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq16 x (Mul16 (Const16 [c]) (Trunc32to16 (Rsh32Ux64 mul:(Mul32 (Const32 [m]) (ZeroExt16to32 x)) (Const64 [s]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<15+umagic16(c).m/2) && s == 16+umagic16(c).s-1 && x.Op != OpConst16 && udivisibleOK16(c)
// result: (Leq16U (RotateLeft16 <typ.UInt16> (Mul16 <typ.UInt16> (Const16 <typ.UInt16> [int16(udivisible16(c).m)]) x) (Const16 <typ.UInt16> [int16(16-udivisible16(c).k)]) ) (Const16 <typ.UInt16> [int16(udivisible16(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_1_0.AuxInt)
if v_1_1.Op != OpTrunc32to16 {
continue
}
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh32Ux64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul32 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if mul_1.Op != OpZeroExt16to32 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<15+umagic16(c).m/2) && s == 16+umagic16(c).s-1 && x.Op != OpConst16 && udivisibleOK16(c)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpRotateLeft16, typ.UInt16)
v1 := b.NewValue0(v.Pos, OpMul16, typ.UInt16)
v2 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v2.AuxInt = int16ToAuxInt(int16(udivisible16(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v3.AuxInt = int16ToAuxInt(int16(16 - udivisible16(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v4.AuxInt = int16ToAuxInt(int16(udivisible16(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq16 x (Mul16 (Const16 [c]) (Trunc32to16 (Rsh32Ux64 mul:(Mul32 (Const32 [m]) (Rsh32Ux64 (ZeroExt16to32 x) (Const64 [1]))) (Const64 [s]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<15+(umagic16(c).m+1)/2) && s == 16+umagic16(c).s-2 && x.Op != OpConst16 && udivisibleOK16(c)
// result: (Leq16U (RotateLeft16 <typ.UInt16> (Mul16 <typ.UInt16> (Const16 <typ.UInt16> [int16(udivisible16(c).m)]) x) (Const16 <typ.UInt16> [int16(16-udivisible16(c).k)]) ) (Const16 <typ.UInt16> [int16(udivisible16(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_1_0.AuxInt)
if v_1_1.Op != OpTrunc32to16 {
continue
}
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh32Ux64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul32 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if mul_1.Op != OpRsh32Ux64 {
continue
}
_ = mul_1.Args[1]
mul_1_0 := mul_1.Args[0]
if mul_1_0.Op != OpZeroExt16to32 || x != mul_1_0.Args[0] {
continue
}
mul_1_1 := mul_1.Args[1]
if mul_1_1.Op != OpConst64 || auxIntToInt64(mul_1_1.AuxInt) != 1 {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<15+(umagic16(c).m+1)/2) && s == 16+umagic16(c).s-2 && x.Op != OpConst16 && udivisibleOK16(c)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpRotateLeft16, typ.UInt16)
v1 := b.NewValue0(v.Pos, OpMul16, typ.UInt16)
v2 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v2.AuxInt = int16ToAuxInt(int16(udivisible16(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v3.AuxInt = int16ToAuxInt(int16(16 - udivisible16(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v4.AuxInt = int16ToAuxInt(int16(udivisible16(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq16 x (Mul16 (Const16 [c]) (Trunc32to16 (Rsh32Ux64 (Avg32u (Lsh32x64 (ZeroExt16to32 x) (Const64 [16])) mul:(Mul32 (Const32 [m]) (ZeroExt16to32 x))) (Const64 [s]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(umagic16(c).m) && s == 16+umagic16(c).s-1 && x.Op != OpConst16 && udivisibleOK16(c)
// result: (Leq16U (RotateLeft16 <typ.UInt16> (Mul16 <typ.UInt16> (Const16 <typ.UInt16> [int16(udivisible16(c).m)]) x) (Const16 <typ.UInt16> [int16(16-udivisible16(c).k)]) ) (Const16 <typ.UInt16> [int16(udivisible16(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_1_0.AuxInt)
if v_1_1.Op != OpTrunc32to16 {
continue
}
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh32Ux64 {
continue
}
_ = v_1_1_0.Args[1]
v_1_1_0_0 := v_1_1_0.Args[0]
if v_1_1_0_0.Op != OpAvg32u {
continue
}
_ = v_1_1_0_0.Args[1]
v_1_1_0_0_0 := v_1_1_0_0.Args[0]
if v_1_1_0_0_0.Op != OpLsh32x64 {
continue
}
_ = v_1_1_0_0_0.Args[1]
v_1_1_0_0_0_0 := v_1_1_0_0_0.Args[0]
if v_1_1_0_0_0_0.Op != OpZeroExt16to32 || x != v_1_1_0_0_0_0.Args[0] {
continue
}
v_1_1_0_0_0_1 := v_1_1_0_0_0.Args[1]
if v_1_1_0_0_0_1.Op != OpConst64 || auxIntToInt64(v_1_1_0_0_0_1.AuxInt) != 16 {
continue
}
mul := v_1_1_0_0.Args[1]
if mul.Op != OpMul32 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if mul_1.Op != OpZeroExt16to32 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(umagic16(c).m) && s == 16+umagic16(c).s-1 && x.Op != OpConst16 && udivisibleOK16(c)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpRotateLeft16, typ.UInt16)
v1 := b.NewValue0(v.Pos, OpMul16, typ.UInt16)
v2 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v2.AuxInt = int16ToAuxInt(int16(udivisible16(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v3.AuxInt = int16ToAuxInt(int16(16 - udivisible16(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v4.AuxInt = int16ToAuxInt(int16(udivisible16(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq16 x (Mul16 (Const16 [c]) (Sub16 (Rsh32x64 mul:(Mul32 (Const32 [m]) (SignExt16to32 x)) (Const64 [s])) (Rsh32x64 (SignExt16to32 x) (Const64 [31]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(smagic16(c).m) && s == 16+smagic16(c).s && x.Op != OpConst16 && sdivisibleOK16(c)
// result: (Leq16U (RotateLeft16 <typ.UInt16> (Add16 <typ.UInt16> (Mul16 <typ.UInt16> (Const16 <typ.UInt16> [int16(sdivisible16(c).m)]) x) (Const16 <typ.UInt16> [int16(sdivisible16(c).a)]) ) (Const16 <typ.UInt16> [int16(16-sdivisible16(c).k)]) ) (Const16 <typ.UInt16> [int16(sdivisible16(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_1_0.AuxInt)
if v_1_1.Op != OpSub16 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh32x64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul32 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if mul_1.Op != OpSignExt16to32 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpRsh32x64 {
continue
}
_ = v_1_1_1.Args[1]
v_1_1_1_0 := v_1_1_1.Args[0]
if v_1_1_1_0.Op != OpSignExt16to32 || x != v_1_1_1_0.Args[0] {
continue
}
v_1_1_1_1 := v_1_1_1.Args[1]
if v_1_1_1_1.Op != OpConst64 || auxIntToInt64(v_1_1_1_1.AuxInt) != 31 || !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(smagic16(c).m) && s == 16+smagic16(c).s && x.Op != OpConst16 && sdivisibleOK16(c)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpRotateLeft16, typ.UInt16)
v1 := b.NewValue0(v.Pos, OpAdd16, typ.UInt16)
v2 := b.NewValue0(v.Pos, OpMul16, typ.UInt16)
v3 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v3.AuxInt = int16ToAuxInt(int16(sdivisible16(c).m))
v2.AddArg2(v3, x)
v4 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v4.AuxInt = int16ToAuxInt(int16(sdivisible16(c).a))
v1.AddArg2(v2, v4)
v5 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v5.AuxInt = int16ToAuxInt(int16(16 - sdivisible16(c).k))
v0.AddArg2(v1, v5)
v6 := b.NewValue0(v.Pos, OpConst16, typ.UInt16)
v6.AuxInt = int16ToAuxInt(int16(sdivisible16(c).max))
v.AddArg2(v0, v6)
return true
}
}
}
break
}
// match: (Eq16 n (Lsh16x64 (Rsh16x64 (Add16 <t> n (Rsh16Ux64 <t> (Rsh16x64 <t> n (Const64 <typ.UInt64> [15])) (Const64 <typ.UInt64> [kbar]))) (Const64 <typ.UInt64> [k])) (Const64 <typ.UInt64> [k])) )
// cond: k > 0 && k < 15 && kbar == 16 - k
// result: (Eq16 (And16 <t> n (Const16 <t> [1<<uint(k)-1])) (Const16 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpLsh16x64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpRsh16x64 {
continue
}
_ = v_1_0.Args[1]
v_1_0_0 := v_1_0.Args[0]
if v_1_0_0.Op != OpAdd16 {
continue
}
t := v_1_0_0.Type
_ = v_1_0_0.Args[1]
v_1_0_0_0 := v_1_0_0.Args[0]
v_1_0_0_1 := v_1_0_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0_0_0, v_1_0_0_1 = _i1+1, v_1_0_0_1, v_1_0_0_0 {
if n != v_1_0_0_0 || v_1_0_0_1.Op != OpRsh16Ux64 || v_1_0_0_1.Type != t {
continue
}
_ = v_1_0_0_1.Args[1]
v_1_0_0_1_0 := v_1_0_0_1.Args[0]
if v_1_0_0_1_0.Op != OpRsh16x64 || v_1_0_0_1_0.Type != t {
continue
}
_ = v_1_0_0_1_0.Args[1]
if n != v_1_0_0_1_0.Args[0] {
continue
}
v_1_0_0_1_0_1 := v_1_0_0_1_0.Args[1]
if v_1_0_0_1_0_1.Op != OpConst64 || v_1_0_0_1_0_1.Type != typ.UInt64 || auxIntToInt64(v_1_0_0_1_0_1.AuxInt) != 15 {
continue
}
v_1_0_0_1_1 := v_1_0_0_1.Args[1]
if v_1_0_0_1_1.Op != OpConst64 || v_1_0_0_1_1.Type != typ.UInt64 {
continue
}
kbar := auxIntToInt64(v_1_0_0_1_1.AuxInt)
v_1_0_1 := v_1_0.Args[1]
if v_1_0_1.Op != OpConst64 || v_1_0_1.Type != typ.UInt64 {
continue
}
k := auxIntToInt64(v_1_0_1.AuxInt)
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != typ.UInt64 || auxIntToInt64(v_1_1.AuxInt) != k || !(k > 0 && k < 15 && kbar == 16-k) {
continue
}
v.reset(OpEq16)
v0 := b.NewValue0(v.Pos, OpAnd16, t)
v1 := b.NewValue0(v.Pos, OpConst16, t)
v1.AuxInt = int16ToAuxInt(1<<uint(k) - 1)
v0.AddArg2(n, v1)
v2 := b.NewValue0(v.Pos, OpConst16, t)
v2.AuxInt = int16ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
// match: (Eq16 s:(Sub16 x y) (Const16 [0]))
// cond: s.Uses == 1
// result: (Eq16 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
s := v_0
if s.Op != OpSub16 {
continue
}
y := s.Args[1]
x := s.Args[0]
if v_1.Op != OpConst16 || auxIntToInt16(v_1.AuxInt) != 0 || !(s.Uses == 1) {
continue
}
v.reset(OpEq16)
v.AddArg2(x, y)
return true
}
break
}
// match: (Eq16 (And16 <t> x (Const16 <t> [y])) (Const16 <t> [y]))
// cond: oneBit16(y)
// result: (Neq16 (And16 <t> x (Const16 <t> [y])) (Const16 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd16 {
continue
}
t := v_0.Type
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst16 || v_0_1.Type != t {
continue
}
y := auxIntToInt16(v_0_1.AuxInt)
if v_1.Op != OpConst16 || v_1.Type != t || auxIntToInt16(v_1.AuxInt) != y || !(oneBit16(y)) {
continue
}
v.reset(OpNeq16)
v0 := b.NewValue0(v.Pos, OpAnd16, t)
v1 := b.NewValue0(v.Pos, OpConst16, t)
v1.AuxInt = int16ToAuxInt(y)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, t)
v2.AuxInt = int16ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpEq32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Eq32 x x)
// result: (ConstBool [true])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (Eq32 (Const32 <t> [c]) (Add32 (Const32 <t> [d]) x))
// result: (Eq32 (Const32 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpAdd32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
x := v_1_1
v.reset(OpEq32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Eq32 (Const32 [c]) (Const32 [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Rsh32Ux64 mul:(Hmul32u (Const32 [m]) x) (Const64 [s])) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<31+umagic32(c).m/2) && s == umagic32(c).s-1 && x.Op != OpConst32 && udivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(udivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(32-udivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(udivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpRsh32Ux64 {
continue
}
_ = v_1_1.Args[1]
mul := v_1_1.Args[0]
if mul.Op != OpHmul32u {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if x != mul_1 {
continue
}
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<31+umagic32(c).m/2) && s == umagic32(c).s-1 && x.Op != OpConst32 && udivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(udivisible32(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(32 - udivisible32(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(udivisible32(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Rsh32Ux64 mul:(Hmul32u (Const32 <typ.UInt32> [m]) (Rsh32Ux64 x (Const64 [1]))) (Const64 [s])) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<31+(umagic32(c).m+1)/2) && s == umagic32(c).s-2 && x.Op != OpConst32 && udivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(udivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(32-udivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(udivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpRsh32Ux64 {
continue
}
_ = v_1_1.Args[1]
mul := v_1_1.Args[0]
if mul.Op != OpHmul32u {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 || mul_0.Type != typ.UInt32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if mul_1.Op != OpRsh32Ux64 {
continue
}
_ = mul_1.Args[1]
if x != mul_1.Args[0] {
continue
}
mul_1_1 := mul_1.Args[1]
if mul_1_1.Op != OpConst64 || auxIntToInt64(mul_1_1.AuxInt) != 1 {
continue
}
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<31+(umagic32(c).m+1)/2) && s == umagic32(c).s-2 && x.Op != OpConst32 && udivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(udivisible32(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(32 - udivisible32(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(udivisible32(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Rsh32Ux64 (Avg32u x mul:(Hmul32u (Const32 [m]) x)) (Const64 [s])) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(umagic32(c).m) && s == umagic32(c).s-1 && x.Op != OpConst32 && udivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(udivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(32-udivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(udivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpRsh32Ux64 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpAvg32u {
continue
}
_ = v_1_1_0.Args[1]
if x != v_1_1_0.Args[0] {
continue
}
mul := v_1_1_0.Args[1]
if mul.Op != OpHmul32u {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if x != mul_1 {
continue
}
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(umagic32(c).m) && s == umagic32(c).s-1 && x.Op != OpConst32 && udivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(udivisible32(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(32 - udivisible32(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(udivisible32(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Trunc64to32 (Rsh64Ux64 mul:(Mul64 (Const64 [m]) (ZeroExt32to64 x)) (Const64 [s]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<31+umagic32(c).m/2) && s == 32+umagic32(c).s-1 && x.Op != OpConst32 && udivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(udivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(32-udivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(udivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpTrunc64to32 {
continue
}
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh64Ux64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul64 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if mul_1.Op != OpZeroExt32to64 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<31+umagic32(c).m/2) && s == 32+umagic32(c).s-1 && x.Op != OpConst32 && udivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(udivisible32(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(32 - udivisible32(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(udivisible32(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Trunc64to32 (Rsh64Ux64 mul:(Mul64 (Const64 [m]) (Rsh64Ux64 (ZeroExt32to64 x) (Const64 [1]))) (Const64 [s]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<31+(umagic32(c).m+1)/2) && s == 32+umagic32(c).s-2 && x.Op != OpConst32 && udivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(udivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(32-udivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(udivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpTrunc64to32 {
continue
}
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh64Ux64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul64 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if mul_1.Op != OpRsh64Ux64 {
continue
}
_ = mul_1.Args[1]
mul_1_0 := mul_1.Args[0]
if mul_1_0.Op != OpZeroExt32to64 || x != mul_1_0.Args[0] {
continue
}
mul_1_1 := mul_1.Args[1]
if mul_1_1.Op != OpConst64 || auxIntToInt64(mul_1_1.AuxInt) != 1 {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<31+(umagic32(c).m+1)/2) && s == 32+umagic32(c).s-2 && x.Op != OpConst32 && udivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(udivisible32(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(32 - udivisible32(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(udivisible32(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Trunc64to32 (Rsh64Ux64 (Avg64u (Lsh64x64 (ZeroExt32to64 x) (Const64 [32])) mul:(Mul64 (Const64 [m]) (ZeroExt32to64 x))) (Const64 [s]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(umagic32(c).m) && s == 32+umagic32(c).s-1 && x.Op != OpConst32 && udivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(udivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(32-udivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(udivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpTrunc64to32 {
continue
}
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh64Ux64 {
continue
}
_ = v_1_1_0.Args[1]
v_1_1_0_0 := v_1_1_0.Args[0]
if v_1_1_0_0.Op != OpAvg64u {
continue
}
_ = v_1_1_0_0.Args[1]
v_1_1_0_0_0 := v_1_1_0_0.Args[0]
if v_1_1_0_0_0.Op != OpLsh64x64 {
continue
}
_ = v_1_1_0_0_0.Args[1]
v_1_1_0_0_0_0 := v_1_1_0_0_0.Args[0]
if v_1_1_0_0_0_0.Op != OpZeroExt32to64 || x != v_1_1_0_0_0_0.Args[0] {
continue
}
v_1_1_0_0_0_1 := v_1_1_0_0_0.Args[1]
if v_1_1_0_0_0_1.Op != OpConst64 || auxIntToInt64(v_1_1_0_0_0_1.AuxInt) != 32 {
continue
}
mul := v_1_1_0_0.Args[1]
if mul.Op != OpMul64 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if mul_1.Op != OpZeroExt32to64 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(umagic32(c).m) && s == 32+umagic32(c).s-1 && x.Op != OpConst32 && udivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(udivisible32(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(32 - udivisible32(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(udivisible32(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Sub32 (Rsh64x64 mul:(Mul64 (Const64 [m]) (SignExt32to64 x)) (Const64 [s])) (Rsh64x64 (SignExt32to64 x) (Const64 [63]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(smagic32(c).m) && s == 32+smagic32(c).s && x.Op != OpConst32 && sdivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Add32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(sdivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(sdivisible32(c).a)]) ) (Const32 <typ.UInt32> [int32(32-sdivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(sdivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpSub32 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh64x64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul64 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if mul_1.Op != OpSignExt32to64 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpRsh64x64 {
continue
}
_ = v_1_1_1.Args[1]
v_1_1_1_0 := v_1_1_1.Args[0]
if v_1_1_1_0.Op != OpSignExt32to64 || x != v_1_1_1_0.Args[0] {
continue
}
v_1_1_1_1 := v_1_1_1.Args[1]
if v_1_1_1_1.Op != OpConst64 || auxIntToInt64(v_1_1_1_1.AuxInt) != 63 || !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(smagic32(c).m) && s == 32+smagic32(c).s && x.Op != OpConst32 && sdivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpAdd32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(sdivisible32(c).m))
v2.AddArg2(v3, x)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(sdivisible32(c).a))
v1.AddArg2(v2, v4)
v5 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v5.AuxInt = int32ToAuxInt(int32(32 - sdivisible32(c).k))
v0.AddArg2(v1, v5)
v6 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v6.AuxInt = int32ToAuxInt(int32(sdivisible32(c).max))
v.AddArg2(v0, v6)
return true
}
}
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Sub32 (Rsh32x64 mul:(Hmul32 (Const32 [m]) x) (Const64 [s])) (Rsh32x64 x (Const64 [31]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(smagic32(c).m/2) && s == smagic32(c).s-1 && x.Op != OpConst32 && sdivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Add32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(sdivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(sdivisible32(c).a)]) ) (Const32 <typ.UInt32> [int32(32-sdivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(sdivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpSub32 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh32x64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpHmul32 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if x != mul_1 {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpRsh32x64 {
continue
}
_ = v_1_1_1.Args[1]
if x != v_1_1_1.Args[0] {
continue
}
v_1_1_1_1 := v_1_1_1.Args[1]
if v_1_1_1_1.Op != OpConst64 || auxIntToInt64(v_1_1_1_1.AuxInt) != 31 || !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(smagic32(c).m/2) && s == smagic32(c).s-1 && x.Op != OpConst32 && sdivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpAdd32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(sdivisible32(c).m))
v2.AddArg2(v3, x)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(sdivisible32(c).a))
v1.AddArg2(v2, v4)
v5 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v5.AuxInt = int32ToAuxInt(int32(32 - sdivisible32(c).k))
v0.AddArg2(v1, v5)
v6 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v6.AuxInt = int32ToAuxInt(int32(sdivisible32(c).max))
v.AddArg2(v0, v6)
return true
}
}
}
break
}
// match: (Eq32 x (Mul32 (Const32 [c]) (Sub32 (Rsh32x64 (Add32 mul:(Hmul32 (Const32 [m]) x) x) (Const64 [s])) (Rsh32x64 x (Const64 [31]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(smagic32(c).m) && s == smagic32(c).s && x.Op != OpConst32 && sdivisibleOK32(c)
// result: (Leq32U (RotateLeft32 <typ.UInt32> (Add32 <typ.UInt32> (Mul32 <typ.UInt32> (Const32 <typ.UInt32> [int32(sdivisible32(c).m)]) x) (Const32 <typ.UInt32> [int32(sdivisible32(c).a)]) ) (Const32 <typ.UInt32> [int32(32-sdivisible32(c).k)]) ) (Const32 <typ.UInt32> [int32(sdivisible32(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_0.AuxInt)
if v_1_1.Op != OpSub32 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh32x64 {
continue
}
_ = v_1_1_0.Args[1]
v_1_1_0_0 := v_1_1_0.Args[0]
if v_1_1_0_0.Op != OpAdd32 {
continue
}
_ = v_1_1_0_0.Args[1]
v_1_1_0_0_0 := v_1_1_0_0.Args[0]
v_1_1_0_0_1 := v_1_1_0_0.Args[1]
for _i2 := 0; _i2 <= 1; _i2, v_1_1_0_0_0, v_1_1_0_0_1 = _i2+1, v_1_1_0_0_1, v_1_1_0_0_0 {
mul := v_1_1_0_0_0
if mul.Op != OpHmul32 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i3 := 0; _i3 <= 1; _i3, mul_0, mul_1 = _i3+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if x != mul_1 || x != v_1_1_0_0_1 {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpRsh32x64 {
continue
}
_ = v_1_1_1.Args[1]
if x != v_1_1_1.Args[0] {
continue
}
v_1_1_1_1 := v_1_1_1.Args[1]
if v_1_1_1_1.Op != OpConst64 || auxIntToInt64(v_1_1_1_1.AuxInt) != 31 || !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(smagic32(c).m) && s == smagic32(c).s && x.Op != OpConst32 && sdivisibleOK32(c)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpRotateLeft32, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpAdd32, typ.UInt32)
v2 := b.NewValue0(v.Pos, OpMul32, typ.UInt32)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(int32(sdivisible32(c).m))
v2.AddArg2(v3, x)
v4 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v4.AuxInt = int32ToAuxInt(int32(sdivisible32(c).a))
v1.AddArg2(v2, v4)
v5 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v5.AuxInt = int32ToAuxInt(int32(32 - sdivisible32(c).k))
v0.AddArg2(v1, v5)
v6 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v6.AuxInt = int32ToAuxInt(int32(sdivisible32(c).max))
v.AddArg2(v0, v6)
return true
}
}
}
}
break
}
// match: (Eq32 n (Lsh32x64 (Rsh32x64 (Add32 <t> n (Rsh32Ux64 <t> (Rsh32x64 <t> n (Const64 <typ.UInt64> [31])) (Const64 <typ.UInt64> [kbar]))) (Const64 <typ.UInt64> [k])) (Const64 <typ.UInt64> [k])) )
// cond: k > 0 && k < 31 && kbar == 32 - k
// result: (Eq32 (And32 <t> n (Const32 <t> [1<<uint(k)-1])) (Const32 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpLsh32x64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpRsh32x64 {
continue
}
_ = v_1_0.Args[1]
v_1_0_0 := v_1_0.Args[0]
if v_1_0_0.Op != OpAdd32 {
continue
}
t := v_1_0_0.Type
_ = v_1_0_0.Args[1]
v_1_0_0_0 := v_1_0_0.Args[0]
v_1_0_0_1 := v_1_0_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0_0_0, v_1_0_0_1 = _i1+1, v_1_0_0_1, v_1_0_0_0 {
if n != v_1_0_0_0 || v_1_0_0_1.Op != OpRsh32Ux64 || v_1_0_0_1.Type != t {
continue
}
_ = v_1_0_0_1.Args[1]
v_1_0_0_1_0 := v_1_0_0_1.Args[0]
if v_1_0_0_1_0.Op != OpRsh32x64 || v_1_0_0_1_0.Type != t {
continue
}
_ = v_1_0_0_1_0.Args[1]
if n != v_1_0_0_1_0.Args[0] {
continue
}
v_1_0_0_1_0_1 := v_1_0_0_1_0.Args[1]
if v_1_0_0_1_0_1.Op != OpConst64 || v_1_0_0_1_0_1.Type != typ.UInt64 || auxIntToInt64(v_1_0_0_1_0_1.AuxInt) != 31 {
continue
}
v_1_0_0_1_1 := v_1_0_0_1.Args[1]
if v_1_0_0_1_1.Op != OpConst64 || v_1_0_0_1_1.Type != typ.UInt64 {
continue
}
kbar := auxIntToInt64(v_1_0_0_1_1.AuxInt)
v_1_0_1 := v_1_0.Args[1]
if v_1_0_1.Op != OpConst64 || v_1_0_1.Type != typ.UInt64 {
continue
}
k := auxIntToInt64(v_1_0_1.AuxInt)
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != typ.UInt64 || auxIntToInt64(v_1_1.AuxInt) != k || !(k > 0 && k < 31 && kbar == 32-k) {
continue
}
v.reset(OpEq32)
v0 := b.NewValue0(v.Pos, OpAnd32, t)
v1 := b.NewValue0(v.Pos, OpConst32, t)
v1.AuxInt = int32ToAuxInt(1<<uint(k) - 1)
v0.AddArg2(n, v1)
v2 := b.NewValue0(v.Pos, OpConst32, t)
v2.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
// match: (Eq32 s:(Sub32 x y) (Const32 [0]))
// cond: s.Uses == 1
// result: (Eq32 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
s := v_0
if s.Op != OpSub32 {
continue
}
y := s.Args[1]
x := s.Args[0]
if v_1.Op != OpConst32 || auxIntToInt32(v_1.AuxInt) != 0 || !(s.Uses == 1) {
continue
}
v.reset(OpEq32)
v.AddArg2(x, y)
return true
}
break
}
// match: (Eq32 (And32 <t> x (Const32 <t> [y])) (Const32 <t> [y]))
// cond: oneBit32(y)
// result: (Neq32 (And32 <t> x (Const32 <t> [y])) (Const32 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd32 {
continue
}
t := v_0.Type
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst32 || v_0_1.Type != t {
continue
}
y := auxIntToInt32(v_0_1.AuxInt)
if v_1.Op != OpConst32 || v_1.Type != t || auxIntToInt32(v_1.AuxInt) != y || !(oneBit32(y)) {
continue
}
v.reset(OpNeq32)
v0 := b.NewValue0(v.Pos, OpAnd32, t)
v1 := b.NewValue0(v.Pos, OpConst32, t)
v1.AuxInt = int32ToAuxInt(y)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, t)
v2.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpEq32F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Eq32F (Const32F [c]) (Const32F [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32F {
continue
}
c := auxIntToFloat32(v_0.AuxInt)
if v_1.Op != OpConst32F {
continue
}
d := auxIntToFloat32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpEq64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Eq64 x x)
// result: (ConstBool [true])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (Eq64 (Const64 <t> [c]) (Add64 (Const64 <t> [d]) x))
// result: (Eq64 (Const64 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpAdd64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
x := v_1_1
v.reset(OpEq64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Eq64 (Const64 [c]) (Const64 [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
// match: (Eq64 x (Mul64 (Const64 [c]) (Rsh64Ux64 mul:(Hmul64u (Const64 [m]) x) (Const64 [s])) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<63+umagic64(c).m/2) && s == umagic64(c).s-1 && x.Op != OpConst64 && udivisibleOK64(c)
// result: (Leq64U (RotateLeft64 <typ.UInt64> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(udivisible64(c).m)]) x) (Const64 <typ.UInt64> [64-udivisible64(c).k]) ) (Const64 <typ.UInt64> [int64(udivisible64(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_0.AuxInt)
if v_1_1.Op != OpRsh64Ux64 {
continue
}
_ = v_1_1.Args[1]
mul := v_1_1.Args[0]
if mul.Op != OpHmul64u {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if x != mul_1 {
continue
}
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<63+umagic64(c).m/2) && s == umagic64(c).s-1 && x.Op != OpConst64 && udivisibleOK64(c)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpRotateLeft64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(udivisible64(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(64 - udivisible64(c).k)
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(udivisible64(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq64 x (Mul64 (Const64 [c]) (Rsh64Ux64 mul:(Hmul64u (Const64 [m]) (Rsh64Ux64 x (Const64 [1]))) (Const64 [s])) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<63+(umagic64(c).m+1)/2) && s == umagic64(c).s-2 && x.Op != OpConst64 && udivisibleOK64(c)
// result: (Leq64U (RotateLeft64 <typ.UInt64> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(udivisible64(c).m)]) x) (Const64 <typ.UInt64> [64-udivisible64(c).k]) ) (Const64 <typ.UInt64> [int64(udivisible64(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_0.AuxInt)
if v_1_1.Op != OpRsh64Ux64 {
continue
}
_ = v_1_1.Args[1]
mul := v_1_1.Args[0]
if mul.Op != OpHmul64u {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if mul_1.Op != OpRsh64Ux64 {
continue
}
_ = mul_1.Args[1]
if x != mul_1.Args[0] {
continue
}
mul_1_1 := mul_1.Args[1]
if mul_1_1.Op != OpConst64 || auxIntToInt64(mul_1_1.AuxInt) != 1 {
continue
}
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(1<<63+(umagic64(c).m+1)/2) && s == umagic64(c).s-2 && x.Op != OpConst64 && udivisibleOK64(c)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpRotateLeft64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(udivisible64(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(64 - udivisible64(c).k)
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(udivisible64(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq64 x (Mul64 (Const64 [c]) (Rsh64Ux64 (Avg64u x mul:(Hmul64u (Const64 [m]) x)) (Const64 [s])) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(umagic64(c).m) && s == umagic64(c).s-1 && x.Op != OpConst64 && udivisibleOK64(c)
// result: (Leq64U (RotateLeft64 <typ.UInt64> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(udivisible64(c).m)]) x) (Const64 <typ.UInt64> [64-udivisible64(c).k]) ) (Const64 <typ.UInt64> [int64(udivisible64(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_0.AuxInt)
if v_1_1.Op != OpRsh64Ux64 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpAvg64u {
continue
}
_ = v_1_1_0.Args[1]
if x != v_1_1_0.Args[0] {
continue
}
mul := v_1_1_0.Args[1]
if mul.Op != OpHmul64u {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if x != mul_1 {
continue
}
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(umagic64(c).m) && s == umagic64(c).s-1 && x.Op != OpConst64 && udivisibleOK64(c)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpRotateLeft64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v2.AuxInt = int64ToAuxInt(int64(udivisible64(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(64 - udivisible64(c).k)
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(udivisible64(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq64 x (Mul64 (Const64 [c]) (Sub64 (Rsh64x64 mul:(Hmul64 (Const64 [m]) x) (Const64 [s])) (Rsh64x64 x (Const64 [63]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(smagic64(c).m/2) && s == smagic64(c).s-1 && x.Op != OpConst64 && sdivisibleOK64(c)
// result: (Leq64U (RotateLeft64 <typ.UInt64> (Add64 <typ.UInt64> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(sdivisible64(c).m)]) x) (Const64 <typ.UInt64> [int64(sdivisible64(c).a)]) ) (Const64 <typ.UInt64> [64-sdivisible64(c).k]) ) (Const64 <typ.UInt64> [int64(sdivisible64(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_0.AuxInt)
if v_1_1.Op != OpSub64 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh64x64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpHmul64 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if x != mul_1 {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpRsh64x64 {
continue
}
_ = v_1_1_1.Args[1]
if x != v_1_1_1.Args[0] {
continue
}
v_1_1_1_1 := v_1_1_1.Args[1]
if v_1_1_1_1.Op != OpConst64 || auxIntToInt64(v_1_1_1_1.AuxInt) != 63 || !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(smagic64(c).m/2) && s == smagic64(c).s-1 && x.Op != OpConst64 && sdivisibleOK64(c)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpRotateLeft64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpAdd64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(int64(sdivisible64(c).m))
v2.AddArg2(v3, x)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(sdivisible64(c).a))
v1.AddArg2(v2, v4)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(64 - sdivisible64(c).k)
v0.AddArg2(v1, v5)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(int64(sdivisible64(c).max))
v.AddArg2(v0, v6)
return true
}
}
}
break
}
// match: (Eq64 x (Mul64 (Const64 [c]) (Sub64 (Rsh64x64 (Add64 mul:(Hmul64 (Const64 [m]) x) x) (Const64 [s])) (Rsh64x64 x (Const64 [63]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(smagic64(c).m) && s == smagic64(c).s && x.Op != OpConst64 && sdivisibleOK64(c)
// result: (Leq64U (RotateLeft64 <typ.UInt64> (Add64 <typ.UInt64> (Mul64 <typ.UInt64> (Const64 <typ.UInt64> [int64(sdivisible64(c).m)]) x) (Const64 <typ.UInt64> [int64(sdivisible64(c).a)]) ) (Const64 <typ.UInt64> [64-sdivisible64(c).k]) ) (Const64 <typ.UInt64> [int64(sdivisible64(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_0.AuxInt)
if v_1_1.Op != OpSub64 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh64x64 {
continue
}
_ = v_1_1_0.Args[1]
v_1_1_0_0 := v_1_1_0.Args[0]
if v_1_1_0_0.Op != OpAdd64 {
continue
}
_ = v_1_1_0_0.Args[1]
v_1_1_0_0_0 := v_1_1_0_0.Args[0]
v_1_1_0_0_1 := v_1_1_0_0.Args[1]
for _i2 := 0; _i2 <= 1; _i2, v_1_1_0_0_0, v_1_1_0_0_1 = _i2+1, v_1_1_0_0_1, v_1_1_0_0_0 {
mul := v_1_1_0_0_0
if mul.Op != OpHmul64 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i3 := 0; _i3 <= 1; _i3, mul_0, mul_1 = _i3+1, mul_1, mul_0 {
if mul_0.Op != OpConst64 {
continue
}
m := auxIntToInt64(mul_0.AuxInt)
if x != mul_1 || x != v_1_1_0_0_1 {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpRsh64x64 {
continue
}
_ = v_1_1_1.Args[1]
if x != v_1_1_1.Args[0] {
continue
}
v_1_1_1_1 := v_1_1_1.Args[1]
if v_1_1_1_1.Op != OpConst64 || auxIntToInt64(v_1_1_1_1.AuxInt) != 63 || !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int64(smagic64(c).m) && s == smagic64(c).s && x.Op != OpConst64 && sdivisibleOK64(c)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpRotateLeft64, typ.UInt64)
v1 := b.NewValue0(v.Pos, OpAdd64, typ.UInt64)
v2 := b.NewValue0(v.Pos, OpMul64, typ.UInt64)
v3 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v3.AuxInt = int64ToAuxInt(int64(sdivisible64(c).m))
v2.AddArg2(v3, x)
v4 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v4.AuxInt = int64ToAuxInt(int64(sdivisible64(c).a))
v1.AddArg2(v2, v4)
v5 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v5.AuxInt = int64ToAuxInt(64 - sdivisible64(c).k)
v0.AddArg2(v1, v5)
v6 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v6.AuxInt = int64ToAuxInt(int64(sdivisible64(c).max))
v.AddArg2(v0, v6)
return true
}
}
}
}
break
}
// match: (Eq64 n (Lsh64x64 (Rsh64x64 (Add64 <t> n (Rsh64Ux64 <t> (Rsh64x64 <t> n (Const64 <typ.UInt64> [63])) (Const64 <typ.UInt64> [kbar]))) (Const64 <typ.UInt64> [k])) (Const64 <typ.UInt64> [k])) )
// cond: k > 0 && k < 63 && kbar == 64 - k
// result: (Eq64 (And64 <t> n (Const64 <t> [1<<uint(k)-1])) (Const64 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpLsh64x64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpRsh64x64 {
continue
}
_ = v_1_0.Args[1]
v_1_0_0 := v_1_0.Args[0]
if v_1_0_0.Op != OpAdd64 {
continue
}
t := v_1_0_0.Type
_ = v_1_0_0.Args[1]
v_1_0_0_0 := v_1_0_0.Args[0]
v_1_0_0_1 := v_1_0_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0_0_0, v_1_0_0_1 = _i1+1, v_1_0_0_1, v_1_0_0_0 {
if n != v_1_0_0_0 || v_1_0_0_1.Op != OpRsh64Ux64 || v_1_0_0_1.Type != t {
continue
}
_ = v_1_0_0_1.Args[1]
v_1_0_0_1_0 := v_1_0_0_1.Args[0]
if v_1_0_0_1_0.Op != OpRsh64x64 || v_1_0_0_1_0.Type != t {
continue
}
_ = v_1_0_0_1_0.Args[1]
if n != v_1_0_0_1_0.Args[0] {
continue
}
v_1_0_0_1_0_1 := v_1_0_0_1_0.Args[1]
if v_1_0_0_1_0_1.Op != OpConst64 || v_1_0_0_1_0_1.Type != typ.UInt64 || auxIntToInt64(v_1_0_0_1_0_1.AuxInt) != 63 {
continue
}
v_1_0_0_1_1 := v_1_0_0_1.Args[1]
if v_1_0_0_1_1.Op != OpConst64 || v_1_0_0_1_1.Type != typ.UInt64 {
continue
}
kbar := auxIntToInt64(v_1_0_0_1_1.AuxInt)
v_1_0_1 := v_1_0.Args[1]
if v_1_0_1.Op != OpConst64 || v_1_0_1.Type != typ.UInt64 {
continue
}
k := auxIntToInt64(v_1_0_1.AuxInt)
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != typ.UInt64 || auxIntToInt64(v_1_1.AuxInt) != k || !(k > 0 && k < 63 && kbar == 64-k) {
continue
}
v.reset(OpEq64)
v0 := b.NewValue0(v.Pos, OpAnd64, t)
v1 := b.NewValue0(v.Pos, OpConst64, t)
v1.AuxInt = int64ToAuxInt(1<<uint(k) - 1)
v0.AddArg2(n, v1)
v2 := b.NewValue0(v.Pos, OpConst64, t)
v2.AuxInt = int64ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
// match: (Eq64 s:(Sub64 x y) (Const64 [0]))
// cond: s.Uses == 1
// result: (Eq64 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
s := v_0
if s.Op != OpSub64 {
continue
}
y := s.Args[1]
x := s.Args[0]
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 || !(s.Uses == 1) {
continue
}
v.reset(OpEq64)
v.AddArg2(x, y)
return true
}
break
}
// match: (Eq64 (And64 <t> x (Const64 <t> [y])) (Const64 <t> [y]))
// cond: oneBit64(y)
// result: (Neq64 (And64 <t> x (Const64 <t> [y])) (Const64 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd64 {
continue
}
t := v_0.Type
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst64 || v_0_1.Type != t {
continue
}
y := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 || v_1.Type != t || auxIntToInt64(v_1.AuxInt) != y || !(oneBit64(y)) {
continue
}
v.reset(OpNeq64)
v0 := b.NewValue0(v.Pos, OpAnd64, t)
v1 := b.NewValue0(v.Pos, OpConst64, t)
v1.AuxInt = int64ToAuxInt(y)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, t)
v2.AuxInt = int64ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpEq64F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Eq64F (Const64F [c]) (Const64F [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64F {
continue
}
c := auxIntToFloat64(v_0.AuxInt)
if v_1.Op != OpConst64F {
continue
}
d := auxIntToFloat64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpEq8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (Eq8 x x)
// result: (ConstBool [true])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (Eq8 (Const8 <t> [c]) (Add8 (Const8 <t> [d]) x))
// result: (Eq8 (Const8 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpAdd8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
continue
}
d := auxIntToInt8(v_1_0.AuxInt)
x := v_1_1
v.reset(OpEq8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Eq8 (Const8 [c]) (Const8 [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
// match: (Eq8 (Mod8u x (Const8 [c])) (Const8 [0]))
// cond: x.Op != OpConst8 && udivisibleOK8(c) && !hasSmallRotate(config)
// result: (Eq32 (Mod32u <typ.UInt32> (ZeroExt8to32 <typ.UInt32> x) (Const32 <typ.UInt32> [int32(uint8(c))])) (Const32 <typ.UInt32> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpMod8u {
continue
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_1.AuxInt)
if v_1.Op != OpConst8 || auxIntToInt8(v_1.AuxInt) != 0 || !(x.Op != OpConst8 && udivisibleOK8(c) && !hasSmallRotate(config)) {
continue
}
v.reset(OpEq32)
v0 := b.NewValue0(v.Pos, OpMod32u, typ.UInt32)
v1 := b.NewValue0(v.Pos, OpZeroExt8to32, typ.UInt32)
v1.AddArg(x)
v2 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v2.AuxInt = int32ToAuxInt(int32(uint8(c)))
v0.AddArg2(v1, v2)
v3 := b.NewValue0(v.Pos, OpConst32, typ.UInt32)
v3.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v3)
return true
}
break
}
// match: (Eq8 (Mod8 x (Const8 [c])) (Const8 [0]))
// cond: x.Op != OpConst8 && sdivisibleOK8(c) && !hasSmallRotate(config)
// result: (Eq32 (Mod32 <typ.Int32> (SignExt8to32 <typ.Int32> x) (Const32 <typ.Int32> [int32(c)])) (Const32 <typ.Int32> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpMod8 {
continue
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_1.AuxInt)
if v_1.Op != OpConst8 || auxIntToInt8(v_1.AuxInt) != 0 || !(x.Op != OpConst8 && sdivisibleOK8(c) && !hasSmallRotate(config)) {
continue
}
v.reset(OpEq32)
v0 := b.NewValue0(v.Pos, OpMod32, typ.Int32)
v1 := b.NewValue0(v.Pos, OpSignExt8to32, typ.Int32)
v1.AddArg(x)
v2 := b.NewValue0(v.Pos, OpConst32, typ.Int32)
v2.AuxInt = int32ToAuxInt(int32(c))
v0.AddArg2(v1, v2)
v3 := b.NewValue0(v.Pos, OpConst32, typ.Int32)
v3.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v3)
return true
}
break
}
// match: (Eq8 x (Mul8 (Const8 [c]) (Trunc32to8 (Rsh32Ux64 mul:(Mul32 (Const32 [m]) (ZeroExt8to32 x)) (Const64 [s]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<8+umagic8(c).m) && s == 8+umagic8(c).s && x.Op != OpConst8 && udivisibleOK8(c)
// result: (Leq8U (RotateLeft8 <typ.UInt8> (Mul8 <typ.UInt8> (Const8 <typ.UInt8> [int8(udivisible8(c).m)]) x) (Const8 <typ.UInt8> [int8(8-udivisible8(c).k)]) ) (Const8 <typ.UInt8> [int8(udivisible8(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_1_0.AuxInt)
if v_1_1.Op != OpTrunc32to8 {
continue
}
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh32Ux64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul32 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if mul_1.Op != OpZeroExt8to32 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
if !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(1<<8+umagic8(c).m) && s == 8+umagic8(c).s && x.Op != OpConst8 && udivisibleOK8(c)) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpRotateLeft8, typ.UInt8)
v1 := b.NewValue0(v.Pos, OpMul8, typ.UInt8)
v2 := b.NewValue0(v.Pos, OpConst8, typ.UInt8)
v2.AuxInt = int8ToAuxInt(int8(udivisible8(c).m))
v1.AddArg2(v2, x)
v3 := b.NewValue0(v.Pos, OpConst8, typ.UInt8)
v3.AuxInt = int8ToAuxInt(int8(8 - udivisible8(c).k))
v0.AddArg2(v1, v3)
v4 := b.NewValue0(v.Pos, OpConst8, typ.UInt8)
v4.AuxInt = int8ToAuxInt(int8(udivisible8(c).max))
v.AddArg2(v0, v4)
return true
}
}
}
break
}
// match: (Eq8 x (Mul8 (Const8 [c]) (Sub8 (Rsh32x64 mul:(Mul32 (Const32 [m]) (SignExt8to32 x)) (Const64 [s])) (Rsh32x64 (SignExt8to32 x) (Const64 [31]))) ) )
// cond: v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(smagic8(c).m) && s == 8+smagic8(c).s && x.Op != OpConst8 && sdivisibleOK8(c)
// result: (Leq8U (RotateLeft8 <typ.UInt8> (Add8 <typ.UInt8> (Mul8 <typ.UInt8> (Const8 <typ.UInt8> [int8(sdivisible8(c).m)]) x) (Const8 <typ.UInt8> [int8(sdivisible8(c).a)]) ) (Const8 <typ.UInt8> [int8(8-sdivisible8(c).k)]) ) (Const8 <typ.UInt8> [int8(sdivisible8(c).max)]) )
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpMul8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_1_0.AuxInt)
if v_1_1.Op != OpSub8 {
continue
}
_ = v_1_1.Args[1]
v_1_1_0 := v_1_1.Args[0]
if v_1_1_0.Op != OpRsh32x64 {
continue
}
_ = v_1_1_0.Args[1]
mul := v_1_1_0.Args[0]
if mul.Op != OpMul32 {
continue
}
_ = mul.Args[1]
mul_0 := mul.Args[0]
mul_1 := mul.Args[1]
for _i2 := 0; _i2 <= 1; _i2, mul_0, mul_1 = _i2+1, mul_1, mul_0 {
if mul_0.Op != OpConst32 {
continue
}
m := auxIntToInt32(mul_0.AuxInt)
if mul_1.Op != OpSignExt8to32 || x != mul_1.Args[0] {
continue
}
v_1_1_0_1 := v_1_1_0.Args[1]
if v_1_1_0_1.Op != OpConst64 {
continue
}
s := auxIntToInt64(v_1_1_0_1.AuxInt)
v_1_1_1 := v_1_1.Args[1]
if v_1_1_1.Op != OpRsh32x64 {
continue
}
_ = v_1_1_1.Args[1]
v_1_1_1_0 := v_1_1_1.Args[0]
if v_1_1_1_0.Op != OpSignExt8to32 || x != v_1_1_1_0.Args[0] {
continue
}
v_1_1_1_1 := v_1_1_1.Args[1]
if v_1_1_1_1.Op != OpConst64 || auxIntToInt64(v_1_1_1_1.AuxInt) != 31 || !(v.Block.Func.pass.name != "opt" && mul.Uses == 1 && m == int32(smagic8(c).m) && s == 8+smagic8(c).s && x.Op != OpConst8 && sdivisibleOK8(c)) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpRotateLeft8, typ.UInt8)
v1 := b.NewValue0(v.Pos, OpAdd8, typ.UInt8)
v2 := b.NewValue0(v.Pos, OpMul8, typ.UInt8)
v3 := b.NewValue0(v.Pos, OpConst8, typ.UInt8)
v3.AuxInt = int8ToAuxInt(int8(sdivisible8(c).m))
v2.AddArg2(v3, x)
v4 := b.NewValue0(v.Pos, OpConst8, typ.UInt8)
v4.AuxInt = int8ToAuxInt(int8(sdivisible8(c).a))
v1.AddArg2(v2, v4)
v5 := b.NewValue0(v.Pos, OpConst8, typ.UInt8)
v5.AuxInt = int8ToAuxInt(int8(8 - sdivisible8(c).k))
v0.AddArg2(v1, v5)
v6 := b.NewValue0(v.Pos, OpConst8, typ.UInt8)
v6.AuxInt = int8ToAuxInt(int8(sdivisible8(c).max))
v.AddArg2(v0, v6)
return true
}
}
}
break
}
// match: (Eq8 n (Lsh8x64 (Rsh8x64 (Add8 <t> n (Rsh8Ux64 <t> (Rsh8x64 <t> n (Const64 <typ.UInt64> [ 7])) (Const64 <typ.UInt64> [kbar]))) (Const64 <typ.UInt64> [k])) (Const64 <typ.UInt64> [k])) )
// cond: k > 0 && k < 7 && kbar == 8 - k
// result: (Eq8 (And8 <t> n (Const8 <t> [1<<uint(k)-1])) (Const8 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpLsh8x64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpRsh8x64 {
continue
}
_ = v_1_0.Args[1]
v_1_0_0 := v_1_0.Args[0]
if v_1_0_0.Op != OpAdd8 {
continue
}
t := v_1_0_0.Type
_ = v_1_0_0.Args[1]
v_1_0_0_0 := v_1_0_0.Args[0]
v_1_0_0_1 := v_1_0_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0_0_0, v_1_0_0_1 = _i1+1, v_1_0_0_1, v_1_0_0_0 {
if n != v_1_0_0_0 || v_1_0_0_1.Op != OpRsh8Ux64 || v_1_0_0_1.Type != t {
continue
}
_ = v_1_0_0_1.Args[1]
v_1_0_0_1_0 := v_1_0_0_1.Args[0]
if v_1_0_0_1_0.Op != OpRsh8x64 || v_1_0_0_1_0.Type != t {
continue
}
_ = v_1_0_0_1_0.Args[1]
if n != v_1_0_0_1_0.Args[0] {
continue
}
v_1_0_0_1_0_1 := v_1_0_0_1_0.Args[1]
if v_1_0_0_1_0_1.Op != OpConst64 || v_1_0_0_1_0_1.Type != typ.UInt64 || auxIntToInt64(v_1_0_0_1_0_1.AuxInt) != 7 {
continue
}
v_1_0_0_1_1 := v_1_0_0_1.Args[1]
if v_1_0_0_1_1.Op != OpConst64 || v_1_0_0_1_1.Type != typ.UInt64 {
continue
}
kbar := auxIntToInt64(v_1_0_0_1_1.AuxInt)
v_1_0_1 := v_1_0.Args[1]
if v_1_0_1.Op != OpConst64 || v_1_0_1.Type != typ.UInt64 {
continue
}
k := auxIntToInt64(v_1_0_1.AuxInt)
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != typ.UInt64 || auxIntToInt64(v_1_1.AuxInt) != k || !(k > 0 && k < 7 && kbar == 8-k) {
continue
}
v.reset(OpEq8)
v0 := b.NewValue0(v.Pos, OpAnd8, t)
v1 := b.NewValue0(v.Pos, OpConst8, t)
v1.AuxInt = int8ToAuxInt(1<<uint(k) - 1)
v0.AddArg2(n, v1)
v2 := b.NewValue0(v.Pos, OpConst8, t)
v2.AuxInt = int8ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
// match: (Eq8 s:(Sub8 x y) (Const8 [0]))
// cond: s.Uses == 1
// result: (Eq8 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
s := v_0
if s.Op != OpSub8 {
continue
}
y := s.Args[1]
x := s.Args[0]
if v_1.Op != OpConst8 || auxIntToInt8(v_1.AuxInt) != 0 || !(s.Uses == 1) {
continue
}
v.reset(OpEq8)
v.AddArg2(x, y)
return true
}
break
}
// match: (Eq8 (And8 <t> x (Const8 <t> [y])) (Const8 <t> [y]))
// cond: oneBit8(y)
// result: (Neq8 (And8 <t> x (Const8 <t> [y])) (Const8 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd8 {
continue
}
t := v_0.Type
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst8 || v_0_1.Type != t {
continue
}
y := auxIntToInt8(v_0_1.AuxInt)
if v_1.Op != OpConst8 || v_1.Type != t || auxIntToInt8(v_1.AuxInt) != y || !(oneBit8(y)) {
continue
}
v.reset(OpNeq8)
v0 := b.NewValue0(v.Pos, OpAnd8, t)
v1 := b.NewValue0(v.Pos, OpConst8, t)
v1.AuxInt = int8ToAuxInt(y)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, t)
v2.AuxInt = int8ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpEqB(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (EqB (ConstBool [c]) (ConstBool [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConstBool {
continue
}
c := auxIntToBool(v_0.AuxInt)
if v_1.Op != OpConstBool {
continue
}
d := auxIntToBool(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
// match: (EqB (ConstBool [false]) x)
// result: (Not x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConstBool || auxIntToBool(v_0.AuxInt) != false {
continue
}
x := v_1
v.reset(OpNot)
v.AddArg(x)
return true
}
break
}
// match: (EqB (ConstBool [true]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConstBool || auxIntToBool(v_0.AuxInt) != true {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpEqInter(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (EqInter x y)
// result: (EqPtr (ITab x) (ITab y))
for {
x := v_0
y := v_1
v.reset(OpEqPtr)
v0 := b.NewValue0(v.Pos, OpITab, typ.Uintptr)
v0.AddArg(x)
v1 := b.NewValue0(v.Pos, OpITab, typ.Uintptr)
v1.AddArg(y)
v.AddArg2(v0, v1)
return true
}
}
func rewriteValuegeneric_OpEqPtr(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (EqPtr x x)
// result: (ConstBool [true])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (EqPtr (Addr {a} _) (Addr {b} _))
// result: (ConstBool [a == b])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAddr {
continue
}
a := auxToSym(v_0.Aux)
if v_1.Op != OpAddr {
continue
}
b := auxToSym(v_1.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a == b)
return true
}
break
}
// match: (EqPtr (Addr {a} _) (OffPtr [o] (Addr {b} _)))
// result: (ConstBool [a == b && o == 0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAddr {
continue
}
a := auxToSym(v_0.Aux)
if v_1.Op != OpOffPtr {
continue
}
o := auxIntToInt64(v_1.AuxInt)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpAddr {
continue
}
b := auxToSym(v_1_0.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a == b && o == 0)
return true
}
break
}
// match: (EqPtr (OffPtr [o1] (Addr {a} _)) (OffPtr [o2] (Addr {b} _)))
// result: (ConstBool [a == b && o1 == o2])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
o1 := auxIntToInt64(v_0.AuxInt)
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAddr {
continue
}
a := auxToSym(v_0_0.Aux)
if v_1.Op != OpOffPtr {
continue
}
o2 := auxIntToInt64(v_1.AuxInt)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpAddr {
continue
}
b := auxToSym(v_1_0.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a == b && o1 == o2)
return true
}
break
}
// match: (EqPtr (LocalAddr {a} _ _) (LocalAddr {b} _ _))
// result: (ConstBool [a == b])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLocalAddr {
continue
}
a := auxToSym(v_0.Aux)
if v_1.Op != OpLocalAddr {
continue
}
b := auxToSym(v_1.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a == b)
return true
}
break
}
// match: (EqPtr (LocalAddr {a} _ _) (OffPtr [o] (LocalAddr {b} _ _)))
// result: (ConstBool [a == b && o == 0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLocalAddr {
continue
}
a := auxToSym(v_0.Aux)
if v_1.Op != OpOffPtr {
continue
}
o := auxIntToInt64(v_1.AuxInt)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpLocalAddr {
continue
}
b := auxToSym(v_1_0.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a == b && o == 0)
return true
}
break
}
// match: (EqPtr (OffPtr [o1] (LocalAddr {a} _ _)) (OffPtr [o2] (LocalAddr {b} _ _)))
// result: (ConstBool [a == b && o1 == o2])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
o1 := auxIntToInt64(v_0.AuxInt)
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLocalAddr {
continue
}
a := auxToSym(v_0_0.Aux)
if v_1.Op != OpOffPtr {
continue
}
o2 := auxIntToInt64(v_1.AuxInt)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpLocalAddr {
continue
}
b := auxToSym(v_1_0.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a == b && o1 == o2)
return true
}
break
}
// match: (EqPtr (OffPtr [o1] p1) p2)
// cond: isSamePtr(p1, p2)
// result: (ConstBool [o1 == 0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
o1 := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
p2 := v_1
if !(isSamePtr(p1, p2)) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(o1 == 0)
return true
}
break
}
// match: (EqPtr (OffPtr [o1] p1) (OffPtr [o2] p2))
// cond: isSamePtr(p1, p2)
// result: (ConstBool [o1 == o2])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
o1 := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpOffPtr {
continue
}
o2 := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(isSamePtr(p1, p2)) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(o1 == o2)
return true
}
break
}
// match: (EqPtr (Const32 [c]) (Const32 [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
// match: (EqPtr (Const64 [c]) (Const64 [d]))
// result: (ConstBool [c == d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c == d)
return true
}
break
}
// match: (EqPtr (LocalAddr _ _) (Addr _))
// result: (ConstBool [false])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLocalAddr || v_1.Op != OpAddr {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
break
}
// match: (EqPtr (OffPtr (LocalAddr _ _)) (Addr _))
// result: (ConstBool [false])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLocalAddr || v_1.Op != OpAddr {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
break
}
// match: (EqPtr (LocalAddr _ _) (OffPtr (Addr _)))
// result: (ConstBool [false])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLocalAddr || v_1.Op != OpOffPtr {
continue
}
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpAddr {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
break
}
// match: (EqPtr (OffPtr (LocalAddr _ _)) (OffPtr (Addr _)))
// result: (ConstBool [false])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLocalAddr || v_1.Op != OpOffPtr {
continue
}
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpAddr {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
break
}
// match: (EqPtr (AddPtr p1 o1) p2)
// cond: isSamePtr(p1, p2)
// result: (Not (IsNonNil o1))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAddPtr {
continue
}
o1 := v_0.Args[1]
p1 := v_0.Args[0]
p2 := v_1
if !(isSamePtr(p1, p2)) {
continue
}
v.reset(OpNot)
v0 := b.NewValue0(v.Pos, OpIsNonNil, typ.Bool)
v0.AddArg(o1)
v.AddArg(v0)
return true
}
break
}
// match: (EqPtr (Const32 [0]) p)
// result: (Not (IsNonNil p))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
continue
}
p := v_1
v.reset(OpNot)
v0 := b.NewValue0(v.Pos, OpIsNonNil, typ.Bool)
v0.AddArg(p)
v.AddArg(v0)
return true
}
break
}
// match: (EqPtr (Const64 [0]) p)
// result: (Not (IsNonNil p))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
continue
}
p := v_1
v.reset(OpNot)
v0 := b.NewValue0(v.Pos, OpIsNonNil, typ.Bool)
v0.AddArg(p)
v.AddArg(v0)
return true
}
break
}
// match: (EqPtr (ConstNil) p)
// result: (Not (IsNonNil p))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConstNil {
continue
}
p := v_1
v.reset(OpNot)
v0 := b.NewValue0(v.Pos, OpIsNonNil, typ.Bool)
v0.AddArg(p)
v.AddArg(v0)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpEqSlice(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (EqSlice x y)
// result: (EqPtr (SlicePtr x) (SlicePtr y))
for {
x := v_0
y := v_1
v.reset(OpEqPtr)
v0 := b.NewValue0(v.Pos, OpSlicePtr, typ.BytePtr)
v0.AddArg(x)
v1 := b.NewValue0(v.Pos, OpSlicePtr, typ.BytePtr)
v1.AddArg(y)
v.AddArg2(v0, v1)
return true
}
}
func rewriteValuegeneric_OpIMake(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (IMake typ (StructMake1 val))
// result: (IMake typ val)
for {
typ := v_0
if v_1.Op != OpStructMake1 {
break
}
val := v_1.Args[0]
v.reset(OpIMake)
v.AddArg2(typ, val)
return true
}
// match: (IMake typ (ArrayMake1 val))
// result: (IMake typ val)
for {
typ := v_0
if v_1.Op != OpArrayMake1 {
break
}
val := v_1.Args[0]
v.reset(OpIMake)
v.AddArg2(typ, val)
return true
}
return false
}
func rewriteValuegeneric_OpInterCall(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (InterCall [argsize] (Load (OffPtr [off] (ITab (IMake (Addr {itab} (SB)) _))) _) mem)
// cond: devirt(v, itab, off) != nil
// result: (StaticCall [int32(argsize)] {devirt(v, itab, off)} mem)
for {
argsize := auxIntToInt64(v.AuxInt)
if v_0.Op != OpLoad {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpOffPtr {
break
}
off := auxIntToInt64(v_0_0.AuxInt)
v_0_0_0 := v_0_0.Args[0]
if v_0_0_0.Op != OpITab {
break
}
v_0_0_0_0 := v_0_0_0.Args[0]
if v_0_0_0_0.Op != OpIMake {
break
}
v_0_0_0_0_0 := v_0_0_0_0.Args[0]
if v_0_0_0_0_0.Op != OpAddr {
break
}
itab := auxToSym(v_0_0_0_0_0.Aux)
v_0_0_0_0_0_0 := v_0_0_0_0_0.Args[0]
if v_0_0_0_0_0_0.Op != OpSB {
break
}
mem := v_1
if !(devirt(v, itab, off) != nil) {
break
}
v.reset(OpStaticCall)
v.AuxInt = int32ToAuxInt(int32(argsize))
v.Aux = symToAux(devirt(v, itab, off))
v.AddArg(mem)
return true
}
return false
}
func rewriteValuegeneric_OpIsInBounds(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (IsInBounds (ZeroExt8to32 _) (Const32 [c]))
// cond: (1 << 8) <= c
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt8to32 || v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !((1 << 8) <= c) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt8to64 _) (Const64 [c]))
// cond: (1 << 8) <= c
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt8to64 || v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !((1 << 8) <= c) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt16to32 _) (Const32 [c]))
// cond: (1 << 16) <= c
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt16to32 || v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !((1 << 16) <= c) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt16to64 _) (Const64 [c]))
// cond: (1 << 16) <= c
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt16to64 || v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !((1 << 16) <= c) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds x x)
// result: (ConstBool [false])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
// match: (IsInBounds (And8 (Const8 [c]) _) (Const8 [d]))
// cond: 0 <= c && c < d
// result: (ConstBool [true])
for {
if v_0.Op != OpAnd8 {
break
}
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1.AuxInt)
if !(0 <= c && c < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (ZeroExt8to16 (And8 (Const8 [c]) _)) (Const16 [d]))
// cond: 0 <= c && int16(c) < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt8to16 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAnd8 {
break
}
v_0_0_0 := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0_0, v_0_0_1 = _i0+1, v_0_0_1, v_0_0_0 {
if v_0_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
if !(0 <= c && int16(c) < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (ZeroExt8to32 (And8 (Const8 [c]) _)) (Const32 [d]))
// cond: 0 <= c && int32(c) < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt8to32 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAnd8 {
break
}
v_0_0_0 := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0_0, v_0_0_1 = _i0+1, v_0_0_1, v_0_0_0 {
if v_0_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
if !(0 <= c && int32(c) < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (ZeroExt8to64 (And8 (Const8 [c]) _)) (Const64 [d]))
// cond: 0 <= c && int64(c) < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt8to64 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAnd8 {
break
}
v_0_0_0 := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0_0, v_0_0_1 = _i0+1, v_0_0_1, v_0_0_0 {
if v_0_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 <= c && int64(c) < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (And16 (Const16 [c]) _) (Const16 [d]))
// cond: 0 <= c && c < d
// result: (ConstBool [true])
for {
if v_0.Op != OpAnd16 {
break
}
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
if !(0 <= c && c < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (ZeroExt16to32 (And16 (Const16 [c]) _)) (Const32 [d]))
// cond: 0 <= c && int32(c) < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt16to32 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAnd16 {
break
}
v_0_0_0 := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0_0, v_0_0_1 = _i0+1, v_0_0_1, v_0_0_0 {
if v_0_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
if !(0 <= c && int32(c) < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (ZeroExt16to64 (And16 (Const16 [c]) _)) (Const64 [d]))
// cond: 0 <= c && int64(c) < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt16to64 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAnd16 {
break
}
v_0_0_0 := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0_0, v_0_0_1 = _i0+1, v_0_0_1, v_0_0_0 {
if v_0_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 <= c && int64(c) < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (And32 (Const32 [c]) _) (Const32 [d]))
// cond: 0 <= c && c < d
// result: (ConstBool [true])
for {
if v_0.Op != OpAnd32 {
break
}
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
if !(0 <= c && c < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (ZeroExt32to64 (And32 (Const32 [c]) _)) (Const64 [d]))
// cond: 0 <= c && int64(c) < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt32to64 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAnd32 {
break
}
v_0_0_0 := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0_0, v_0_0_1 = _i0+1, v_0_0_1, v_0_0_0 {
if v_0_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 <= c && int64(c) < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (And64 (Const64 [c]) _) (Const64 [d]))
// cond: 0 <= c && c < d
// result: (ConstBool [true])
for {
if v_0.Op != OpAnd64 {
break
}
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 <= c && c < d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsInBounds (Const32 [c]) (Const32 [d]))
// result: (ConstBool [0 <= c && c < d])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(0 <= c && c < d)
return true
}
// match: (IsInBounds (Const64 [c]) (Const64 [d]))
// result: (ConstBool [0 <= c && c < d])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(0 <= c && c < d)
return true
}
// match: (IsInBounds (Mod32u _ y) y)
// result: (ConstBool [true])
for {
if v_0.Op != OpMod32u {
break
}
y := v_0.Args[1]
if y != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (Mod64u _ y) y)
// result: (ConstBool [true])
for {
if v_0.Op != OpMod64u {
break
}
y := v_0.Args[1]
if y != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt8to64 (Rsh8Ux64 _ (Const64 [c]))) (Const64 [d]))
// cond: 0 < c && c < 8 && 1<<uint( 8-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt8to64 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh8Ux64 {
break
}
_ = v_0_0.Args[1]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 < c && c < 8 && 1<<uint(8-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt8to32 (Rsh8Ux64 _ (Const64 [c]))) (Const32 [d]))
// cond: 0 < c && c < 8 && 1<<uint( 8-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt8to32 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh8Ux64 {
break
}
_ = v_0_0.Args[1]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_0_1.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
if !(0 < c && c < 8 && 1<<uint(8-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt8to16 (Rsh8Ux64 _ (Const64 [c]))) (Const16 [d]))
// cond: 0 < c && c < 8 && 1<<uint( 8-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt8to16 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh8Ux64 {
break
}
_ = v_0_0.Args[1]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_0_1.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
if !(0 < c && c < 8 && 1<<uint(8-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (Rsh8Ux64 _ (Const64 [c])) (Const64 [d]))
// cond: 0 < c && c < 8 && 1<<uint( 8-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpRsh8Ux64 {
break
}
_ = v_0.Args[1]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 < c && c < 8 && 1<<uint(8-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt16to64 (Rsh16Ux64 _ (Const64 [c]))) (Const64 [d]))
// cond: 0 < c && c < 16 && 1<<uint(16-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt16to64 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh16Ux64 {
break
}
_ = v_0_0.Args[1]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 < c && c < 16 && 1<<uint(16-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt16to32 (Rsh16Ux64 _ (Const64 [c]))) (Const64 [d]))
// cond: 0 < c && c < 16 && 1<<uint(16-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt16to32 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh16Ux64 {
break
}
_ = v_0_0.Args[1]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 < c && c < 16 && 1<<uint(16-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (Rsh16Ux64 _ (Const64 [c])) (Const64 [d]))
// cond: 0 < c && c < 16 && 1<<uint(16-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpRsh16Ux64 {
break
}
_ = v_0.Args[1]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 < c && c < 16 && 1<<uint(16-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (ZeroExt32to64 (Rsh32Ux64 _ (Const64 [c]))) (Const64 [d]))
// cond: 0 < c && c < 32 && 1<<uint(32-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpZeroExt32to64 {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh32Ux64 {
break
}
_ = v_0_0.Args[1]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 < c && c < 32 && 1<<uint(32-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (Rsh32Ux64 _ (Const64 [c])) (Const64 [d]))
// cond: 0 < c && c < 32 && 1<<uint(32-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpRsh32Ux64 {
break
}
_ = v_0.Args[1]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 < c && c < 32 && 1<<uint(32-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsInBounds (Rsh64Ux64 _ (Const64 [c])) (Const64 [d]))
// cond: 0 < c && c < 64 && 1<<uint(64-c)-1 < d
// result: (ConstBool [true])
for {
if v_0.Op != OpRsh64Ux64 {
break
}
_ = v_0.Args[1]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 < c && c < 64 && 1<<uint(64-c)-1 < d) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
return false
}
func rewriteValuegeneric_OpIsNonNil(v *Value) bool {
v_0 := v.Args[0]
// match: (IsNonNil (ConstNil))
// result: (ConstBool [false])
for {
if v_0.Op != OpConstNil {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
// match: (IsNonNil (Const32 [c]))
// result: (ConstBool [c != 0])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != 0)
return true
}
// match: (IsNonNil (Const64 [c]))
// result: (ConstBool [c != 0])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != 0)
return true
}
// match: (IsNonNil (Addr _))
// result: (ConstBool [true])
for {
if v_0.Op != OpAddr {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsNonNil (LocalAddr _ _))
// result: (ConstBool [true])
for {
if v_0.Op != OpLocalAddr {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
return false
}
func rewriteValuegeneric_OpIsSliceInBounds(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (IsSliceInBounds x x)
// result: (ConstBool [true])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsSliceInBounds (And32 (Const32 [c]) _) (Const32 [d]))
// cond: 0 <= c && c <= d
// result: (ConstBool [true])
for {
if v_0.Op != OpAnd32 {
break
}
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
if !(0 <= c && c <= d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsSliceInBounds (And64 (Const64 [c]) _) (Const64 [d]))
// cond: 0 <= c && c <= d
// result: (ConstBool [true])
for {
if v_0.Op != OpAnd64 {
break
}
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
if !(0 <= c && c <= d) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (IsSliceInBounds (Const32 [0]) _)
// result: (ConstBool [true])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsSliceInBounds (Const64 [0]) _)
// result: (ConstBool [true])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
// match: (IsSliceInBounds (Const32 [c]) (Const32 [d]))
// result: (ConstBool [0 <= c && c <= d])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(0 <= c && c <= d)
return true
}
// match: (IsSliceInBounds (Const64 [c]) (Const64 [d]))
// result: (ConstBool [0 <= c && c <= d])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(0 <= c && c <= d)
return true
}
// match: (IsSliceInBounds (SliceLen x) (SliceCap x))
// result: (ConstBool [true])
for {
if v_0.Op != OpSliceLen {
break
}
x := v_0.Args[0]
if v_1.Op != OpSliceCap || x != v_1.Args[0] {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
return false
}
func rewriteValuegeneric_OpLeq16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq16 (Const16 [c]) (Const16 [d]))
// result: (ConstBool [c <= d])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c <= d)
return true
}
// match: (Leq16 (Const16 [0]) (And16 _ (Const16 [c])))
// cond: c >= 0
// result: (ConstBool [true])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 || v_1.Op != OpAnd16 {
break
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_1_0, v_1_1 = _i0+1, v_1_1, v_1_0 {
if v_1_1.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_1_1.AuxInt)
if !(c >= 0) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (Leq16 (Const16 [0]) (Rsh16Ux64 _ (Const64 [c])))
// cond: c > 0
// result: (ConstBool [true])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 || v_1.Op != OpRsh16Ux64 {
break
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c > 0) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
return false
}
func rewriteValuegeneric_OpLeq16U(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq16U (Const16 [c]) (Const16 [d]))
// result: (ConstBool [uint16(c) <= uint16(d)])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(uint16(c) <= uint16(d))
return true
}
return false
}
func rewriteValuegeneric_OpLeq32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq32 (Const32 [c]) (Const32 [d]))
// result: (ConstBool [c <= d])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c <= d)
return true
}
// match: (Leq32 (Const32 [0]) (And32 _ (Const32 [c])))
// cond: c >= 0
// result: (ConstBool [true])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 || v_1.Op != OpAnd32 {
break
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_1_0, v_1_1 = _i0+1, v_1_1, v_1_0 {
if v_1_1.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1_1.AuxInt)
if !(c >= 0) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (Leq32 (Const32 [0]) (Rsh32Ux64 _ (Const64 [c])))
// cond: c > 0
// result: (ConstBool [true])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 || v_1.Op != OpRsh32Ux64 {
break
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c > 0) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
return false
}
func rewriteValuegeneric_OpLeq32F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq32F (Const32F [c]) (Const32F [d]))
// result: (ConstBool [c <= d])
for {
if v_0.Op != OpConst32F {
break
}
c := auxIntToFloat32(v_0.AuxInt)
if v_1.Op != OpConst32F {
break
}
d := auxIntToFloat32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c <= d)
return true
}
return false
}
func rewriteValuegeneric_OpLeq32U(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq32U (Const32 [c]) (Const32 [d]))
// result: (ConstBool [uint32(c) <= uint32(d)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(uint32(c) <= uint32(d))
return true
}
return false
}
func rewriteValuegeneric_OpLeq64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq64 (Const64 [c]) (Const64 [d]))
// result: (ConstBool [c <= d])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c <= d)
return true
}
// match: (Leq64 (Const64 [0]) (And64 _ (Const64 [c])))
// cond: c >= 0
// result: (ConstBool [true])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 || v_1.Op != OpAnd64 {
break
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_1_0, v_1_1 = _i0+1, v_1_1, v_1_0 {
if v_1_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c >= 0) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (Leq64 (Const64 [0]) (Rsh64Ux64 _ (Const64 [c])))
// cond: c > 0
// result: (ConstBool [true])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 || v_1.Op != OpRsh64Ux64 {
break
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c > 0) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
return false
}
func rewriteValuegeneric_OpLeq64F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq64F (Const64F [c]) (Const64F [d]))
// result: (ConstBool [c <= d])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
if v_1.Op != OpConst64F {
break
}
d := auxIntToFloat64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c <= d)
return true
}
return false
}
func rewriteValuegeneric_OpLeq64U(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq64U (Const64 [c]) (Const64 [d]))
// result: (ConstBool [uint64(c) <= uint64(d)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(uint64(c) <= uint64(d))
return true
}
return false
}
func rewriteValuegeneric_OpLeq8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq8 (Const8 [c]) (Const8 [d]))
// result: (ConstBool [c <= d])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c <= d)
return true
}
// match: (Leq8 (Const8 [0]) (And8 _ (Const8 [c])))
// cond: c >= 0
// result: (ConstBool [true])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 || v_1.Op != OpAnd8 {
break
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_1_0, v_1_1 = _i0+1, v_1_1, v_1_0 {
if v_1_1.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_1_1.AuxInt)
if !(c >= 0) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (Leq8 (Const8 [0]) (Rsh8Ux64 _ (Const64 [c])))
// cond: c > 0
// result: (ConstBool [true])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 || v_1.Op != OpRsh8Ux64 {
break
}
_ = v_1.Args[1]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1_1.AuxInt)
if !(c > 0) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
return false
}
func rewriteValuegeneric_OpLeq8U(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Leq8U (Const8 [c]) (Const8 [d]))
// result: (ConstBool [ uint8(c) <= uint8(d)])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(uint8(c) <= uint8(d))
return true
}
return false
}
func rewriteValuegeneric_OpLess16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less16 (Const16 [c]) (Const16 [d]))
// result: (ConstBool [c < d])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c < d)
return true
}
return false
}
func rewriteValuegeneric_OpLess16U(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less16U (Const16 [c]) (Const16 [d]))
// result: (ConstBool [uint16(c) < uint16(d)])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(uint16(c) < uint16(d))
return true
}
return false
}
func rewriteValuegeneric_OpLess32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less32 (Const32 [c]) (Const32 [d]))
// result: (ConstBool [c < d])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c < d)
return true
}
return false
}
func rewriteValuegeneric_OpLess32F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less32F (Const32F [c]) (Const32F [d]))
// result: (ConstBool [c < d])
for {
if v_0.Op != OpConst32F {
break
}
c := auxIntToFloat32(v_0.AuxInt)
if v_1.Op != OpConst32F {
break
}
d := auxIntToFloat32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c < d)
return true
}
return false
}
func rewriteValuegeneric_OpLess32U(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less32U (Const32 [c]) (Const32 [d]))
// result: (ConstBool [uint32(c) < uint32(d)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(uint32(c) < uint32(d))
return true
}
return false
}
func rewriteValuegeneric_OpLess64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less64 (Const64 [c]) (Const64 [d]))
// result: (ConstBool [c < d])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c < d)
return true
}
return false
}
func rewriteValuegeneric_OpLess64F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less64F (Const64F [c]) (Const64F [d]))
// result: (ConstBool [c < d])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
if v_1.Op != OpConst64F {
break
}
d := auxIntToFloat64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c < d)
return true
}
return false
}
func rewriteValuegeneric_OpLess64U(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less64U (Const64 [c]) (Const64 [d]))
// result: (ConstBool [uint64(c) < uint64(d)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(uint64(c) < uint64(d))
return true
}
return false
}
func rewriteValuegeneric_OpLess8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less8 (Const8 [c]) (Const8 [d]))
// result: (ConstBool [c < d])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c < d)
return true
}
return false
}
func rewriteValuegeneric_OpLess8U(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Less8U (Const8 [c]) (Const8 [d]))
// result: (ConstBool [ uint8(c) < uint8(d)])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(uint8(c) < uint8(d))
return true
}
return false
}
func rewriteValuegeneric_OpLoad(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
fe := b.Func.fe
// match: (Load <t1> p1 (Store {t2} p2 x _))
// cond: isSamePtr(p1, p2) && t1.Compare(x.Type) == types.CMPeq && t1.Size() == t2.Size()
// result: x
for {
t1 := v.Type
p1 := v_0
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
x := v_1.Args[1]
p2 := v_1.Args[0]
if !(isSamePtr(p1, p2) && t1.Compare(x.Type) == types.CMPeq && t1.Size() == t2.Size()) {
break
}
v.copyOf(x)
return true
}
// match: (Load <t1> p1 (Store {t2} p2 _ (Store {t3} p3 x _)))
// cond: isSamePtr(p1, p3) && t1.Compare(x.Type) == types.CMPeq && t1.Size() == t2.Size() && disjoint(p3, t3.Size(), p2, t2.Size())
// result: x
for {
t1 := v.Type
p1 := v_0
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[2]
p2 := v_1.Args[0]
v_1_2 := v_1.Args[2]
if v_1_2.Op != OpStore {
break
}
t3 := auxToType(v_1_2.Aux)
x := v_1_2.Args[1]
p3 := v_1_2.Args[0]
if !(isSamePtr(p1, p3) && t1.Compare(x.Type) == types.CMPeq && t1.Size() == t2.Size() && disjoint(p3, t3.Size(), p2, t2.Size())) {
break
}
v.copyOf(x)
return true
}
// match: (Load <t1> p1 (Store {t2} p2 _ (Store {t3} p3 _ (Store {t4} p4 x _))))
// cond: isSamePtr(p1, p4) && t1.Compare(x.Type) == types.CMPeq && t1.Size() == t2.Size() && disjoint(p4, t4.Size(), p2, t2.Size()) && disjoint(p4, t4.Size(), p3, t3.Size())
// result: x
for {
t1 := v.Type
p1 := v_0
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[2]
p2 := v_1.Args[0]
v_1_2 := v_1.Args[2]
if v_1_2.Op != OpStore {
break
}
t3 := auxToType(v_1_2.Aux)
_ = v_1_2.Args[2]
p3 := v_1_2.Args[0]
v_1_2_2 := v_1_2.Args[2]
if v_1_2_2.Op != OpStore {
break
}
t4 := auxToType(v_1_2_2.Aux)
x := v_1_2_2.Args[1]
p4 := v_1_2_2.Args[0]
if !(isSamePtr(p1, p4) && t1.Compare(x.Type) == types.CMPeq && t1.Size() == t2.Size() && disjoint(p4, t4.Size(), p2, t2.Size()) && disjoint(p4, t4.Size(), p3, t3.Size())) {
break
}
v.copyOf(x)
return true
}
// match: (Load <t1> p1 (Store {t2} p2 _ (Store {t3} p3 _ (Store {t4} p4 _ (Store {t5} p5 x _)))))
// cond: isSamePtr(p1, p5) && t1.Compare(x.Type) == types.CMPeq && t1.Size() == t2.Size() && disjoint(p5, t5.Size(), p2, t2.Size()) && disjoint(p5, t5.Size(), p3, t3.Size()) && disjoint(p5, t5.Size(), p4, t4.Size())
// result: x
for {
t1 := v.Type
p1 := v_0
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[2]
p2 := v_1.Args[0]
v_1_2 := v_1.Args[2]
if v_1_2.Op != OpStore {
break
}
t3 := auxToType(v_1_2.Aux)
_ = v_1_2.Args[2]
p3 := v_1_2.Args[0]
v_1_2_2 := v_1_2.Args[2]
if v_1_2_2.Op != OpStore {
break
}
t4 := auxToType(v_1_2_2.Aux)
_ = v_1_2_2.Args[2]
p4 := v_1_2_2.Args[0]
v_1_2_2_2 := v_1_2_2.Args[2]
if v_1_2_2_2.Op != OpStore {
break
}
t5 := auxToType(v_1_2_2_2.Aux)
x := v_1_2_2_2.Args[1]
p5 := v_1_2_2_2.Args[0]
if !(isSamePtr(p1, p5) && t1.Compare(x.Type) == types.CMPeq && t1.Size() == t2.Size() && disjoint(p5, t5.Size(), p2, t2.Size()) && disjoint(p5, t5.Size(), p3, t3.Size()) && disjoint(p5, t5.Size(), p4, t4.Size())) {
break
}
v.copyOf(x)
return true
}
// match: (Load <t1> p1 (Store {t2} p2 (Const64 [x]) _))
// cond: isSamePtr(p1,p2) && sizeof(t2) == 8 && is64BitFloat(t1) && !math.IsNaN(math.Float64frombits(uint64(x)))
// result: (Const64F [math.Float64frombits(uint64(x))])
for {
t1 := v.Type
p1 := v_0
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[1]
p2 := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
break
}
x := auxIntToInt64(v_1_1.AuxInt)
if !(isSamePtr(p1, p2) && sizeof(t2) == 8 && is64BitFloat(t1) && !math.IsNaN(math.Float64frombits(uint64(x)))) {
break
}
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(math.Float64frombits(uint64(x)))
return true
}
// match: (Load <t1> p1 (Store {t2} p2 (Const32 [x]) _))
// cond: isSamePtr(p1,p2) && sizeof(t2) == 4 && is32BitFloat(t1) && !math.IsNaN(float64(math.Float32frombits(uint32(x))))
// result: (Const32F [math.Float32frombits(uint32(x))])
for {
t1 := v.Type
p1 := v_0
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[1]
p2 := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
break
}
x := auxIntToInt32(v_1_1.AuxInt)
if !(isSamePtr(p1, p2) && sizeof(t2) == 4 && is32BitFloat(t1) && !math.IsNaN(float64(math.Float32frombits(uint32(x))))) {
break
}
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(math.Float32frombits(uint32(x)))
return true
}
// match: (Load <t1> p1 (Store {t2} p2 (Const64F [x]) _))
// cond: isSamePtr(p1,p2) && sizeof(t2) == 8 && is64BitInt(t1)
// result: (Const64 [int64(math.Float64bits(x))])
for {
t1 := v.Type
p1 := v_0
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[1]
p2 := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64F {
break
}
x := auxIntToFloat64(v_1_1.AuxInt)
if !(isSamePtr(p1, p2) && sizeof(t2) == 8 && is64BitInt(t1)) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(math.Float64bits(x)))
return true
}
// match: (Load <t1> p1 (Store {t2} p2 (Const32F [x]) _))
// cond: isSamePtr(p1,p2) && sizeof(t2) == 4 && is32BitInt(t1)
// result: (Const32 [int32(math.Float32bits(x))])
for {
t1 := v.Type
p1 := v_0
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[1]
p2 := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32F {
break
}
x := auxIntToFloat32(v_1_1.AuxInt)
if !(isSamePtr(p1, p2) && sizeof(t2) == 4 && is32BitInt(t1)) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(math.Float32bits(x)))
return true
}
// match: (Load <t1> op:(OffPtr [o1] p1) (Store {t2} p2 _ mem:(Zero [n] p3 _)))
// cond: o1 >= 0 && o1+t1.Size() <= n && isSamePtr(p1, p3) && fe.CanSSA(t1) && disjoint(op, t1.Size(), p2, t2.Size())
// result: @mem.Block (Load <t1> (OffPtr <op.Type> [o1] p3) mem)
for {
t1 := v.Type
op := v_0
if op.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op.AuxInt)
p1 := op.Args[0]
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[2]
p2 := v_1.Args[0]
mem := v_1.Args[2]
if mem.Op != OpZero {
break
}
n := auxIntToInt64(mem.AuxInt)
p3 := mem.Args[0]
if !(o1 >= 0 && o1+t1.Size() <= n && isSamePtr(p1, p3) && fe.CanSSA(t1) && disjoint(op, t1.Size(), p2, t2.Size())) {
break
}
b = mem.Block
v0 := b.NewValue0(v.Pos, OpLoad, t1)
v.copyOf(v0)
v1 := b.NewValue0(v.Pos, OpOffPtr, op.Type)
v1.AuxInt = int64ToAuxInt(o1)
v1.AddArg(p3)
v0.AddArg2(v1, mem)
return true
}
// match: (Load <t1> op:(OffPtr [o1] p1) (Store {t2} p2 _ (Store {t3} p3 _ mem:(Zero [n] p4 _))))
// cond: o1 >= 0 && o1+t1.Size() <= n && isSamePtr(p1, p4) && fe.CanSSA(t1) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size())
// result: @mem.Block (Load <t1> (OffPtr <op.Type> [o1] p4) mem)
for {
t1 := v.Type
op := v_0
if op.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op.AuxInt)
p1 := op.Args[0]
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[2]
p2 := v_1.Args[0]
v_1_2 := v_1.Args[2]
if v_1_2.Op != OpStore {
break
}
t3 := auxToType(v_1_2.Aux)
_ = v_1_2.Args[2]
p3 := v_1_2.Args[0]
mem := v_1_2.Args[2]
if mem.Op != OpZero {
break
}
n := auxIntToInt64(mem.AuxInt)
p4 := mem.Args[0]
if !(o1 >= 0 && o1+t1.Size() <= n && isSamePtr(p1, p4) && fe.CanSSA(t1) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size())) {
break
}
b = mem.Block
v0 := b.NewValue0(v.Pos, OpLoad, t1)
v.copyOf(v0)
v1 := b.NewValue0(v.Pos, OpOffPtr, op.Type)
v1.AuxInt = int64ToAuxInt(o1)
v1.AddArg(p4)
v0.AddArg2(v1, mem)
return true
}
// match: (Load <t1> op:(OffPtr [o1] p1) (Store {t2} p2 _ (Store {t3} p3 _ (Store {t4} p4 _ mem:(Zero [n] p5 _)))))
// cond: o1 >= 0 && o1+t1.Size() <= n && isSamePtr(p1, p5) && fe.CanSSA(t1) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size()) && disjoint(op, t1.Size(), p4, t4.Size())
// result: @mem.Block (Load <t1> (OffPtr <op.Type> [o1] p5) mem)
for {
t1 := v.Type
op := v_0
if op.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op.AuxInt)
p1 := op.Args[0]
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[2]
p2 := v_1.Args[0]
v_1_2 := v_1.Args[2]
if v_1_2.Op != OpStore {
break
}
t3 := auxToType(v_1_2.Aux)
_ = v_1_2.Args[2]
p3 := v_1_2.Args[0]
v_1_2_2 := v_1_2.Args[2]
if v_1_2_2.Op != OpStore {
break
}
t4 := auxToType(v_1_2_2.Aux)
_ = v_1_2_2.Args[2]
p4 := v_1_2_2.Args[0]
mem := v_1_2_2.Args[2]
if mem.Op != OpZero {
break
}
n := auxIntToInt64(mem.AuxInt)
p5 := mem.Args[0]
if !(o1 >= 0 && o1+t1.Size() <= n && isSamePtr(p1, p5) && fe.CanSSA(t1) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size()) && disjoint(op, t1.Size(), p4, t4.Size())) {
break
}
b = mem.Block
v0 := b.NewValue0(v.Pos, OpLoad, t1)
v.copyOf(v0)
v1 := b.NewValue0(v.Pos, OpOffPtr, op.Type)
v1.AuxInt = int64ToAuxInt(o1)
v1.AddArg(p5)
v0.AddArg2(v1, mem)
return true
}
// match: (Load <t1> op:(OffPtr [o1] p1) (Store {t2} p2 _ (Store {t3} p3 _ (Store {t4} p4 _ (Store {t5} p5 _ mem:(Zero [n] p6 _))))))
// cond: o1 >= 0 && o1+t1.Size() <= n && isSamePtr(p1, p6) && fe.CanSSA(t1) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size()) && disjoint(op, t1.Size(), p4, t4.Size()) && disjoint(op, t1.Size(), p5, t5.Size())
// result: @mem.Block (Load <t1> (OffPtr <op.Type> [o1] p6) mem)
for {
t1 := v.Type
op := v_0
if op.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op.AuxInt)
p1 := op.Args[0]
if v_1.Op != OpStore {
break
}
t2 := auxToType(v_1.Aux)
_ = v_1.Args[2]
p2 := v_1.Args[0]
v_1_2 := v_1.Args[2]
if v_1_2.Op != OpStore {
break
}
t3 := auxToType(v_1_2.Aux)
_ = v_1_2.Args[2]
p3 := v_1_2.Args[0]
v_1_2_2 := v_1_2.Args[2]
if v_1_2_2.Op != OpStore {
break
}
t4 := auxToType(v_1_2_2.Aux)
_ = v_1_2_2.Args[2]
p4 := v_1_2_2.Args[0]
v_1_2_2_2 := v_1_2_2.Args[2]
if v_1_2_2_2.Op != OpStore {
break
}
t5 := auxToType(v_1_2_2_2.Aux)
_ = v_1_2_2_2.Args[2]
p5 := v_1_2_2_2.Args[0]
mem := v_1_2_2_2.Args[2]
if mem.Op != OpZero {
break
}
n := auxIntToInt64(mem.AuxInt)
p6 := mem.Args[0]
if !(o1 >= 0 && o1+t1.Size() <= n && isSamePtr(p1, p6) && fe.CanSSA(t1) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size()) && disjoint(op, t1.Size(), p4, t4.Size()) && disjoint(op, t1.Size(), p5, t5.Size())) {
break
}
b = mem.Block
v0 := b.NewValue0(v.Pos, OpLoad, t1)
v.copyOf(v0)
v1 := b.NewValue0(v.Pos, OpOffPtr, op.Type)
v1.AuxInt = int64ToAuxInt(o1)
v1.AddArg(p6)
v0.AddArg2(v1, mem)
return true
}
// match: (Load <t1> (OffPtr [o] p1) (Zero [n] p2 _))
// cond: t1.IsBoolean() && isSamePtr(p1, p2) && n >= o + 1
// result: (ConstBool [false])
for {
t1 := v.Type
if v_0.Op != OpOffPtr {
break
}
o := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpZero {
break
}
n := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(t1.IsBoolean() && isSamePtr(p1, p2) && n >= o+1) {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
// match: (Load <t1> (OffPtr [o] p1) (Zero [n] p2 _))
// cond: is8BitInt(t1) && isSamePtr(p1, p2) && n >= o + 1
// result: (Const8 [0])
for {
t1 := v.Type
if v_0.Op != OpOffPtr {
break
}
o := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpZero {
break
}
n := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(is8BitInt(t1) && isSamePtr(p1, p2) && n >= o+1) {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (Load <t1> (OffPtr [o] p1) (Zero [n] p2 _))
// cond: is16BitInt(t1) && isSamePtr(p1, p2) && n >= o + 2
// result: (Const16 [0])
for {
t1 := v.Type
if v_0.Op != OpOffPtr {
break
}
o := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpZero {
break
}
n := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(is16BitInt(t1) && isSamePtr(p1, p2) && n >= o+2) {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
// match: (Load <t1> (OffPtr [o] p1) (Zero [n] p2 _))
// cond: is32BitInt(t1) && isSamePtr(p1, p2) && n >= o + 4
// result: (Const32 [0])
for {
t1 := v.Type
if v_0.Op != OpOffPtr {
break
}
o := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpZero {
break
}
n := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(is32BitInt(t1) && isSamePtr(p1, p2) && n >= o+4) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Load <t1> (OffPtr [o] p1) (Zero [n] p2 _))
// cond: is64BitInt(t1) && isSamePtr(p1, p2) && n >= o + 8
// result: (Const64 [0])
for {
t1 := v.Type
if v_0.Op != OpOffPtr {
break
}
o := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpZero {
break
}
n := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(is64BitInt(t1) && isSamePtr(p1, p2) && n >= o+8) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Load <t1> (OffPtr [o] p1) (Zero [n] p2 _))
// cond: is32BitFloat(t1) && isSamePtr(p1, p2) && n >= o + 4
// result: (Const32F [0])
for {
t1 := v.Type
if v_0.Op != OpOffPtr {
break
}
o := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpZero {
break
}
n := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(is32BitFloat(t1) && isSamePtr(p1, p2) && n >= o+4) {
break
}
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(0)
return true
}
// match: (Load <t1> (OffPtr [o] p1) (Zero [n] p2 _))
// cond: is64BitFloat(t1) && isSamePtr(p1, p2) && n >= o + 8
// result: (Const64F [0])
for {
t1 := v.Type
if v_0.Op != OpOffPtr {
break
}
o := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpZero {
break
}
n := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(is64BitFloat(t1) && isSamePtr(p1, p2) && n >= o+8) {
break
}
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(0)
return true
}
// match: (Load <t> _ _)
// cond: t.IsStruct() && t.NumFields() == 0 && fe.CanSSA(t)
// result: (StructMake0)
for {
t := v.Type
if !(t.IsStruct() && t.NumFields() == 0 && fe.CanSSA(t)) {
break
}
v.reset(OpStructMake0)
return true
}
// match: (Load <t> ptr mem)
// cond: t.IsStruct() && t.NumFields() == 1 && fe.CanSSA(t)
// result: (StructMake1 (Load <t.FieldType(0)> (OffPtr <t.FieldType(0).PtrTo()> [0] ptr) mem))
for {
t := v.Type
ptr := v_0
mem := v_1
if !(t.IsStruct() && t.NumFields() == 1 && fe.CanSSA(t)) {
break
}
v.reset(OpStructMake1)
v0 := b.NewValue0(v.Pos, OpLoad, t.FieldType(0))
v1 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(0).PtrTo())
v1.AuxInt = int64ToAuxInt(0)
v1.AddArg(ptr)
v0.AddArg2(v1, mem)
v.AddArg(v0)
return true
}
// match: (Load <t> ptr mem)
// cond: t.IsStruct() && t.NumFields() == 2 && fe.CanSSA(t)
// result: (StructMake2 (Load <t.FieldType(0)> (OffPtr <t.FieldType(0).PtrTo()> [0] ptr) mem) (Load <t.FieldType(1)> (OffPtr <t.FieldType(1).PtrTo()> [t.FieldOff(1)] ptr) mem))
for {
t := v.Type
ptr := v_0
mem := v_1
if !(t.IsStruct() && t.NumFields() == 2 && fe.CanSSA(t)) {
break
}
v.reset(OpStructMake2)
v0 := b.NewValue0(v.Pos, OpLoad, t.FieldType(0))
v1 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(0).PtrTo())
v1.AuxInt = int64ToAuxInt(0)
v1.AddArg(ptr)
v0.AddArg2(v1, mem)
v2 := b.NewValue0(v.Pos, OpLoad, t.FieldType(1))
v3 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(1).PtrTo())
v3.AuxInt = int64ToAuxInt(t.FieldOff(1))
v3.AddArg(ptr)
v2.AddArg2(v3, mem)
v.AddArg2(v0, v2)
return true
}
// match: (Load <t> ptr mem)
// cond: t.IsStruct() && t.NumFields() == 3 && fe.CanSSA(t)
// result: (StructMake3 (Load <t.FieldType(0)> (OffPtr <t.FieldType(0).PtrTo()> [0] ptr) mem) (Load <t.FieldType(1)> (OffPtr <t.FieldType(1).PtrTo()> [t.FieldOff(1)] ptr) mem) (Load <t.FieldType(2)> (OffPtr <t.FieldType(2).PtrTo()> [t.FieldOff(2)] ptr) mem))
for {
t := v.Type
ptr := v_0
mem := v_1
if !(t.IsStruct() && t.NumFields() == 3 && fe.CanSSA(t)) {
break
}
v.reset(OpStructMake3)
v0 := b.NewValue0(v.Pos, OpLoad, t.FieldType(0))
v1 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(0).PtrTo())
v1.AuxInt = int64ToAuxInt(0)
v1.AddArg(ptr)
v0.AddArg2(v1, mem)
v2 := b.NewValue0(v.Pos, OpLoad, t.FieldType(1))
v3 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(1).PtrTo())
v3.AuxInt = int64ToAuxInt(t.FieldOff(1))
v3.AddArg(ptr)
v2.AddArg2(v3, mem)
v4 := b.NewValue0(v.Pos, OpLoad, t.FieldType(2))
v5 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(2).PtrTo())
v5.AuxInt = int64ToAuxInt(t.FieldOff(2))
v5.AddArg(ptr)
v4.AddArg2(v5, mem)
v.AddArg3(v0, v2, v4)
return true
}
// match: (Load <t> ptr mem)
// cond: t.IsStruct() && t.NumFields() == 4 && fe.CanSSA(t)
// result: (StructMake4 (Load <t.FieldType(0)> (OffPtr <t.FieldType(0).PtrTo()> [0] ptr) mem) (Load <t.FieldType(1)> (OffPtr <t.FieldType(1).PtrTo()> [t.FieldOff(1)] ptr) mem) (Load <t.FieldType(2)> (OffPtr <t.FieldType(2).PtrTo()> [t.FieldOff(2)] ptr) mem) (Load <t.FieldType(3)> (OffPtr <t.FieldType(3).PtrTo()> [t.FieldOff(3)] ptr) mem))
for {
t := v.Type
ptr := v_0
mem := v_1
if !(t.IsStruct() && t.NumFields() == 4 && fe.CanSSA(t)) {
break
}
v.reset(OpStructMake4)
v0 := b.NewValue0(v.Pos, OpLoad, t.FieldType(0))
v1 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(0).PtrTo())
v1.AuxInt = int64ToAuxInt(0)
v1.AddArg(ptr)
v0.AddArg2(v1, mem)
v2 := b.NewValue0(v.Pos, OpLoad, t.FieldType(1))
v3 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(1).PtrTo())
v3.AuxInt = int64ToAuxInt(t.FieldOff(1))
v3.AddArg(ptr)
v2.AddArg2(v3, mem)
v4 := b.NewValue0(v.Pos, OpLoad, t.FieldType(2))
v5 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(2).PtrTo())
v5.AuxInt = int64ToAuxInt(t.FieldOff(2))
v5.AddArg(ptr)
v4.AddArg2(v5, mem)
v6 := b.NewValue0(v.Pos, OpLoad, t.FieldType(3))
v7 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(3).PtrTo())
v7.AuxInt = int64ToAuxInt(t.FieldOff(3))
v7.AddArg(ptr)
v6.AddArg2(v7, mem)
v.AddArg4(v0, v2, v4, v6)
return true
}
// match: (Load <t> _ _)
// cond: t.IsArray() && t.NumElem() == 0
// result: (ArrayMake0)
for {
t := v.Type
if !(t.IsArray() && t.NumElem() == 0) {
break
}
v.reset(OpArrayMake0)
return true
}
// match: (Load <t> ptr mem)
// cond: t.IsArray() && t.NumElem() == 1 && fe.CanSSA(t)
// result: (ArrayMake1 (Load <t.Elem()> ptr mem))
for {
t := v.Type
ptr := v_0
mem := v_1
if !(t.IsArray() && t.NumElem() == 1 && fe.CanSSA(t)) {
break
}
v.reset(OpArrayMake1)
v0 := b.NewValue0(v.Pos, OpLoad, t.Elem())
v0.AddArg2(ptr, mem)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh16x16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh16x16 <t> x (Const16 [c]))
// result: (Lsh16x64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpLsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh16x16 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh16x32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh16x32 <t> x (Const32 [c]))
// result: (Lsh16x64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpLsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh16x32 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh16x64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Lsh16x64 (Const16 [c]) (Const64 [d]))
// result: (Const16 [c << uint64(d)])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c << uint64(d))
return true
}
// match: (Lsh16x64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Lsh16x64 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
// match: (Lsh16x64 _ (Const64 [c]))
// cond: uint64(c) >= 16
// result: (Const16 [0])
for {
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(uint64(c) >= 16) {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
// match: (Lsh16x64 <t> (Lsh16x64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Lsh16x64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpLsh16x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpLsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Lsh16x64 (Rsh16Ux64 (Lsh16x64 x (Const64 [c1])) (Const64 [c2])) (Const64 [c3]))
// cond: uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)
// result: (Lsh16x64 x (Const64 <typ.UInt64> [c1-c2+c3]))
for {
if v_0.Op != OpRsh16Ux64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLsh16x64 {
break
}
_ = v_0_0.Args[1]
x := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c1 := auxIntToInt64(v_0_0_1.AuxInt)
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
c3 := auxIntToInt64(v_1.AuxInt)
if !(uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)) {
break
}
v.reset(OpLsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(c1 - c2 + c3)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh16x8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh16x8 <t> x (Const8 [c]))
// result: (Lsh16x64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpLsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh16x8 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh32x16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh32x16 <t> x (Const16 [c]))
// result: (Lsh32x64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpLsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh32x16 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh32x32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh32x32 <t> x (Const32 [c]))
// result: (Lsh32x64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpLsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh32x32 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh32x64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Lsh32x64 (Const32 [c]) (Const64 [d]))
// result: (Const32 [c << uint64(d)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c << uint64(d))
return true
}
// match: (Lsh32x64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Lsh32x64 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Lsh32x64 _ (Const64 [c]))
// cond: uint64(c) >= 32
// result: (Const32 [0])
for {
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(uint64(c) >= 32) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Lsh32x64 <t> (Lsh32x64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Lsh32x64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpLsh32x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpLsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Lsh32x64 (Rsh32Ux64 (Lsh32x64 x (Const64 [c1])) (Const64 [c2])) (Const64 [c3]))
// cond: uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)
// result: (Lsh32x64 x (Const64 <typ.UInt64> [c1-c2+c3]))
for {
if v_0.Op != OpRsh32Ux64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLsh32x64 {
break
}
_ = v_0_0.Args[1]
x := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c1 := auxIntToInt64(v_0_0_1.AuxInt)
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
c3 := auxIntToInt64(v_1.AuxInt)
if !(uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)) {
break
}
v.reset(OpLsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(c1 - c2 + c3)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh32x8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh32x8 <t> x (Const8 [c]))
// result: (Lsh32x64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpLsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh32x8 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh64x16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh64x16 <t> x (Const16 [c]))
// result: (Lsh64x64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpLsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh64x16 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh64x32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh64x32 <t> x (Const32 [c]))
// result: (Lsh64x64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpLsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh64x32 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh64x64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Lsh64x64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [c << uint64(d)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c << uint64(d))
return true
}
// match: (Lsh64x64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Lsh64x64 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Lsh64x64 _ (Const64 [c]))
// cond: uint64(c) >= 64
// result: (Const64 [0])
for {
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(uint64(c) >= 64) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Lsh64x64 <t> (Lsh64x64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Lsh64x64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpLsh64x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpLsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Lsh64x64 (Rsh64Ux64 (Lsh64x64 x (Const64 [c1])) (Const64 [c2])) (Const64 [c3]))
// cond: uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)
// result: (Lsh64x64 x (Const64 <typ.UInt64> [c1-c2+c3]))
for {
if v_0.Op != OpRsh64Ux64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLsh64x64 {
break
}
_ = v_0_0.Args[1]
x := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c1 := auxIntToInt64(v_0_0_1.AuxInt)
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
c3 := auxIntToInt64(v_1.AuxInt)
if !(uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)) {
break
}
v.reset(OpLsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(c1 - c2 + c3)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh64x8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh64x8 <t> x (Const8 [c]))
// result: (Lsh64x64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpLsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh64x8 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh8x16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh8x16 <t> x (Const16 [c]))
// result: (Lsh8x64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpLsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh8x16 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh8x32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh8x32 <t> x (Const32 [c]))
// result: (Lsh8x64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpLsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh8x32 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh8x64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Lsh8x64 (Const8 [c]) (Const64 [d]))
// result: (Const8 [c << uint64(d)])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c << uint64(d))
return true
}
// match: (Lsh8x64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Lsh8x64 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (Lsh8x64 _ (Const64 [c]))
// cond: uint64(c) >= 8
// result: (Const8 [0])
for {
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(uint64(c) >= 8) {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (Lsh8x64 <t> (Lsh8x64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Lsh8x64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpLsh8x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpLsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Lsh8x64 (Rsh8Ux64 (Lsh8x64 x (Const64 [c1])) (Const64 [c2])) (Const64 [c3]))
// cond: uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)
// result: (Lsh8x64 x (Const64 <typ.UInt64> [c1-c2+c3]))
for {
if v_0.Op != OpRsh8Ux64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLsh8x64 {
break
}
_ = v_0_0.Args[1]
x := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c1 := auxIntToInt64(v_0_0_1.AuxInt)
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
c3 := auxIntToInt64(v_1.AuxInt)
if !(uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)) {
break
}
v.reset(OpLsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(c1 - c2 + c3)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpLsh8x8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Lsh8x8 <t> x (Const8 [c]))
// result: (Lsh8x64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpLsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Lsh8x8 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpMod16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Mod16 (Const16 [c]) (Const16 [d]))
// cond: d != 0
// result: (Const16 [c % d])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c % d)
return true
}
// match: (Mod16 <t> n (Const16 [c]))
// cond: isNonNegative(n) && isPowerOfTwo16(c)
// result: (And16 n (Const16 <t> [c-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(isNonNegative(n) && isPowerOfTwo16(c)) {
break
}
v.reset(OpAnd16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod16 <t> n (Const16 [c]))
// cond: c < 0 && c != -1<<15
// result: (Mod16 <t> n (Const16 <t> [-c]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(c < 0 && c != -1<<15) {
break
}
v.reset(OpMod16)
v.Type = t
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(-c)
v.AddArg2(n, v0)
return true
}
// match: (Mod16 <t> x (Const16 [c]))
// cond: x.Op != OpConst16 && (c > 0 || c == -1<<15)
// result: (Sub16 x (Mul16 <t> (Div16 <t> x (Const16 <t> [c])) (Const16 <t> [c])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(x.Op != OpConst16 && (c > 0 || c == -1<<15)) {
break
}
v.reset(OpSub16)
v0 := b.NewValue0(v.Pos, OpMul16, t)
v1 := b.NewValue0(v.Pos, OpDiv16, t)
v2 := b.NewValue0(v.Pos, OpConst16, t)
v2.AuxInt = int16ToAuxInt(c)
v1.AddArg2(x, v2)
v0.AddArg2(v1, v2)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpMod16u(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Mod16u (Const16 [c]) (Const16 [d]))
// cond: d != 0
// result: (Const16 [int16(uint16(c) % uint16(d))])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(int16(uint16(c) % uint16(d)))
return true
}
// match: (Mod16u <t> n (Const16 [c]))
// cond: isPowerOfTwo16(c)
// result: (And16 n (Const16 <t> [c-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(isPowerOfTwo16(c)) {
break
}
v.reset(OpAnd16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod16u <t> x (Const16 [c]))
// cond: x.Op != OpConst16 && c > 0 && umagicOK16(c)
// result: (Sub16 x (Mul16 <t> (Div16u <t> x (Const16 <t> [c])) (Const16 <t> [c])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(x.Op != OpConst16 && c > 0 && umagicOK16(c)) {
break
}
v.reset(OpSub16)
v0 := b.NewValue0(v.Pos, OpMul16, t)
v1 := b.NewValue0(v.Pos, OpDiv16u, t)
v2 := b.NewValue0(v.Pos, OpConst16, t)
v2.AuxInt = int16ToAuxInt(c)
v1.AddArg2(x, v2)
v0.AddArg2(v1, v2)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpMod32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Mod32 (Const32 [c]) (Const32 [d]))
// cond: d != 0
// result: (Const32 [c % d])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c % d)
return true
}
// match: (Mod32 <t> n (Const32 [c]))
// cond: isNonNegative(n) && isPowerOfTwo32(c)
// result: (And32 n (Const32 <t> [c-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(isNonNegative(n) && isPowerOfTwo32(c)) {
break
}
v.reset(OpAnd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod32 <t> n (Const32 [c]))
// cond: c < 0 && c != -1<<31
// result: (Mod32 <t> n (Const32 <t> [-c]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(c < 0 && c != -1<<31) {
break
}
v.reset(OpMod32)
v.Type = t
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(-c)
v.AddArg2(n, v0)
return true
}
// match: (Mod32 <t> x (Const32 [c]))
// cond: x.Op != OpConst32 && (c > 0 || c == -1<<31)
// result: (Sub32 x (Mul32 <t> (Div32 <t> x (Const32 <t> [c])) (Const32 <t> [c])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(x.Op != OpConst32 && (c > 0 || c == -1<<31)) {
break
}
v.reset(OpSub32)
v0 := b.NewValue0(v.Pos, OpMul32, t)
v1 := b.NewValue0(v.Pos, OpDiv32, t)
v2 := b.NewValue0(v.Pos, OpConst32, t)
v2.AuxInt = int32ToAuxInt(c)
v1.AddArg2(x, v2)
v0.AddArg2(v1, v2)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpMod32u(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Mod32u (Const32 [c]) (Const32 [d]))
// cond: d != 0
// result: (Const32 [int32(uint32(c) % uint32(d))])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(uint32(c) % uint32(d)))
return true
}
// match: (Mod32u <t> n (Const32 [c]))
// cond: isPowerOfTwo32(c)
// result: (And32 n (Const32 <t> [c-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(isPowerOfTwo32(c)) {
break
}
v.reset(OpAnd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod32u <t> x (Const32 [c]))
// cond: x.Op != OpConst32 && c > 0 && umagicOK32(c)
// result: (Sub32 x (Mul32 <t> (Div32u <t> x (Const32 <t> [c])) (Const32 <t> [c])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(x.Op != OpConst32 && c > 0 && umagicOK32(c)) {
break
}
v.reset(OpSub32)
v0 := b.NewValue0(v.Pos, OpMul32, t)
v1 := b.NewValue0(v.Pos, OpDiv32u, t)
v2 := b.NewValue0(v.Pos, OpConst32, t)
v2.AuxInt = int32ToAuxInt(c)
v1.AddArg2(x, v2)
v0.AddArg2(v1, v2)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpMod64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Mod64 (Const64 [c]) (Const64 [d]))
// cond: d != 0
// result: (Const64 [c % d])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c % d)
return true
}
// match: (Mod64 <t> n (Const64 [c]))
// cond: isNonNegative(n) && isPowerOfTwo64(c)
// result: (And64 n (Const64 <t> [c-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(isNonNegative(n) && isPowerOfTwo64(c)) {
break
}
v.reset(OpAnd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod64 n (Const64 [-1<<63]))
// cond: isNonNegative(n)
// result: n
for {
n := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != -1<<63 || !(isNonNegative(n)) {
break
}
v.copyOf(n)
return true
}
// match: (Mod64 <t> n (Const64 [c]))
// cond: c < 0 && c != -1<<63
// result: (Mod64 <t> n (Const64 <t> [-c]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(c < 0 && c != -1<<63) {
break
}
v.reset(OpMod64)
v.Type = t
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(-c)
v.AddArg2(n, v0)
return true
}
// match: (Mod64 <t> x (Const64 [c]))
// cond: x.Op != OpConst64 && (c > 0 || c == -1<<63)
// result: (Sub64 x (Mul64 <t> (Div64 <t> x (Const64 <t> [c])) (Const64 <t> [c])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(x.Op != OpConst64 && (c > 0 || c == -1<<63)) {
break
}
v.reset(OpSub64)
v0 := b.NewValue0(v.Pos, OpMul64, t)
v1 := b.NewValue0(v.Pos, OpDiv64, t)
v2 := b.NewValue0(v.Pos, OpConst64, t)
v2.AuxInt = int64ToAuxInt(c)
v1.AddArg2(x, v2)
v0.AddArg2(v1, v2)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpMod64u(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Mod64u (Const64 [c]) (Const64 [d]))
// cond: d != 0
// result: (Const64 [int64(uint64(c) % uint64(d))])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(uint64(c) % uint64(d)))
return true
}
// match: (Mod64u <t> n (Const64 [c]))
// cond: isPowerOfTwo64(c)
// result: (And64 n (Const64 <t> [c-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(isPowerOfTwo64(c)) {
break
}
v.reset(OpAnd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod64u <t> n (Const64 [-1<<63]))
// result: (And64 n (Const64 <t> [1<<63-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != -1<<63 {
break
}
v.reset(OpAnd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(1<<63 - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod64u <t> x (Const64 [c]))
// cond: x.Op != OpConst64 && c > 0 && umagicOK64(c)
// result: (Sub64 x (Mul64 <t> (Div64u <t> x (Const64 <t> [c])) (Const64 <t> [c])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(x.Op != OpConst64 && c > 0 && umagicOK64(c)) {
break
}
v.reset(OpSub64)
v0 := b.NewValue0(v.Pos, OpMul64, t)
v1 := b.NewValue0(v.Pos, OpDiv64u, t)
v2 := b.NewValue0(v.Pos, OpConst64, t)
v2.AuxInt = int64ToAuxInt(c)
v1.AddArg2(x, v2)
v0.AddArg2(v1, v2)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpMod8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Mod8 (Const8 [c]) (Const8 [d]))
// cond: d != 0
// result: (Const8 [c % d])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c % d)
return true
}
// match: (Mod8 <t> n (Const8 [c]))
// cond: isNonNegative(n) && isPowerOfTwo8(c)
// result: (And8 n (Const8 <t> [c-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(isNonNegative(n) && isPowerOfTwo8(c)) {
break
}
v.reset(OpAnd8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod8 <t> n (Const8 [c]))
// cond: c < 0 && c != -1<<7
// result: (Mod8 <t> n (Const8 <t> [-c]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(c < 0 && c != -1<<7) {
break
}
v.reset(OpMod8)
v.Type = t
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(-c)
v.AddArg2(n, v0)
return true
}
// match: (Mod8 <t> x (Const8 [c]))
// cond: x.Op != OpConst8 && (c > 0 || c == -1<<7)
// result: (Sub8 x (Mul8 <t> (Div8 <t> x (Const8 <t> [c])) (Const8 <t> [c])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(x.Op != OpConst8 && (c > 0 || c == -1<<7)) {
break
}
v.reset(OpSub8)
v0 := b.NewValue0(v.Pos, OpMul8, t)
v1 := b.NewValue0(v.Pos, OpDiv8, t)
v2 := b.NewValue0(v.Pos, OpConst8, t)
v2.AuxInt = int8ToAuxInt(c)
v1.AddArg2(x, v2)
v0.AddArg2(v1, v2)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpMod8u(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Mod8u (Const8 [c]) (Const8 [d]))
// cond: d != 0
// result: (Const8 [int8(uint8(c) % uint8(d))])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
if !(d != 0) {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(int8(uint8(c) % uint8(d)))
return true
}
// match: (Mod8u <t> n (Const8 [c]))
// cond: isPowerOfTwo8(c)
// result: (And8 n (Const8 <t> [c-1]))
for {
t := v.Type
n := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(isPowerOfTwo8(c)) {
break
}
v.reset(OpAnd8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c - 1)
v.AddArg2(n, v0)
return true
}
// match: (Mod8u <t> x (Const8 [c]))
// cond: x.Op != OpConst8 && c > 0 && umagicOK8( c)
// result: (Sub8 x (Mul8 <t> (Div8u <t> x (Const8 <t> [c])) (Const8 <t> [c])))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(x.Op != OpConst8 && c > 0 && umagicOK8(c)) {
break
}
v.reset(OpSub8)
v0 := b.NewValue0(v.Pos, OpMul8, t)
v1 := b.NewValue0(v.Pos, OpDiv8u, t)
v2 := b.NewValue0(v.Pos, OpConst8, t)
v2.AuxInt = int8ToAuxInt(c)
v1.AddArg2(x, v2)
v0.AddArg2(v1, v2)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpMove(v *Value) bool {
v_2 := v.Args[2]
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
// match: (Move {t} [n] dst1 src mem:(Zero {t} [n] dst2 _))
// cond: isSamePtr(src, dst2)
// result: (Zero {t} [n] dst1 mem)
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
src := v_1
mem := v_2
if mem.Op != OpZero || auxIntToInt64(mem.AuxInt) != n || auxToType(mem.Aux) != t {
break
}
dst2 := mem.Args[0]
if !(isSamePtr(src, dst2)) {
break
}
v.reset(OpZero)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v.AddArg2(dst1, mem)
return true
}
// match: (Move {t} [n] dst1 src mem:(VarDef (Zero {t} [n] dst0 _)))
// cond: isSamePtr(src, dst0)
// result: (Zero {t} [n] dst1 mem)
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
src := v_1
mem := v_2
if mem.Op != OpVarDef {
break
}
mem_0 := mem.Args[0]
if mem_0.Op != OpZero || auxIntToInt64(mem_0.AuxInt) != n || auxToType(mem_0.Aux) != t {
break
}
dst0 := mem_0.Args[0]
if !(isSamePtr(src, dst0)) {
break
}
v.reset(OpZero)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v.AddArg2(dst1, mem)
return true
}
// match: (Move {t} [n] dst (Addr {sym} (SB)) mem)
// cond: symIsROZero(sym)
// result: (Zero {t} [n] dst mem)
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst := v_0
if v_1.Op != OpAddr {
break
}
sym := auxToSym(v_1.Aux)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpSB {
break
}
mem := v_2
if !(symIsROZero(sym)) {
break
}
v.reset(OpZero)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v.AddArg2(dst, mem)
return true
}
// match: (Move {t1} [n] dst1 src1 store:(Store {t2} op:(OffPtr [o2] dst2) _ mem))
// cond: isSamePtr(dst1, dst2) && store.Uses == 1 && n >= o2 + t2.Size() && disjoint(src1, n, op, t2.Size()) && clobber(store)
// result: (Move {t1} [n] dst1 src1 mem)
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst1 := v_0
src1 := v_1
store := v_2
if store.Op != OpStore {
break
}
t2 := auxToType(store.Aux)
mem := store.Args[2]
op := store.Args[0]
if op.Op != OpOffPtr {
break
}
o2 := auxIntToInt64(op.AuxInt)
dst2 := op.Args[0]
if !(isSamePtr(dst1, dst2) && store.Uses == 1 && n >= o2+t2.Size() && disjoint(src1, n, op, t2.Size()) && clobber(store)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t1)
v.AddArg3(dst1, src1, mem)
return true
}
// match: (Move {t} [n] dst1 src1 move:(Move {t} [n] dst2 _ mem))
// cond: move.Uses == 1 && isSamePtr(dst1, dst2) && disjoint(src1, n, dst2, n) && clobber(move)
// result: (Move {t} [n] dst1 src1 mem)
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
src1 := v_1
move := v_2
if move.Op != OpMove || auxIntToInt64(move.AuxInt) != n || auxToType(move.Aux) != t {
break
}
mem := move.Args[2]
dst2 := move.Args[0]
if !(move.Uses == 1 && isSamePtr(dst1, dst2) && disjoint(src1, n, dst2, n) && clobber(move)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v.AddArg3(dst1, src1, mem)
return true
}
// match: (Move {t} [n] dst1 src1 vardef:(VarDef {x} move:(Move {t} [n] dst2 _ mem)))
// cond: move.Uses == 1 && vardef.Uses == 1 && isSamePtr(dst1, dst2) && disjoint(src1, n, dst2, n) && clobber(move, vardef)
// result: (Move {t} [n] dst1 src1 (VarDef {x} mem))
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
src1 := v_1
vardef := v_2
if vardef.Op != OpVarDef {
break
}
x := auxToSym(vardef.Aux)
move := vardef.Args[0]
if move.Op != OpMove || auxIntToInt64(move.AuxInt) != n || auxToType(move.Aux) != t {
break
}
mem := move.Args[2]
dst2 := move.Args[0]
if !(move.Uses == 1 && vardef.Uses == 1 && isSamePtr(dst1, dst2) && disjoint(src1, n, dst2, n) && clobber(move, vardef)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v0 := b.NewValue0(v.Pos, OpVarDef, types.TypeMem)
v0.Aux = symToAux(x)
v0.AddArg(mem)
v.AddArg3(dst1, src1, v0)
return true
}
// match: (Move {t} [n] dst1 src1 zero:(Zero {t} [n] dst2 mem))
// cond: zero.Uses == 1 && isSamePtr(dst1, dst2) && disjoint(src1, n, dst2, n) && clobber(zero)
// result: (Move {t} [n] dst1 src1 mem)
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
src1 := v_1
zero := v_2
if zero.Op != OpZero || auxIntToInt64(zero.AuxInt) != n || auxToType(zero.Aux) != t {
break
}
mem := zero.Args[1]
dst2 := zero.Args[0]
if !(zero.Uses == 1 && isSamePtr(dst1, dst2) && disjoint(src1, n, dst2, n) && clobber(zero)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v.AddArg3(dst1, src1, mem)
return true
}
// match: (Move {t} [n] dst1 src1 vardef:(VarDef {x} zero:(Zero {t} [n] dst2 mem)))
// cond: zero.Uses == 1 && vardef.Uses == 1 && isSamePtr(dst1, dst2) && disjoint(src1, n, dst2, n) && clobber(zero, vardef)
// result: (Move {t} [n] dst1 src1 (VarDef {x} mem))
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
src1 := v_1
vardef := v_2
if vardef.Op != OpVarDef {
break
}
x := auxToSym(vardef.Aux)
zero := vardef.Args[0]
if zero.Op != OpZero || auxIntToInt64(zero.AuxInt) != n || auxToType(zero.Aux) != t {
break
}
mem := zero.Args[1]
dst2 := zero.Args[0]
if !(zero.Uses == 1 && vardef.Uses == 1 && isSamePtr(dst1, dst2) && disjoint(src1, n, dst2, n) && clobber(zero, vardef)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v0 := b.NewValue0(v.Pos, OpVarDef, types.TypeMem)
v0.Aux = symToAux(x)
v0.AddArg(mem)
v.AddArg3(dst1, src1, v0)
return true
}
// match: (Move {t1} [n] dst p1 mem:(Store {t2} op2:(OffPtr <tt2> [o2] p2) d1 (Store {t3} op3:(OffPtr <tt3> [0] p3) d2 _)))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && o2 == t3.Size() && n == t2.Size() + t3.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [0] dst) d2 mem))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
op2 := mem.Args[0]
if op2.Op != OpOffPtr {
break
}
tt2 := op2.Type
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d1 := mem.Args[1]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t3 := auxToType(mem_2.Aux)
d2 := mem_2.Args[1]
op3 := mem_2.Args[0]
if op3.Op != OpOffPtr {
break
}
tt3 := op3.Type
if auxIntToInt64(op3.AuxInt) != 0 {
break
}
p3 := op3.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && o2 == t3.Size() && n == t2.Size()+t3.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(0)
v2.AddArg(dst)
v1.AddArg3(v2, d2, mem)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(Store {t2} op2:(OffPtr <tt2> [o2] p2) d1 (Store {t3} op3:(OffPtr <tt3> [o3] p3) d2 (Store {t4} op4:(OffPtr <tt4> [0] p4) d3 _))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && o3 == t4.Size() && o2-o3 == t3.Size() && n == t2.Size() + t3.Size() + t4.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Store {t4} (OffPtr <tt4> [0] dst) d3 mem)))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
op2 := mem.Args[0]
if op2.Op != OpOffPtr {
break
}
tt2 := op2.Type
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d1 := mem.Args[1]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t3 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
op3 := mem_2.Args[0]
if op3.Op != OpOffPtr {
break
}
tt3 := op3.Type
o3 := auxIntToInt64(op3.AuxInt)
p3 := op3.Args[0]
d2 := mem_2.Args[1]
mem_2_2 := mem_2.Args[2]
if mem_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_2_2.Aux)
d3 := mem_2_2.Args[1]
op4 := mem_2_2.Args[0]
if op4.Op != OpOffPtr {
break
}
tt4 := op4.Type
if auxIntToInt64(op4.AuxInt) != 0 {
break
}
p4 := op4.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && o3 == t4.Size() && o2-o3 == t3.Size() && n == t2.Size()+t3.Size()+t4.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t4)
v4 := b.NewValue0(v.Pos, OpOffPtr, tt4)
v4.AuxInt = int64ToAuxInt(0)
v4.AddArg(dst)
v3.AddArg3(v4, d3, mem)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(Store {t2} op2:(OffPtr <tt2> [o2] p2) d1 (Store {t3} op3:(OffPtr <tt3> [o3] p3) d2 (Store {t4} op4:(OffPtr <tt4> [o4] p4) d3 (Store {t5} op5:(OffPtr <tt5> [0] p5) d4 _)))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && registerizable(b, t5) && o4 == t5.Size() && o3-o4 == t4.Size() && o2-o3 == t3.Size() && n == t2.Size() + t3.Size() + t4.Size() + t5.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Store {t4} (OffPtr <tt4> [o4] dst) d3 (Store {t5} (OffPtr <tt5> [0] dst) d4 mem))))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
op2 := mem.Args[0]
if op2.Op != OpOffPtr {
break
}
tt2 := op2.Type
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d1 := mem.Args[1]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t3 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
op3 := mem_2.Args[0]
if op3.Op != OpOffPtr {
break
}
tt3 := op3.Type
o3 := auxIntToInt64(op3.AuxInt)
p3 := op3.Args[0]
d2 := mem_2.Args[1]
mem_2_2 := mem_2.Args[2]
if mem_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_2_2.Aux)
_ = mem_2_2.Args[2]
op4 := mem_2_2.Args[0]
if op4.Op != OpOffPtr {
break
}
tt4 := op4.Type
o4 := auxIntToInt64(op4.AuxInt)
p4 := op4.Args[0]
d3 := mem_2_2.Args[1]
mem_2_2_2 := mem_2_2.Args[2]
if mem_2_2_2.Op != OpStore {
break
}
t5 := auxToType(mem_2_2_2.Aux)
d4 := mem_2_2_2.Args[1]
op5 := mem_2_2_2.Args[0]
if op5.Op != OpOffPtr {
break
}
tt5 := op5.Type
if auxIntToInt64(op5.AuxInt) != 0 {
break
}
p5 := op5.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && registerizable(b, t5) && o4 == t5.Size() && o3-o4 == t4.Size() && o2-o3 == t3.Size() && n == t2.Size()+t3.Size()+t4.Size()+t5.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t4)
v4 := b.NewValue0(v.Pos, OpOffPtr, tt4)
v4.AuxInt = int64ToAuxInt(o4)
v4.AddArg(dst)
v5 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v5.Aux = typeToAux(t5)
v6 := b.NewValue0(v.Pos, OpOffPtr, tt5)
v6.AuxInt = int64ToAuxInt(0)
v6.AddArg(dst)
v5.AddArg3(v6, d4, mem)
v3.AddArg3(v4, d3, v5)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(VarDef (Store {t2} op2:(OffPtr <tt2> [o2] p2) d1 (Store {t3} op3:(OffPtr <tt3> [0] p3) d2 _))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && o2 == t3.Size() && n == t2.Size() + t3.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [0] dst) d2 mem))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpVarDef {
break
}
mem_0 := mem.Args[0]
if mem_0.Op != OpStore {
break
}
t2 := auxToType(mem_0.Aux)
_ = mem_0.Args[2]
op2 := mem_0.Args[0]
if op2.Op != OpOffPtr {
break
}
tt2 := op2.Type
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d1 := mem_0.Args[1]
mem_0_2 := mem_0.Args[2]
if mem_0_2.Op != OpStore {
break
}
t3 := auxToType(mem_0_2.Aux)
d2 := mem_0_2.Args[1]
op3 := mem_0_2.Args[0]
if op3.Op != OpOffPtr {
break
}
tt3 := op3.Type
if auxIntToInt64(op3.AuxInt) != 0 {
break
}
p3 := op3.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && o2 == t3.Size() && n == t2.Size()+t3.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(0)
v2.AddArg(dst)
v1.AddArg3(v2, d2, mem)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(VarDef (Store {t2} op2:(OffPtr <tt2> [o2] p2) d1 (Store {t3} op3:(OffPtr <tt3> [o3] p3) d2 (Store {t4} op4:(OffPtr <tt4> [0] p4) d3 _)))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && o3 == t4.Size() && o2-o3 == t3.Size() && n == t2.Size() + t3.Size() + t4.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Store {t4} (OffPtr <tt4> [0] dst) d3 mem)))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpVarDef {
break
}
mem_0 := mem.Args[0]
if mem_0.Op != OpStore {
break
}
t2 := auxToType(mem_0.Aux)
_ = mem_0.Args[2]
op2 := mem_0.Args[0]
if op2.Op != OpOffPtr {
break
}
tt2 := op2.Type
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d1 := mem_0.Args[1]
mem_0_2 := mem_0.Args[2]
if mem_0_2.Op != OpStore {
break
}
t3 := auxToType(mem_0_2.Aux)
_ = mem_0_2.Args[2]
op3 := mem_0_2.Args[0]
if op3.Op != OpOffPtr {
break
}
tt3 := op3.Type
o3 := auxIntToInt64(op3.AuxInt)
p3 := op3.Args[0]
d2 := mem_0_2.Args[1]
mem_0_2_2 := mem_0_2.Args[2]
if mem_0_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_0_2_2.Aux)
d3 := mem_0_2_2.Args[1]
op4 := mem_0_2_2.Args[0]
if op4.Op != OpOffPtr {
break
}
tt4 := op4.Type
if auxIntToInt64(op4.AuxInt) != 0 {
break
}
p4 := op4.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && o3 == t4.Size() && o2-o3 == t3.Size() && n == t2.Size()+t3.Size()+t4.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t4)
v4 := b.NewValue0(v.Pos, OpOffPtr, tt4)
v4.AuxInt = int64ToAuxInt(0)
v4.AddArg(dst)
v3.AddArg3(v4, d3, mem)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(VarDef (Store {t2} op2:(OffPtr <tt2> [o2] p2) d1 (Store {t3} op3:(OffPtr <tt3> [o3] p3) d2 (Store {t4} op4:(OffPtr <tt4> [o4] p4) d3 (Store {t5} op5:(OffPtr <tt5> [0] p5) d4 _))))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && registerizable(b, t5) && o4 == t5.Size() && o3-o4 == t4.Size() && o2-o3 == t3.Size() && n == t2.Size() + t3.Size() + t4.Size() + t5.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Store {t4} (OffPtr <tt4> [o4] dst) d3 (Store {t5} (OffPtr <tt5> [0] dst) d4 mem))))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpVarDef {
break
}
mem_0 := mem.Args[0]
if mem_0.Op != OpStore {
break
}
t2 := auxToType(mem_0.Aux)
_ = mem_0.Args[2]
op2 := mem_0.Args[0]
if op2.Op != OpOffPtr {
break
}
tt2 := op2.Type
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d1 := mem_0.Args[1]
mem_0_2 := mem_0.Args[2]
if mem_0_2.Op != OpStore {
break
}
t3 := auxToType(mem_0_2.Aux)
_ = mem_0_2.Args[2]
op3 := mem_0_2.Args[0]
if op3.Op != OpOffPtr {
break
}
tt3 := op3.Type
o3 := auxIntToInt64(op3.AuxInt)
p3 := op3.Args[0]
d2 := mem_0_2.Args[1]
mem_0_2_2 := mem_0_2.Args[2]
if mem_0_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_0_2_2.Aux)
_ = mem_0_2_2.Args[2]
op4 := mem_0_2_2.Args[0]
if op4.Op != OpOffPtr {
break
}
tt4 := op4.Type
o4 := auxIntToInt64(op4.AuxInt)
p4 := op4.Args[0]
d3 := mem_0_2_2.Args[1]
mem_0_2_2_2 := mem_0_2_2.Args[2]
if mem_0_2_2_2.Op != OpStore {
break
}
t5 := auxToType(mem_0_2_2_2.Aux)
d4 := mem_0_2_2_2.Args[1]
op5 := mem_0_2_2_2.Args[0]
if op5.Op != OpOffPtr {
break
}
tt5 := op5.Type
if auxIntToInt64(op5.AuxInt) != 0 {
break
}
p5 := op5.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && registerizable(b, t5) && o4 == t5.Size() && o3-o4 == t4.Size() && o2-o3 == t3.Size() && n == t2.Size()+t3.Size()+t4.Size()+t5.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t4)
v4 := b.NewValue0(v.Pos, OpOffPtr, tt4)
v4.AuxInt = int64ToAuxInt(o4)
v4.AddArg(dst)
v5 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v5.Aux = typeToAux(t5)
v6 := b.NewValue0(v.Pos, OpOffPtr, tt5)
v6.AuxInt = int64ToAuxInt(0)
v6.AddArg(dst)
v5.AddArg3(v6, d4, mem)
v3.AddArg3(v4, d3, v5)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(Store {t2} op2:(OffPtr <tt2> [o2] p2) d1 (Zero {t3} [n] p3 _)))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && registerizable(b, t2) && n >= o2 + t2.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Zero {t1} [n] dst mem))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
op2 := mem.Args[0]
if op2.Op != OpOffPtr {
break
}
tt2 := op2.Type
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d1 := mem.Args[1]
mem_2 := mem.Args[2]
if mem_2.Op != OpZero || auxIntToInt64(mem_2.AuxInt) != n {
break
}
t3 := auxToType(mem_2.Aux)
p3 := mem_2.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && registerizable(b, t2) && n >= o2+t2.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpZero, types.TypeMem)
v1.AuxInt = int64ToAuxInt(n)
v1.Aux = typeToAux(t1)
v1.AddArg2(dst, mem)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(Store {t2} (OffPtr <tt2> [o2] p2) d1 (Store {t3} (OffPtr <tt3> [o3] p3) d2 (Zero {t4} [n] p4 _))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && n >= o2 + t2.Size() && n >= o3 + t3.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Zero {t1} [n] dst mem)))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
mem_0 := mem.Args[0]
if mem_0.Op != OpOffPtr {
break
}
tt2 := mem_0.Type
o2 := auxIntToInt64(mem_0.AuxInt)
p2 := mem_0.Args[0]
d1 := mem.Args[1]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t3 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
mem_2_0 := mem_2.Args[0]
if mem_2_0.Op != OpOffPtr {
break
}
tt3 := mem_2_0.Type
o3 := auxIntToInt64(mem_2_0.AuxInt)
p3 := mem_2_0.Args[0]
d2 := mem_2.Args[1]
mem_2_2 := mem_2.Args[2]
if mem_2_2.Op != OpZero || auxIntToInt64(mem_2_2.AuxInt) != n {
break
}
t4 := auxToType(mem_2_2.Aux)
p4 := mem_2_2.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && n >= o2+t2.Size() && n >= o3+t3.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpZero, types.TypeMem)
v3.AuxInt = int64ToAuxInt(n)
v3.Aux = typeToAux(t1)
v3.AddArg2(dst, mem)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(Store {t2} (OffPtr <tt2> [o2] p2) d1 (Store {t3} (OffPtr <tt3> [o3] p3) d2 (Store {t4} (OffPtr <tt4> [o4] p4) d3 (Zero {t5} [n] p5 _)))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && n >= o2 + t2.Size() && n >= o3 + t3.Size() && n >= o4 + t4.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Store {t4} (OffPtr <tt4> [o4] dst) d3 (Zero {t1} [n] dst mem))))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
mem_0 := mem.Args[0]
if mem_0.Op != OpOffPtr {
break
}
tt2 := mem_0.Type
o2 := auxIntToInt64(mem_0.AuxInt)
p2 := mem_0.Args[0]
d1 := mem.Args[1]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t3 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
mem_2_0 := mem_2.Args[0]
if mem_2_0.Op != OpOffPtr {
break
}
tt3 := mem_2_0.Type
o3 := auxIntToInt64(mem_2_0.AuxInt)
p3 := mem_2_0.Args[0]
d2 := mem_2.Args[1]
mem_2_2 := mem_2.Args[2]
if mem_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_2_2.Aux)
_ = mem_2_2.Args[2]
mem_2_2_0 := mem_2_2.Args[0]
if mem_2_2_0.Op != OpOffPtr {
break
}
tt4 := mem_2_2_0.Type
o4 := auxIntToInt64(mem_2_2_0.AuxInt)
p4 := mem_2_2_0.Args[0]
d3 := mem_2_2.Args[1]
mem_2_2_2 := mem_2_2.Args[2]
if mem_2_2_2.Op != OpZero || auxIntToInt64(mem_2_2_2.AuxInt) != n {
break
}
t5 := auxToType(mem_2_2_2.Aux)
p5 := mem_2_2_2.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && n >= o2+t2.Size() && n >= o3+t3.Size() && n >= o4+t4.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t4)
v4 := b.NewValue0(v.Pos, OpOffPtr, tt4)
v4.AuxInt = int64ToAuxInt(o4)
v4.AddArg(dst)
v5 := b.NewValue0(v.Pos, OpZero, types.TypeMem)
v5.AuxInt = int64ToAuxInt(n)
v5.Aux = typeToAux(t1)
v5.AddArg2(dst, mem)
v3.AddArg3(v4, d3, v5)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(Store {t2} (OffPtr <tt2> [o2] p2) d1 (Store {t3} (OffPtr <tt3> [o3] p3) d2 (Store {t4} (OffPtr <tt4> [o4] p4) d3 (Store {t5} (OffPtr <tt5> [o5] p5) d4 (Zero {t6} [n] p6 _))))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && isSamePtr(p5, p6) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && t6.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && registerizable(b, t5) && n >= o2 + t2.Size() && n >= o3 + t3.Size() && n >= o4 + t4.Size() && n >= o5 + t5.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Store {t4} (OffPtr <tt4> [o4] dst) d3 (Store {t5} (OffPtr <tt5> [o5] dst) d4 (Zero {t1} [n] dst mem)))))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
mem_0 := mem.Args[0]
if mem_0.Op != OpOffPtr {
break
}
tt2 := mem_0.Type
o2 := auxIntToInt64(mem_0.AuxInt)
p2 := mem_0.Args[0]
d1 := mem.Args[1]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t3 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
mem_2_0 := mem_2.Args[0]
if mem_2_0.Op != OpOffPtr {
break
}
tt3 := mem_2_0.Type
o3 := auxIntToInt64(mem_2_0.AuxInt)
p3 := mem_2_0.Args[0]
d2 := mem_2.Args[1]
mem_2_2 := mem_2.Args[2]
if mem_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_2_2.Aux)
_ = mem_2_2.Args[2]
mem_2_2_0 := mem_2_2.Args[0]
if mem_2_2_0.Op != OpOffPtr {
break
}
tt4 := mem_2_2_0.Type
o4 := auxIntToInt64(mem_2_2_0.AuxInt)
p4 := mem_2_2_0.Args[0]
d3 := mem_2_2.Args[1]
mem_2_2_2 := mem_2_2.Args[2]
if mem_2_2_2.Op != OpStore {
break
}
t5 := auxToType(mem_2_2_2.Aux)
_ = mem_2_2_2.Args[2]
mem_2_2_2_0 := mem_2_2_2.Args[0]
if mem_2_2_2_0.Op != OpOffPtr {
break
}
tt5 := mem_2_2_2_0.Type
o5 := auxIntToInt64(mem_2_2_2_0.AuxInt)
p5 := mem_2_2_2_0.Args[0]
d4 := mem_2_2_2.Args[1]
mem_2_2_2_2 := mem_2_2_2.Args[2]
if mem_2_2_2_2.Op != OpZero || auxIntToInt64(mem_2_2_2_2.AuxInt) != n {
break
}
t6 := auxToType(mem_2_2_2_2.Aux)
p6 := mem_2_2_2_2.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && isSamePtr(p5, p6) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && t6.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && registerizable(b, t5) && n >= o2+t2.Size() && n >= o3+t3.Size() && n >= o4+t4.Size() && n >= o5+t5.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t4)
v4 := b.NewValue0(v.Pos, OpOffPtr, tt4)
v4.AuxInt = int64ToAuxInt(o4)
v4.AddArg(dst)
v5 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v5.Aux = typeToAux(t5)
v6 := b.NewValue0(v.Pos, OpOffPtr, tt5)
v6.AuxInt = int64ToAuxInt(o5)
v6.AddArg(dst)
v7 := b.NewValue0(v.Pos, OpZero, types.TypeMem)
v7.AuxInt = int64ToAuxInt(n)
v7.Aux = typeToAux(t1)
v7.AddArg2(dst, mem)
v5.AddArg3(v6, d4, v7)
v3.AddArg3(v4, d3, v5)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(VarDef (Store {t2} op2:(OffPtr <tt2> [o2] p2) d1 (Zero {t3} [n] p3 _))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && registerizable(b, t2) && n >= o2 + t2.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Zero {t1} [n] dst mem))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpVarDef {
break
}
mem_0 := mem.Args[0]
if mem_0.Op != OpStore {
break
}
t2 := auxToType(mem_0.Aux)
_ = mem_0.Args[2]
op2 := mem_0.Args[0]
if op2.Op != OpOffPtr {
break
}
tt2 := op2.Type
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d1 := mem_0.Args[1]
mem_0_2 := mem_0.Args[2]
if mem_0_2.Op != OpZero || auxIntToInt64(mem_0_2.AuxInt) != n {
break
}
t3 := auxToType(mem_0_2.Aux)
p3 := mem_0_2.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && registerizable(b, t2) && n >= o2+t2.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpZero, types.TypeMem)
v1.AuxInt = int64ToAuxInt(n)
v1.Aux = typeToAux(t1)
v1.AddArg2(dst, mem)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(VarDef (Store {t2} (OffPtr <tt2> [o2] p2) d1 (Store {t3} (OffPtr <tt3> [o3] p3) d2 (Zero {t4} [n] p4 _)))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && n >= o2 + t2.Size() && n >= o3 + t3.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Zero {t1} [n] dst mem)))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpVarDef {
break
}
mem_0 := mem.Args[0]
if mem_0.Op != OpStore {
break
}
t2 := auxToType(mem_0.Aux)
_ = mem_0.Args[2]
mem_0_0 := mem_0.Args[0]
if mem_0_0.Op != OpOffPtr {
break
}
tt2 := mem_0_0.Type
o2 := auxIntToInt64(mem_0_0.AuxInt)
p2 := mem_0_0.Args[0]
d1 := mem_0.Args[1]
mem_0_2 := mem_0.Args[2]
if mem_0_2.Op != OpStore {
break
}
t3 := auxToType(mem_0_2.Aux)
_ = mem_0_2.Args[2]
mem_0_2_0 := mem_0_2.Args[0]
if mem_0_2_0.Op != OpOffPtr {
break
}
tt3 := mem_0_2_0.Type
o3 := auxIntToInt64(mem_0_2_0.AuxInt)
p3 := mem_0_2_0.Args[0]
d2 := mem_0_2.Args[1]
mem_0_2_2 := mem_0_2.Args[2]
if mem_0_2_2.Op != OpZero || auxIntToInt64(mem_0_2_2.AuxInt) != n {
break
}
t4 := auxToType(mem_0_2_2.Aux)
p4 := mem_0_2_2.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && n >= o2+t2.Size() && n >= o3+t3.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpZero, types.TypeMem)
v3.AuxInt = int64ToAuxInt(n)
v3.Aux = typeToAux(t1)
v3.AddArg2(dst, mem)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(VarDef (Store {t2} (OffPtr <tt2> [o2] p2) d1 (Store {t3} (OffPtr <tt3> [o3] p3) d2 (Store {t4} (OffPtr <tt4> [o4] p4) d3 (Zero {t5} [n] p5 _))))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && n >= o2 + t2.Size() && n >= o3 + t3.Size() && n >= o4 + t4.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Store {t4} (OffPtr <tt4> [o4] dst) d3 (Zero {t1} [n] dst mem))))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpVarDef {
break
}
mem_0 := mem.Args[0]
if mem_0.Op != OpStore {
break
}
t2 := auxToType(mem_0.Aux)
_ = mem_0.Args[2]
mem_0_0 := mem_0.Args[0]
if mem_0_0.Op != OpOffPtr {
break
}
tt2 := mem_0_0.Type
o2 := auxIntToInt64(mem_0_0.AuxInt)
p2 := mem_0_0.Args[0]
d1 := mem_0.Args[1]
mem_0_2 := mem_0.Args[2]
if mem_0_2.Op != OpStore {
break
}
t3 := auxToType(mem_0_2.Aux)
_ = mem_0_2.Args[2]
mem_0_2_0 := mem_0_2.Args[0]
if mem_0_2_0.Op != OpOffPtr {
break
}
tt3 := mem_0_2_0.Type
o3 := auxIntToInt64(mem_0_2_0.AuxInt)
p3 := mem_0_2_0.Args[0]
d2 := mem_0_2.Args[1]
mem_0_2_2 := mem_0_2.Args[2]
if mem_0_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_0_2_2.Aux)
_ = mem_0_2_2.Args[2]
mem_0_2_2_0 := mem_0_2_2.Args[0]
if mem_0_2_2_0.Op != OpOffPtr {
break
}
tt4 := mem_0_2_2_0.Type
o4 := auxIntToInt64(mem_0_2_2_0.AuxInt)
p4 := mem_0_2_2_0.Args[0]
d3 := mem_0_2_2.Args[1]
mem_0_2_2_2 := mem_0_2_2.Args[2]
if mem_0_2_2_2.Op != OpZero || auxIntToInt64(mem_0_2_2_2.AuxInt) != n {
break
}
t5 := auxToType(mem_0_2_2_2.Aux)
p5 := mem_0_2_2_2.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && n >= o2+t2.Size() && n >= o3+t3.Size() && n >= o4+t4.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t4)
v4 := b.NewValue0(v.Pos, OpOffPtr, tt4)
v4.AuxInt = int64ToAuxInt(o4)
v4.AddArg(dst)
v5 := b.NewValue0(v.Pos, OpZero, types.TypeMem)
v5.AuxInt = int64ToAuxInt(n)
v5.Aux = typeToAux(t1)
v5.AddArg2(dst, mem)
v3.AddArg3(v4, d3, v5)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [n] dst p1 mem:(VarDef (Store {t2} (OffPtr <tt2> [o2] p2) d1 (Store {t3} (OffPtr <tt3> [o3] p3) d2 (Store {t4} (OffPtr <tt4> [o4] p4) d3 (Store {t5} (OffPtr <tt5> [o5] p5) d4 (Zero {t6} [n] p6 _)))))))
// cond: isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && isSamePtr(p5, p6) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && t6.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && registerizable(b, t5) && n >= o2 + t2.Size() && n >= o3 + t3.Size() && n >= o4 + t4.Size() && n >= o5 + t5.Size()
// result: (Store {t2} (OffPtr <tt2> [o2] dst) d1 (Store {t3} (OffPtr <tt3> [o3] dst) d2 (Store {t4} (OffPtr <tt4> [o4] dst) d3 (Store {t5} (OffPtr <tt5> [o5] dst) d4 (Zero {t1} [n] dst mem)))))
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
p1 := v_1
mem := v_2
if mem.Op != OpVarDef {
break
}
mem_0 := mem.Args[0]
if mem_0.Op != OpStore {
break
}
t2 := auxToType(mem_0.Aux)
_ = mem_0.Args[2]
mem_0_0 := mem_0.Args[0]
if mem_0_0.Op != OpOffPtr {
break
}
tt2 := mem_0_0.Type
o2 := auxIntToInt64(mem_0_0.AuxInt)
p2 := mem_0_0.Args[0]
d1 := mem_0.Args[1]
mem_0_2 := mem_0.Args[2]
if mem_0_2.Op != OpStore {
break
}
t3 := auxToType(mem_0_2.Aux)
_ = mem_0_2.Args[2]
mem_0_2_0 := mem_0_2.Args[0]
if mem_0_2_0.Op != OpOffPtr {
break
}
tt3 := mem_0_2_0.Type
o3 := auxIntToInt64(mem_0_2_0.AuxInt)
p3 := mem_0_2_0.Args[0]
d2 := mem_0_2.Args[1]
mem_0_2_2 := mem_0_2.Args[2]
if mem_0_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_0_2_2.Aux)
_ = mem_0_2_2.Args[2]
mem_0_2_2_0 := mem_0_2_2.Args[0]
if mem_0_2_2_0.Op != OpOffPtr {
break
}
tt4 := mem_0_2_2_0.Type
o4 := auxIntToInt64(mem_0_2_2_0.AuxInt)
p4 := mem_0_2_2_0.Args[0]
d3 := mem_0_2_2.Args[1]
mem_0_2_2_2 := mem_0_2_2.Args[2]
if mem_0_2_2_2.Op != OpStore {
break
}
t5 := auxToType(mem_0_2_2_2.Aux)
_ = mem_0_2_2_2.Args[2]
mem_0_2_2_2_0 := mem_0_2_2_2.Args[0]
if mem_0_2_2_2_0.Op != OpOffPtr {
break
}
tt5 := mem_0_2_2_2_0.Type
o5 := auxIntToInt64(mem_0_2_2_2_0.AuxInt)
p5 := mem_0_2_2_2_0.Args[0]
d4 := mem_0_2_2_2.Args[1]
mem_0_2_2_2_2 := mem_0_2_2_2.Args[2]
if mem_0_2_2_2_2.Op != OpZero || auxIntToInt64(mem_0_2_2_2_2.AuxInt) != n {
break
}
t6 := auxToType(mem_0_2_2_2_2.Aux)
p6 := mem_0_2_2_2_2.Args[0]
if !(isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && isSamePtr(p5, p6) && t2.Alignment() <= t1.Alignment() && t3.Alignment() <= t1.Alignment() && t4.Alignment() <= t1.Alignment() && t5.Alignment() <= t1.Alignment() && t6.Alignment() <= t1.Alignment() && registerizable(b, t2) && registerizable(b, t3) && registerizable(b, t4) && registerizable(b, t5) && n >= o2+t2.Size() && n >= o3+t3.Size() && n >= o4+t4.Size() && n >= o5+t5.Size()) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t2)
v0 := b.NewValue0(v.Pos, OpOffPtr, tt2)
v0.AuxInt = int64ToAuxInt(o2)
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpOffPtr, tt3)
v2.AuxInt = int64ToAuxInt(o3)
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t4)
v4 := b.NewValue0(v.Pos, OpOffPtr, tt4)
v4.AuxInt = int64ToAuxInt(o4)
v4.AddArg(dst)
v5 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v5.Aux = typeToAux(t5)
v6 := b.NewValue0(v.Pos, OpOffPtr, tt5)
v6.AuxInt = int64ToAuxInt(o5)
v6.AddArg(dst)
v7 := b.NewValue0(v.Pos, OpZero, types.TypeMem)
v7.AuxInt = int64ToAuxInt(n)
v7.Aux = typeToAux(t1)
v7.AddArg2(dst, mem)
v5.AddArg3(v6, d4, v7)
v3.AddArg3(v4, d3, v5)
v1.AddArg3(v2, d2, v3)
v.AddArg3(v0, d1, v1)
return true
}
// match: (Move {t1} [s] dst tmp1 midmem:(Move {t2} [s] tmp2 src _))
// cond: t1.Compare(t2) == types.CMPeq && isSamePtr(tmp1, tmp2) && isStackPtr(src) && disjoint(src, s, tmp2, s) && (disjoint(src, s, dst, s) || isInlinableMemmove(dst, src, s, config))
// result: (Move {t1} [s] dst src midmem)
for {
s := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
tmp1 := v_1
midmem := v_2
if midmem.Op != OpMove || auxIntToInt64(midmem.AuxInt) != s {
break
}
t2 := auxToType(midmem.Aux)
src := midmem.Args[1]
tmp2 := midmem.Args[0]
if !(t1.Compare(t2) == types.CMPeq && isSamePtr(tmp1, tmp2) && isStackPtr(src) && disjoint(src, s, tmp2, s) && (disjoint(src, s, dst, s) || isInlinableMemmove(dst, src, s, config))) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(s)
v.Aux = typeToAux(t1)
v.AddArg3(dst, src, midmem)
return true
}
// match: (Move {t1} [s] dst tmp1 midmem:(VarDef (Move {t2} [s] tmp2 src _)))
// cond: t1.Compare(t2) == types.CMPeq && isSamePtr(tmp1, tmp2) && isStackPtr(src) && disjoint(src, s, tmp2, s) && (disjoint(src, s, dst, s) || isInlinableMemmove(dst, src, s, config))
// result: (Move {t1} [s] dst src midmem)
for {
s := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
dst := v_0
tmp1 := v_1
midmem := v_2
if midmem.Op != OpVarDef {
break
}
midmem_0 := midmem.Args[0]
if midmem_0.Op != OpMove || auxIntToInt64(midmem_0.AuxInt) != s {
break
}
t2 := auxToType(midmem_0.Aux)
src := midmem_0.Args[1]
tmp2 := midmem_0.Args[0]
if !(t1.Compare(t2) == types.CMPeq && isSamePtr(tmp1, tmp2) && isStackPtr(src) && disjoint(src, s, tmp2, s) && (disjoint(src, s, dst, s) || isInlinableMemmove(dst, src, s, config))) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(s)
v.Aux = typeToAux(t1)
v.AddArg3(dst, src, midmem)
return true
}
// match: (Move dst src mem)
// cond: isSamePtr(dst, src)
// result: mem
for {
dst := v_0
src := v_1
mem := v_2
if !(isSamePtr(dst, src)) {
break
}
v.copyOf(mem)
return true
}
return false
}
func rewriteValuegeneric_OpMul16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Mul16 (Const16 [c]) (Const16 [d]))
// result: (Const16 [c*d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c * d)
return true
}
break
}
// match: (Mul16 (Const16 [1]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 1 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Mul16 (Const16 [-1]) x)
// result: (Neg16 x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != -1 {
continue
}
x := v_1
v.reset(OpNeg16)
v.AddArg(x)
return true
}
break
}
// match: (Mul16 <t> n (Const16 [c]))
// cond: isPowerOfTwo16(c)
// result: (Lsh16x64 <t> n (Const64 <typ.UInt64> [log16(c)]))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_1.AuxInt)
if !(isPowerOfTwo16(c)) {
continue
}
v.reset(OpLsh16x64)
v.Type = t
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log16(c))
v.AddArg2(n, v0)
return true
}
break
}
// match: (Mul16 <t> n (Const16 [c]))
// cond: t.IsSigned() && isPowerOfTwo16(-c)
// result: (Neg16 (Lsh16x64 <t> n (Const64 <typ.UInt64> [log16(-c)])))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_1.AuxInt)
if !(t.IsSigned() && isPowerOfTwo16(-c)) {
continue
}
v.reset(OpNeg16)
v0 := b.NewValue0(v.Pos, OpLsh16x64, t)
v1 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v1.AuxInt = int64ToAuxInt(log16(-c))
v0.AddArg2(n, v1)
v.AddArg(v0)
return true
}
break
}
// match: (Mul16 (Const16 [0]) _)
// result: (Const16 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
continue
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
break
}
// match: (Mul16 (Const16 <t> [c]) (Mul16 (Const16 <t> [d]) x))
// result: (Mul16 (Const16 <t> [c*d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpMul16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
continue
}
d := auxIntToInt16(v_1_0.AuxInt)
x := v_1_1
v.reset(OpMul16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c * d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpMul32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Mul32 (Const32 [c]) (Const32 [d]))
// result: (Const32 [c*d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c * d)
return true
}
break
}
// match: (Mul32 (Const32 [1]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 1 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Mul32 (Const32 [-1]) x)
// result: (Neg32 x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != -1 {
continue
}
x := v_1
v.reset(OpNeg32)
v.AddArg(x)
return true
}
break
}
// match: (Mul32 <t> n (Const32 [c]))
// cond: isPowerOfTwo32(c)
// result: (Lsh32x64 <t> n (Const64 <typ.UInt64> [log32(c)]))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1.AuxInt)
if !(isPowerOfTwo32(c)) {
continue
}
v.reset(OpLsh32x64)
v.Type = t
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log32(c))
v.AddArg2(n, v0)
return true
}
break
}
// match: (Mul32 <t> n (Const32 [c]))
// cond: t.IsSigned() && isPowerOfTwo32(-c)
// result: (Neg32 (Lsh32x64 <t> n (Const64 <typ.UInt64> [log32(-c)])))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_1.AuxInt)
if !(t.IsSigned() && isPowerOfTwo32(-c)) {
continue
}
v.reset(OpNeg32)
v0 := b.NewValue0(v.Pos, OpLsh32x64, t)
v1 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v1.AuxInt = int64ToAuxInt(log32(-c))
v0.AddArg2(n, v1)
v.AddArg(v0)
return true
}
break
}
// match: (Mul32 (Const32 <t> [c]) (Add32 <t> (Const32 <t> [d]) x))
// result: (Add32 (Const32 <t> [c*d]) (Mul32 <t> (Const32 <t> [c]) x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpAdd32 || v_1.Type != t {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c * d)
v1 := b.NewValue0(v.Pos, OpMul32, t)
v2 := b.NewValue0(v.Pos, OpConst32, t)
v2.AuxInt = int32ToAuxInt(c)
v1.AddArg2(v2, x)
v.AddArg2(v0, v1)
return true
}
}
break
}
// match: (Mul32 (Const32 [0]) _)
// result: (Const32 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
continue
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
break
}
// match: (Mul32 (Const32 <t> [c]) (Mul32 (Const32 <t> [d]) x))
// result: (Mul32 (Const32 <t> [c*d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
x := v_1_1
v.reset(OpMul32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c * d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpMul32F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Mul32F (Const32F [c]) (Const32F [d]))
// cond: c*d == c*d
// result: (Const32F [c*d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32F {
continue
}
c := auxIntToFloat32(v_0.AuxInt)
if v_1.Op != OpConst32F {
continue
}
d := auxIntToFloat32(v_1.AuxInt)
if !(c*d == c*d) {
continue
}
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(c * d)
return true
}
break
}
// match: (Mul32F x (Const32F [1]))
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpConst32F || auxIntToFloat32(v_1.AuxInt) != 1 {
continue
}
v.copyOf(x)
return true
}
break
}
// match: (Mul32F x (Const32F [-1]))
// result: (Neg32F x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpConst32F || auxIntToFloat32(v_1.AuxInt) != -1 {
continue
}
v.reset(OpNeg32F)
v.AddArg(x)
return true
}
break
}
// match: (Mul32F x (Const32F [2]))
// result: (Add32F x x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpConst32F || auxIntToFloat32(v_1.AuxInt) != 2 {
continue
}
v.reset(OpAdd32F)
v.AddArg2(x, x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpMul64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Mul64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [c*d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c * d)
return true
}
break
}
// match: (Mul64 (Const64 [1]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 1 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Mul64 (Const64 [-1]) x)
// result: (Neg64 x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != -1 {
continue
}
x := v_1
v.reset(OpNeg64)
v.AddArg(x)
return true
}
break
}
// match: (Mul64 <t> n (Const64 [c]))
// cond: isPowerOfTwo64(c)
// result: (Lsh64x64 <t> n (Const64 <typ.UInt64> [log64(c)]))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1.AuxInt)
if !(isPowerOfTwo64(c)) {
continue
}
v.reset(OpLsh64x64)
v.Type = t
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log64(c))
v.AddArg2(n, v0)
return true
}
break
}
// match: (Mul64 <t> n (Const64 [c]))
// cond: t.IsSigned() && isPowerOfTwo64(-c)
// result: (Neg64 (Lsh64x64 <t> n (Const64 <typ.UInt64> [log64(-c)])))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_1.AuxInt)
if !(t.IsSigned() && isPowerOfTwo64(-c)) {
continue
}
v.reset(OpNeg64)
v0 := b.NewValue0(v.Pos, OpLsh64x64, t)
v1 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v1.AuxInt = int64ToAuxInt(log64(-c))
v0.AddArg2(n, v1)
v.AddArg(v0)
return true
}
break
}
// match: (Mul64 (Const64 <t> [c]) (Add64 <t> (Const64 <t> [d]) x))
// result: (Add64 (Const64 <t> [c*d]) (Mul64 <t> (Const64 <t> [c]) x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpAdd64 || v_1.Type != t {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
x := v_1_1
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c * d)
v1 := b.NewValue0(v.Pos, OpMul64, t)
v2 := b.NewValue0(v.Pos, OpConst64, t)
v2.AuxInt = int64ToAuxInt(c)
v1.AddArg2(v2, x)
v.AddArg2(v0, v1)
return true
}
}
break
}
// match: (Mul64 (Const64 [0]) _)
// result: (Const64 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
continue
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
break
}
// match: (Mul64 (Const64 <t> [c]) (Mul64 (Const64 <t> [d]) x))
// result: (Mul64 (Const64 <t> [c*d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpMul64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
x := v_1_1
v.reset(OpMul64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c * d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpMul64F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Mul64F (Const64F [c]) (Const64F [d]))
// cond: c*d == c*d
// result: (Const64F [c*d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64F {
continue
}
c := auxIntToFloat64(v_0.AuxInt)
if v_1.Op != OpConst64F {
continue
}
d := auxIntToFloat64(v_1.AuxInt)
if !(c*d == c*d) {
continue
}
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(c * d)
return true
}
break
}
// match: (Mul64F x (Const64F [1]))
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpConst64F || auxIntToFloat64(v_1.AuxInt) != 1 {
continue
}
v.copyOf(x)
return true
}
break
}
// match: (Mul64F x (Const64F [-1]))
// result: (Neg64F x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpConst64F || auxIntToFloat64(v_1.AuxInt) != -1 {
continue
}
v.reset(OpNeg64F)
v.AddArg(x)
return true
}
break
}
// match: (Mul64F x (Const64F [2]))
// result: (Add64F x x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpConst64F || auxIntToFloat64(v_1.AuxInt) != 2 {
continue
}
v.reset(OpAdd64F)
v.AddArg2(x, x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpMul8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Mul8 (Const8 [c]) (Const8 [d]))
// result: (Const8 [c*d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c * d)
return true
}
break
}
// match: (Mul8 (Const8 [1]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 1 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Mul8 (Const8 [-1]) x)
// result: (Neg8 x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != -1 {
continue
}
x := v_1
v.reset(OpNeg8)
v.AddArg(x)
return true
}
break
}
// match: (Mul8 <t> n (Const8 [c]))
// cond: isPowerOfTwo8(c)
// result: (Lsh8x64 <t> n (Const64 <typ.UInt64> [log8(c)]))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_1.AuxInt)
if !(isPowerOfTwo8(c)) {
continue
}
v.reset(OpLsh8x64)
v.Type = t
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(log8(c))
v.AddArg2(n, v0)
return true
}
break
}
// match: (Mul8 <t> n (Const8 [c]))
// cond: t.IsSigned() && isPowerOfTwo8(-c)
// result: (Neg8 (Lsh8x64 <t> n (Const64 <typ.UInt64> [log8(-c)])))
for {
t := v.Type
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_1.AuxInt)
if !(t.IsSigned() && isPowerOfTwo8(-c)) {
continue
}
v.reset(OpNeg8)
v0 := b.NewValue0(v.Pos, OpLsh8x64, t)
v1 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v1.AuxInt = int64ToAuxInt(log8(-c))
v0.AddArg2(n, v1)
v.AddArg(v0)
return true
}
break
}
// match: (Mul8 (Const8 [0]) _)
// result: (Const8 [0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
continue
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
break
}
// match: (Mul8 (Const8 <t> [c]) (Mul8 (Const8 <t> [d]) x))
// result: (Mul8 (Const8 <t> [c*d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpMul8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
continue
}
d := auxIntToInt8(v_1_0.AuxInt)
x := v_1_1
v.reset(OpMul8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c * d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpNeg16(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
// match: (Neg16 (Const16 [c]))
// result: (Const16 [-c])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(-c)
return true
}
// match: (Neg16 (Sub16 x y))
// result: (Sub16 y x)
for {
if v_0.Op != OpSub16 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpSub16)
v.AddArg2(y, x)
return true
}
// match: (Neg16 (Neg16 x))
// result: x
for {
if v_0.Op != OpNeg16 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Neg16 <t> (Com16 x))
// result: (Add16 (Const16 <t> [1]) x)
for {
t := v.Type
if v_0.Op != OpCom16 {
break
}
x := v_0.Args[0]
v.reset(OpAdd16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(1)
v.AddArg2(v0, x)
return true
}
return false
}
func rewriteValuegeneric_OpNeg32(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
// match: (Neg32 (Const32 [c]))
// result: (Const32 [-c])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(-c)
return true
}
// match: (Neg32 (Sub32 x y))
// result: (Sub32 y x)
for {
if v_0.Op != OpSub32 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpSub32)
v.AddArg2(y, x)
return true
}
// match: (Neg32 (Neg32 x))
// result: x
for {
if v_0.Op != OpNeg32 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Neg32 <t> (Com32 x))
// result: (Add32 (Const32 <t> [1]) x)
for {
t := v.Type
if v_0.Op != OpCom32 {
break
}
x := v_0.Args[0]
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(1)
v.AddArg2(v0, x)
return true
}
return false
}
func rewriteValuegeneric_OpNeg32F(v *Value) bool {
v_0 := v.Args[0]
// match: (Neg32F (Const32F [c]))
// cond: c != 0
// result: (Const32F [-c])
for {
if v_0.Op != OpConst32F {
break
}
c := auxIntToFloat32(v_0.AuxInt)
if !(c != 0) {
break
}
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(-c)
return true
}
return false
}
func rewriteValuegeneric_OpNeg64(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
// match: (Neg64 (Const64 [c]))
// result: (Const64 [-c])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(-c)
return true
}
// match: (Neg64 (Sub64 x y))
// result: (Sub64 y x)
for {
if v_0.Op != OpSub64 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpSub64)
v.AddArg2(y, x)
return true
}
// match: (Neg64 (Neg64 x))
// result: x
for {
if v_0.Op != OpNeg64 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Neg64 <t> (Com64 x))
// result: (Add64 (Const64 <t> [1]) x)
for {
t := v.Type
if v_0.Op != OpCom64 {
break
}
x := v_0.Args[0]
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(1)
v.AddArg2(v0, x)
return true
}
return false
}
func rewriteValuegeneric_OpNeg64F(v *Value) bool {
v_0 := v.Args[0]
// match: (Neg64F (Const64F [c]))
// cond: c != 0
// result: (Const64F [-c])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
if !(c != 0) {
break
}
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(-c)
return true
}
return false
}
func rewriteValuegeneric_OpNeg8(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
// match: (Neg8 (Const8 [c]))
// result: (Const8 [-c])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(-c)
return true
}
// match: (Neg8 (Sub8 x y))
// result: (Sub8 y x)
for {
if v_0.Op != OpSub8 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpSub8)
v.AddArg2(y, x)
return true
}
// match: (Neg8 (Neg8 x))
// result: x
for {
if v_0.Op != OpNeg8 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Neg8 <t> (Com8 x))
// result: (Add8 (Const8 <t> [1]) x)
for {
t := v.Type
if v_0.Op != OpCom8 {
break
}
x := v_0.Args[0]
v.reset(OpAdd8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(1)
v.AddArg2(v0, x)
return true
}
return false
}
func rewriteValuegeneric_OpNeq16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Neq16 x x)
// result: (ConstBool [false])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
// match: (Neq16 (Const16 <t> [c]) (Add16 (Const16 <t> [d]) x))
// result: (Neq16 (Const16 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpAdd16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
continue
}
d := auxIntToInt16(v_1_0.AuxInt)
x := v_1_1
v.reset(OpNeq16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Neq16 (Const16 [c]) (Const16 [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
// match: (Neq16 n (Lsh16x64 (Rsh16x64 (Add16 <t> n (Rsh16Ux64 <t> (Rsh16x64 <t> n (Const64 <typ.UInt64> [15])) (Const64 <typ.UInt64> [kbar]))) (Const64 <typ.UInt64> [k])) (Const64 <typ.UInt64> [k])) )
// cond: k > 0 && k < 15 && kbar == 16 - k
// result: (Neq16 (And16 <t> n (Const16 <t> [1<<uint(k)-1])) (Const16 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpLsh16x64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpRsh16x64 {
continue
}
_ = v_1_0.Args[1]
v_1_0_0 := v_1_0.Args[0]
if v_1_0_0.Op != OpAdd16 {
continue
}
t := v_1_0_0.Type
_ = v_1_0_0.Args[1]
v_1_0_0_0 := v_1_0_0.Args[0]
v_1_0_0_1 := v_1_0_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0_0_0, v_1_0_0_1 = _i1+1, v_1_0_0_1, v_1_0_0_0 {
if n != v_1_0_0_0 || v_1_0_0_1.Op != OpRsh16Ux64 || v_1_0_0_1.Type != t {
continue
}
_ = v_1_0_0_1.Args[1]
v_1_0_0_1_0 := v_1_0_0_1.Args[0]
if v_1_0_0_1_0.Op != OpRsh16x64 || v_1_0_0_1_0.Type != t {
continue
}
_ = v_1_0_0_1_0.Args[1]
if n != v_1_0_0_1_0.Args[0] {
continue
}
v_1_0_0_1_0_1 := v_1_0_0_1_0.Args[1]
if v_1_0_0_1_0_1.Op != OpConst64 || v_1_0_0_1_0_1.Type != typ.UInt64 || auxIntToInt64(v_1_0_0_1_0_1.AuxInt) != 15 {
continue
}
v_1_0_0_1_1 := v_1_0_0_1.Args[1]
if v_1_0_0_1_1.Op != OpConst64 || v_1_0_0_1_1.Type != typ.UInt64 {
continue
}
kbar := auxIntToInt64(v_1_0_0_1_1.AuxInt)
v_1_0_1 := v_1_0.Args[1]
if v_1_0_1.Op != OpConst64 || v_1_0_1.Type != typ.UInt64 {
continue
}
k := auxIntToInt64(v_1_0_1.AuxInt)
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != typ.UInt64 || auxIntToInt64(v_1_1.AuxInt) != k || !(k > 0 && k < 15 && kbar == 16-k) {
continue
}
v.reset(OpNeq16)
v0 := b.NewValue0(v.Pos, OpAnd16, t)
v1 := b.NewValue0(v.Pos, OpConst16, t)
v1.AuxInt = int16ToAuxInt(1<<uint(k) - 1)
v0.AddArg2(n, v1)
v2 := b.NewValue0(v.Pos, OpConst16, t)
v2.AuxInt = int16ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
// match: (Neq16 s:(Sub16 x y) (Const16 [0]))
// cond: s.Uses == 1
// result: (Neq16 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
s := v_0
if s.Op != OpSub16 {
continue
}
y := s.Args[1]
x := s.Args[0]
if v_1.Op != OpConst16 || auxIntToInt16(v_1.AuxInt) != 0 || !(s.Uses == 1) {
continue
}
v.reset(OpNeq16)
v.AddArg2(x, y)
return true
}
break
}
// match: (Neq16 (And16 <t> x (Const16 <t> [y])) (Const16 <t> [y]))
// cond: oneBit16(y)
// result: (Eq16 (And16 <t> x (Const16 <t> [y])) (Const16 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd16 {
continue
}
t := v_0.Type
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst16 || v_0_1.Type != t {
continue
}
y := auxIntToInt16(v_0_1.AuxInt)
if v_1.Op != OpConst16 || v_1.Type != t || auxIntToInt16(v_1.AuxInt) != y || !(oneBit16(y)) {
continue
}
v.reset(OpEq16)
v0 := b.NewValue0(v.Pos, OpAnd16, t)
v1 := b.NewValue0(v.Pos, OpConst16, t)
v1.AuxInt = int16ToAuxInt(y)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst16, t)
v2.AuxInt = int16ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpNeq32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Neq32 x x)
// result: (ConstBool [false])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
// match: (Neq32 (Const32 <t> [c]) (Add32 (Const32 <t> [d]) x))
// result: (Neq32 (Const32 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpAdd32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
x := v_1_1
v.reset(OpNeq32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Neq32 (Const32 [c]) (Const32 [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
// match: (Neq32 n (Lsh32x64 (Rsh32x64 (Add32 <t> n (Rsh32Ux64 <t> (Rsh32x64 <t> n (Const64 <typ.UInt64> [31])) (Const64 <typ.UInt64> [kbar]))) (Const64 <typ.UInt64> [k])) (Const64 <typ.UInt64> [k])) )
// cond: k > 0 && k < 31 && kbar == 32 - k
// result: (Neq32 (And32 <t> n (Const32 <t> [1<<uint(k)-1])) (Const32 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpLsh32x64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpRsh32x64 {
continue
}
_ = v_1_0.Args[1]
v_1_0_0 := v_1_0.Args[0]
if v_1_0_0.Op != OpAdd32 {
continue
}
t := v_1_0_0.Type
_ = v_1_0_0.Args[1]
v_1_0_0_0 := v_1_0_0.Args[0]
v_1_0_0_1 := v_1_0_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0_0_0, v_1_0_0_1 = _i1+1, v_1_0_0_1, v_1_0_0_0 {
if n != v_1_0_0_0 || v_1_0_0_1.Op != OpRsh32Ux64 || v_1_0_0_1.Type != t {
continue
}
_ = v_1_0_0_1.Args[1]
v_1_0_0_1_0 := v_1_0_0_1.Args[0]
if v_1_0_0_1_0.Op != OpRsh32x64 || v_1_0_0_1_0.Type != t {
continue
}
_ = v_1_0_0_1_0.Args[1]
if n != v_1_0_0_1_0.Args[0] {
continue
}
v_1_0_0_1_0_1 := v_1_0_0_1_0.Args[1]
if v_1_0_0_1_0_1.Op != OpConst64 || v_1_0_0_1_0_1.Type != typ.UInt64 || auxIntToInt64(v_1_0_0_1_0_1.AuxInt) != 31 {
continue
}
v_1_0_0_1_1 := v_1_0_0_1.Args[1]
if v_1_0_0_1_1.Op != OpConst64 || v_1_0_0_1_1.Type != typ.UInt64 {
continue
}
kbar := auxIntToInt64(v_1_0_0_1_1.AuxInt)
v_1_0_1 := v_1_0.Args[1]
if v_1_0_1.Op != OpConst64 || v_1_0_1.Type != typ.UInt64 {
continue
}
k := auxIntToInt64(v_1_0_1.AuxInt)
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != typ.UInt64 || auxIntToInt64(v_1_1.AuxInt) != k || !(k > 0 && k < 31 && kbar == 32-k) {
continue
}
v.reset(OpNeq32)
v0 := b.NewValue0(v.Pos, OpAnd32, t)
v1 := b.NewValue0(v.Pos, OpConst32, t)
v1.AuxInt = int32ToAuxInt(1<<uint(k) - 1)
v0.AddArg2(n, v1)
v2 := b.NewValue0(v.Pos, OpConst32, t)
v2.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
// match: (Neq32 s:(Sub32 x y) (Const32 [0]))
// cond: s.Uses == 1
// result: (Neq32 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
s := v_0
if s.Op != OpSub32 {
continue
}
y := s.Args[1]
x := s.Args[0]
if v_1.Op != OpConst32 || auxIntToInt32(v_1.AuxInt) != 0 || !(s.Uses == 1) {
continue
}
v.reset(OpNeq32)
v.AddArg2(x, y)
return true
}
break
}
// match: (Neq32 (And32 <t> x (Const32 <t> [y])) (Const32 <t> [y]))
// cond: oneBit32(y)
// result: (Eq32 (And32 <t> x (Const32 <t> [y])) (Const32 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd32 {
continue
}
t := v_0.Type
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst32 || v_0_1.Type != t {
continue
}
y := auxIntToInt32(v_0_1.AuxInt)
if v_1.Op != OpConst32 || v_1.Type != t || auxIntToInt32(v_1.AuxInt) != y || !(oneBit32(y)) {
continue
}
v.reset(OpEq32)
v0 := b.NewValue0(v.Pos, OpAnd32, t)
v1 := b.NewValue0(v.Pos, OpConst32, t)
v1.AuxInt = int32ToAuxInt(y)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst32, t)
v2.AuxInt = int32ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpNeq32F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Neq32F (Const32F [c]) (Const32F [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32F {
continue
}
c := auxIntToFloat32(v_0.AuxInt)
if v_1.Op != OpConst32F {
continue
}
d := auxIntToFloat32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpNeq64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Neq64 x x)
// result: (ConstBool [false])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
// match: (Neq64 (Const64 <t> [c]) (Add64 (Const64 <t> [d]) x))
// result: (Neq64 (Const64 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpAdd64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
x := v_1_1
v.reset(OpNeq64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Neq64 (Const64 [c]) (Const64 [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
// match: (Neq64 n (Lsh64x64 (Rsh64x64 (Add64 <t> n (Rsh64Ux64 <t> (Rsh64x64 <t> n (Const64 <typ.UInt64> [63])) (Const64 <typ.UInt64> [kbar]))) (Const64 <typ.UInt64> [k])) (Const64 <typ.UInt64> [k])) )
// cond: k > 0 && k < 63 && kbar == 64 - k
// result: (Neq64 (And64 <t> n (Const64 <t> [1<<uint(k)-1])) (Const64 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpLsh64x64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpRsh64x64 {
continue
}
_ = v_1_0.Args[1]
v_1_0_0 := v_1_0.Args[0]
if v_1_0_0.Op != OpAdd64 {
continue
}
t := v_1_0_0.Type
_ = v_1_0_0.Args[1]
v_1_0_0_0 := v_1_0_0.Args[0]
v_1_0_0_1 := v_1_0_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0_0_0, v_1_0_0_1 = _i1+1, v_1_0_0_1, v_1_0_0_0 {
if n != v_1_0_0_0 || v_1_0_0_1.Op != OpRsh64Ux64 || v_1_0_0_1.Type != t {
continue
}
_ = v_1_0_0_1.Args[1]
v_1_0_0_1_0 := v_1_0_0_1.Args[0]
if v_1_0_0_1_0.Op != OpRsh64x64 || v_1_0_0_1_0.Type != t {
continue
}
_ = v_1_0_0_1_0.Args[1]
if n != v_1_0_0_1_0.Args[0] {
continue
}
v_1_0_0_1_0_1 := v_1_0_0_1_0.Args[1]
if v_1_0_0_1_0_1.Op != OpConst64 || v_1_0_0_1_0_1.Type != typ.UInt64 || auxIntToInt64(v_1_0_0_1_0_1.AuxInt) != 63 {
continue
}
v_1_0_0_1_1 := v_1_0_0_1.Args[1]
if v_1_0_0_1_1.Op != OpConst64 || v_1_0_0_1_1.Type != typ.UInt64 {
continue
}
kbar := auxIntToInt64(v_1_0_0_1_1.AuxInt)
v_1_0_1 := v_1_0.Args[1]
if v_1_0_1.Op != OpConst64 || v_1_0_1.Type != typ.UInt64 {
continue
}
k := auxIntToInt64(v_1_0_1.AuxInt)
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != typ.UInt64 || auxIntToInt64(v_1_1.AuxInt) != k || !(k > 0 && k < 63 && kbar == 64-k) {
continue
}
v.reset(OpNeq64)
v0 := b.NewValue0(v.Pos, OpAnd64, t)
v1 := b.NewValue0(v.Pos, OpConst64, t)
v1.AuxInt = int64ToAuxInt(1<<uint(k) - 1)
v0.AddArg2(n, v1)
v2 := b.NewValue0(v.Pos, OpConst64, t)
v2.AuxInt = int64ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
// match: (Neq64 s:(Sub64 x y) (Const64 [0]))
// cond: s.Uses == 1
// result: (Neq64 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
s := v_0
if s.Op != OpSub64 {
continue
}
y := s.Args[1]
x := s.Args[0]
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 || !(s.Uses == 1) {
continue
}
v.reset(OpNeq64)
v.AddArg2(x, y)
return true
}
break
}
// match: (Neq64 (And64 <t> x (Const64 <t> [y])) (Const64 <t> [y]))
// cond: oneBit64(y)
// result: (Eq64 (And64 <t> x (Const64 <t> [y])) (Const64 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd64 {
continue
}
t := v_0.Type
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst64 || v_0_1.Type != t {
continue
}
y := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 || v_1.Type != t || auxIntToInt64(v_1.AuxInt) != y || !(oneBit64(y)) {
continue
}
v.reset(OpEq64)
v0 := b.NewValue0(v.Pos, OpAnd64, t)
v1 := b.NewValue0(v.Pos, OpConst64, t)
v1.AuxInt = int64ToAuxInt(y)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst64, t)
v2.AuxInt = int64ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpNeq64F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Neq64F (Const64F [c]) (Const64F [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64F {
continue
}
c := auxIntToFloat64(v_0.AuxInt)
if v_1.Op != OpConst64F {
continue
}
d := auxIntToFloat64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpNeq8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Neq8 x x)
// result: (ConstBool [false])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
// match: (Neq8 (Const8 <t> [c]) (Add8 (Const8 <t> [d]) x))
// result: (Neq8 (Const8 <t> [c-d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpAdd8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
continue
}
d := auxIntToInt8(v_1_0.AuxInt)
x := v_1_1
v.reset(OpNeq8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Neq8 (Const8 [c]) (Const8 [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
// match: (Neq8 n (Lsh8x64 (Rsh8x64 (Add8 <t> n (Rsh8Ux64 <t> (Rsh8x64 <t> n (Const64 <typ.UInt64> [ 7])) (Const64 <typ.UInt64> [kbar]))) (Const64 <typ.UInt64> [k])) (Const64 <typ.UInt64> [k])) )
// cond: k > 0 && k < 7 && kbar == 8 - k
// result: (Neq8 (And8 <t> n (Const8 <t> [1<<uint(k)-1])) (Const8 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
n := v_0
if v_1.Op != OpLsh8x64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpRsh8x64 {
continue
}
_ = v_1_0.Args[1]
v_1_0_0 := v_1_0.Args[0]
if v_1_0_0.Op != OpAdd8 {
continue
}
t := v_1_0_0.Type
_ = v_1_0_0.Args[1]
v_1_0_0_0 := v_1_0_0.Args[0]
v_1_0_0_1 := v_1_0_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0_0_0, v_1_0_0_1 = _i1+1, v_1_0_0_1, v_1_0_0_0 {
if n != v_1_0_0_0 || v_1_0_0_1.Op != OpRsh8Ux64 || v_1_0_0_1.Type != t {
continue
}
_ = v_1_0_0_1.Args[1]
v_1_0_0_1_0 := v_1_0_0_1.Args[0]
if v_1_0_0_1_0.Op != OpRsh8x64 || v_1_0_0_1_0.Type != t {
continue
}
_ = v_1_0_0_1_0.Args[1]
if n != v_1_0_0_1_0.Args[0] {
continue
}
v_1_0_0_1_0_1 := v_1_0_0_1_0.Args[1]
if v_1_0_0_1_0_1.Op != OpConst64 || v_1_0_0_1_0_1.Type != typ.UInt64 || auxIntToInt64(v_1_0_0_1_0_1.AuxInt) != 7 {
continue
}
v_1_0_0_1_1 := v_1_0_0_1.Args[1]
if v_1_0_0_1_1.Op != OpConst64 || v_1_0_0_1_1.Type != typ.UInt64 {
continue
}
kbar := auxIntToInt64(v_1_0_0_1_1.AuxInt)
v_1_0_1 := v_1_0.Args[1]
if v_1_0_1.Op != OpConst64 || v_1_0_1.Type != typ.UInt64 {
continue
}
k := auxIntToInt64(v_1_0_1.AuxInt)
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != typ.UInt64 || auxIntToInt64(v_1_1.AuxInt) != k || !(k > 0 && k < 7 && kbar == 8-k) {
continue
}
v.reset(OpNeq8)
v0 := b.NewValue0(v.Pos, OpAnd8, t)
v1 := b.NewValue0(v.Pos, OpConst8, t)
v1.AuxInt = int8ToAuxInt(1<<uint(k) - 1)
v0.AddArg2(n, v1)
v2 := b.NewValue0(v.Pos, OpConst8, t)
v2.AuxInt = int8ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
// match: (Neq8 s:(Sub8 x y) (Const8 [0]))
// cond: s.Uses == 1
// result: (Neq8 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
s := v_0
if s.Op != OpSub8 {
continue
}
y := s.Args[1]
x := s.Args[0]
if v_1.Op != OpConst8 || auxIntToInt8(v_1.AuxInt) != 0 || !(s.Uses == 1) {
continue
}
v.reset(OpNeq8)
v.AddArg2(x, y)
return true
}
break
}
// match: (Neq8 (And8 <t> x (Const8 <t> [y])) (Const8 <t> [y]))
// cond: oneBit8(y)
// result: (Eq8 (And8 <t> x (Const8 <t> [y])) (Const8 <t> [0]))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd8 {
continue
}
t := v_0.Type
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst8 || v_0_1.Type != t {
continue
}
y := auxIntToInt8(v_0_1.AuxInt)
if v_1.Op != OpConst8 || v_1.Type != t || auxIntToInt8(v_1.AuxInt) != y || !(oneBit8(y)) {
continue
}
v.reset(OpEq8)
v0 := b.NewValue0(v.Pos, OpAnd8, t)
v1 := b.NewValue0(v.Pos, OpConst8, t)
v1.AuxInt = int8ToAuxInt(y)
v0.AddArg2(x, v1)
v2 := b.NewValue0(v.Pos, OpConst8, t)
v2.AuxInt = int8ToAuxInt(0)
v.AddArg2(v0, v2)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpNeqB(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (NeqB (ConstBool [c]) (ConstBool [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConstBool {
continue
}
c := auxIntToBool(v_0.AuxInt)
if v_1.Op != OpConstBool {
continue
}
d := auxIntToBool(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
// match: (NeqB (ConstBool [false]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConstBool || auxIntToBool(v_0.AuxInt) != false {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (NeqB (ConstBool [true]) x)
// result: (Not x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConstBool || auxIntToBool(v_0.AuxInt) != true {
continue
}
x := v_1
v.reset(OpNot)
v.AddArg(x)
return true
}
break
}
// match: (NeqB (Not x) (Not y))
// result: (NeqB x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpNot {
continue
}
x := v_0.Args[0]
if v_1.Op != OpNot {
continue
}
y := v_1.Args[0]
v.reset(OpNeqB)
v.AddArg2(x, y)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpNeqInter(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (NeqInter x y)
// result: (NeqPtr (ITab x) (ITab y))
for {
x := v_0
y := v_1
v.reset(OpNeqPtr)
v0 := b.NewValue0(v.Pos, OpITab, typ.Uintptr)
v0.AddArg(x)
v1 := b.NewValue0(v.Pos, OpITab, typ.Uintptr)
v1.AddArg(y)
v.AddArg2(v0, v1)
return true
}
}
func rewriteValuegeneric_OpNeqPtr(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (NeqPtr x x)
// result: (ConstBool [false])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(false)
return true
}
// match: (NeqPtr (Addr {a} _) (Addr {b} _))
// result: (ConstBool [a != b])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAddr {
continue
}
a := auxToSym(v_0.Aux)
if v_1.Op != OpAddr {
continue
}
b := auxToSym(v_1.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a != b)
return true
}
break
}
// match: (NeqPtr (Addr {a} _) (OffPtr [o] (Addr {b} _)))
// result: (ConstBool [a != b || o != 0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAddr {
continue
}
a := auxToSym(v_0.Aux)
if v_1.Op != OpOffPtr {
continue
}
o := auxIntToInt64(v_1.AuxInt)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpAddr {
continue
}
b := auxToSym(v_1_0.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a != b || o != 0)
return true
}
break
}
// match: (NeqPtr (OffPtr [o1] (Addr {a} _)) (OffPtr [o2] (Addr {b} _)))
// result: (ConstBool [a != b || o1 != o2])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
o1 := auxIntToInt64(v_0.AuxInt)
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAddr {
continue
}
a := auxToSym(v_0_0.Aux)
if v_1.Op != OpOffPtr {
continue
}
o2 := auxIntToInt64(v_1.AuxInt)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpAddr {
continue
}
b := auxToSym(v_1_0.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a != b || o1 != o2)
return true
}
break
}
// match: (NeqPtr (LocalAddr {a} _ _) (LocalAddr {b} _ _))
// result: (ConstBool [a != b])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLocalAddr {
continue
}
a := auxToSym(v_0.Aux)
if v_1.Op != OpLocalAddr {
continue
}
b := auxToSym(v_1.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a != b)
return true
}
break
}
// match: (NeqPtr (LocalAddr {a} _ _) (OffPtr [o] (LocalAddr {b} _ _)))
// result: (ConstBool [a != b || o != 0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLocalAddr {
continue
}
a := auxToSym(v_0.Aux)
if v_1.Op != OpOffPtr {
continue
}
o := auxIntToInt64(v_1.AuxInt)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpLocalAddr {
continue
}
b := auxToSym(v_1_0.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a != b || o != 0)
return true
}
break
}
// match: (NeqPtr (OffPtr [o1] (LocalAddr {a} _ _)) (OffPtr [o2] (LocalAddr {b} _ _)))
// result: (ConstBool [a != b || o1 != o2])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
o1 := auxIntToInt64(v_0.AuxInt)
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLocalAddr {
continue
}
a := auxToSym(v_0_0.Aux)
if v_1.Op != OpOffPtr {
continue
}
o2 := auxIntToInt64(v_1.AuxInt)
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpLocalAddr {
continue
}
b := auxToSym(v_1_0.Aux)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(a != b || o1 != o2)
return true
}
break
}
// match: (NeqPtr (OffPtr [o1] p1) p2)
// cond: isSamePtr(p1, p2)
// result: (ConstBool [o1 != 0])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
o1 := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
p2 := v_1
if !(isSamePtr(p1, p2)) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(o1 != 0)
return true
}
break
}
// match: (NeqPtr (OffPtr [o1] p1) (OffPtr [o2] p2))
// cond: isSamePtr(p1, p2)
// result: (ConstBool [o1 != o2])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
o1 := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
if v_1.Op != OpOffPtr {
continue
}
o2 := auxIntToInt64(v_1.AuxInt)
p2 := v_1.Args[0]
if !(isSamePtr(p1, p2)) {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(o1 != o2)
return true
}
break
}
// match: (NeqPtr (Const32 [c]) (Const32 [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
// match: (NeqPtr (Const64 [c]) (Const64 [d]))
// result: (ConstBool [c != d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(c != d)
return true
}
break
}
// match: (NeqPtr (LocalAddr _ _) (Addr _))
// result: (ConstBool [true])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLocalAddr || v_1.Op != OpAddr {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (NeqPtr (OffPtr (LocalAddr _ _)) (Addr _))
// result: (ConstBool [true])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLocalAddr || v_1.Op != OpAddr {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (NeqPtr (LocalAddr _ _) (OffPtr (Addr _)))
// result: (ConstBool [true])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLocalAddr || v_1.Op != OpOffPtr {
continue
}
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpAddr {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (NeqPtr (OffPtr (LocalAddr _ _)) (OffPtr (Addr _)))
// result: (ConstBool [true])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOffPtr {
continue
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLocalAddr || v_1.Op != OpOffPtr {
continue
}
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpAddr {
continue
}
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(true)
return true
}
break
}
// match: (NeqPtr (AddPtr p1 o1) p2)
// cond: isSamePtr(p1, p2)
// result: (IsNonNil o1)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAddPtr {
continue
}
o1 := v_0.Args[1]
p1 := v_0.Args[0]
p2 := v_1
if !(isSamePtr(p1, p2)) {
continue
}
v.reset(OpIsNonNil)
v.AddArg(o1)
return true
}
break
}
// match: (NeqPtr (Const32 [0]) p)
// result: (IsNonNil p)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
continue
}
p := v_1
v.reset(OpIsNonNil)
v.AddArg(p)
return true
}
break
}
// match: (NeqPtr (Const64 [0]) p)
// result: (IsNonNil p)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
continue
}
p := v_1
v.reset(OpIsNonNil)
v.AddArg(p)
return true
}
break
}
// match: (NeqPtr (ConstNil) p)
// result: (IsNonNil p)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConstNil {
continue
}
p := v_1
v.reset(OpIsNonNil)
v.AddArg(p)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpNeqSlice(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (NeqSlice x y)
// result: (NeqPtr (SlicePtr x) (SlicePtr y))
for {
x := v_0
y := v_1
v.reset(OpNeqPtr)
v0 := b.NewValue0(v.Pos, OpSlicePtr, typ.BytePtr)
v0.AddArg(x)
v1 := b.NewValue0(v.Pos, OpSlicePtr, typ.BytePtr)
v1.AddArg(y)
v.AddArg2(v0, v1)
return true
}
}
func rewriteValuegeneric_OpNilCheck(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
fe := b.Func.fe
// match: (NilCheck (GetG mem) mem)
// result: mem
for {
if v_0.Op != OpGetG {
break
}
mem := v_0.Args[0]
if mem != v_1 {
break
}
v.copyOf(mem)
return true
}
// match: (NilCheck (Load (OffPtr [c] (SP)) (StaticCall {sym} _)) _)
// cond: symNamed(sym, "runtime.newobject") && c == config.ctxt.FixedFrameSize() + config.RegSize && warnRule(fe.Debug_checknil(), v, "removed nil check")
// result: (Invalid)
for {
if v_0.Op != OpLoad {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpOffPtr {
break
}
c := auxIntToInt64(v_0_0.AuxInt)
v_0_0_0 := v_0_0.Args[0]
if v_0_0_0.Op != OpSP {
break
}
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpStaticCall {
break
}
sym := auxToSym(v_0_1.Aux)
if !(symNamed(sym, "runtime.newobject") && c == config.ctxt.FixedFrameSize()+config.RegSize && warnRule(fe.Debug_checknil(), v, "removed nil check")) {
break
}
v.reset(OpInvalid)
return true
}
// match: (NilCheck (OffPtr (Load (OffPtr [c] (SP)) (StaticCall {sym} _))) _)
// cond: symNamed(sym, "runtime.newobject") && c == config.ctxt.FixedFrameSize() + config.RegSize && warnRule(fe.Debug_checknil(), v, "removed nil check")
// result: (Invalid)
for {
if v_0.Op != OpOffPtr {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLoad {
break
}
_ = v_0_0.Args[1]
v_0_0_0 := v_0_0.Args[0]
if v_0_0_0.Op != OpOffPtr {
break
}
c := auxIntToInt64(v_0_0_0.AuxInt)
v_0_0_0_0 := v_0_0_0.Args[0]
if v_0_0_0_0.Op != OpSP {
break
}
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpStaticCall {
break
}
sym := auxToSym(v_0_0_1.Aux)
if !(symNamed(sym, "runtime.newobject") && c == config.ctxt.FixedFrameSize()+config.RegSize && warnRule(fe.Debug_checknil(), v, "removed nil check")) {
break
}
v.reset(OpInvalid)
return true
}
return false
}
func rewriteValuegeneric_OpNot(v *Value) bool {
v_0 := v.Args[0]
// match: (Not (ConstBool [c]))
// result: (ConstBool [!c])
for {
if v_0.Op != OpConstBool {
break
}
c := auxIntToBool(v_0.AuxInt)
v.reset(OpConstBool)
v.AuxInt = boolToAuxInt(!c)
return true
}
// match: (Not (Eq64 x y))
// result: (Neq64 x y)
for {
if v_0.Op != OpEq64 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpNeq64)
v.AddArg2(x, y)
return true
}
// match: (Not (Eq32 x y))
// result: (Neq32 x y)
for {
if v_0.Op != OpEq32 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpNeq32)
v.AddArg2(x, y)
return true
}
// match: (Not (Eq16 x y))
// result: (Neq16 x y)
for {
if v_0.Op != OpEq16 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpNeq16)
v.AddArg2(x, y)
return true
}
// match: (Not (Eq8 x y))
// result: (Neq8 x y)
for {
if v_0.Op != OpEq8 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpNeq8)
v.AddArg2(x, y)
return true
}
// match: (Not (EqB x y))
// result: (NeqB x y)
for {
if v_0.Op != OpEqB {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpNeqB)
v.AddArg2(x, y)
return true
}
// match: (Not (EqPtr x y))
// result: (NeqPtr x y)
for {
if v_0.Op != OpEqPtr {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpNeqPtr)
v.AddArg2(x, y)
return true
}
// match: (Not (Eq64F x y))
// result: (Neq64F x y)
for {
if v_0.Op != OpEq64F {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpNeq64F)
v.AddArg2(x, y)
return true
}
// match: (Not (Eq32F x y))
// result: (Neq32F x y)
for {
if v_0.Op != OpEq32F {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpNeq32F)
v.AddArg2(x, y)
return true
}
// match: (Not (Neq64 x y))
// result: (Eq64 x y)
for {
if v_0.Op != OpNeq64 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpEq64)
v.AddArg2(x, y)
return true
}
// match: (Not (Neq32 x y))
// result: (Eq32 x y)
for {
if v_0.Op != OpNeq32 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpEq32)
v.AddArg2(x, y)
return true
}
// match: (Not (Neq16 x y))
// result: (Eq16 x y)
for {
if v_0.Op != OpNeq16 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpEq16)
v.AddArg2(x, y)
return true
}
// match: (Not (Neq8 x y))
// result: (Eq8 x y)
for {
if v_0.Op != OpNeq8 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpEq8)
v.AddArg2(x, y)
return true
}
// match: (Not (NeqB x y))
// result: (EqB x y)
for {
if v_0.Op != OpNeqB {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpEqB)
v.AddArg2(x, y)
return true
}
// match: (Not (NeqPtr x y))
// result: (EqPtr x y)
for {
if v_0.Op != OpNeqPtr {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpEqPtr)
v.AddArg2(x, y)
return true
}
// match: (Not (Neq64F x y))
// result: (Eq64F x y)
for {
if v_0.Op != OpNeq64F {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpEq64F)
v.AddArg2(x, y)
return true
}
// match: (Not (Neq32F x y))
// result: (Eq32F x y)
for {
if v_0.Op != OpNeq32F {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpEq32F)
v.AddArg2(x, y)
return true
}
// match: (Not (Less64 x y))
// result: (Leq64 y x)
for {
if v_0.Op != OpLess64 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLeq64)
v.AddArg2(y, x)
return true
}
// match: (Not (Less32 x y))
// result: (Leq32 y x)
for {
if v_0.Op != OpLess32 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLeq32)
v.AddArg2(y, x)
return true
}
// match: (Not (Less16 x y))
// result: (Leq16 y x)
for {
if v_0.Op != OpLess16 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLeq16)
v.AddArg2(y, x)
return true
}
// match: (Not (Less8 x y))
// result: (Leq8 y x)
for {
if v_0.Op != OpLess8 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLeq8)
v.AddArg2(y, x)
return true
}
// match: (Not (Less64U x y))
// result: (Leq64U y x)
for {
if v_0.Op != OpLess64U {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLeq64U)
v.AddArg2(y, x)
return true
}
// match: (Not (Less32U x y))
// result: (Leq32U y x)
for {
if v_0.Op != OpLess32U {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLeq32U)
v.AddArg2(y, x)
return true
}
// match: (Not (Less16U x y))
// result: (Leq16U y x)
for {
if v_0.Op != OpLess16U {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLeq16U)
v.AddArg2(y, x)
return true
}
// match: (Not (Less8U x y))
// result: (Leq8U y x)
for {
if v_0.Op != OpLess8U {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLeq8U)
v.AddArg2(y, x)
return true
}
// match: (Not (Leq64 x y))
// result: (Less64 y x)
for {
if v_0.Op != OpLeq64 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLess64)
v.AddArg2(y, x)
return true
}
// match: (Not (Leq32 x y))
// result: (Less32 y x)
for {
if v_0.Op != OpLeq32 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLess32)
v.AddArg2(y, x)
return true
}
// match: (Not (Leq16 x y))
// result: (Less16 y x)
for {
if v_0.Op != OpLeq16 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLess16)
v.AddArg2(y, x)
return true
}
// match: (Not (Leq8 x y))
// result: (Less8 y x)
for {
if v_0.Op != OpLeq8 {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLess8)
v.AddArg2(y, x)
return true
}
// match: (Not (Leq64U x y))
// result: (Less64U y x)
for {
if v_0.Op != OpLeq64U {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLess64U)
v.AddArg2(y, x)
return true
}
// match: (Not (Leq32U x y))
// result: (Less32U y x)
for {
if v_0.Op != OpLeq32U {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLess32U)
v.AddArg2(y, x)
return true
}
// match: (Not (Leq16U x y))
// result: (Less16U y x)
for {
if v_0.Op != OpLeq16U {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLess16U)
v.AddArg2(y, x)
return true
}
// match: (Not (Leq8U x y))
// result: (Less8U y x)
for {
if v_0.Op != OpLeq8U {
break
}
y := v_0.Args[1]
x := v_0.Args[0]
v.reset(OpLess8U)
v.AddArg2(y, x)
return true
}
return false
}
func rewriteValuegeneric_OpOffPtr(v *Value) bool {
v_0 := v.Args[0]
// match: (OffPtr (OffPtr p [b]) [a])
// result: (OffPtr p [a+b])
for {
a := auxIntToInt64(v.AuxInt)
if v_0.Op != OpOffPtr {
break
}
b := auxIntToInt64(v_0.AuxInt)
p := v_0.Args[0]
v.reset(OpOffPtr)
v.AuxInt = int64ToAuxInt(a + b)
v.AddArg(p)
return true
}
// match: (OffPtr p [0])
// cond: v.Type.Compare(p.Type) == types.CMPeq
// result: p
for {
if auxIntToInt64(v.AuxInt) != 0 {
break
}
p := v_0
if !(v.Type.Compare(p.Type) == types.CMPeq) {
break
}
v.copyOf(p)
return true
}
return false
}
func rewriteValuegeneric_OpOr16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Or16 (Const16 [c]) (Const16 [d]))
// result: (Const16 [c|d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c | d)
return true
}
break
}
// match: (Or16 x x)
// result: x
for {
x := v_0
if x != v_1 {
break
}
v.copyOf(x)
return true
}
// match: (Or16 (Const16 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Or16 (Const16 [-1]) _)
// result: (Const16 [-1])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != -1 {
continue
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(-1)
return true
}
break
}
// match: (Or16 x (Or16 x y))
// result: (Or16 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpOr16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.reset(OpOr16)
v.AddArg2(x, y)
return true
}
}
break
}
// match: (Or16 (And16 x (Const16 [c2])) (Const16 <t> [c1]))
// cond: ^(c1 | c2) == 0
// result: (Or16 (Const16 <t> [c1]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd16 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst16 {
continue
}
c2 := auxIntToInt16(v_0_1.AuxInt)
if v_1.Op != OpConst16 {
continue
}
t := v_1.Type
c1 := auxIntToInt16(v_1.AuxInt)
if !(^(c1 | c2) == 0) {
continue
}
v.reset(OpOr16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c1)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Or16 (Or16 i:(Const16 <t>) z) x)
// cond: (z.Op != OpConst16 && x.Op != OpConst16)
// result: (Or16 i (Or16 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOr16 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst16 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst16 && x.Op != OpConst16) {
continue
}
v.reset(OpOr16)
v0 := b.NewValue0(v.Pos, OpOr16, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Or16 (Const16 <t> [c]) (Or16 (Const16 <t> [d]) x))
// result: (Or16 (Const16 <t> [c|d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpOr16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
continue
}
d := auxIntToInt16(v_1_0.AuxInt)
x := v_1_1
v.reset(OpOr16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c | d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpOr32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Or32 (Const32 [c]) (Const32 [d]))
// result: (Const32 [c|d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c | d)
return true
}
break
}
// match: (Or32 x x)
// result: x
for {
x := v_0
if x != v_1 {
break
}
v.copyOf(x)
return true
}
// match: (Or32 (Const32 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Or32 (Const32 [-1]) _)
// result: (Const32 [-1])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != -1 {
continue
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(-1)
return true
}
break
}
// match: (Or32 x (Or32 x y))
// result: (Or32 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpOr32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.reset(OpOr32)
v.AddArg2(x, y)
return true
}
}
break
}
// match: (Or32 (And32 x (Const32 [c2])) (Const32 <t> [c1]))
// cond: ^(c1 | c2) == 0
// result: (Or32 (Const32 <t> [c1]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd32 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst32 {
continue
}
c2 := auxIntToInt32(v_0_1.AuxInt)
if v_1.Op != OpConst32 {
continue
}
t := v_1.Type
c1 := auxIntToInt32(v_1.AuxInt)
if !(^(c1 | c2) == 0) {
continue
}
v.reset(OpOr32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c1)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Or32 (Or32 i:(Const32 <t>) z) x)
// cond: (z.Op != OpConst32 && x.Op != OpConst32)
// result: (Or32 i (Or32 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOr32 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst32 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst32 && x.Op != OpConst32) {
continue
}
v.reset(OpOr32)
v0 := b.NewValue0(v.Pos, OpOr32, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Or32 (Const32 <t> [c]) (Or32 (Const32 <t> [d]) x))
// result: (Or32 (Const32 <t> [c|d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpOr32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
x := v_1_1
v.reset(OpOr32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c | d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpOr64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Or64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [c|d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c | d)
return true
}
break
}
// match: (Or64 x x)
// result: x
for {
x := v_0
if x != v_1 {
break
}
v.copyOf(x)
return true
}
// match: (Or64 (Const64 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Or64 (Const64 [-1]) _)
// result: (Const64 [-1])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != -1 {
continue
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(-1)
return true
}
break
}
// match: (Or64 x (Or64 x y))
// result: (Or64 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpOr64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.reset(OpOr64)
v.AddArg2(x, y)
return true
}
}
break
}
// match: (Or64 (And64 x (Const64 [c2])) (Const64 <t> [c1]))
// cond: ^(c1 | c2) == 0
// result: (Or64 (Const64 <t> [c1]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd64 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst64 {
continue
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
continue
}
t := v_1.Type
c1 := auxIntToInt64(v_1.AuxInt)
if !(^(c1 | c2) == 0) {
continue
}
v.reset(OpOr64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c1)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Or64 (Or64 i:(Const64 <t>) z) x)
// cond: (z.Op != OpConst64 && x.Op != OpConst64)
// result: (Or64 i (Or64 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOr64 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst64 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst64 && x.Op != OpConst64) {
continue
}
v.reset(OpOr64)
v0 := b.NewValue0(v.Pos, OpOr64, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Or64 (Const64 <t> [c]) (Or64 (Const64 <t> [d]) x))
// result: (Or64 (Const64 <t> [c|d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpOr64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
x := v_1_1
v.reset(OpOr64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c | d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpOr8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Or8 (Const8 [c]) (Const8 [d]))
// result: (Const8 [c|d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c | d)
return true
}
break
}
// match: (Or8 x x)
// result: x
for {
x := v_0
if x != v_1 {
break
}
v.copyOf(x)
return true
}
// match: (Or8 (Const8 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Or8 (Const8 [-1]) _)
// result: (Const8 [-1])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != -1 {
continue
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(-1)
return true
}
break
}
// match: (Or8 x (Or8 x y))
// result: (Or8 x y)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpOr8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.reset(OpOr8)
v.AddArg2(x, y)
return true
}
}
break
}
// match: (Or8 (And8 x (Const8 [c2])) (Const8 <t> [c1]))
// cond: ^(c1 | c2) == 0
// result: (Or8 (Const8 <t> [c1]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpAnd8 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
x := v_0_0
if v_0_1.Op != OpConst8 {
continue
}
c2 := auxIntToInt8(v_0_1.AuxInt)
if v_1.Op != OpConst8 {
continue
}
t := v_1.Type
c1 := auxIntToInt8(v_1.AuxInt)
if !(^(c1 | c2) == 0) {
continue
}
v.reset(OpOr8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c1)
v.AddArg2(v0, x)
return true
}
}
break
}
// match: (Or8 (Or8 i:(Const8 <t>) z) x)
// cond: (z.Op != OpConst8 && x.Op != OpConst8)
// result: (Or8 i (Or8 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpOr8 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst8 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst8 && x.Op != OpConst8) {
continue
}
v.reset(OpOr8)
v0 := b.NewValue0(v.Pos, OpOr8, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Or8 (Const8 <t> [c]) (Or8 (Const8 <t> [d]) x))
// result: (Or8 (Const8 <t> [c|d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpOr8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
continue
}
d := auxIntToInt8(v_1_0.AuxInt)
x := v_1_1
v.reset(OpOr8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c | d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpOrB(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (OrB (Less64 (Const64 [c]) x) (Less64 x (Const64 [d])))
// cond: c >= d
// result: (Less64U (Const64 <x.Type> [c-d]) (Sub64 <x.Type> x (Const64 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess64 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLess64 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(c >= d) {
continue
}
v.reset(OpLess64U)
v0 := b.NewValue0(v.Pos, OpConst64, x.Type)
v0.AuxInt = int64ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub64, x.Type)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq64 (Const64 [c]) x) (Less64 x (Const64 [d])))
// cond: c >= d
// result: (Leq64U (Const64 <x.Type> [c-d]) (Sub64 <x.Type> x (Const64 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq64 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLess64 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(c >= d) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpConst64, x.Type)
v0.AuxInt = int64ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub64, x.Type)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less32 (Const32 [c]) x) (Less32 x (Const32 [d])))
// cond: c >= d
// result: (Less32U (Const32 <x.Type> [c-d]) (Sub32 <x.Type> x (Const32 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess32 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLess32 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(c >= d) {
continue
}
v.reset(OpLess32U)
v0 := b.NewValue0(v.Pos, OpConst32, x.Type)
v0.AuxInt = int32ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub32, x.Type)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq32 (Const32 [c]) x) (Less32 x (Const32 [d])))
// cond: c >= d
// result: (Leq32U (Const32 <x.Type> [c-d]) (Sub32 <x.Type> x (Const32 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq32 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLess32 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(c >= d) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpConst32, x.Type)
v0.AuxInt = int32ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub32, x.Type)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less16 (Const16 [c]) x) (Less16 x (Const16 [d])))
// cond: c >= d
// result: (Less16U (Const16 <x.Type> [c-d]) (Sub16 <x.Type> x (Const16 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess16 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLess16 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(c >= d) {
continue
}
v.reset(OpLess16U)
v0 := b.NewValue0(v.Pos, OpConst16, x.Type)
v0.AuxInt = int16ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub16, x.Type)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq16 (Const16 [c]) x) (Less16 x (Const16 [d])))
// cond: c >= d
// result: (Leq16U (Const16 <x.Type> [c-d]) (Sub16 <x.Type> x (Const16 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq16 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLess16 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(c >= d) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpConst16, x.Type)
v0.AuxInt = int16ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub16, x.Type)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less8 (Const8 [c]) x) (Less8 x (Const8 [d])))
// cond: c >= d
// result: (Less8U (Const8 <x.Type> [c-d]) (Sub8 <x.Type> x (Const8 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess8 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLess8 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(c >= d) {
continue
}
v.reset(OpLess8U)
v0 := b.NewValue0(v.Pos, OpConst8, x.Type)
v0.AuxInt = int8ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub8, x.Type)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq8 (Const8 [c]) x) (Less8 x (Const8 [d])))
// cond: c >= d
// result: (Leq8U (Const8 <x.Type> [c-d]) (Sub8 <x.Type> x (Const8 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq8 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLess8 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(c >= d) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpConst8, x.Type)
v0.AuxInt = int8ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub8, x.Type)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less64 (Const64 [c]) x) (Leq64 x (Const64 [d])))
// cond: c >= d+1 && d+1 > d
// result: (Less64U (Const64 <x.Type> [c-d-1]) (Sub64 <x.Type> x (Const64 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess64 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLeq64 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(c >= d+1 && d+1 > d) {
continue
}
v.reset(OpLess64U)
v0 := b.NewValue0(v.Pos, OpConst64, x.Type)
v0.AuxInt = int64ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub64, x.Type)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq64 (Const64 [c]) x) (Leq64 x (Const64 [d])))
// cond: c >= d+1 && d+1 > d
// result: (Leq64U (Const64 <x.Type> [c-d-1]) (Sub64 <x.Type> x (Const64 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq64 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLeq64 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(c >= d+1 && d+1 > d) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpConst64, x.Type)
v0.AuxInt = int64ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub64, x.Type)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less32 (Const32 [c]) x) (Leq32 x (Const32 [d])))
// cond: c >= d+1 && d+1 > d
// result: (Less32U (Const32 <x.Type> [c-d-1]) (Sub32 <x.Type> x (Const32 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess32 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLeq32 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(c >= d+1 && d+1 > d) {
continue
}
v.reset(OpLess32U)
v0 := b.NewValue0(v.Pos, OpConst32, x.Type)
v0.AuxInt = int32ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub32, x.Type)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq32 (Const32 [c]) x) (Leq32 x (Const32 [d])))
// cond: c >= d+1 && d+1 > d
// result: (Leq32U (Const32 <x.Type> [c-d-1]) (Sub32 <x.Type> x (Const32 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq32 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLeq32 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(c >= d+1 && d+1 > d) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpConst32, x.Type)
v0.AuxInt = int32ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub32, x.Type)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less16 (Const16 [c]) x) (Leq16 x (Const16 [d])))
// cond: c >= d+1 && d+1 > d
// result: (Less16U (Const16 <x.Type> [c-d-1]) (Sub16 <x.Type> x (Const16 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess16 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLeq16 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(c >= d+1 && d+1 > d) {
continue
}
v.reset(OpLess16U)
v0 := b.NewValue0(v.Pos, OpConst16, x.Type)
v0.AuxInt = int16ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub16, x.Type)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq16 (Const16 [c]) x) (Leq16 x (Const16 [d])))
// cond: c >= d+1 && d+1 > d
// result: (Leq16U (Const16 <x.Type> [c-d-1]) (Sub16 <x.Type> x (Const16 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq16 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLeq16 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(c >= d+1 && d+1 > d) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpConst16, x.Type)
v0.AuxInt = int16ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub16, x.Type)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less8 (Const8 [c]) x) (Leq8 x (Const8 [d])))
// cond: c >= d+1 && d+1 > d
// result: (Less8U (Const8 <x.Type> [c-d-1]) (Sub8 <x.Type> x (Const8 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess8 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLeq8 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(c >= d+1 && d+1 > d) {
continue
}
v.reset(OpLess8U)
v0 := b.NewValue0(v.Pos, OpConst8, x.Type)
v0.AuxInt = int8ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub8, x.Type)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq8 (Const8 [c]) x) (Leq8 x (Const8 [d])))
// cond: c >= d+1 && d+1 > d
// result: (Leq8U (Const8 <x.Type> [c-d-1]) (Sub8 <x.Type> x (Const8 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq8 {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLeq8 {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(c >= d+1 && d+1 > d) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpConst8, x.Type)
v0.AuxInt = int8ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub8, x.Type)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less64U (Const64 [c]) x) (Less64U x (Const64 [d])))
// cond: uint64(c) >= uint64(d)
// result: (Less64U (Const64 <x.Type> [c-d]) (Sub64 <x.Type> x (Const64 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess64U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLess64U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(uint64(c) >= uint64(d)) {
continue
}
v.reset(OpLess64U)
v0 := b.NewValue0(v.Pos, OpConst64, x.Type)
v0.AuxInt = int64ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub64, x.Type)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq64U (Const64 [c]) x) (Less64U x (Const64 [d])))
// cond: uint64(c) >= uint64(d)
// result: (Leq64U (Const64 <x.Type> [c-d]) (Sub64 <x.Type> x (Const64 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq64U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLess64U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(uint64(c) >= uint64(d)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpConst64, x.Type)
v0.AuxInt = int64ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub64, x.Type)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less32U (Const32 [c]) x) (Less32U x (Const32 [d])))
// cond: uint32(c) >= uint32(d)
// result: (Less32U (Const32 <x.Type> [c-d]) (Sub32 <x.Type> x (Const32 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess32U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLess32U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(uint32(c) >= uint32(d)) {
continue
}
v.reset(OpLess32U)
v0 := b.NewValue0(v.Pos, OpConst32, x.Type)
v0.AuxInt = int32ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub32, x.Type)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq32U (Const32 [c]) x) (Less32U x (Const32 [d])))
// cond: uint32(c) >= uint32(d)
// result: (Leq32U (Const32 <x.Type> [c-d]) (Sub32 <x.Type> x (Const32 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq32U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLess32U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(uint32(c) >= uint32(d)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpConst32, x.Type)
v0.AuxInt = int32ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub32, x.Type)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less16U (Const16 [c]) x) (Less16U x (Const16 [d])))
// cond: uint16(c) >= uint16(d)
// result: (Less16U (Const16 <x.Type> [c-d]) (Sub16 <x.Type> x (Const16 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess16U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLess16U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(uint16(c) >= uint16(d)) {
continue
}
v.reset(OpLess16U)
v0 := b.NewValue0(v.Pos, OpConst16, x.Type)
v0.AuxInt = int16ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub16, x.Type)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq16U (Const16 [c]) x) (Less16U x (Const16 [d])))
// cond: uint16(c) >= uint16(d)
// result: (Leq16U (Const16 <x.Type> [c-d]) (Sub16 <x.Type> x (Const16 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq16U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLess16U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(uint16(c) >= uint16(d)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpConst16, x.Type)
v0.AuxInt = int16ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub16, x.Type)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less8U (Const8 [c]) x) (Less8U x (Const8 [d])))
// cond: uint8(c) >= uint8(d)
// result: (Less8U (Const8 <x.Type> [c-d]) (Sub8 <x.Type> x (Const8 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess8U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLess8U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(uint8(c) >= uint8(d)) {
continue
}
v.reset(OpLess8U)
v0 := b.NewValue0(v.Pos, OpConst8, x.Type)
v0.AuxInt = int8ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub8, x.Type)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq8U (Const8 [c]) x) (Less8U x (Const8 [d])))
// cond: uint8(c) >= uint8(d)
// result: (Leq8U (Const8 <x.Type> [c-d]) (Sub8 <x.Type> x (Const8 <x.Type> [d])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq8U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLess8U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(uint8(c) >= uint8(d)) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpConst8, x.Type)
v0.AuxInt = int8ToAuxInt(c - d)
v1 := b.NewValue0(v.Pos, OpSub8, x.Type)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less64U (Const64 [c]) x) (Leq64U x (Const64 [d])))
// cond: uint64(c) >= uint64(d+1) && uint64(d+1) > uint64(d)
// result: (Less64U (Const64 <x.Type> [c-d-1]) (Sub64 <x.Type> x (Const64 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess64U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLeq64U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(uint64(c) >= uint64(d+1) && uint64(d+1) > uint64(d)) {
continue
}
v.reset(OpLess64U)
v0 := b.NewValue0(v.Pos, OpConst64, x.Type)
v0.AuxInt = int64ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub64, x.Type)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq64U (Const64 [c]) x) (Leq64U x (Const64 [d])))
// cond: uint64(c) >= uint64(d+1) && uint64(d+1) > uint64(d)
// result: (Leq64U (Const64 <x.Type> [c-d-1]) (Sub64 <x.Type> x (Const64 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq64U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0_0.AuxInt)
if v_1.Op != OpLeq64U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1_1.AuxInt)
if !(uint64(c) >= uint64(d+1) && uint64(d+1) > uint64(d)) {
continue
}
v.reset(OpLeq64U)
v0 := b.NewValue0(v.Pos, OpConst64, x.Type)
v0.AuxInt = int64ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub64, x.Type)
v2 := b.NewValue0(v.Pos, OpConst64, x.Type)
v2.AuxInt = int64ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less32U (Const32 [c]) x) (Leq32U x (Const32 [d])))
// cond: uint32(c) >= uint32(d+1) && uint32(d+1) > uint32(d)
// result: (Less32U (Const32 <x.Type> [c-d-1]) (Sub32 <x.Type> x (Const32 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess32U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLeq32U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(uint32(c) >= uint32(d+1) && uint32(d+1) > uint32(d)) {
continue
}
v.reset(OpLess32U)
v0 := b.NewValue0(v.Pos, OpConst32, x.Type)
v0.AuxInt = int32ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub32, x.Type)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq32U (Const32 [c]) x) (Leq32U x (Const32 [d])))
// cond: uint32(c) >= uint32(d+1) && uint32(d+1) > uint32(d)
// result: (Leq32U (Const32 <x.Type> [c-d-1]) (Sub32 <x.Type> x (Const32 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq32U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0_0.AuxInt)
if v_1.Op != OpLeq32U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1_1.AuxInt)
if !(uint32(c) >= uint32(d+1) && uint32(d+1) > uint32(d)) {
continue
}
v.reset(OpLeq32U)
v0 := b.NewValue0(v.Pos, OpConst32, x.Type)
v0.AuxInt = int32ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub32, x.Type)
v2 := b.NewValue0(v.Pos, OpConst32, x.Type)
v2.AuxInt = int32ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less16U (Const16 [c]) x) (Leq16U x (Const16 [d])))
// cond: uint16(c) >= uint16(d+1) && uint16(d+1) > uint16(d)
// result: (Less16U (Const16 <x.Type> [c-d-1]) (Sub16 <x.Type> x (Const16 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess16U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLeq16U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(uint16(c) >= uint16(d+1) && uint16(d+1) > uint16(d)) {
continue
}
v.reset(OpLess16U)
v0 := b.NewValue0(v.Pos, OpConst16, x.Type)
v0.AuxInt = int16ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub16, x.Type)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq16U (Const16 [c]) x) (Leq16U x (Const16 [d])))
// cond: uint16(c) >= uint16(d+1) && uint16(d+1) > uint16(d)
// result: (Leq16U (Const16 <x.Type> [c-d-1]) (Sub16 <x.Type> x (Const16 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq16U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0_0.AuxInt)
if v_1.Op != OpLeq16U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1_1.AuxInt)
if !(uint16(c) >= uint16(d+1) && uint16(d+1) > uint16(d)) {
continue
}
v.reset(OpLeq16U)
v0 := b.NewValue0(v.Pos, OpConst16, x.Type)
v0.AuxInt = int16ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub16, x.Type)
v2 := b.NewValue0(v.Pos, OpConst16, x.Type)
v2.AuxInt = int16ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Less8U (Const8 [c]) x) (Leq8U x (Const8 [d])))
// cond: uint8(c) >= uint8(d+1) && uint8(d+1) > uint8(d)
// result: (Less8U (Const8 <x.Type> [c-d-1]) (Sub8 <x.Type> x (Const8 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLess8U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLeq8U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(uint8(c) >= uint8(d+1) && uint8(d+1) > uint8(d)) {
continue
}
v.reset(OpLess8U)
v0 := b.NewValue0(v.Pos, OpConst8, x.Type)
v0.AuxInt = int8ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub8, x.Type)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
// match: (OrB (Leq8U (Const8 [c]) x) (Leq8U x (Const8 [d])))
// cond: uint8(c) >= uint8(d+1) && uint8(d+1) > uint8(d)
// result: (Leq8U (Const8 <x.Type> [c-d-1]) (Sub8 <x.Type> x (Const8 <x.Type> [d+1])))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpLeq8U {
continue
}
x := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0_0.AuxInt)
if v_1.Op != OpLeq8U {
continue
}
_ = v_1.Args[1]
if x != v_1.Args[0] {
continue
}
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1_1.AuxInt)
if !(uint8(c) >= uint8(d+1) && uint8(d+1) > uint8(d)) {
continue
}
v.reset(OpLeq8U)
v0 := b.NewValue0(v.Pos, OpConst8, x.Type)
v0.AuxInt = int8ToAuxInt(c - d - 1)
v1 := b.NewValue0(v.Pos, OpSub8, x.Type)
v2 := b.NewValue0(v.Pos, OpConst8, x.Type)
v2.AuxInt = int8ToAuxInt(d + 1)
v1.AddArg2(x, v2)
v.AddArg2(v0, v1)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpPhi(v *Value) bool {
// match: (Phi (Const8 [c]) (Const8 [c]))
// result: (Const8 [c])
for {
_ = v.Args[1]
v_0 := v.Args[0]
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v_1 := v.Args[1]
if v_1.Op != OpConst8 || auxIntToInt8(v_1.AuxInt) != c || len(v.Args) != 2 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c)
return true
}
// match: (Phi (Const16 [c]) (Const16 [c]))
// result: (Const16 [c])
for {
_ = v.Args[1]
v_0 := v.Args[0]
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
v_1 := v.Args[1]
if v_1.Op != OpConst16 || auxIntToInt16(v_1.AuxInt) != c || len(v.Args) != 2 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c)
return true
}
// match: (Phi (Const32 [c]) (Const32 [c]))
// result: (Const32 [c])
for {
_ = v.Args[1]
v_0 := v.Args[0]
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v_1 := v.Args[1]
if v_1.Op != OpConst32 || auxIntToInt32(v_1.AuxInt) != c || len(v.Args) != 2 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c)
return true
}
// match: (Phi (Const64 [c]) (Const64 [c]))
// result: (Const64 [c])
for {
_ = v.Args[1]
v_0 := v.Args[0]
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v_1 := v.Args[1]
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != c || len(v.Args) != 2 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c)
return true
}
return false
}
func rewriteValuegeneric_OpPtrIndex(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
typ := &b.Func.Config.Types
// match: (PtrIndex <t> ptr idx)
// cond: config.PtrSize == 4 && is32Bit(t.Elem().Size())
// result: (AddPtr ptr (Mul32 <typ.Int> idx (Const32 <typ.Int> [int32(t.Elem().Size())])))
for {
t := v.Type
ptr := v_0
idx := v_1
if !(config.PtrSize == 4 && is32Bit(t.Elem().Size())) {
break
}
v.reset(OpAddPtr)
v0 := b.NewValue0(v.Pos, OpMul32, typ.Int)
v1 := b.NewValue0(v.Pos, OpConst32, typ.Int)
v1.AuxInt = int32ToAuxInt(int32(t.Elem().Size()))
v0.AddArg2(idx, v1)
v.AddArg2(ptr, v0)
return true
}
// match: (PtrIndex <t> ptr idx)
// cond: config.PtrSize == 8
// result: (AddPtr ptr (Mul64 <typ.Int> idx (Const64 <typ.Int> [t.Elem().Size()])))
for {
t := v.Type
ptr := v_0
idx := v_1
if !(config.PtrSize == 8) {
break
}
v.reset(OpAddPtr)
v0 := b.NewValue0(v.Pos, OpMul64, typ.Int)
v1 := b.NewValue0(v.Pos, OpConst64, typ.Int)
v1.AuxInt = int64ToAuxInt(t.Elem().Size())
v0.AddArg2(idx, v1)
v.AddArg2(ptr, v0)
return true
}
return false
}
func rewriteValuegeneric_OpRotateLeft16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (RotateLeft16 x (Const16 [c]))
// cond: c%16 == 0
// result: x
for {
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
if !(c%16 == 0) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpRotateLeft32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (RotateLeft32 x (Const32 [c]))
// cond: c%32 == 0
// result: x
for {
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
if !(c%32 == 0) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpRotateLeft64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (RotateLeft64 x (Const64 [c]))
// cond: c%64 == 0
// result: x
for {
x := v_0
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(c%64 == 0) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpRotateLeft8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (RotateLeft8 x (Const8 [c]))
// cond: c%8 == 0
// result: x
for {
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
if !(c%8 == 0) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpRound32F(v *Value) bool {
v_0 := v.Args[0]
// match: (Round32F x:(Const32F))
// result: x
for {
x := v_0
if x.Op != OpConst32F {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpRound64F(v *Value) bool {
v_0 := v.Args[0]
// match: (Round64F x:(Const64F))
// result: x
for {
x := v_0
if x.Op != OpConst64F {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpRsh16Ux16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh16Ux16 <t> x (Const16 [c]))
// result: (Rsh16Ux64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh16Ux16 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh16Ux32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh16Ux32 <t> x (Const32 [c]))
// result: (Rsh16Ux64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh16Ux32 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh16Ux64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Rsh16Ux64 (Const16 [c]) (Const64 [d]))
// result: (Const16 [int16(uint16(c) >> uint64(d))])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(int16(uint16(c) >> uint64(d)))
return true
}
// match: (Rsh16Ux64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Rsh16Ux64 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
// match: (Rsh16Ux64 _ (Const64 [c]))
// cond: uint64(c) >= 16
// result: (Const16 [0])
for {
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(uint64(c) >= 16) {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
// match: (Rsh16Ux64 <t> (Rsh16Ux64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Rsh16Ux64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpRsh16Ux64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Rsh16Ux64 (Rsh16x64 x _) (Const64 <t> [15]))
// result: (Rsh16Ux64 x (Const64 <t> [15]))
for {
if v_0.Op != OpRsh16x64 {
break
}
x := v_0.Args[0]
if v_1.Op != OpConst64 {
break
}
t := v_1.Type
if auxIntToInt64(v_1.AuxInt) != 15 {
break
}
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(15)
v.AddArg2(x, v0)
return true
}
// match: (Rsh16Ux64 (Lsh16x64 (Rsh16Ux64 x (Const64 [c1])) (Const64 [c2])) (Const64 [c3]))
// cond: uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)
// result: (Rsh16Ux64 x (Const64 <typ.UInt64> [c1-c2+c3]))
for {
if v_0.Op != OpLsh16x64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh16Ux64 {
break
}
_ = v_0_0.Args[1]
x := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c1 := auxIntToInt64(v_0_0_1.AuxInt)
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
c3 := auxIntToInt64(v_1.AuxInt)
if !(uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)) {
break
}
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(c1 - c2 + c3)
v.AddArg2(x, v0)
return true
}
// match: (Rsh16Ux64 (Lsh16x64 x (Const64 [8])) (Const64 [8]))
// result: (ZeroExt8to16 (Trunc16to8 <typ.UInt8> x))
for {
if v_0.Op != OpLsh16x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 8 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 8 {
break
}
v.reset(OpZeroExt8to16)
v0 := b.NewValue0(v.Pos, OpTrunc16to8, typ.UInt8)
v0.AddArg(x)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh16Ux8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh16Ux8 <t> x (Const8 [c]))
// result: (Rsh16Ux64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpRsh16Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh16Ux8 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh16x16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh16x16 <t> x (Const16 [c]))
// result: (Rsh16x64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpRsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh16x16 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh16x32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh16x32 <t> x (Const32 [c]))
// result: (Rsh16x64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpRsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh16x32 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh16x64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Rsh16x64 (Const16 [c]) (Const64 [d]))
// result: (Const16 [c >> uint64(d)])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c >> uint64(d))
return true
}
// match: (Rsh16x64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Rsh16x64 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
// match: (Rsh16x64 <t> (Rsh16x64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Rsh16x64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpRsh16x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpRsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Rsh16x64 (Lsh16x64 x (Const64 [8])) (Const64 [8]))
// result: (SignExt8to16 (Trunc16to8 <typ.Int8> x))
for {
if v_0.Op != OpLsh16x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 8 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 8 {
break
}
v.reset(OpSignExt8to16)
v0 := b.NewValue0(v.Pos, OpTrunc16to8, typ.Int8)
v0.AddArg(x)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh16x8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh16x8 <t> x (Const8 [c]))
// result: (Rsh16x64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpRsh16x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh16x8 (Const16 [0]) _)
// result: (Const16 [0])
for {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh32Ux16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh32Ux16 <t> x (Const16 [c]))
// result: (Rsh32Ux64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh32Ux16 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh32Ux32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh32Ux32 <t> x (Const32 [c]))
// result: (Rsh32Ux64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh32Ux32 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh32Ux64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Rsh32Ux64 (Const32 [c]) (Const64 [d]))
// result: (Const32 [int32(uint32(c) >> uint64(d))])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(uint32(c) >> uint64(d)))
return true
}
// match: (Rsh32Ux64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Rsh32Ux64 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Rsh32Ux64 _ (Const64 [c]))
// cond: uint64(c) >= 32
// result: (Const32 [0])
for {
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(uint64(c) >= 32) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Rsh32Ux64 <t> (Rsh32Ux64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Rsh32Ux64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpRsh32Ux64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Rsh32Ux64 (Rsh32x64 x _) (Const64 <t> [31]))
// result: (Rsh32Ux64 x (Const64 <t> [31]))
for {
if v_0.Op != OpRsh32x64 {
break
}
x := v_0.Args[0]
if v_1.Op != OpConst64 {
break
}
t := v_1.Type
if auxIntToInt64(v_1.AuxInt) != 31 {
break
}
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(31)
v.AddArg2(x, v0)
return true
}
// match: (Rsh32Ux64 (Lsh32x64 (Rsh32Ux64 x (Const64 [c1])) (Const64 [c2])) (Const64 [c3]))
// cond: uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)
// result: (Rsh32Ux64 x (Const64 <typ.UInt64> [c1-c2+c3]))
for {
if v_0.Op != OpLsh32x64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh32Ux64 {
break
}
_ = v_0_0.Args[1]
x := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c1 := auxIntToInt64(v_0_0_1.AuxInt)
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
c3 := auxIntToInt64(v_1.AuxInt)
if !(uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)) {
break
}
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(c1 - c2 + c3)
v.AddArg2(x, v0)
return true
}
// match: (Rsh32Ux64 (Lsh32x64 x (Const64 [24])) (Const64 [24]))
// result: (ZeroExt8to32 (Trunc32to8 <typ.UInt8> x))
for {
if v_0.Op != OpLsh32x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 24 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 24 {
break
}
v.reset(OpZeroExt8to32)
v0 := b.NewValue0(v.Pos, OpTrunc32to8, typ.UInt8)
v0.AddArg(x)
v.AddArg(v0)
return true
}
// match: (Rsh32Ux64 (Lsh32x64 x (Const64 [16])) (Const64 [16]))
// result: (ZeroExt16to32 (Trunc32to16 <typ.UInt16> x))
for {
if v_0.Op != OpLsh32x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 16 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 16 {
break
}
v.reset(OpZeroExt16to32)
v0 := b.NewValue0(v.Pos, OpTrunc32to16, typ.UInt16)
v0.AddArg(x)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh32Ux8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh32Ux8 <t> x (Const8 [c]))
// result: (Rsh32Ux64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpRsh32Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh32Ux8 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh32x16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh32x16 <t> x (Const16 [c]))
// result: (Rsh32x64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpRsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh32x16 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh32x32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh32x32 <t> x (Const32 [c]))
// result: (Rsh32x64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpRsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh32x32 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh32x64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Rsh32x64 (Const32 [c]) (Const64 [d]))
// result: (Const32 [c >> uint64(d)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c >> uint64(d))
return true
}
// match: (Rsh32x64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Rsh32x64 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Rsh32x64 <t> (Rsh32x64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Rsh32x64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpRsh32x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpRsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Rsh32x64 (Lsh32x64 x (Const64 [24])) (Const64 [24]))
// result: (SignExt8to32 (Trunc32to8 <typ.Int8> x))
for {
if v_0.Op != OpLsh32x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 24 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 24 {
break
}
v.reset(OpSignExt8to32)
v0 := b.NewValue0(v.Pos, OpTrunc32to8, typ.Int8)
v0.AddArg(x)
v.AddArg(v0)
return true
}
// match: (Rsh32x64 (Lsh32x64 x (Const64 [16])) (Const64 [16]))
// result: (SignExt16to32 (Trunc32to16 <typ.Int16> x))
for {
if v_0.Op != OpLsh32x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 16 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 16 {
break
}
v.reset(OpSignExt16to32)
v0 := b.NewValue0(v.Pos, OpTrunc32to16, typ.Int16)
v0.AddArg(x)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh32x8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh32x8 <t> x (Const8 [c]))
// result: (Rsh32x64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpRsh32x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh32x8 (Const32 [0]) _)
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh64Ux16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh64Ux16 <t> x (Const16 [c]))
// result: (Rsh64Ux64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh64Ux16 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh64Ux32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh64Ux32 <t> x (Const32 [c]))
// result: (Rsh64Ux64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh64Ux32 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh64Ux64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Rsh64Ux64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [int64(uint64(c) >> uint64(d))])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(uint64(c) >> uint64(d)))
return true
}
// match: (Rsh64Ux64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Rsh64Ux64 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Rsh64Ux64 _ (Const64 [c]))
// cond: uint64(c) >= 64
// result: (Const64 [0])
for {
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(uint64(c) >= 64) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Rsh64Ux64 <t> (Rsh64Ux64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Rsh64Ux64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpRsh64Ux64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Rsh64Ux64 (Rsh64x64 x _) (Const64 <t> [63]))
// result: (Rsh64Ux64 x (Const64 <t> [63]))
for {
if v_0.Op != OpRsh64x64 {
break
}
x := v_0.Args[0]
if v_1.Op != OpConst64 {
break
}
t := v_1.Type
if auxIntToInt64(v_1.AuxInt) != 63 {
break
}
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(63)
v.AddArg2(x, v0)
return true
}
// match: (Rsh64Ux64 (Lsh64x64 (Rsh64Ux64 x (Const64 [c1])) (Const64 [c2])) (Const64 [c3]))
// cond: uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)
// result: (Rsh64Ux64 x (Const64 <typ.UInt64> [c1-c2+c3]))
for {
if v_0.Op != OpLsh64x64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh64Ux64 {
break
}
_ = v_0_0.Args[1]
x := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c1 := auxIntToInt64(v_0_0_1.AuxInt)
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
c3 := auxIntToInt64(v_1.AuxInt)
if !(uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)) {
break
}
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(c1 - c2 + c3)
v.AddArg2(x, v0)
return true
}
// match: (Rsh64Ux64 (Lsh64x64 x (Const64 [56])) (Const64 [56]))
// result: (ZeroExt8to64 (Trunc64to8 <typ.UInt8> x))
for {
if v_0.Op != OpLsh64x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 56 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 56 {
break
}
v.reset(OpZeroExt8to64)
v0 := b.NewValue0(v.Pos, OpTrunc64to8, typ.UInt8)
v0.AddArg(x)
v.AddArg(v0)
return true
}
// match: (Rsh64Ux64 (Lsh64x64 x (Const64 [48])) (Const64 [48]))
// result: (ZeroExt16to64 (Trunc64to16 <typ.UInt16> x))
for {
if v_0.Op != OpLsh64x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 48 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 48 {
break
}
v.reset(OpZeroExt16to64)
v0 := b.NewValue0(v.Pos, OpTrunc64to16, typ.UInt16)
v0.AddArg(x)
v.AddArg(v0)
return true
}
// match: (Rsh64Ux64 (Lsh64x64 x (Const64 [32])) (Const64 [32]))
// result: (ZeroExt32to64 (Trunc64to32 <typ.UInt32> x))
for {
if v_0.Op != OpLsh64x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 32 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 32 {
break
}
v.reset(OpZeroExt32to64)
v0 := b.NewValue0(v.Pos, OpTrunc64to32, typ.UInt32)
v0.AddArg(x)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh64Ux8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh64Ux8 <t> x (Const8 [c]))
// result: (Rsh64Ux64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpRsh64Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh64Ux8 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh64x16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh64x16 <t> x (Const16 [c]))
// result: (Rsh64x64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpRsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh64x16 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh64x32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh64x32 <t> x (Const32 [c]))
// result: (Rsh64x64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpRsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh64x32 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh64x64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Rsh64x64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [c >> uint64(d)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c >> uint64(d))
return true
}
// match: (Rsh64x64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Rsh64x64 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Rsh64x64 <t> (Rsh64x64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Rsh64x64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpRsh64x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpRsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Rsh64x64 (Lsh64x64 x (Const64 [56])) (Const64 [56]))
// result: (SignExt8to64 (Trunc64to8 <typ.Int8> x))
for {
if v_0.Op != OpLsh64x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 56 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 56 {
break
}
v.reset(OpSignExt8to64)
v0 := b.NewValue0(v.Pos, OpTrunc64to8, typ.Int8)
v0.AddArg(x)
v.AddArg(v0)
return true
}
// match: (Rsh64x64 (Lsh64x64 x (Const64 [48])) (Const64 [48]))
// result: (SignExt16to64 (Trunc64to16 <typ.Int16> x))
for {
if v_0.Op != OpLsh64x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 48 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 48 {
break
}
v.reset(OpSignExt16to64)
v0 := b.NewValue0(v.Pos, OpTrunc64to16, typ.Int16)
v0.AddArg(x)
v.AddArg(v0)
return true
}
// match: (Rsh64x64 (Lsh64x64 x (Const64 [32])) (Const64 [32]))
// result: (SignExt32to64 (Trunc64to32 <typ.Int32> x))
for {
if v_0.Op != OpLsh64x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 || auxIntToInt64(v_0_1.AuxInt) != 32 || v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 32 {
break
}
v.reset(OpSignExt32to64)
v0 := b.NewValue0(v.Pos, OpTrunc64to32, typ.Int32)
v0.AddArg(x)
v.AddArg(v0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh64x8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh64x8 <t> x (Const8 [c]))
// result: (Rsh64x64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpRsh64x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh64x8 (Const64 [0]) _)
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh8Ux16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh8Ux16 <t> x (Const16 [c]))
// result: (Rsh8Ux64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh8Ux16 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh8Ux32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh8Ux32 <t> x (Const32 [c]))
// result: (Rsh8Ux64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh8Ux32 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh8Ux64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (Rsh8Ux64 (Const8 [c]) (Const64 [d]))
// result: (Const8 [int8(uint8(c) >> uint64(d))])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(int8(uint8(c) >> uint64(d)))
return true
}
// match: (Rsh8Ux64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Rsh8Ux64 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (Rsh8Ux64 _ (Const64 [c]))
// cond: uint64(c) >= 8
// result: (Const8 [0])
for {
if v_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_1.AuxInt)
if !(uint64(c) >= 8) {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (Rsh8Ux64 <t> (Rsh8Ux64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Rsh8Ux64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpRsh8Ux64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
// match: (Rsh8Ux64 (Rsh8x64 x _) (Const64 <t> [7] ))
// result: (Rsh8Ux64 x (Const64 <t> [7] ))
for {
if v_0.Op != OpRsh8x64 {
break
}
x := v_0.Args[0]
if v_1.Op != OpConst64 {
break
}
t := v_1.Type
if auxIntToInt64(v_1.AuxInt) != 7 {
break
}
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(7)
v.AddArg2(x, v0)
return true
}
// match: (Rsh8Ux64 (Lsh8x64 (Rsh8Ux64 x (Const64 [c1])) (Const64 [c2])) (Const64 [c3]))
// cond: uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)
// result: (Rsh8Ux64 x (Const64 <typ.UInt64> [c1-c2+c3]))
for {
if v_0.Op != OpLsh8x64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpRsh8Ux64 {
break
}
_ = v_0_0.Args[1]
x := v_0_0.Args[0]
v_0_0_1 := v_0_0.Args[1]
if v_0_0_1.Op != OpConst64 {
break
}
c1 := auxIntToInt64(v_0_0_1.AuxInt)
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c2 := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
c3 := auxIntToInt64(v_1.AuxInt)
if !(uint64(c1) >= uint64(c2) && uint64(c3) >= uint64(c2) && !uaddOvf(c1-c2, c3)) {
break
}
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, typ.UInt64)
v0.AuxInt = int64ToAuxInt(c1 - c2 + c3)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh8Ux8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh8Ux8 <t> x (Const8 [c]))
// result: (Rsh8Ux64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpRsh8Ux64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh8Ux8 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh8x16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh8x16 <t> x (Const16 [c]))
// result: (Rsh8x64 x (Const64 <t> [int64(uint16(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst16 {
break
}
c := auxIntToInt16(v_1.AuxInt)
v.reset(OpRsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint16(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh8x16 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh8x32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh8x32 <t> x (Const32 [c]))
// result: (Rsh8x64 x (Const64 <t> [int64(uint32(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst32 {
break
}
c := auxIntToInt32(v_1.AuxInt)
v.reset(OpRsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint32(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh8x32 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh8x64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh8x64 (Const8 [c]) (Const64 [d]))
// result: (Const8 [c >> uint64(d)])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c >> uint64(d))
return true
}
// match: (Rsh8x64 x (Const64 [0]))
// result: x
for {
x := v_0
if v_1.Op != OpConst64 || auxIntToInt64(v_1.AuxInt) != 0 {
break
}
v.copyOf(x)
return true
}
// match: (Rsh8x64 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (Rsh8x64 <t> (Rsh8x64 x (Const64 [c])) (Const64 [d]))
// cond: !uaddOvf(c,d)
// result: (Rsh8x64 x (Const64 <t> [c+d]))
for {
t := v.Type
if v_0.Op != OpRsh8x64 {
break
}
_ = v_0.Args[1]
x := v_0.Args[0]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0_1.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
if !(!uaddOvf(c, d)) {
break
}
v.reset(OpRsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(x, v0)
return true
}
return false
}
func rewriteValuegeneric_OpRsh8x8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Rsh8x8 <t> x (Const8 [c]))
// result: (Rsh8x64 x (Const64 <t> [int64(uint8(c))]))
for {
t := v.Type
x := v_0
if v_1.Op != OpConst8 {
break
}
c := auxIntToInt8(v_1.AuxInt)
v.reset(OpRsh8x64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(int64(uint8(c)))
v.AddArg2(x, v0)
return true
}
// match: (Rsh8x8 (Const8 [0]) _)
// result: (Const8 [0])
for {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpSelect0(v *Value) bool {
v_0 := v.Args[0]
// match: (Select0 (Div128u (Const64 [0]) lo y))
// result: (Div64u lo y)
for {
if v_0.Op != OpDiv128u {
break
}
y := v_0.Args[2]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 || auxIntToInt64(v_0_0.AuxInt) != 0 {
break
}
lo := v_0.Args[1]
v.reset(OpDiv64u)
v.AddArg2(lo, y)
return true
}
return false
}
func rewriteValuegeneric_OpSelect1(v *Value) bool {
v_0 := v.Args[0]
// match: (Select1 (Div128u (Const64 [0]) lo y))
// result: (Mod64u lo y)
for {
if v_0.Op != OpDiv128u {
break
}
y := v_0.Args[2]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpConst64 || auxIntToInt64(v_0_0.AuxInt) != 0 {
break
}
lo := v_0.Args[1]
v.reset(OpMod64u)
v.AddArg2(lo, y)
return true
}
return false
}
func rewriteValuegeneric_OpSignExt16to32(v *Value) bool {
v_0 := v.Args[0]
// match: (SignExt16to32 (Const16 [c]))
// result: (Const32 [int32(c)])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(c))
return true
}
// match: (SignExt16to32 (Trunc32to16 x:(Rsh32x64 _ (Const64 [s]))))
// cond: s >= 16
// result: x
for {
if v_0.Op != OpTrunc32to16 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh32x64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 16) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpSignExt16to64(v *Value) bool {
v_0 := v.Args[0]
// match: (SignExt16to64 (Const16 [c]))
// result: (Const64 [int64(c)])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(c))
return true
}
// match: (SignExt16to64 (Trunc64to16 x:(Rsh64x64 _ (Const64 [s]))))
// cond: s >= 48
// result: x
for {
if v_0.Op != OpTrunc64to16 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh64x64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 48) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpSignExt32to64(v *Value) bool {
v_0 := v.Args[0]
// match: (SignExt32to64 (Const32 [c]))
// result: (Const64 [int64(c)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(c))
return true
}
// match: (SignExt32to64 (Trunc64to32 x:(Rsh64x64 _ (Const64 [s]))))
// cond: s >= 32
// result: x
for {
if v_0.Op != OpTrunc64to32 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh64x64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 32) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpSignExt8to16(v *Value) bool {
v_0 := v.Args[0]
// match: (SignExt8to16 (Const8 [c]))
// result: (Const16 [int16(c)])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(int16(c))
return true
}
// match: (SignExt8to16 (Trunc16to8 x:(Rsh16x64 _ (Const64 [s]))))
// cond: s >= 8
// result: x
for {
if v_0.Op != OpTrunc16to8 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh16x64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 8) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpSignExt8to32(v *Value) bool {
v_0 := v.Args[0]
// match: (SignExt8to32 (Const8 [c]))
// result: (Const32 [int32(c)])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(c))
return true
}
// match: (SignExt8to32 (Trunc32to8 x:(Rsh32x64 _ (Const64 [s]))))
// cond: s >= 24
// result: x
for {
if v_0.Op != OpTrunc32to8 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh32x64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 24) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpSignExt8to64(v *Value) bool {
v_0 := v.Args[0]
// match: (SignExt8to64 (Const8 [c]))
// result: (Const64 [int64(c)])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(c))
return true
}
// match: (SignExt8to64 (Trunc64to8 x:(Rsh64x64 _ (Const64 [s]))))
// cond: s >= 56
// result: x
for {
if v_0.Op != OpTrunc64to8 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh64x64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 56) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpSliceCap(v *Value) bool {
v_0 := v.Args[0]
// match: (SliceCap (SliceMake _ _ (Const64 <t> [c])))
// result: (Const64 <t> [c])
for {
if v_0.Op != OpSliceMake {
break
}
_ = v_0.Args[2]
v_0_2 := v_0.Args[2]
if v_0_2.Op != OpConst64 {
break
}
t := v_0_2.Type
c := auxIntToInt64(v_0_2.AuxInt)
v.reset(OpConst64)
v.Type = t
v.AuxInt = int64ToAuxInt(c)
return true
}
// match: (SliceCap (SliceMake _ _ (Const32 <t> [c])))
// result: (Const32 <t> [c])
for {
if v_0.Op != OpSliceMake {
break
}
_ = v_0.Args[2]
v_0_2 := v_0.Args[2]
if v_0_2.Op != OpConst32 {
break
}
t := v_0_2.Type
c := auxIntToInt32(v_0_2.AuxInt)
v.reset(OpConst32)
v.Type = t
v.AuxInt = int32ToAuxInt(c)
return true
}
// match: (SliceCap (SliceMake _ _ (SliceCap x)))
// result: (SliceCap x)
for {
if v_0.Op != OpSliceMake {
break
}
_ = v_0.Args[2]
v_0_2 := v_0.Args[2]
if v_0_2.Op != OpSliceCap {
break
}
x := v_0_2.Args[0]
v.reset(OpSliceCap)
v.AddArg(x)
return true
}
// match: (SliceCap (SliceMake _ _ (SliceLen x)))
// result: (SliceLen x)
for {
if v_0.Op != OpSliceMake {
break
}
_ = v_0.Args[2]
v_0_2 := v_0.Args[2]
if v_0_2.Op != OpSliceLen {
break
}
x := v_0_2.Args[0]
v.reset(OpSliceLen)
v.AddArg(x)
return true
}
return false
}
func rewriteValuegeneric_OpSliceLen(v *Value) bool {
v_0 := v.Args[0]
// match: (SliceLen (SliceMake _ (Const64 <t> [c]) _))
// result: (Const64 <t> [c])
for {
if v_0.Op != OpSliceMake {
break
}
_ = v_0.Args[1]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
t := v_0_1.Type
c := auxIntToInt64(v_0_1.AuxInt)
v.reset(OpConst64)
v.Type = t
v.AuxInt = int64ToAuxInt(c)
return true
}
// match: (SliceLen (SliceMake _ (Const32 <t> [c]) _))
// result: (Const32 <t> [c])
for {
if v_0.Op != OpSliceMake {
break
}
_ = v_0.Args[1]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst32 {
break
}
t := v_0_1.Type
c := auxIntToInt32(v_0_1.AuxInt)
v.reset(OpConst32)
v.Type = t
v.AuxInt = int32ToAuxInt(c)
return true
}
// match: (SliceLen (SliceMake _ (SliceLen x) _))
// result: (SliceLen x)
for {
if v_0.Op != OpSliceMake {
break
}
_ = v_0.Args[1]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpSliceLen {
break
}
x := v_0_1.Args[0]
v.reset(OpSliceLen)
v.AddArg(x)
return true
}
return false
}
func rewriteValuegeneric_OpSlicePtr(v *Value) bool {
v_0 := v.Args[0]
// match: (SlicePtr (SliceMake (SlicePtr x) _ _))
// result: (SlicePtr x)
for {
if v_0.Op != OpSliceMake {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpSlicePtr {
break
}
x := v_0_0.Args[0]
v.reset(OpSlicePtr)
v.AddArg(x)
return true
}
return false
}
func rewriteValuegeneric_OpSlicemask(v *Value) bool {
v_0 := v.Args[0]
// match: (Slicemask (Const32 [x]))
// cond: x > 0
// result: (Const32 [-1])
for {
if v_0.Op != OpConst32 {
break
}
x := auxIntToInt32(v_0.AuxInt)
if !(x > 0) {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(-1)
return true
}
// match: (Slicemask (Const32 [0]))
// result: (Const32 [0])
for {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Slicemask (Const64 [x]))
// cond: x > 0
// result: (Const64 [-1])
for {
if v_0.Op != OpConst64 {
break
}
x := auxIntToInt64(v_0.AuxInt)
if !(x > 0) {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(-1)
return true
}
// match: (Slicemask (Const64 [0]))
// result: (Const64 [0])
for {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
return false
}
func rewriteValuegeneric_OpSqrt(v *Value) bool {
v_0 := v.Args[0]
// match: (Sqrt (Const64F [c]))
// cond: !math.IsNaN(math.Sqrt(c))
// result: (Const64F [math.Sqrt(c)])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
if !(!math.IsNaN(math.Sqrt(c))) {
break
}
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(math.Sqrt(c))
return true
}
return false
}
func rewriteValuegeneric_OpStaticCall(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
// match: (StaticCall {sym} s1:(Store _ (Const64 [sz]) s2:(Store _ src s3:(Store {t} _ dst mem))))
// cond: sz >= 0 && symNamed(sym, "runtime.memmove") && t.IsPtr() && s1.Uses == 1 && s2.Uses == 1 && s3.Uses == 1 && isInlinableMemmove(dst, src, int64(sz), config) && clobber(s1, s2, s3)
// result: (Move {t.Elem()} [int64(sz)] dst src mem)
for {
sym := auxToSym(v.Aux)
s1 := v_0
if s1.Op != OpStore {
break
}
_ = s1.Args[2]
s1_1 := s1.Args[1]
if s1_1.Op != OpConst64 {
break
}
sz := auxIntToInt64(s1_1.AuxInt)
s2 := s1.Args[2]
if s2.Op != OpStore {
break
}
_ = s2.Args[2]
src := s2.Args[1]
s3 := s2.Args[2]
if s3.Op != OpStore {
break
}
t := auxToType(s3.Aux)
mem := s3.Args[2]
dst := s3.Args[1]
if !(sz >= 0 && symNamed(sym, "runtime.memmove") && t.IsPtr() && s1.Uses == 1 && s2.Uses == 1 && s3.Uses == 1 && isInlinableMemmove(dst, src, int64(sz), config) && clobber(s1, s2, s3)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(int64(sz))
v.Aux = typeToAux(t.Elem())
v.AddArg3(dst, src, mem)
return true
}
// match: (StaticCall {sym} s1:(Store _ (Const32 [sz]) s2:(Store _ src s3:(Store {t} _ dst mem))))
// cond: sz >= 0 && symNamed(sym, "runtime.memmove") && t.IsPtr() && s1.Uses == 1 && s2.Uses == 1 && s3.Uses == 1 && isInlinableMemmove(dst, src, int64(sz), config) && clobber(s1, s2, s3)
// result: (Move {t.Elem()} [int64(sz)] dst src mem)
for {
sym := auxToSym(v.Aux)
s1 := v_0
if s1.Op != OpStore {
break
}
_ = s1.Args[2]
s1_1 := s1.Args[1]
if s1_1.Op != OpConst32 {
break
}
sz := auxIntToInt32(s1_1.AuxInt)
s2 := s1.Args[2]
if s2.Op != OpStore {
break
}
_ = s2.Args[2]
src := s2.Args[1]
s3 := s2.Args[2]
if s3.Op != OpStore {
break
}
t := auxToType(s3.Aux)
mem := s3.Args[2]
dst := s3.Args[1]
if !(sz >= 0 && symNamed(sym, "runtime.memmove") && t.IsPtr() && s1.Uses == 1 && s2.Uses == 1 && s3.Uses == 1 && isInlinableMemmove(dst, src, int64(sz), config) && clobber(s1, s2, s3)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(int64(sz))
v.Aux = typeToAux(t.Elem())
v.AddArg3(dst, src, mem)
return true
}
// match: (StaticCall {sym} x)
// cond: needRaceCleanup(sym, v)
// result: x
for {
sym := auxToSym(v.Aux)
x := v_0
if !(needRaceCleanup(sym, v)) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpStore(v *Value) bool {
v_2 := v.Args[2]
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
fe := b.Func.fe
// match: (Store {t1} p1 (Load <t2> p2 mem) mem)
// cond: isSamePtr(p1, p2) && t2.Size() == t1.Size()
// result: mem
for {
t1 := auxToType(v.Aux)
p1 := v_0
if v_1.Op != OpLoad {
break
}
t2 := v_1.Type
mem := v_1.Args[1]
p2 := v_1.Args[0]
if mem != v_2 || !(isSamePtr(p1, p2) && t2.Size() == t1.Size()) {
break
}
v.copyOf(mem)
return true
}
// match: (Store {t1} p1 (Load <t2> p2 oldmem) mem:(Store {t3} p3 _ oldmem))
// cond: isSamePtr(p1, p2) && t2.Size() == t1.Size() && disjoint(p1, t1.Size(), p3, t3.Size())
// result: mem
for {
t1 := auxToType(v.Aux)
p1 := v_0
if v_1.Op != OpLoad {
break
}
t2 := v_1.Type
oldmem := v_1.Args[1]
p2 := v_1.Args[0]
mem := v_2
if mem.Op != OpStore {
break
}
t3 := auxToType(mem.Aux)
_ = mem.Args[2]
p3 := mem.Args[0]
if oldmem != mem.Args[2] || !(isSamePtr(p1, p2) && t2.Size() == t1.Size() && disjoint(p1, t1.Size(), p3, t3.Size())) {
break
}
v.copyOf(mem)
return true
}
// match: (Store {t1} p1 (Load <t2> p2 oldmem) mem:(Store {t3} p3 _ (Store {t4} p4 _ oldmem)))
// cond: isSamePtr(p1, p2) && t2.Size() == t1.Size() && disjoint(p1, t1.Size(), p3, t3.Size()) && disjoint(p1, t1.Size(), p4, t4.Size())
// result: mem
for {
t1 := auxToType(v.Aux)
p1 := v_0
if v_1.Op != OpLoad {
break
}
t2 := v_1.Type
oldmem := v_1.Args[1]
p2 := v_1.Args[0]
mem := v_2
if mem.Op != OpStore {
break
}
t3 := auxToType(mem.Aux)
_ = mem.Args[2]
p3 := mem.Args[0]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t4 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
p4 := mem_2.Args[0]
if oldmem != mem_2.Args[2] || !(isSamePtr(p1, p2) && t2.Size() == t1.Size() && disjoint(p1, t1.Size(), p3, t3.Size()) && disjoint(p1, t1.Size(), p4, t4.Size())) {
break
}
v.copyOf(mem)
return true
}
// match: (Store {t1} p1 (Load <t2> p2 oldmem) mem:(Store {t3} p3 _ (Store {t4} p4 _ (Store {t5} p5 _ oldmem))))
// cond: isSamePtr(p1, p2) && t2.Size() == t1.Size() && disjoint(p1, t1.Size(), p3, t3.Size()) && disjoint(p1, t1.Size(), p4, t4.Size()) && disjoint(p1, t1.Size(), p5, t5.Size())
// result: mem
for {
t1 := auxToType(v.Aux)
p1 := v_0
if v_1.Op != OpLoad {
break
}
t2 := v_1.Type
oldmem := v_1.Args[1]
p2 := v_1.Args[0]
mem := v_2
if mem.Op != OpStore {
break
}
t3 := auxToType(mem.Aux)
_ = mem.Args[2]
p3 := mem.Args[0]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t4 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
p4 := mem_2.Args[0]
mem_2_2 := mem_2.Args[2]
if mem_2_2.Op != OpStore {
break
}
t5 := auxToType(mem_2_2.Aux)
_ = mem_2_2.Args[2]
p5 := mem_2_2.Args[0]
if oldmem != mem_2_2.Args[2] || !(isSamePtr(p1, p2) && t2.Size() == t1.Size() && disjoint(p1, t1.Size(), p3, t3.Size()) && disjoint(p1, t1.Size(), p4, t4.Size()) && disjoint(p1, t1.Size(), p5, t5.Size())) {
break
}
v.copyOf(mem)
return true
}
// match: (Store {t} (OffPtr [o] p1) x mem:(Zero [n] p2 _))
// cond: isConstZero(x) && o >= 0 && t.Size() + o <= n && isSamePtr(p1, p2)
// result: mem
for {
t := auxToType(v.Aux)
if v_0.Op != OpOffPtr {
break
}
o := auxIntToInt64(v_0.AuxInt)
p1 := v_0.Args[0]
x := v_1
mem := v_2
if mem.Op != OpZero {
break
}
n := auxIntToInt64(mem.AuxInt)
p2 := mem.Args[0]
if !(isConstZero(x) && o >= 0 && t.Size()+o <= n && isSamePtr(p1, p2)) {
break
}
v.copyOf(mem)
return true
}
// match: (Store {t1} op:(OffPtr [o1] p1) x mem:(Store {t2} p2 _ (Zero [n] p3 _)))
// cond: isConstZero(x) && o1 >= 0 && t1.Size() + o1 <= n && isSamePtr(p1, p3) && disjoint(op, t1.Size(), p2, t2.Size())
// result: mem
for {
t1 := auxToType(v.Aux)
op := v_0
if op.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op.AuxInt)
p1 := op.Args[0]
x := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
p2 := mem.Args[0]
mem_2 := mem.Args[2]
if mem_2.Op != OpZero {
break
}
n := auxIntToInt64(mem_2.AuxInt)
p3 := mem_2.Args[0]
if !(isConstZero(x) && o1 >= 0 && t1.Size()+o1 <= n && isSamePtr(p1, p3) && disjoint(op, t1.Size(), p2, t2.Size())) {
break
}
v.copyOf(mem)
return true
}
// match: (Store {t1} op:(OffPtr [o1] p1) x mem:(Store {t2} p2 _ (Store {t3} p3 _ (Zero [n] p4 _))))
// cond: isConstZero(x) && o1 >= 0 && t1.Size() + o1 <= n && isSamePtr(p1, p4) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size())
// result: mem
for {
t1 := auxToType(v.Aux)
op := v_0
if op.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op.AuxInt)
p1 := op.Args[0]
x := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
p2 := mem.Args[0]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t3 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
p3 := mem_2.Args[0]
mem_2_2 := mem_2.Args[2]
if mem_2_2.Op != OpZero {
break
}
n := auxIntToInt64(mem_2_2.AuxInt)
p4 := mem_2_2.Args[0]
if !(isConstZero(x) && o1 >= 0 && t1.Size()+o1 <= n && isSamePtr(p1, p4) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size())) {
break
}
v.copyOf(mem)
return true
}
// match: (Store {t1} op:(OffPtr [o1] p1) x mem:(Store {t2} p2 _ (Store {t3} p3 _ (Store {t4} p4 _ (Zero [n] p5 _)))))
// cond: isConstZero(x) && o1 >= 0 && t1.Size() + o1 <= n && isSamePtr(p1, p5) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size()) && disjoint(op, t1.Size(), p4, t4.Size())
// result: mem
for {
t1 := auxToType(v.Aux)
op := v_0
if op.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op.AuxInt)
p1 := op.Args[0]
x := v_1
mem := v_2
if mem.Op != OpStore {
break
}
t2 := auxToType(mem.Aux)
_ = mem.Args[2]
p2 := mem.Args[0]
mem_2 := mem.Args[2]
if mem_2.Op != OpStore {
break
}
t3 := auxToType(mem_2.Aux)
_ = mem_2.Args[2]
p3 := mem_2.Args[0]
mem_2_2 := mem_2.Args[2]
if mem_2_2.Op != OpStore {
break
}
t4 := auxToType(mem_2_2.Aux)
_ = mem_2_2.Args[2]
p4 := mem_2_2.Args[0]
mem_2_2_2 := mem_2_2.Args[2]
if mem_2_2_2.Op != OpZero {
break
}
n := auxIntToInt64(mem_2_2_2.AuxInt)
p5 := mem_2_2_2.Args[0]
if !(isConstZero(x) && o1 >= 0 && t1.Size()+o1 <= n && isSamePtr(p1, p5) && disjoint(op, t1.Size(), p2, t2.Size()) && disjoint(op, t1.Size(), p3, t3.Size()) && disjoint(op, t1.Size(), p4, t4.Size())) {
break
}
v.copyOf(mem)
return true
}
// match: (Store _ (StructMake0) mem)
// result: mem
for {
if v_1.Op != OpStructMake0 {
break
}
mem := v_2
v.copyOf(mem)
return true
}
// match: (Store dst (StructMake1 <t> f0) mem)
// result: (Store {t.FieldType(0)} (OffPtr <t.FieldType(0).PtrTo()> [0] dst) f0 mem)
for {
dst := v_0
if v_1.Op != OpStructMake1 {
break
}
t := v_1.Type
f0 := v_1.Args[0]
mem := v_2
v.reset(OpStore)
v.Aux = typeToAux(t.FieldType(0))
v0 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(0).PtrTo())
v0.AuxInt = int64ToAuxInt(0)
v0.AddArg(dst)
v.AddArg3(v0, f0, mem)
return true
}
// match: (Store dst (StructMake2 <t> f0 f1) mem)
// result: (Store {t.FieldType(1)} (OffPtr <t.FieldType(1).PtrTo()> [t.FieldOff(1)] dst) f1 (Store {t.FieldType(0)} (OffPtr <t.FieldType(0).PtrTo()> [0] dst) f0 mem))
for {
dst := v_0
if v_1.Op != OpStructMake2 {
break
}
t := v_1.Type
f1 := v_1.Args[1]
f0 := v_1.Args[0]
mem := v_2
v.reset(OpStore)
v.Aux = typeToAux(t.FieldType(1))
v0 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(1).PtrTo())
v0.AuxInt = int64ToAuxInt(t.FieldOff(1))
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t.FieldType(0))
v2 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(0).PtrTo())
v2.AuxInt = int64ToAuxInt(0)
v2.AddArg(dst)
v1.AddArg3(v2, f0, mem)
v.AddArg3(v0, f1, v1)
return true
}
// match: (Store dst (StructMake3 <t> f0 f1 f2) mem)
// result: (Store {t.FieldType(2)} (OffPtr <t.FieldType(2).PtrTo()> [t.FieldOff(2)] dst) f2 (Store {t.FieldType(1)} (OffPtr <t.FieldType(1).PtrTo()> [t.FieldOff(1)] dst) f1 (Store {t.FieldType(0)} (OffPtr <t.FieldType(0).PtrTo()> [0] dst) f0 mem)))
for {
dst := v_0
if v_1.Op != OpStructMake3 {
break
}
t := v_1.Type
f2 := v_1.Args[2]
f0 := v_1.Args[0]
f1 := v_1.Args[1]
mem := v_2
v.reset(OpStore)
v.Aux = typeToAux(t.FieldType(2))
v0 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(2).PtrTo())
v0.AuxInt = int64ToAuxInt(t.FieldOff(2))
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t.FieldType(1))
v2 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(1).PtrTo())
v2.AuxInt = int64ToAuxInt(t.FieldOff(1))
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t.FieldType(0))
v4 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(0).PtrTo())
v4.AuxInt = int64ToAuxInt(0)
v4.AddArg(dst)
v3.AddArg3(v4, f0, mem)
v1.AddArg3(v2, f1, v3)
v.AddArg3(v0, f2, v1)
return true
}
// match: (Store dst (StructMake4 <t> f0 f1 f2 f3) mem)
// result: (Store {t.FieldType(3)} (OffPtr <t.FieldType(3).PtrTo()> [t.FieldOff(3)] dst) f3 (Store {t.FieldType(2)} (OffPtr <t.FieldType(2).PtrTo()> [t.FieldOff(2)] dst) f2 (Store {t.FieldType(1)} (OffPtr <t.FieldType(1).PtrTo()> [t.FieldOff(1)] dst) f1 (Store {t.FieldType(0)} (OffPtr <t.FieldType(0).PtrTo()> [0] dst) f0 mem))))
for {
dst := v_0
if v_1.Op != OpStructMake4 {
break
}
t := v_1.Type
f3 := v_1.Args[3]
f0 := v_1.Args[0]
f1 := v_1.Args[1]
f2 := v_1.Args[2]
mem := v_2
v.reset(OpStore)
v.Aux = typeToAux(t.FieldType(3))
v0 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(3).PtrTo())
v0.AuxInt = int64ToAuxInt(t.FieldOff(3))
v0.AddArg(dst)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t.FieldType(2))
v2 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(2).PtrTo())
v2.AuxInt = int64ToAuxInt(t.FieldOff(2))
v2.AddArg(dst)
v3 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v3.Aux = typeToAux(t.FieldType(1))
v4 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(1).PtrTo())
v4.AuxInt = int64ToAuxInt(t.FieldOff(1))
v4.AddArg(dst)
v5 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v5.Aux = typeToAux(t.FieldType(0))
v6 := b.NewValue0(v.Pos, OpOffPtr, t.FieldType(0).PtrTo())
v6.AuxInt = int64ToAuxInt(0)
v6.AddArg(dst)
v5.AddArg3(v6, f0, mem)
v3.AddArg3(v4, f1, v5)
v1.AddArg3(v2, f2, v3)
v.AddArg3(v0, f3, v1)
return true
}
// match: (Store {t} dst (Load src mem) mem)
// cond: !fe.CanSSA(t)
// result: (Move {t} [t.Size()] dst src mem)
for {
t := auxToType(v.Aux)
dst := v_0
if v_1.Op != OpLoad {
break
}
mem := v_1.Args[1]
src := v_1.Args[0]
if mem != v_2 || !(!fe.CanSSA(t)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(t.Size())
v.Aux = typeToAux(t)
v.AddArg3(dst, src, mem)
return true
}
// match: (Store {t} dst (Load src mem) (VarDef {x} mem))
// cond: !fe.CanSSA(t)
// result: (Move {t} [t.Size()] dst src (VarDef {x} mem))
for {
t := auxToType(v.Aux)
dst := v_0
if v_1.Op != OpLoad {
break
}
mem := v_1.Args[1]
src := v_1.Args[0]
if v_2.Op != OpVarDef {
break
}
x := auxToSym(v_2.Aux)
if mem != v_2.Args[0] || !(!fe.CanSSA(t)) {
break
}
v.reset(OpMove)
v.AuxInt = int64ToAuxInt(t.Size())
v.Aux = typeToAux(t)
v0 := b.NewValue0(v.Pos, OpVarDef, types.TypeMem)
v0.Aux = symToAux(x)
v0.AddArg(mem)
v.AddArg3(dst, src, v0)
return true
}
// match: (Store _ (ArrayMake0) mem)
// result: mem
for {
if v_1.Op != OpArrayMake0 {
break
}
mem := v_2
v.copyOf(mem)
return true
}
// match: (Store dst (ArrayMake1 e) mem)
// result: (Store {e.Type} dst e mem)
for {
dst := v_0
if v_1.Op != OpArrayMake1 {
break
}
e := v_1.Args[0]
mem := v_2
v.reset(OpStore)
v.Aux = typeToAux(e.Type)
v.AddArg3(dst, e, mem)
return true
}
// match: (Store (Load (OffPtr [c] (SP)) mem) x mem)
// cond: isConstZero(x) && mem.Op == OpStaticCall && isSameSym(mem.Aux, "runtime.newobject") && c == config.ctxt.FixedFrameSize() + config.RegSize
// result: mem
for {
if v_0.Op != OpLoad {
break
}
mem := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpOffPtr {
break
}
c := auxIntToInt64(v_0_0.AuxInt)
v_0_0_0 := v_0_0.Args[0]
if v_0_0_0.Op != OpSP {
break
}
x := v_1
if mem != v_2 || !(isConstZero(x) && mem.Op == OpStaticCall && isSameSym(mem.Aux, "runtime.newobject") && c == config.ctxt.FixedFrameSize()+config.RegSize) {
break
}
v.copyOf(mem)
return true
}
// match: (Store (OffPtr (Load (OffPtr [c] (SP)) mem)) x mem)
// cond: isConstZero(x) && mem.Op == OpStaticCall && isSameSym(mem.Aux, "runtime.newobject") && c == config.ctxt.FixedFrameSize() + config.RegSize
// result: mem
for {
if v_0.Op != OpOffPtr {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpLoad {
break
}
mem := v_0_0.Args[1]
v_0_0_0 := v_0_0.Args[0]
if v_0_0_0.Op != OpOffPtr {
break
}
c := auxIntToInt64(v_0_0_0.AuxInt)
v_0_0_0_0 := v_0_0_0.Args[0]
if v_0_0_0_0.Op != OpSP {
break
}
x := v_1
if mem != v_2 || !(isConstZero(x) && mem.Op == OpStaticCall && isSameSym(mem.Aux, "runtime.newobject") && c == config.ctxt.FixedFrameSize()+config.RegSize) {
break
}
v.copyOf(mem)
return true
}
// match: (Store {t1} op1:(OffPtr [o1] p1) d1 m2:(Store {t2} op2:(OffPtr [0] p2) d2 m3:(Move [n] p3 _ mem)))
// cond: m2.Uses == 1 && m3.Uses == 1 && o1 == t2.Size() && n == t2.Size() + t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && clobber(m2, m3)
// result: (Store {t1} op1 d1 (Store {t2} op2 d2 mem))
for {
t1 := auxToType(v.Aux)
op1 := v_0
if op1.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op1.AuxInt)
p1 := op1.Args[0]
d1 := v_1
m2 := v_2
if m2.Op != OpStore {
break
}
t2 := auxToType(m2.Aux)
_ = m2.Args[2]
op2 := m2.Args[0]
if op2.Op != OpOffPtr || auxIntToInt64(op2.AuxInt) != 0 {
break
}
p2 := op2.Args[0]
d2 := m2.Args[1]
m3 := m2.Args[2]
if m3.Op != OpMove {
break
}
n := auxIntToInt64(m3.AuxInt)
mem := m3.Args[2]
p3 := m3.Args[0]
if !(m2.Uses == 1 && m3.Uses == 1 && o1 == t2.Size() && n == t2.Size()+t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && clobber(m2, m3)) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t1)
v0 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v0.Aux = typeToAux(t2)
v0.AddArg3(op2, d2, mem)
v.AddArg3(op1, d1, v0)
return true
}
// match: (Store {t1} op1:(OffPtr [o1] p1) d1 m2:(Store {t2} op2:(OffPtr [o2] p2) d2 m3:(Store {t3} op3:(OffPtr [0] p3) d3 m4:(Move [n] p4 _ mem))))
// cond: m2.Uses == 1 && m3.Uses == 1 && m4.Uses == 1 && o2 == t3.Size() && o1-o2 == t2.Size() && n == t3.Size() + t2.Size() + t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && clobber(m2, m3, m4)
// result: (Store {t1} op1 d1 (Store {t2} op2 d2 (Store {t3} op3 d3 mem)))
for {
t1 := auxToType(v.Aux)
op1 := v_0
if op1.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op1.AuxInt)
p1 := op1.Args[0]
d1 := v_1
m2 := v_2
if m2.Op != OpStore {
break
}
t2 := auxToType(m2.Aux)
_ = m2.Args[2]
op2 := m2.Args[0]
if op2.Op != OpOffPtr {
break
}
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d2 := m2.Args[1]
m3 := m2.Args[2]
if m3.Op != OpStore {
break
}
t3 := auxToType(m3.Aux)
_ = m3.Args[2]
op3 := m3.Args[0]
if op3.Op != OpOffPtr || auxIntToInt64(op3.AuxInt) != 0 {
break
}
p3 := op3.Args[0]
d3 := m3.Args[1]
m4 := m3.Args[2]
if m4.Op != OpMove {
break
}
n := auxIntToInt64(m4.AuxInt)
mem := m4.Args[2]
p4 := m4.Args[0]
if !(m2.Uses == 1 && m3.Uses == 1 && m4.Uses == 1 && o2 == t3.Size() && o1-o2 == t2.Size() && n == t3.Size()+t2.Size()+t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && clobber(m2, m3, m4)) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t1)
v0 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v0.Aux = typeToAux(t2)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v1.AddArg3(op3, d3, mem)
v0.AddArg3(op2, d2, v1)
v.AddArg3(op1, d1, v0)
return true
}
// match: (Store {t1} op1:(OffPtr [o1] p1) d1 m2:(Store {t2} op2:(OffPtr [o2] p2) d2 m3:(Store {t3} op3:(OffPtr [o3] p3) d3 m4:(Store {t4} op4:(OffPtr [0] p4) d4 m5:(Move [n] p5 _ mem)))))
// cond: m2.Uses == 1 && m3.Uses == 1 && m4.Uses == 1 && m5.Uses == 1 && o3 == t4.Size() && o2-o3 == t3.Size() && o1-o2 == t2.Size() && n == t4.Size() + t3.Size() + t2.Size() + t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && clobber(m2, m3, m4, m5)
// result: (Store {t1} op1 d1 (Store {t2} op2 d2 (Store {t3} op3 d3 (Store {t4} op4 d4 mem))))
for {
t1 := auxToType(v.Aux)
op1 := v_0
if op1.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op1.AuxInt)
p1 := op1.Args[0]
d1 := v_1
m2 := v_2
if m2.Op != OpStore {
break
}
t2 := auxToType(m2.Aux)
_ = m2.Args[2]
op2 := m2.Args[0]
if op2.Op != OpOffPtr {
break
}
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d2 := m2.Args[1]
m3 := m2.Args[2]
if m3.Op != OpStore {
break
}
t3 := auxToType(m3.Aux)
_ = m3.Args[2]
op3 := m3.Args[0]
if op3.Op != OpOffPtr {
break
}
o3 := auxIntToInt64(op3.AuxInt)
p3 := op3.Args[0]
d3 := m3.Args[1]
m4 := m3.Args[2]
if m4.Op != OpStore {
break
}
t4 := auxToType(m4.Aux)
_ = m4.Args[2]
op4 := m4.Args[0]
if op4.Op != OpOffPtr || auxIntToInt64(op4.AuxInt) != 0 {
break
}
p4 := op4.Args[0]
d4 := m4.Args[1]
m5 := m4.Args[2]
if m5.Op != OpMove {
break
}
n := auxIntToInt64(m5.AuxInt)
mem := m5.Args[2]
p5 := m5.Args[0]
if !(m2.Uses == 1 && m3.Uses == 1 && m4.Uses == 1 && m5.Uses == 1 && o3 == t4.Size() && o2-o3 == t3.Size() && o1-o2 == t2.Size() && n == t4.Size()+t3.Size()+t2.Size()+t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && clobber(m2, m3, m4, m5)) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t1)
v0 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v0.Aux = typeToAux(t2)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v2.Aux = typeToAux(t4)
v2.AddArg3(op4, d4, mem)
v1.AddArg3(op3, d3, v2)
v0.AddArg3(op2, d2, v1)
v.AddArg3(op1, d1, v0)
return true
}
// match: (Store {t1} op1:(OffPtr [o1] p1) d1 m2:(Store {t2} op2:(OffPtr [0] p2) d2 m3:(Zero [n] p3 mem)))
// cond: m2.Uses == 1 && m3.Uses == 1 && o1 == t2.Size() && n == t2.Size() + t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && clobber(m2, m3)
// result: (Store {t1} op1 d1 (Store {t2} op2 d2 mem))
for {
t1 := auxToType(v.Aux)
op1 := v_0
if op1.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op1.AuxInt)
p1 := op1.Args[0]
d1 := v_1
m2 := v_2
if m2.Op != OpStore {
break
}
t2 := auxToType(m2.Aux)
_ = m2.Args[2]
op2 := m2.Args[0]
if op2.Op != OpOffPtr || auxIntToInt64(op2.AuxInt) != 0 {
break
}
p2 := op2.Args[0]
d2 := m2.Args[1]
m3 := m2.Args[2]
if m3.Op != OpZero {
break
}
n := auxIntToInt64(m3.AuxInt)
mem := m3.Args[1]
p3 := m3.Args[0]
if !(m2.Uses == 1 && m3.Uses == 1 && o1 == t2.Size() && n == t2.Size()+t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && clobber(m2, m3)) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t1)
v0 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v0.Aux = typeToAux(t2)
v0.AddArg3(op2, d2, mem)
v.AddArg3(op1, d1, v0)
return true
}
// match: (Store {t1} op1:(OffPtr [o1] p1) d1 m2:(Store {t2} op2:(OffPtr [o2] p2) d2 m3:(Store {t3} op3:(OffPtr [0] p3) d3 m4:(Zero [n] p4 mem))))
// cond: m2.Uses == 1 && m3.Uses == 1 && m4.Uses == 1 && o2 == t3.Size() && o1-o2 == t2.Size() && n == t3.Size() + t2.Size() + t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && clobber(m2, m3, m4)
// result: (Store {t1} op1 d1 (Store {t2} op2 d2 (Store {t3} op3 d3 mem)))
for {
t1 := auxToType(v.Aux)
op1 := v_0
if op1.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op1.AuxInt)
p1 := op1.Args[0]
d1 := v_1
m2 := v_2
if m2.Op != OpStore {
break
}
t2 := auxToType(m2.Aux)
_ = m2.Args[2]
op2 := m2.Args[0]
if op2.Op != OpOffPtr {
break
}
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d2 := m2.Args[1]
m3 := m2.Args[2]
if m3.Op != OpStore {
break
}
t3 := auxToType(m3.Aux)
_ = m3.Args[2]
op3 := m3.Args[0]
if op3.Op != OpOffPtr || auxIntToInt64(op3.AuxInt) != 0 {
break
}
p3 := op3.Args[0]
d3 := m3.Args[1]
m4 := m3.Args[2]
if m4.Op != OpZero {
break
}
n := auxIntToInt64(m4.AuxInt)
mem := m4.Args[1]
p4 := m4.Args[0]
if !(m2.Uses == 1 && m3.Uses == 1 && m4.Uses == 1 && o2 == t3.Size() && o1-o2 == t2.Size() && n == t3.Size()+t2.Size()+t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && clobber(m2, m3, m4)) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t1)
v0 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v0.Aux = typeToAux(t2)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v1.AddArg3(op3, d3, mem)
v0.AddArg3(op2, d2, v1)
v.AddArg3(op1, d1, v0)
return true
}
// match: (Store {t1} op1:(OffPtr [o1] p1) d1 m2:(Store {t2} op2:(OffPtr [o2] p2) d2 m3:(Store {t3} op3:(OffPtr [o3] p3) d3 m4:(Store {t4} op4:(OffPtr [0] p4) d4 m5:(Zero [n] p5 mem)))))
// cond: m2.Uses == 1 && m3.Uses == 1 && m4.Uses == 1 && m5.Uses == 1 && o3 == t4.Size() && o2-o3 == t3.Size() && o1-o2 == t2.Size() && n == t4.Size() + t3.Size() + t2.Size() + t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && clobber(m2, m3, m4, m5)
// result: (Store {t1} op1 d1 (Store {t2} op2 d2 (Store {t3} op3 d3 (Store {t4} op4 d4 mem))))
for {
t1 := auxToType(v.Aux)
op1 := v_0
if op1.Op != OpOffPtr {
break
}
o1 := auxIntToInt64(op1.AuxInt)
p1 := op1.Args[0]
d1 := v_1
m2 := v_2
if m2.Op != OpStore {
break
}
t2 := auxToType(m2.Aux)
_ = m2.Args[2]
op2 := m2.Args[0]
if op2.Op != OpOffPtr {
break
}
o2 := auxIntToInt64(op2.AuxInt)
p2 := op2.Args[0]
d2 := m2.Args[1]
m3 := m2.Args[2]
if m3.Op != OpStore {
break
}
t3 := auxToType(m3.Aux)
_ = m3.Args[2]
op3 := m3.Args[0]
if op3.Op != OpOffPtr {
break
}
o3 := auxIntToInt64(op3.AuxInt)
p3 := op3.Args[0]
d3 := m3.Args[1]
m4 := m3.Args[2]
if m4.Op != OpStore {
break
}
t4 := auxToType(m4.Aux)
_ = m4.Args[2]
op4 := m4.Args[0]
if op4.Op != OpOffPtr || auxIntToInt64(op4.AuxInt) != 0 {
break
}
p4 := op4.Args[0]
d4 := m4.Args[1]
m5 := m4.Args[2]
if m5.Op != OpZero {
break
}
n := auxIntToInt64(m5.AuxInt)
mem := m5.Args[1]
p5 := m5.Args[0]
if !(m2.Uses == 1 && m3.Uses == 1 && m4.Uses == 1 && m5.Uses == 1 && o3 == t4.Size() && o2-o3 == t3.Size() && o1-o2 == t2.Size() && n == t4.Size()+t3.Size()+t2.Size()+t1.Size() && isSamePtr(p1, p2) && isSamePtr(p2, p3) && isSamePtr(p3, p4) && isSamePtr(p4, p5) && clobber(m2, m3, m4, m5)) {
break
}
v.reset(OpStore)
v.Aux = typeToAux(t1)
v0 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v0.Aux = typeToAux(t2)
v1 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v1.Aux = typeToAux(t3)
v2 := b.NewValue0(v.Pos, OpStore, types.TypeMem)
v2.Aux = typeToAux(t4)
v2.AddArg3(op4, d4, mem)
v1.AddArg3(op3, d3, v2)
v0.AddArg3(op2, d2, v1)
v.AddArg3(op1, d1, v0)
return true
}
return false
}
func rewriteValuegeneric_OpStringLen(v *Value) bool {
v_0 := v.Args[0]
// match: (StringLen (StringMake _ (Const64 <t> [c])))
// result: (Const64 <t> [c])
for {
if v_0.Op != OpStringMake {
break
}
_ = v_0.Args[1]
v_0_1 := v_0.Args[1]
if v_0_1.Op != OpConst64 {
break
}
t := v_0_1.Type
c := auxIntToInt64(v_0_1.AuxInt)
v.reset(OpConst64)
v.Type = t
v.AuxInt = int64ToAuxInt(c)
return true
}
return false
}
func rewriteValuegeneric_OpStringPtr(v *Value) bool {
v_0 := v.Args[0]
// match: (StringPtr (StringMake (Addr <t> {s} base) _))
// result: (Addr <t> {s} base)
for {
if v_0.Op != OpStringMake {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAddr {
break
}
t := v_0_0.Type
s := auxToSym(v_0_0.Aux)
base := v_0_0.Args[0]
v.reset(OpAddr)
v.Type = t
v.Aux = symToAux(s)
v.AddArg(base)
return true
}
return false
}
func rewriteValuegeneric_OpStructSelect(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
fe := b.Func.fe
// match: (StructSelect (StructMake1 x))
// result: x
for {
if v_0.Op != OpStructMake1 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (StructSelect [0] (StructMake2 x _))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 0 || v_0.Op != OpStructMake2 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (StructSelect [1] (StructMake2 _ x))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 1 || v_0.Op != OpStructMake2 {
break
}
x := v_0.Args[1]
v.copyOf(x)
return true
}
// match: (StructSelect [0] (StructMake3 x _ _))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 0 || v_0.Op != OpStructMake3 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (StructSelect [1] (StructMake3 _ x _))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 1 || v_0.Op != OpStructMake3 {
break
}
x := v_0.Args[1]
v.copyOf(x)
return true
}
// match: (StructSelect [2] (StructMake3 _ _ x))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 2 || v_0.Op != OpStructMake3 {
break
}
x := v_0.Args[2]
v.copyOf(x)
return true
}
// match: (StructSelect [0] (StructMake4 x _ _ _))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 0 || v_0.Op != OpStructMake4 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (StructSelect [1] (StructMake4 _ x _ _))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 1 || v_0.Op != OpStructMake4 {
break
}
x := v_0.Args[1]
v.copyOf(x)
return true
}
// match: (StructSelect [2] (StructMake4 _ _ x _))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 2 || v_0.Op != OpStructMake4 {
break
}
x := v_0.Args[2]
v.copyOf(x)
return true
}
// match: (StructSelect [3] (StructMake4 _ _ _ x))
// result: x
for {
if auxIntToInt64(v.AuxInt) != 3 || v_0.Op != OpStructMake4 {
break
}
x := v_0.Args[3]
v.copyOf(x)
return true
}
// match: (StructSelect [i] x:(Load <t> ptr mem))
// cond: !fe.CanSSA(t)
// result: @x.Block (Load <v.Type> (OffPtr <v.Type.PtrTo()> [t.FieldOff(int(i))] ptr) mem)
for {
i := auxIntToInt64(v.AuxInt)
x := v_0
if x.Op != OpLoad {
break
}
t := x.Type
mem := x.Args[1]
ptr := x.Args[0]
if !(!fe.CanSSA(t)) {
break
}
b = x.Block
v0 := b.NewValue0(v.Pos, OpLoad, v.Type)
v.copyOf(v0)
v1 := b.NewValue0(v.Pos, OpOffPtr, v.Type.PtrTo())
v1.AuxInt = int64ToAuxInt(t.FieldOff(int(i)))
v1.AddArg(ptr)
v0.AddArg2(v1, mem)
return true
}
// match: (StructSelect [0] (IData x))
// result: (IData x)
for {
if auxIntToInt64(v.AuxInt) != 0 || v_0.Op != OpIData {
break
}
x := v_0.Args[0]
v.reset(OpIData)
v.AddArg(x)
return true
}
return false
}
func rewriteValuegeneric_OpSub16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Sub16 (Const16 [c]) (Const16 [d]))
// result: (Const16 [c-d])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
break
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c - d)
return true
}
// match: (Sub16 x (Const16 <t> [c]))
// cond: x.Op != OpConst16
// result: (Add16 (Const16 <t> [-c]) x)
for {
x := v_0
if v_1.Op != OpConst16 {
break
}
t := v_1.Type
c := auxIntToInt16(v_1.AuxInt)
if !(x.Op != OpConst16) {
break
}
v.reset(OpAdd16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(-c)
v.AddArg2(v0, x)
return true
}
// match: (Sub16 <t> (Mul16 x y) (Mul16 x z))
// result: (Mul16 x (Sub16 <t> y z))
for {
t := v.Type
if v_0.Op != OpMul16 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if v_1.Op != OpMul16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
z := v_1_1
v.reset(OpMul16)
v0 := b.NewValue0(v.Pos, OpSub16, t)
v0.AddArg2(y, z)
v.AddArg2(x, v0)
return true
}
}
break
}
// match: (Sub16 x x)
// result: (Const16 [0])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
// match: (Sub16 (Add16 x y) x)
// result: y
for {
if v_0.Op != OpAdd16 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if x != v_1 {
continue
}
v.copyOf(y)
return true
}
break
}
// match: (Sub16 (Add16 x y) y)
// result: x
for {
if v_0.Op != OpAdd16 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if y != v_1 {
continue
}
v.copyOf(x)
return true
}
break
}
// match: (Sub16 x (Sub16 i:(Const16 <t>) z))
// cond: (z.Op != OpConst16 && x.Op != OpConst16)
// result: (Sub16 (Add16 <t> x z) i)
for {
x := v_0
if v_1.Op != OpSub16 {
break
}
z := v_1.Args[1]
i := v_1.Args[0]
if i.Op != OpConst16 {
break
}
t := i.Type
if !(z.Op != OpConst16 && x.Op != OpConst16) {
break
}
v.reset(OpSub16)
v0 := b.NewValue0(v.Pos, OpAdd16, t)
v0.AddArg2(x, z)
v.AddArg2(v0, i)
return true
}
// match: (Sub16 x (Sub16 z i:(Const16 <t>)))
// cond: (z.Op != OpConst16 && x.Op != OpConst16)
// result: (Add16 i (Sub16 <t> x z))
for {
x := v_0
if v_1.Op != OpSub16 {
break
}
_ = v_1.Args[1]
z := v_1.Args[0]
i := v_1.Args[1]
if i.Op != OpConst16 {
break
}
t := i.Type
if !(z.Op != OpConst16 && x.Op != OpConst16) {
break
}
v.reset(OpAdd16)
v0 := b.NewValue0(v.Pos, OpSub16, t)
v0.AddArg2(x, z)
v.AddArg2(i, v0)
return true
}
// match: (Sub16 (Const16 <t> [c]) (Sub16 x (Const16 <t> [d])))
// result: (Sub16 (Const16 <t> [c+d]) x)
for {
if v_0.Op != OpConst16 {
break
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpSub16 {
break
}
_ = v_1.Args[1]
x := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst16 || v_1_1.Type != t {
break
}
d := auxIntToInt16(v_1_1.AuxInt)
v.reset(OpSub16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
// match: (Sub16 (Const16 <t> [c]) (Sub16 (Const16 <t> [d]) x))
// result: (Add16 (Const16 <t> [c-d]) x)
for {
if v_0.Op != OpConst16 {
break
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpSub16 {
break
}
x := v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
break
}
d := auxIntToInt16(v_1_0.AuxInt)
v.reset(OpAdd16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
return false
}
func rewriteValuegeneric_OpSub32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Sub32 (Const32 [c]) (Const32 [d]))
// result: (Const32 [c-d])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
break
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c - d)
return true
}
// match: (Sub32 x (Const32 <t> [c]))
// cond: x.Op != OpConst32
// result: (Add32 (Const32 <t> [-c]) x)
for {
x := v_0
if v_1.Op != OpConst32 {
break
}
t := v_1.Type
c := auxIntToInt32(v_1.AuxInt)
if !(x.Op != OpConst32) {
break
}
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(-c)
v.AddArg2(v0, x)
return true
}
// match: (Sub32 <t> (Mul32 x y) (Mul32 x z))
// result: (Mul32 x (Sub32 <t> y z))
for {
t := v.Type
if v_0.Op != OpMul32 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if v_1.Op != OpMul32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
z := v_1_1
v.reset(OpMul32)
v0 := b.NewValue0(v.Pos, OpSub32, t)
v0.AddArg2(y, z)
v.AddArg2(x, v0)
return true
}
}
break
}
// match: (Sub32 x x)
// result: (Const32 [0])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Sub32 (Add32 x y) x)
// result: y
for {
if v_0.Op != OpAdd32 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if x != v_1 {
continue
}
v.copyOf(y)
return true
}
break
}
// match: (Sub32 (Add32 x y) y)
// result: x
for {
if v_0.Op != OpAdd32 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if y != v_1 {
continue
}
v.copyOf(x)
return true
}
break
}
// match: (Sub32 x (Sub32 i:(Const32 <t>) z))
// cond: (z.Op != OpConst32 && x.Op != OpConst32)
// result: (Sub32 (Add32 <t> x z) i)
for {
x := v_0
if v_1.Op != OpSub32 {
break
}
z := v_1.Args[1]
i := v_1.Args[0]
if i.Op != OpConst32 {
break
}
t := i.Type
if !(z.Op != OpConst32 && x.Op != OpConst32) {
break
}
v.reset(OpSub32)
v0 := b.NewValue0(v.Pos, OpAdd32, t)
v0.AddArg2(x, z)
v.AddArg2(v0, i)
return true
}
// match: (Sub32 x (Sub32 z i:(Const32 <t>)))
// cond: (z.Op != OpConst32 && x.Op != OpConst32)
// result: (Add32 i (Sub32 <t> x z))
for {
x := v_0
if v_1.Op != OpSub32 {
break
}
_ = v_1.Args[1]
z := v_1.Args[0]
i := v_1.Args[1]
if i.Op != OpConst32 {
break
}
t := i.Type
if !(z.Op != OpConst32 && x.Op != OpConst32) {
break
}
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpSub32, t)
v0.AddArg2(x, z)
v.AddArg2(i, v0)
return true
}
// match: (Sub32 (Const32 <t> [c]) (Sub32 x (Const32 <t> [d])))
// result: (Sub32 (Const32 <t> [c+d]) x)
for {
if v_0.Op != OpConst32 {
break
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpSub32 {
break
}
_ = v_1.Args[1]
x := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst32 || v_1_1.Type != t {
break
}
d := auxIntToInt32(v_1_1.AuxInt)
v.reset(OpSub32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
// match: (Sub32 (Const32 <t> [c]) (Sub32 (Const32 <t> [d]) x))
// result: (Add32 (Const32 <t> [c-d]) x)
for {
if v_0.Op != OpConst32 {
break
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpSub32 {
break
}
x := v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
break
}
d := auxIntToInt32(v_1_0.AuxInt)
v.reset(OpAdd32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
return false
}
func rewriteValuegeneric_OpSub32F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Sub32F (Const32F [c]) (Const32F [d]))
// cond: c-d == c-d
// result: (Const32F [c-d])
for {
if v_0.Op != OpConst32F {
break
}
c := auxIntToFloat32(v_0.AuxInt)
if v_1.Op != OpConst32F {
break
}
d := auxIntToFloat32(v_1.AuxInt)
if !(c-d == c-d) {
break
}
v.reset(OpConst32F)
v.AuxInt = float32ToAuxInt(c - d)
return true
}
return false
}
func rewriteValuegeneric_OpSub64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Sub64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [c-d])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
break
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c - d)
return true
}
// match: (Sub64 x (Const64 <t> [c]))
// cond: x.Op != OpConst64
// result: (Add64 (Const64 <t> [-c]) x)
for {
x := v_0
if v_1.Op != OpConst64 {
break
}
t := v_1.Type
c := auxIntToInt64(v_1.AuxInt)
if !(x.Op != OpConst64) {
break
}
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(-c)
v.AddArg2(v0, x)
return true
}
// match: (Sub64 <t> (Mul64 x y) (Mul64 x z))
// result: (Mul64 x (Sub64 <t> y z))
for {
t := v.Type
if v_0.Op != OpMul64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if v_1.Op != OpMul64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
z := v_1_1
v.reset(OpMul64)
v0 := b.NewValue0(v.Pos, OpSub64, t)
v0.AddArg2(y, z)
v.AddArg2(x, v0)
return true
}
}
break
}
// match: (Sub64 x x)
// result: (Const64 [0])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Sub64 (Add64 x y) x)
// result: y
for {
if v_0.Op != OpAdd64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if x != v_1 {
continue
}
v.copyOf(y)
return true
}
break
}
// match: (Sub64 (Add64 x y) y)
// result: x
for {
if v_0.Op != OpAdd64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if y != v_1 {
continue
}
v.copyOf(x)
return true
}
break
}
// match: (Sub64 x (Sub64 i:(Const64 <t>) z))
// cond: (z.Op != OpConst64 && x.Op != OpConst64)
// result: (Sub64 (Add64 <t> x z) i)
for {
x := v_0
if v_1.Op != OpSub64 {
break
}
z := v_1.Args[1]
i := v_1.Args[0]
if i.Op != OpConst64 {
break
}
t := i.Type
if !(z.Op != OpConst64 && x.Op != OpConst64) {
break
}
v.reset(OpSub64)
v0 := b.NewValue0(v.Pos, OpAdd64, t)
v0.AddArg2(x, z)
v.AddArg2(v0, i)
return true
}
// match: (Sub64 x (Sub64 z i:(Const64 <t>)))
// cond: (z.Op != OpConst64 && x.Op != OpConst64)
// result: (Add64 i (Sub64 <t> x z))
for {
x := v_0
if v_1.Op != OpSub64 {
break
}
_ = v_1.Args[1]
z := v_1.Args[0]
i := v_1.Args[1]
if i.Op != OpConst64 {
break
}
t := i.Type
if !(z.Op != OpConst64 && x.Op != OpConst64) {
break
}
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpSub64, t)
v0.AddArg2(x, z)
v.AddArg2(i, v0)
return true
}
// match: (Sub64 (Const64 <t> [c]) (Sub64 x (Const64 <t> [d])))
// result: (Sub64 (Const64 <t> [c+d]) x)
for {
if v_0.Op != OpConst64 {
break
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpSub64 {
break
}
_ = v_1.Args[1]
x := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst64 || v_1_1.Type != t {
break
}
d := auxIntToInt64(v_1_1.AuxInt)
v.reset(OpSub64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
// match: (Sub64 (Const64 <t> [c]) (Sub64 (Const64 <t> [d]) x))
// result: (Add64 (Const64 <t> [c-d]) x)
for {
if v_0.Op != OpConst64 {
break
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpSub64 {
break
}
x := v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
break
}
d := auxIntToInt64(v_1_0.AuxInt)
v.reset(OpAdd64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
return false
}
func rewriteValuegeneric_OpSub64F(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
// match: (Sub64F (Const64F [c]) (Const64F [d]))
// cond: c-d == c-d
// result: (Const64F [c-d])
for {
if v_0.Op != OpConst64F {
break
}
c := auxIntToFloat64(v_0.AuxInt)
if v_1.Op != OpConst64F {
break
}
d := auxIntToFloat64(v_1.AuxInt)
if !(c-d == c-d) {
break
}
v.reset(OpConst64F)
v.AuxInt = float64ToAuxInt(c - d)
return true
}
return false
}
func rewriteValuegeneric_OpSub8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Sub8 (Const8 [c]) (Const8 [d]))
// result: (Const8 [c-d])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
break
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c - d)
return true
}
// match: (Sub8 x (Const8 <t> [c]))
// cond: x.Op != OpConst8
// result: (Add8 (Const8 <t> [-c]) x)
for {
x := v_0
if v_1.Op != OpConst8 {
break
}
t := v_1.Type
c := auxIntToInt8(v_1.AuxInt)
if !(x.Op != OpConst8) {
break
}
v.reset(OpAdd8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(-c)
v.AddArg2(v0, x)
return true
}
// match: (Sub8 <t> (Mul8 x y) (Mul8 x z))
// result: (Mul8 x (Sub8 <t> y z))
for {
t := v.Type
if v_0.Op != OpMul8 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if v_1.Op != OpMul8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
z := v_1_1
v.reset(OpMul8)
v0 := b.NewValue0(v.Pos, OpSub8, t)
v0.AddArg2(y, z)
v.AddArg2(x, v0)
return true
}
}
break
}
// match: (Sub8 x x)
// result: (Const8 [0])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (Sub8 (Add8 x y) x)
// result: y
for {
if v_0.Op != OpAdd8 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if x != v_1 {
continue
}
v.copyOf(y)
return true
}
break
}
// match: (Sub8 (Add8 x y) y)
// result: x
for {
if v_0.Op != OpAdd8 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
x := v_0_0
y := v_0_1
if y != v_1 {
continue
}
v.copyOf(x)
return true
}
break
}
// match: (Sub8 x (Sub8 i:(Const8 <t>) z))
// cond: (z.Op != OpConst8 && x.Op != OpConst8)
// result: (Sub8 (Add8 <t> x z) i)
for {
x := v_0
if v_1.Op != OpSub8 {
break
}
z := v_1.Args[1]
i := v_1.Args[0]
if i.Op != OpConst8 {
break
}
t := i.Type
if !(z.Op != OpConst8 && x.Op != OpConst8) {
break
}
v.reset(OpSub8)
v0 := b.NewValue0(v.Pos, OpAdd8, t)
v0.AddArg2(x, z)
v.AddArg2(v0, i)
return true
}
// match: (Sub8 x (Sub8 z i:(Const8 <t>)))
// cond: (z.Op != OpConst8 && x.Op != OpConst8)
// result: (Add8 i (Sub8 <t> x z))
for {
x := v_0
if v_1.Op != OpSub8 {
break
}
_ = v_1.Args[1]
z := v_1.Args[0]
i := v_1.Args[1]
if i.Op != OpConst8 {
break
}
t := i.Type
if !(z.Op != OpConst8 && x.Op != OpConst8) {
break
}
v.reset(OpAdd8)
v0 := b.NewValue0(v.Pos, OpSub8, t)
v0.AddArg2(x, z)
v.AddArg2(i, v0)
return true
}
// match: (Sub8 (Const8 <t> [c]) (Sub8 x (Const8 <t> [d])))
// result: (Sub8 (Const8 <t> [c+d]) x)
for {
if v_0.Op != OpConst8 {
break
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpSub8 {
break
}
_ = v_1.Args[1]
x := v_1.Args[0]
v_1_1 := v_1.Args[1]
if v_1_1.Op != OpConst8 || v_1_1.Type != t {
break
}
d := auxIntToInt8(v_1_1.AuxInt)
v.reset(OpSub8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c + d)
v.AddArg2(v0, x)
return true
}
// match: (Sub8 (Const8 <t> [c]) (Sub8 (Const8 <t> [d]) x))
// result: (Add8 (Const8 <t> [c-d]) x)
for {
if v_0.Op != OpConst8 {
break
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpSub8 {
break
}
x := v_1.Args[1]
v_1_0 := v_1.Args[0]
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
break
}
d := auxIntToInt8(v_1_0.AuxInt)
v.reset(OpAdd8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c - d)
v.AddArg2(v0, x)
return true
}
return false
}
func rewriteValuegeneric_OpTrunc16to8(v *Value) bool {
v_0 := v.Args[0]
// match: (Trunc16to8 (Const16 [c]))
// result: (Const8 [int8(c)])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(int8(c))
return true
}
// match: (Trunc16to8 (ZeroExt8to16 x))
// result: x
for {
if v_0.Op != OpZeroExt8to16 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc16to8 (SignExt8to16 x))
// result: x
for {
if v_0.Op != OpSignExt8to16 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc16to8 (And16 (Const16 [y]) x))
// cond: y&0xFF == 0xFF
// result: (Trunc16to8 x)
for {
if v_0.Op != OpAnd16 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst16 {
continue
}
y := auxIntToInt16(v_0_0.AuxInt)
x := v_0_1
if !(y&0xFF == 0xFF) {
continue
}
v.reset(OpTrunc16to8)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpTrunc32to16(v *Value) bool {
v_0 := v.Args[0]
// match: (Trunc32to16 (Const32 [c]))
// result: (Const16 [int16(c)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(int16(c))
return true
}
// match: (Trunc32to16 (ZeroExt8to32 x))
// result: (ZeroExt8to16 x)
for {
if v_0.Op != OpZeroExt8to32 {
break
}
x := v_0.Args[0]
v.reset(OpZeroExt8to16)
v.AddArg(x)
return true
}
// match: (Trunc32to16 (ZeroExt16to32 x))
// result: x
for {
if v_0.Op != OpZeroExt16to32 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc32to16 (SignExt8to32 x))
// result: (SignExt8to16 x)
for {
if v_0.Op != OpSignExt8to32 {
break
}
x := v_0.Args[0]
v.reset(OpSignExt8to16)
v.AddArg(x)
return true
}
// match: (Trunc32to16 (SignExt16to32 x))
// result: x
for {
if v_0.Op != OpSignExt16to32 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc32to16 (And32 (Const32 [y]) x))
// cond: y&0xFFFF == 0xFFFF
// result: (Trunc32to16 x)
for {
if v_0.Op != OpAnd32 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst32 {
continue
}
y := auxIntToInt32(v_0_0.AuxInt)
x := v_0_1
if !(y&0xFFFF == 0xFFFF) {
continue
}
v.reset(OpTrunc32to16)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpTrunc32to8(v *Value) bool {
v_0 := v.Args[0]
// match: (Trunc32to8 (Const32 [c]))
// result: (Const8 [int8(c)])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(int8(c))
return true
}
// match: (Trunc32to8 (ZeroExt8to32 x))
// result: x
for {
if v_0.Op != OpZeroExt8to32 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc32to8 (SignExt8to32 x))
// result: x
for {
if v_0.Op != OpSignExt8to32 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc32to8 (And32 (Const32 [y]) x))
// cond: y&0xFF == 0xFF
// result: (Trunc32to8 x)
for {
if v_0.Op != OpAnd32 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst32 {
continue
}
y := auxIntToInt32(v_0_0.AuxInt)
x := v_0_1
if !(y&0xFF == 0xFF) {
continue
}
v.reset(OpTrunc32to8)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpTrunc64to16(v *Value) bool {
v_0 := v.Args[0]
// match: (Trunc64to16 (Const64 [c]))
// result: (Const16 [int16(c)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(int16(c))
return true
}
// match: (Trunc64to16 (ZeroExt8to64 x))
// result: (ZeroExt8to16 x)
for {
if v_0.Op != OpZeroExt8to64 {
break
}
x := v_0.Args[0]
v.reset(OpZeroExt8to16)
v.AddArg(x)
return true
}
// match: (Trunc64to16 (ZeroExt16to64 x))
// result: x
for {
if v_0.Op != OpZeroExt16to64 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc64to16 (SignExt8to64 x))
// result: (SignExt8to16 x)
for {
if v_0.Op != OpSignExt8to64 {
break
}
x := v_0.Args[0]
v.reset(OpSignExt8to16)
v.AddArg(x)
return true
}
// match: (Trunc64to16 (SignExt16to64 x))
// result: x
for {
if v_0.Op != OpSignExt16to64 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc64to16 (And64 (Const64 [y]) x))
// cond: y&0xFFFF == 0xFFFF
// result: (Trunc64to16 x)
for {
if v_0.Op != OpAnd64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst64 {
continue
}
y := auxIntToInt64(v_0_0.AuxInt)
x := v_0_1
if !(y&0xFFFF == 0xFFFF) {
continue
}
v.reset(OpTrunc64to16)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpTrunc64to32(v *Value) bool {
v_0 := v.Args[0]
// match: (Trunc64to32 (Const64 [c]))
// result: (Const32 [int32(c)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(c))
return true
}
// match: (Trunc64to32 (ZeroExt8to64 x))
// result: (ZeroExt8to32 x)
for {
if v_0.Op != OpZeroExt8to64 {
break
}
x := v_0.Args[0]
v.reset(OpZeroExt8to32)
v.AddArg(x)
return true
}
// match: (Trunc64to32 (ZeroExt16to64 x))
// result: (ZeroExt16to32 x)
for {
if v_0.Op != OpZeroExt16to64 {
break
}
x := v_0.Args[0]
v.reset(OpZeroExt16to32)
v.AddArg(x)
return true
}
// match: (Trunc64to32 (ZeroExt32to64 x))
// result: x
for {
if v_0.Op != OpZeroExt32to64 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc64to32 (SignExt8to64 x))
// result: (SignExt8to32 x)
for {
if v_0.Op != OpSignExt8to64 {
break
}
x := v_0.Args[0]
v.reset(OpSignExt8to32)
v.AddArg(x)
return true
}
// match: (Trunc64to32 (SignExt16to64 x))
// result: (SignExt16to32 x)
for {
if v_0.Op != OpSignExt16to64 {
break
}
x := v_0.Args[0]
v.reset(OpSignExt16to32)
v.AddArg(x)
return true
}
// match: (Trunc64to32 (SignExt32to64 x))
// result: x
for {
if v_0.Op != OpSignExt32to64 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc64to32 (And64 (Const64 [y]) x))
// cond: y&0xFFFFFFFF == 0xFFFFFFFF
// result: (Trunc64to32 x)
for {
if v_0.Op != OpAnd64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst64 {
continue
}
y := auxIntToInt64(v_0_0.AuxInt)
x := v_0_1
if !(y&0xFFFFFFFF == 0xFFFFFFFF) {
continue
}
v.reset(OpTrunc64to32)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpTrunc64to8(v *Value) bool {
v_0 := v.Args[0]
// match: (Trunc64to8 (Const64 [c]))
// result: (Const8 [int8(c)])
for {
if v_0.Op != OpConst64 {
break
}
c := auxIntToInt64(v_0.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(int8(c))
return true
}
// match: (Trunc64to8 (ZeroExt8to64 x))
// result: x
for {
if v_0.Op != OpZeroExt8to64 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc64to8 (SignExt8to64 x))
// result: x
for {
if v_0.Op != OpSignExt8to64 {
break
}
x := v_0.Args[0]
v.copyOf(x)
return true
}
// match: (Trunc64to8 (And64 (Const64 [y]) x))
// cond: y&0xFF == 0xFF
// result: (Trunc64to8 x)
for {
if v_0.Op != OpAnd64 {
break
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i0 := 0; _i0 <= 1; _i0, v_0_0, v_0_1 = _i0+1, v_0_1, v_0_0 {
if v_0_0.Op != OpConst64 {
continue
}
y := auxIntToInt64(v_0_0.AuxInt)
x := v_0_1
if !(y&0xFF == 0xFF) {
continue
}
v.reset(OpTrunc64to8)
v.AddArg(x)
return true
}
break
}
return false
}
func rewriteValuegeneric_OpXor16(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Xor16 (Const16 [c]) (Const16 [d]))
// result: (Const16 [c^d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpConst16 {
continue
}
d := auxIntToInt16(v_1.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(c ^ d)
return true
}
break
}
// match: (Xor16 x x)
// result: (Const16 [0])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(0)
return true
}
// match: (Xor16 (Const16 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 || auxIntToInt16(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Xor16 x (Xor16 x y))
// result: y
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpXor16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.copyOf(y)
return true
}
}
break
}
// match: (Xor16 (Xor16 i:(Const16 <t>) z) x)
// cond: (z.Op != OpConst16 && x.Op != OpConst16)
// result: (Xor16 i (Xor16 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpXor16 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst16 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst16 && x.Op != OpConst16) {
continue
}
v.reset(OpXor16)
v0 := b.NewValue0(v.Pos, OpXor16, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Xor16 (Const16 <t> [c]) (Xor16 (Const16 <t> [d]) x))
// result: (Xor16 (Const16 <t> [c^d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst16 {
continue
}
t := v_0.Type
c := auxIntToInt16(v_0.AuxInt)
if v_1.Op != OpXor16 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst16 || v_1_0.Type != t {
continue
}
d := auxIntToInt16(v_1_0.AuxInt)
x := v_1_1
v.reset(OpXor16)
v0 := b.NewValue0(v.Pos, OpConst16, t)
v0.AuxInt = int16ToAuxInt(c ^ d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpXor32(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Xor32 (Const32 [c]) (Const32 [d]))
// result: (Const32 [c^d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpConst32 {
continue
}
d := auxIntToInt32(v_1.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(c ^ d)
return true
}
break
}
// match: (Xor32 x x)
// result: (Const32 [0])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(0)
return true
}
// match: (Xor32 (Const32 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 || auxIntToInt32(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Xor32 x (Xor32 x y))
// result: y
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpXor32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.copyOf(y)
return true
}
}
break
}
// match: (Xor32 (Xor32 i:(Const32 <t>) z) x)
// cond: (z.Op != OpConst32 && x.Op != OpConst32)
// result: (Xor32 i (Xor32 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpXor32 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst32 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst32 && x.Op != OpConst32) {
continue
}
v.reset(OpXor32)
v0 := b.NewValue0(v.Pos, OpXor32, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Xor32 (Const32 <t> [c]) (Xor32 (Const32 <t> [d]) x))
// result: (Xor32 (Const32 <t> [c^d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst32 {
continue
}
t := v_0.Type
c := auxIntToInt32(v_0.AuxInt)
if v_1.Op != OpXor32 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst32 || v_1_0.Type != t {
continue
}
d := auxIntToInt32(v_1_0.AuxInt)
x := v_1_1
v.reset(OpXor32)
v0 := b.NewValue0(v.Pos, OpConst32, t)
v0.AuxInt = int32ToAuxInt(c ^ d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpXor64(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Xor64 (Const64 [c]) (Const64 [d]))
// result: (Const64 [c^d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpConst64 {
continue
}
d := auxIntToInt64(v_1.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(c ^ d)
return true
}
break
}
// match: (Xor64 x x)
// result: (Const64 [0])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(0)
return true
}
// match: (Xor64 (Const64 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 || auxIntToInt64(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Xor64 x (Xor64 x y))
// result: y
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpXor64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.copyOf(y)
return true
}
}
break
}
// match: (Xor64 (Xor64 i:(Const64 <t>) z) x)
// cond: (z.Op != OpConst64 && x.Op != OpConst64)
// result: (Xor64 i (Xor64 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpXor64 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst64 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst64 && x.Op != OpConst64) {
continue
}
v.reset(OpXor64)
v0 := b.NewValue0(v.Pos, OpXor64, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Xor64 (Const64 <t> [c]) (Xor64 (Const64 <t> [d]) x))
// result: (Xor64 (Const64 <t> [c^d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst64 {
continue
}
t := v_0.Type
c := auxIntToInt64(v_0.AuxInt)
if v_1.Op != OpXor64 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst64 || v_1_0.Type != t {
continue
}
d := auxIntToInt64(v_1_0.AuxInt)
x := v_1_1
v.reset(OpXor64)
v0 := b.NewValue0(v.Pos, OpConst64, t)
v0.AuxInt = int64ToAuxInt(c ^ d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpXor8(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
// match: (Xor8 (Const8 [c]) (Const8 [d]))
// result: (Const8 [c^d])
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpConst8 {
continue
}
d := auxIntToInt8(v_1.AuxInt)
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(c ^ d)
return true
}
break
}
// match: (Xor8 x x)
// result: (Const8 [0])
for {
x := v_0
if x != v_1 {
break
}
v.reset(OpConst8)
v.AuxInt = int8ToAuxInt(0)
return true
}
// match: (Xor8 (Const8 [0]) x)
// result: x
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 || auxIntToInt8(v_0.AuxInt) != 0 {
continue
}
x := v_1
v.copyOf(x)
return true
}
break
}
// match: (Xor8 x (Xor8 x y))
// result: y
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
x := v_0
if v_1.Op != OpXor8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if x != v_1_0 {
continue
}
y := v_1_1
v.copyOf(y)
return true
}
}
break
}
// match: (Xor8 (Xor8 i:(Const8 <t>) z) x)
// cond: (z.Op != OpConst8 && x.Op != OpConst8)
// result: (Xor8 i (Xor8 <t> z x))
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpXor8 {
continue
}
_ = v_0.Args[1]
v_0_0 := v_0.Args[0]
v_0_1 := v_0.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_0_0, v_0_1 = _i1+1, v_0_1, v_0_0 {
i := v_0_0
if i.Op != OpConst8 {
continue
}
t := i.Type
z := v_0_1
x := v_1
if !(z.Op != OpConst8 && x.Op != OpConst8) {
continue
}
v.reset(OpXor8)
v0 := b.NewValue0(v.Pos, OpXor8, t)
v0.AddArg2(z, x)
v.AddArg2(i, v0)
return true
}
}
break
}
// match: (Xor8 (Const8 <t> [c]) (Xor8 (Const8 <t> [d]) x))
// result: (Xor8 (Const8 <t> [c^d]) x)
for {
for _i0 := 0; _i0 <= 1; _i0, v_0, v_1 = _i0+1, v_1, v_0 {
if v_0.Op != OpConst8 {
continue
}
t := v_0.Type
c := auxIntToInt8(v_0.AuxInt)
if v_1.Op != OpXor8 {
continue
}
_ = v_1.Args[1]
v_1_0 := v_1.Args[0]
v_1_1 := v_1.Args[1]
for _i1 := 0; _i1 <= 1; _i1, v_1_0, v_1_1 = _i1+1, v_1_1, v_1_0 {
if v_1_0.Op != OpConst8 || v_1_0.Type != t {
continue
}
d := auxIntToInt8(v_1_0.AuxInt)
x := v_1_1
v.reset(OpXor8)
v0 := b.NewValue0(v.Pos, OpConst8, t)
v0.AuxInt = int8ToAuxInt(c ^ d)
v.AddArg2(v0, x)
return true
}
}
break
}
return false
}
func rewriteValuegeneric_OpZero(v *Value) bool {
v_1 := v.Args[1]
v_0 := v.Args[0]
b := v.Block
config := b.Func.Config
// match: (Zero (Load (OffPtr [c] (SP)) mem) mem)
// cond: mem.Op == OpStaticCall && isSameSym(mem.Aux, "runtime.newobject") && c == config.ctxt.FixedFrameSize() + config.RegSize
// result: mem
for {
if v_0.Op != OpLoad {
break
}
mem := v_0.Args[1]
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpOffPtr {
break
}
c := auxIntToInt64(v_0_0.AuxInt)
v_0_0_0 := v_0_0.Args[0]
if v_0_0_0.Op != OpSP || mem != v_1 || !(mem.Op == OpStaticCall && isSameSym(mem.Aux, "runtime.newobject") && c == config.ctxt.FixedFrameSize()+config.RegSize) {
break
}
v.copyOf(mem)
return true
}
// match: (Zero {t1} [n] p1 store:(Store {t2} (OffPtr [o2] p2) _ mem))
// cond: isSamePtr(p1, p2) && store.Uses == 1 && n >= o2 + t2.Size() && clobber(store)
// result: (Zero {t1} [n] p1 mem)
for {
n := auxIntToInt64(v.AuxInt)
t1 := auxToType(v.Aux)
p1 := v_0
store := v_1
if store.Op != OpStore {
break
}
t2 := auxToType(store.Aux)
mem := store.Args[2]
store_0 := store.Args[0]
if store_0.Op != OpOffPtr {
break
}
o2 := auxIntToInt64(store_0.AuxInt)
p2 := store_0.Args[0]
if !(isSamePtr(p1, p2) && store.Uses == 1 && n >= o2+t2.Size() && clobber(store)) {
break
}
v.reset(OpZero)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t1)
v.AddArg2(p1, mem)
return true
}
// match: (Zero {t} [n] dst1 move:(Move {t} [n] dst2 _ mem))
// cond: move.Uses == 1 && isSamePtr(dst1, dst2) && clobber(move)
// result: (Zero {t} [n] dst1 mem)
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
move := v_1
if move.Op != OpMove || auxIntToInt64(move.AuxInt) != n || auxToType(move.Aux) != t {
break
}
mem := move.Args[2]
dst2 := move.Args[0]
if !(move.Uses == 1 && isSamePtr(dst1, dst2) && clobber(move)) {
break
}
v.reset(OpZero)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v.AddArg2(dst1, mem)
return true
}
// match: (Zero {t} [n] dst1 vardef:(VarDef {x} move:(Move {t} [n] dst2 _ mem)))
// cond: move.Uses == 1 && vardef.Uses == 1 && isSamePtr(dst1, dst2) && clobber(move, vardef)
// result: (Zero {t} [n] dst1 (VarDef {x} mem))
for {
n := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
vardef := v_1
if vardef.Op != OpVarDef {
break
}
x := auxToSym(vardef.Aux)
move := vardef.Args[0]
if move.Op != OpMove || auxIntToInt64(move.AuxInt) != n || auxToType(move.Aux) != t {
break
}
mem := move.Args[2]
dst2 := move.Args[0]
if !(move.Uses == 1 && vardef.Uses == 1 && isSamePtr(dst1, dst2) && clobber(move, vardef)) {
break
}
v.reset(OpZero)
v.AuxInt = int64ToAuxInt(n)
v.Aux = typeToAux(t)
v0 := b.NewValue0(v.Pos, OpVarDef, types.TypeMem)
v0.Aux = symToAux(x)
v0.AddArg(mem)
v.AddArg2(dst1, v0)
return true
}
// match: (Zero {t} [s] dst1 zero:(Zero {t} [s] dst2 _))
// cond: isSamePtr(dst1, dst2)
// result: zero
for {
s := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
zero := v_1
if zero.Op != OpZero || auxIntToInt64(zero.AuxInt) != s || auxToType(zero.Aux) != t {
break
}
dst2 := zero.Args[0]
if !(isSamePtr(dst1, dst2)) {
break
}
v.copyOf(zero)
return true
}
// match: (Zero {t} [s] dst1 vardef:(VarDef (Zero {t} [s] dst2 _)))
// cond: isSamePtr(dst1, dst2)
// result: vardef
for {
s := auxIntToInt64(v.AuxInt)
t := auxToType(v.Aux)
dst1 := v_0
vardef := v_1
if vardef.Op != OpVarDef {
break
}
vardef_0 := vardef.Args[0]
if vardef_0.Op != OpZero || auxIntToInt64(vardef_0.AuxInt) != s || auxToType(vardef_0.Aux) != t {
break
}
dst2 := vardef_0.Args[0]
if !(isSamePtr(dst1, dst2)) {
break
}
v.copyOf(vardef)
return true
}
return false
}
func rewriteValuegeneric_OpZeroExt16to32(v *Value) bool {
v_0 := v.Args[0]
// match: (ZeroExt16to32 (Const16 [c]))
// result: (Const32 [int32(uint16(c))])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(uint16(c)))
return true
}
// match: (ZeroExt16to32 (Trunc32to16 x:(Rsh32Ux64 _ (Const64 [s]))))
// cond: s >= 16
// result: x
for {
if v_0.Op != OpTrunc32to16 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh32Ux64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 16) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpZeroExt16to64(v *Value) bool {
v_0 := v.Args[0]
// match: (ZeroExt16to64 (Const16 [c]))
// result: (Const64 [int64(uint16(c))])
for {
if v_0.Op != OpConst16 {
break
}
c := auxIntToInt16(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(uint16(c)))
return true
}
// match: (ZeroExt16to64 (Trunc64to16 x:(Rsh64Ux64 _ (Const64 [s]))))
// cond: s >= 48
// result: x
for {
if v_0.Op != OpTrunc64to16 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh64Ux64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 48) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpZeroExt32to64(v *Value) bool {
v_0 := v.Args[0]
// match: (ZeroExt32to64 (Const32 [c]))
// result: (Const64 [int64(uint32(c))])
for {
if v_0.Op != OpConst32 {
break
}
c := auxIntToInt32(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(uint32(c)))
return true
}
// match: (ZeroExt32to64 (Trunc64to32 x:(Rsh64Ux64 _ (Const64 [s]))))
// cond: s >= 32
// result: x
for {
if v_0.Op != OpTrunc64to32 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh64Ux64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 32) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpZeroExt8to16(v *Value) bool {
v_0 := v.Args[0]
// match: (ZeroExt8to16 (Const8 [c]))
// result: (Const16 [int16( uint8(c))])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v.reset(OpConst16)
v.AuxInt = int16ToAuxInt(int16(uint8(c)))
return true
}
// match: (ZeroExt8to16 (Trunc16to8 x:(Rsh16Ux64 _ (Const64 [s]))))
// cond: s >= 8
// result: x
for {
if v_0.Op != OpTrunc16to8 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh16Ux64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 8) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpZeroExt8to32(v *Value) bool {
v_0 := v.Args[0]
// match: (ZeroExt8to32 (Const8 [c]))
// result: (Const32 [int32( uint8(c))])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v.reset(OpConst32)
v.AuxInt = int32ToAuxInt(int32(uint8(c)))
return true
}
// match: (ZeroExt8to32 (Trunc32to8 x:(Rsh32Ux64 _ (Const64 [s]))))
// cond: s >= 24
// result: x
for {
if v_0.Op != OpTrunc32to8 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh32Ux64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 24) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteValuegeneric_OpZeroExt8to64(v *Value) bool {
v_0 := v.Args[0]
// match: (ZeroExt8to64 (Const8 [c]))
// result: (Const64 [int64( uint8(c))])
for {
if v_0.Op != OpConst8 {
break
}
c := auxIntToInt8(v_0.AuxInt)
v.reset(OpConst64)
v.AuxInt = int64ToAuxInt(int64(uint8(c)))
return true
}
// match: (ZeroExt8to64 (Trunc64to8 x:(Rsh64Ux64 _ (Const64 [s]))))
// cond: s >= 56
// result: x
for {
if v_0.Op != OpTrunc64to8 {
break
}
x := v_0.Args[0]
if x.Op != OpRsh64Ux64 {
break
}
_ = x.Args[1]
x_1 := x.Args[1]
if x_1.Op != OpConst64 {
break
}
s := auxIntToInt64(x_1.AuxInt)
if !(s >= 56) {
break
}
v.copyOf(x)
return true
}
return false
}
func rewriteBlockgeneric(b *Block) bool {
switch b.Kind {
case BlockIf:
// match: (If (Not cond) yes no)
// result: (If cond no yes)
for b.Controls[0].Op == OpNot {
v_0 := b.Controls[0]
cond := v_0.Args[0]
b.resetWithControl(BlockIf, cond)
b.swapSuccessors()
return true
}
// match: (If (ConstBool [c]) yes no)
// cond: c
// result: (First yes no)
for b.Controls[0].Op == OpConstBool {
v_0 := b.Controls[0]
c := auxIntToBool(v_0.AuxInt)
if !(c) {
break
}
b.Reset(BlockFirst)
return true
}
// match: (If (ConstBool [c]) yes no)
// cond: !c
// result: (First no yes)
for b.Controls[0].Op == OpConstBool {
v_0 := b.Controls[0]
c := auxIntToBool(v_0.AuxInt)
if !(!c) {
break
}
b.Reset(BlockFirst)
b.swapSuccessors()
return true
}
}
return false
}
|
akutz/go
|
src/cmd/compile/internal/ssa/rewritegeneric.go
|
GO
|
bsd-3-clause
| 597,533 |
/*L
* Copyright Oracle Inc
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
*/
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-04 The eXist Project
* http://exist-db.org
*
* 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 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 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.xmldb;
import java.io.File;
import java.net.BindException;
import java.util.Iterator;
import junit.framework.TestCase;
import junit.textui.TestRunner;
import org.exist.storage.DBBroker;
import org.exist.StandaloneServer;
import org.exist.xmldb.concurrent.DBUtils;
import org.mortbay.util.MultiException;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;
/**
* @author ???
* @author Pierrick Brihaye <pierrick.brihaye@free.fr>
*/
public class StorageStressTest extends TestCase {
private static StandaloneServer server = null;
//TODO : why a remote test ?
protected final static String URI = "xmldb:exist://localhost:8088/xmlrpc";
//protected final static String URI = "xmldb:exist://";
public final static String DB_DRIVER = "org.exist.xmldb.DatabaseImpl";
private final static String COLLECTION_NAME = "unit-testing-collection";
private final static String CONFIG =
"<collection xmlns=\"http://exist-db.org/collection-config/1.0\">" +
" <index xmlns:x=\"http://www.foo.com\" xmlns:xx=\"http://test.com\">" +
" <fulltext default=\"all\" attributes=\"true\">" +
" </fulltext>" +
" <create path=\"//ELEMENT-1/@attribute-1\" type=\"xs:string\"/>" +
" </index>" +
"</collection>";
private Collection collection = null;
public void testStore() {
try {
String[] wordList = DBUtils.wordList(collection);
long start = System.currentTimeMillis();
for (int i = 0; i < 30000; i++) {
File f = DBUtils.generateXMLFile(6, 3, wordList, false);
System.out.println("Storing file: " + f.getName() + "; size: " + (f.length() / 1024) + "kB");
Resource res = collection.createResource("test_" + i, "XMLResource");
res.setContent(f);
collection.storeResource(res);
f.delete();
}
System.out.println("Indexing took " + (System.currentTimeMillis() - start));
} catch (Exception e) {
fail(e.getMessage());
}
}
protected void setUp() {
//Don't worry about closing the server : the shutdown hook will do the job
initServer();
setUpRemoteDatabase();
}
private void initServer() {
try {
if (server == null) {
server = new StandaloneServer();
if (!server.isStarted()) {
try {
System.out.println("Starting standalone server...");
String[] args = {};
server.run(args);
while (!server.isStarted()) {
Thread.sleep(1000);
}
} catch (MultiException e) {
boolean rethrow = true;
Iterator i = e.getExceptions().iterator();
while (i.hasNext()) {
Exception e0 = (Exception)i.next();
if (e0 instanceof BindException) {
System.out.println("A server is running already !");
rethrow = false;
break;
}
}
if (rethrow) throw e;
}
}
}
} catch (Exception e) {
fail(e.getMessage());
}
}
protected void setUpRemoteDatabase() {
try {
Class cl = Class.forName(DB_DRIVER);
Database database = (Database) cl.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
Collection rootCollection = DatabaseManager.getCollection(URI + DBBroker.ROOT_COLLECTION, "admin", null);
Collection childCollection = rootCollection.getChildCollection(COLLECTION_NAME);
if (childCollection == null) {
CollectionManagementService cms = (CollectionManagementService) rootCollection.getService(
"CollectionManagementService", "1.0");
this.collection = cms.createCollection(COLLECTION_NAME);
} else {
this.collection = childCollection;
}
String existHome = System.getProperty("exist.home");
File existDir = existHome==null ? new File(".") : new File(existHome);
File f = new File(existDir,"samples/shakespeare/hamlet.xml");
Resource res = collection.createResource("test1.xml", "XMLResource");
res.setContent(f);
collection.storeResource(res);
IndexQueryService idxConf = (IndexQueryService)
collection.getService("IndexQueryService", "1.0");
// idxConf.configureCollection(CONFIG);
} catch (Exception e) {
fail(e.getMessage());
}
}
public static void main(String[] args) {
TestRunner.run(StorageStressTest.class);
//Explicit shutdown for the shutdown hook
System.exit(0);
}
}
|
NCIP/cadsr-cgmdr-nci-uk
|
test/src/org/exist/xmldb/StorageStressTest.java
|
Java
|
bsd-3-clause
| 6,249 |
/*
* This file is part of `et engine`
* Copyright 2009-2016 by Sergey Reznik
* Please, modify content only if you know what are you doing.
*
*/
#pragma once
#include <et/rendering/vulkan/vulkan_buffer.h>
#include <et/rendering/vulkan/vulkan_compute.h>
#include <et/rendering/vulkan/vulkan_program.h>
#include <et/rendering/vulkan/vulkan_texture.h>
#include <et/rendering/vulkan/vulkan_sampler.h>
#include <et/rendering/vulkan/vulkan_renderpass.h>
#include <et/rendering/vulkan/vulkan_textureset.h>
#include <et/rendering/vulkan/vulkan_pipelinestate.h>
#include <et/rendering/vulkan/vulkan_renderer.h>
#include <et/rendering/vulkan/vulkan.h>
#include <et/rendering/vulkan/glslang/vulkan_glslang.h>
#include <et/app/application.h>
namespace et {
class VulkanRendererPrivate : public VulkanState
{
public:
VulkanState & vulkan() {
return *this;
}
struct FrameInternal : public Shared
{
ET_DECLARE_POINTER(FrameInternal);
RendererFrame frame;
Vector<VulkanRenderPass::Pointer> passes;
};
PipelineStateCache pipelineCache;
std::mutex framesMutex;
Vector<FrameInternal::Pointer> framesQueue;
Vector<FrameInternal::Pointer> framesCache;
FrameInternal::Pointer buildingFrame;
Vector<VkSubmitInfo> allSubmits;
Vector<VkSemaphore> waitSemaphores;
Vector<VkSemaphore> signalSemaphores;
Vector<VkPipelineStageFlags> waitStages;
Vector<VkCommandBuffer> commandBuffers;
uint64_t continuousFrameNumber = 0;
void presentFrame(VulkanRenderer* renderer, FrameInternal::Pointer&);
};
VulkanRenderer::VulkanRenderer() {
ET_PIMPL_INIT(VulkanRenderer);
Camera::renderingOriginTransform = -1.0f;
Camera::zeroClipRange = true;
}
VulkanRenderer::~VulkanRenderer() {
ET_PIMPL_FINALIZE(VulkanRenderer);
}
VkResult vkEnumerateInstanceLayerPropertiesWrapper(int, uint32_t* count, VkLayerProperties* props) {
return vkEnumerateInstanceLayerProperties(count, props);
}
VkResult vkEnumerateDeviceExtensionPropertiesWrapper(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkExtensionProperties* pProperties) {
return vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, pPropertyCount, pProperties);
}
VkBool32 VKAPI_CALL vulkanDebugCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj,
size_t location, int32_t code, const char* layerPrefix, const char* msg, void* userData) {
if (obj == static_cast<uint64_t>(-1))
obj = 0;
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
{
log::error("%s [%llx] : %s", layerPrefix, obj, msg);
debug::debugBreak();
}
else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
{
log::warning("%s [%llx] : %s", layerPrefix, obj, msg);
}
else
{
log::info("%s [%llx] : %s", layerPrefix, obj, msg);
}
return VK_FALSE;
}
void VulkanRenderer::init(const RenderContextParameters& params) {
_parameters = params;
initGlslangResources();
Vector<const char*> validationLayers;
#if (ET_VULKAN_ENABLE_VALIDATION)
auto layerProps = enumerateVulkanObjects<VkLayerProperties>(0, vkEnumerateInstanceLayerPropertiesWrapper);
validationLayers.reserve(4);
for (const VkLayerProperties& layerProp : layerProps)
{
if (strstr(layerProp.layerName, "validation") || strstr(layerProp.layerName, "thread"))
{
validationLayers.emplace_back(layerProp.layerName);
log::info("Vulkan validation layer used: %s (%s)", layerProp.layerName, layerProp.description);
}
}
#endif
VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
appInfo.pApplicationName = application().identifier().applicationName.c_str();
appInfo.pEngineName = "et-engine";
appInfo.apiVersion = VK_API_VERSION_1_0;
std::vector<const char*> instanceExtensions =
{
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
# if (ET_VULKAN_ENABLE_VALIDATION)
VK_EXT_DEBUG_REPORT_EXTENSION_NAME,
# endif
};
VkInstanceCreateInfo instanceCreateInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
instanceCreateInfo.pApplicationInfo = &appInfo;
instanceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(instanceExtensions.size());
instanceCreateInfo.ppEnabledExtensionNames = instanceExtensions.data();
instanceCreateInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
instanceCreateInfo.ppEnabledLayerNames = validationLayers.data();
VULKAN_CALL(vkCreateInstance(&instanceCreateInfo, nullptr, &_private->instance));
#if (ET_VULKAN_ENABLE_VALIDATION)
PFN_vkCreateDebugReportCallbackEXT createDebugCb =
reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(vkGetInstanceProcAddr(_private->instance, "vkCreateDebugReportCallbackEXT"));
if (createDebugCb)
{
VkDebugReportCallbackCreateInfoEXT debugInfo = { VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT };
debugInfo.flags = VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT;
debugInfo.pfnCallback = reinterpret_cast<PFN_vkDebugReportCallbackEXT>(vulkanDebugCallback);
VULKAN_CALL(createDebugCb(_private->instance, &debugInfo, nullptr, &_private->debugCallback));
}
#endif
auto physicalDevices = enumerateVulkanObjects<VkPhysicalDevice>(_private->instance, vkEnumeratePhysicalDevices);
ET_ASSERT(!physicalDevices.empty());
_private->physicalDevice = physicalDevices.front();
vkGetPhysicalDeviceProperties(_private->physicalDevice, &_private->physicalDeviceProperties);
vkGetPhysicalDeviceFeatures(_private->physicalDevice, &_private->physicalDeviceFeatures);
Vector<VkQueueFamilyProperties> queueProperties =
enumerateVulkanObjects<VkQueueFamilyProperties>(_private->physicalDevice, vkGetPhysicalDeviceQueueFamilyProperties);
ET_ASSERT(queueProperties.size() > 0);
VkDeviceQueueCreateInfo queueCreateInfos[VulkanQueueClass_Count] = {
{ VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO }, { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO } };
uint32_t queuesIndex = 0;
float queuePriorities[] = { 0.0f };
for (const VkQueueFamilyProperties& props : queueProperties)
{
if (props.queueFlags & VK_QUEUE_GRAPHICS_BIT && (_private->queues[VulkanQueueClass::Graphics].index == static_cast<uint32_t>(-1)))
{
_private->queues[VulkanQueueClass::Graphics].index = queuesIndex;
queueCreateInfos[VulkanQueueClass::Graphics].queueFamilyIndex = queuesIndex;
queueCreateInfos[VulkanQueueClass::Graphics].queueCount = 1;
queueCreateInfos[VulkanQueueClass::Graphics].pQueuePriorities = queuePriorities;
_private->queues[VulkanQueueClass::Graphics].properties = props;
}
if ((props.queueFlags & VK_QUEUE_COMPUTE_BIT) && (_private->queues[VulkanQueueClass::Compute].index == static_cast<uint32_t>(-1)))
{
_private->queues[VulkanQueueClass::Compute].index = queuesIndex;
queueCreateInfos[VulkanQueueClass::Compute].queueFamilyIndex = queuesIndex;
queueCreateInfos[VulkanQueueClass::Compute].queueCount = 1;
queueCreateInfos[VulkanQueueClass::Compute].pQueuePriorities = queuePriorities;
_private->queues[VulkanQueueClass::Compute].properties = props;
}
++queuesIndex;
}
bool computeAndGraphicsIsTheSame =
(_private->queues[VulkanQueueClass::Compute].index == _private->queues[VulkanQueueClass::Graphics].index);;
uint32_t totalQueuesCount = computeAndGraphicsIsTheSame ? 1 : queuesIndex;
Vector<VkExtensionProperties> availableExtensions =
enumerateVulkanObjects<VkExtensionProperties>(_private->physicalDevice, vkEnumerateDeviceExtensionPropertiesWrapper);
bool hasDebugMarker = std::find_if(std::begin(availableExtensions), std::end(availableExtensions), [](const VkExtensionProperties& i) {
return (strcmp(i.extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME) == 0);
}) != std::end(availableExtensions);
Vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
if (hasDebugMarker)
{
deviceExtensions.emplace_back(VK_EXT_DEBUG_MARKER_EXTENSION_NAME);
}
VkPhysicalDeviceFeatures deviceFeatures = { };
deviceFeatures.samplerAnisotropy = VK_TRUE;
deviceFeatures.textureCompressionBC = VK_TRUE;
VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
deviceCreateInfo.queueCreateInfoCount = totalQueuesCount;
deviceCreateInfo.pQueueCreateInfos = queueCreateInfos;
deviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions.data();
deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
VULKAN_CALL(vkCreateDevice(_private->physicalDevice, &deviceCreateInfo, nullptr, &_private->device));
for (uint32_t i = 0; i < totalQueuesCount; ++i)
{
VulkanQueue& queue = _private->queues[i];
vkGetDeviceQueue(_private->device, queue.index, 0, &queue.queue);
VkCommandPoolCreateInfo cmdPoolCreateInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
cmdPoolCreateInfo.queueFamilyIndex = queue.index;
cmdPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
VULKAN_CALL(vkCreateCommandPool(_private->device, &cmdPoolCreateInfo, nullptr, &queue.commandPool));
VkCommandBufferAllocateInfo serviceBufferInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
serviceBufferInfo.commandPool = queue.commandPool;
serviceBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
serviceBufferInfo.commandBufferCount = 1;
VULKAN_CALL(vkAllocateCommandBuffers(_private->device, &serviceBufferInfo, &queue.serviceCommandBuffer));
}
if (computeAndGraphicsIsTheSame)
{
_private->queues[VulkanQueueClass::Compute] = _private->queues[VulkanQueueClass::Graphics];
}
_private->graphicsCommandPool = _private->queues[VulkanQueueClass::Graphics].commandPool;
_private->computeCommandPool = _private->queues[VulkanQueueClass::Compute].commandPool;
HWND mainWindow = reinterpret_cast<HWND>(application().context().objects[0]);
_private->allocator.init(_private->vulkan());
_private->swapchain.init(_private->vulkan(), params, mainWindow);
uint32_t defaultPoolSize = 8192;
VkDescriptorPoolSize poolSizes[] = {
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, defaultPoolSize },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, defaultPoolSize },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, defaultPoolSize },
{ VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, defaultPoolSize },
{ VK_DESCRIPTOR_TYPE_SAMPLER, defaultPoolSize },
};
VkDescriptorPoolCreateInfo poolInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
poolInfo.maxSets = defaultPoolSize;
poolInfo.poolSizeCount = sizeof(poolSizes) / sizeof(poolSizes[0]);
poolInfo.pPoolSizes = poolSizes;
VULKAN_CALL(vkCreateDescriptorPool(_private->device, &poolInfo, nullptr, &_private->descriptorPool));
RECT clientRect = { };
GetClientRect(mainWindow, &clientRect);
resize(vec2i(clientRect.right - clientRect.left, clientRect.bottom - clientRect.top));
for (uint32_t i = 0; i < RendererFrameCount; ++i)
_private->framesCache.emplace_back(VulkanRendererPrivate::FrameInternal::Pointer::create());
initInternalStructures();
}
void VulkanRenderer::shutdown() {
VULKAN_CALL(vkDeviceWaitIdle(_private->device));
_private->framesQueue.clear();
_private->framesCache.clear();
_private->buildingFrame.reset(nullptr);
VULKAN_CALL(vkDeviceWaitIdle(_private->device));
}
void VulkanRenderer::destroy() {
_private->pipelineCache.clear();
shutdownInternalStructures();
vkDestroyDescriptorPool(_private->device, _private->descriptorPool, nullptr);
// TODO : clean up Vulkan
cleanupGlslangResources();
}
void VulkanRenderer::resize(const vec2i& sz) {
_private->swapchain.createSizeDependentResources(_private->vulkan(), sz);
}
vec2i VulkanRenderer::contextSize() const {
return vec2i(static_cast<int32_t>(_private->swapchain.extent.width), static_cast<int32_t>(_private->swapchain.extent.height));
}
Buffer::Pointer VulkanRenderer::createBuffer(const std::string&, const Buffer::Description& desc) {
return VulkanBuffer::Pointer::create(_private->vulkan(), desc);
}
Texture::Pointer VulkanRenderer::createTexture(const TextureDescription::Pointer& desc) {
return VulkanTexture::Pointer::create(_private->vulkan(), desc.reference(), desc->data);
}
TextureSet::Pointer VulkanRenderer::createTextureSet(const TextureSet::Description& desc) {
TextureSet::Pointer result;
bool hasObjects = false;
for (const auto& e : desc)
{
hasObjects |= e.second.allowEmptySet;
hasObjects |= !e.second.images.empty();
hasObjects |= !e.second.textures.empty();
hasObjects |= !e.second.samplers.empty();
}
return hasObjects ? VulkanTextureSet::Pointer::create(this, _private->vulkan(), desc) : emptyTextureBindingsSet();
}
Sampler::Pointer VulkanRenderer::createSampler(const Sampler::Description& desc) {
return VulkanSampler::Pointer::create(_private->vulkan(), desc);
}
Program::Pointer VulkanRenderer::createProgram(uint32_t stages, const std::string& source) {
VulkanProgram::Pointer program = VulkanProgram::Pointer::create(_private->vulkan());
program->build(stages, source);
return program;
}
PipelineState::Pointer VulkanRenderer::acquireGraphicsPipeline(const RenderPass::Pointer& pass, const Material::Pointer& mat,
const VertexStream::Pointer& vs) {
ET_ASSERT(mat->pipelineClass() == PipelineClass::Graphics);
ET_ASSERT(mat->isInstance() == false);
const std::string& cls = pass->info().name;
const Material::Configuration& config = mat->configuration(cls);
VulkanPipelineState::Pointer ps = _private->pipelineCache.find(pass->identifier(), vs->vertexDeclaration(), config.program,
config.depthState, config.blendState, config.cullMode, vs->primitiveType());
if (ps.invalid())
{
ps = VulkanPipelineState::Pointer::create(this, _private->vulkan());
ps->setPrimitiveType(vs->primitiveType());
ps->setInputLayout(vs->vertexDeclaration());
ps->setDepthState(config.depthState);
ps->setBlendState(config.blendState);
ps->setCullMode(config.cullMode);
ps->setProgram(config.program);
ps->build(pass);
_private->pipelineCache.addToCache(pass, ps);
}
return ps;
}
Compute::Pointer VulkanRenderer::createCompute(const Material::Pointer& mtl) {
return VulkanCompute::Pointer::create(_private->vulkan(), mtl);
}
RenderPass::Pointer VulkanRenderer::allocateRenderPass(const RenderPass::ConstructionInfo& info) {
return VulkanRenderPass::Pointer::create(this, _private->vulkan(), info);
}
RendererFrame VulkanRenderer::allocateFrame() {
ET_ASSERT(_private->buildingFrame.invalid());
while (_private->framesCache.empty())
threading::sleepMSec(0);
{
std::unique_lock<std::mutex> lock(_private->framesMutex);
_private->buildingFrame = _private->framesCache.back();
_private->framesCache.pop_back();
}
_private->buildingFrame->frame.continuousNumber = _private->continuousFrameNumber++;
_private->buildingFrame->frame.identifier = _private->buildingFrame->frame.continuousNumber ^ uint64_t(reinterpret_cast<uintptr_t>(this));
uint64_t frameIndex = _private->buildingFrame->frame.index();
VulkanSwapchain::SwapchainFrame& swapchainFrame = _private->swapchain.mutableFrame(frameIndex);
// VulkanSwapchain::SwapchainFrame& swapchainFrame = swapchain.mutableFrame(frame->frame.index());
_private->swapchain.acquireFrameImage(swapchainFrame, _private->vulkan());
if (swapchainFrame.timestampIndex > 0)
{
uint64_t timestampData[1024] = {};
VULKAN_CALL(vkGetQueryPoolResults(_private->vulkan().device, swapchainFrame.timestampsQueryPool, 0,
swapchainFrame.timestampIndex, sizeof(timestampData), timestampData, sizeof(uint64_t), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT));
_statistics = {};
for (VulkanRenderPass::Pointer& pass : _private->buildingFrame->passes)
{
if (pass->fillStatistics(frameIndex, timestampData, _statistics.passes[_statistics.activeRenderPasses]))
{
++_statistics.activeRenderPasses;
}
}
swapchainFrame.timestampIndex = 0;
}
_private->buildingFrame->passes.clear();
return _private->buildingFrame->frame;
}
void VulkanRenderer::submitFrame(const RendererFrame& frame) {
ET_ASSERT(_private->buildingFrame.valid());
ET_ASSERT(_private->buildingFrame->frame.identifier == frame.identifier);
{
std::unique_lock<std::mutex> lock(_private->framesMutex);
_private->framesQueue.emplace_back(_private->buildingFrame);
_private->buildingFrame.reset(nullptr);
}
}
void VulkanRenderer::present() {
VulkanRendererPrivate::FrameInternal::Pointer frameToExecute;
{
std::unique_lock<std::mutex> lock(_private->framesMutex);
if (_private->framesQueue.empty() == false)
{
frameToExecute = _private->framesQueue.front();
_private->framesQueue.erase(_private->framesQueue.begin());
}
}
if (frameToExecute.valid())
{
_private->presentFrame(this, frameToExecute);
{
std::unique_lock<std::mutex> lock(_private->framesMutex);
_private->framesCache.insert(_private->framesCache.begin(), frameToExecute);
}
}
}
void VulkanRenderer::beginRenderPass(const RenderPass::Pointer& p, const RenderPassBeginInfo& info) {
ET_ASSERT(_private->buildingFrame.valid());
VulkanRenderPass::Pointer pass = p;
pass->begin(_private->buildingFrame->frame, info);
}
void VulkanRenderer::submitRenderPass(const RenderPass::Pointer& inPass) {
ET_ASSERT(_private->buildingFrame.valid());
VulkanRenderPass::Pointer pass = inPass;
pass->end(_private->buildingFrame->frame);
_private->buildingFrame->passes.emplace_back(pass);
}
void VulkanRendererPrivate::presentFrame(VulkanRenderer* renderer, FrameInternal::Pointer& frame) {
static VkPipelineStageFlags firstWaitStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
static VkPipelineStageFlags lastWaitStage = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
VulkanSwapchain::SwapchainFrame& swapchainFrame = swapchain.mutableFrame(frame->frame.index());
Vector<VulkanRenderPass::Pointer>& passes = frame->passes;
std::stable_sort(passes.begin(), passes.end(), [](const VulkanRenderPass::Pointer& l, const VulkanRenderPass::Pointer& r) {
return l->info().priority > r->info().priority;
});
renderer->sharedConstantBuffer().flush(frame->frame.continuousNumber);
size_t maxQueueSize = 2 * (1 + std::min(32ull, sqr(passes.size())));
allSubmits.clear();
allSubmits.reserve(maxQueueSize);
commandBuffers.clear();
commandBuffers.reserve(maxQueueSize);
waitStages.clear();
waitStages.reserve(maxQueueSize);
waitSemaphores.clear();
waitSemaphores.reserve(maxQueueSize);
signalSemaphores.clear();
signalSemaphores.reserve(maxQueueSize);
{
allSubmits.emplace_back();
VkSubmitInfo& submitInfo = allSubmits.back();
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &swapchainFrame.barrierFromPresent;
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &swapchainFrame.imageAcquired;
submitInfo.pWaitDstStageMask = &firstWaitStage;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &swapchainFrame.semaphoreFromPresent;
}
uint32_t commandBuffersBegin = 0;
uint32_t waitBegin = 0;
uint32_t signalBegin = 0;
uint32_t submittedCommandBuffers = 0;
uint32_t submittedWait = 0;
uint32_t submittedSignal = 0;
for (auto i = passes.begin(), e = passes.end(); i != e; ++i)
{
uint32_t commandBuffersEnd = commandBuffersBegin;
uint32_t waitEnd = waitBegin;
uint32_t signalEnd = signalBegin;
if (i == passes.begin())
{
waitSemaphores.emplace_back(swapchainFrame.semaphoreFromPresent);
waitStages.emplace_back(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
++waitEnd;
}
for (auto si = signalSemaphores.begin() + signalBegin - submittedSignal, se = signalSemaphores.end(); si != se; ++si)
{
waitSemaphores.emplace_back(*si);
waitStages.emplace_back(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
++waitEnd;
}
const VulkanRenderPass::Pointer& passI = *i;
signalSemaphores.emplace_back(passI->nativeRenderPassContent().semaphore);
commandBuffers.emplace_back(passI->nativeRenderPassContent().commandBuffer);
++commandBuffersEnd;
++signalEnd;
for (auto j = i + 1; (j != e) && ((*j)->info().priority == (*i)->info().priority); ++j, ++i)
{
const VulkanRenderPass::Pointer& passJ = *j;
commandBuffers.emplace_back(passJ->nativeRenderPassContent().commandBuffer);
signalSemaphores.emplace_back(passJ->nativeRenderPassContent().semaphore);
++commandBuffersEnd;
++signalEnd;
}
if (i + 1 == e)
{
signalSemaphores.emplace_back(swapchainFrame.semaphoreToPresent);
signalBegin = static_cast<uint32_t>(signalSemaphores.size()) - 1;
signalEnd = signalBegin + 1;
}
submittedCommandBuffers = commandBuffersEnd - commandBuffersBegin;
submittedSignal = signalEnd - signalBegin;
submittedWait = waitEnd - waitBegin;
allSubmits.emplace_back();
VkSubmitInfo& submitInfo = allSubmits.back();
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.pCommandBuffers = commandBuffers.data() + commandBuffersBegin;
submitInfo.commandBufferCount = submittedCommandBuffers;
ET_ASSERT(submitInfo.commandBufferCount > 0);
submitInfo.pSignalSemaphores = signalSemaphores.data() + signalBegin;
submitInfo.signalSemaphoreCount = submittedSignal;
ET_ASSERT(submitInfo.signalSemaphoreCount > 0);
submitInfo.pWaitDstStageMask = waitStages.data() + waitBegin;
submitInfo.pWaitSemaphores = waitSemaphores.data() + waitBegin;
submitInfo.waitSemaphoreCount = submittedWait;
ET_ASSERT(submitInfo.waitSemaphoreCount > 0);
commandBuffersBegin = commandBuffersEnd;
signalBegin = signalEnd;
waitBegin = waitEnd;
}
{
allSubmits.emplace_back();
VkSubmitInfo& submitInfo = allSubmits.back();
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &swapchainFrame.barrierToPresent;
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = passes.empty() ? &swapchainFrame.semaphoreFromPresent : &swapchainFrame.semaphoreToPresent;
submitInfo.pWaitDstStageMask = &lastWaitStage;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &swapchainFrame.submitCompleted;
}
VULKAN_CALL(vkQueueSubmit(queues[VulkanQueueClass::Graphics].queue, static_cast<uint32_t>(allSubmits.size()),
allSubmits.data(), swapchainFrame.imageFence));
allSubmits.clear();
swapchain.present(swapchainFrame, *this);
}
}
|
sergeyreznik/et-engine
|
include/et/rendering/vulkan/vulkan_renderer.cpp
|
C++
|
bsd-3-clause
| 22,196 |
def extractFullybookedtranslationsWordpressCom(item):
'''
Parser for 'fullybookedtranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
fake-name/ReadableWebProxy
|
WebMirror/management/rss_parser_funcs/feed_parse_extractFullybookedtranslationsWordpressCom.py
|
Python
|
bsd-3-clause
| 586 |
<?php
namespace garethp\ews\API\Enumeration;
use garethp\ews\API\Enumeration;
/**
* Class representing SubscriptionStatusFrequencyType
*
*
* XSD Type: SubscriptionStatusFrequencyType
*/
class SubscriptionStatusFrequencyType extends Enumeration
{
}
|
Garethp/php-ews
|
src/API/Enumeration/SubscriptionStatusFrequencyType.php
|
PHP
|
bsd-3-clause
| 258 |
<script type="text/javascript"></script>
<div class="content-box">
<div class="content-box-header">
<h3 id="title" style="cursor: s-resize;">List Article</h3>
<ul class="content-box-tabs">
<li><a href="#tab1" id="clickTab1" class="default-tab current">List Article</a></li>
<!-- href must be unique and match the id of target div -->
<li><a href="#tab2" id="clickTab2">Create New Article</a></li>
</ul>
<div class="clear"></div>
</div>
<div class="content-box-content">
<div class="tab-content default-tab" id="tab1" style="display: block;">
<!-- This is the target div. id must match the href of this div's tab -->
<div class="notification attention png_bg">
<a href="#" class="close"><img
src="<?php echo Yii::app()->request->baseUrl; ?>/css/admin/images/icons/cross_grey_small.png"
title="Close this notification" alt="close"></a>
<div>
This is a Content Box. You can put whatever you want in it. By the way, you can close this notification with
the top-right cross.
</div>
</div>
<table>
<thead>
<tr>
<th><input class="check-all" type="checkbox"></th>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="6">
<div class="bulk-actions align-left">
<select name="dropdown">
<option value="option1">Choose an action...</option>
<option value="option2">Edit</option>
<option value="option3">Delete</option>
</select>
<a class="button" href="#">Apply to selected</a>
</div>
<div class="pagination">
<a href="#" title="First Page"> << First</a><a href="#" title="Previous Page">< Previous</a>
<a href="#" class="number" title="1">1</a>
<a href="#" class="number" title="2">2</a>
<a href="#" class="number current" title="3">3</a>
<a href="#" class="number" title="4">4</a>
<a href="#" title="Next Page">Next > </a><a href="#" title="Last Page">Last >> </a>
</div>
<!-- End .pagination -->
<div class="clear"></div>
</td>
</tr>
</tfoot>
<tbody>
<tr class="alt-row">
<td><input type="checkbox"></td>
<td>Lorem ipsum dolor</td>
<td><a href="#" title="title">Sit amet</a></td>
<td>Consectetur adipiscing</td>
<td>Donec tortor diam</td>
<td>
<!-- Icons -->
<a href="#" title="Edit"><img
src="<?php echo Yii::app()->request->baseUrl; ?>/css/admin/images/icons/pencil.png" alt="Edit"></a>
<a href="#" title="Delete"><img
src="<?php echo Yii::app()->request->baseUrl; ?>/css/admin/images/icons/cross.png" alt="Delete"></a>
<a href="#" title="Edit Meta"><img
src="<?php echo Yii::app()->request->baseUrl; ?>/css/admin/images/icons/hammer_screwdriver.png"
alt="Edit Meta"></a>
</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>Lorem ipsum dolor</td>
<td><a href="#" title="title">Sit amet</a></td>
<td>Consectetur adipiscing</td>
<td>Donec tortor diam</td>
<td>
<!-- Icons -->
<a href="#" title="Edit"><img
src="<?php echo Yii::app()->request->baseUrl; ?>/css/admin/images/icons/pencil.png" alt="Edit"></a>
<a href="#" title="Delete"><img
src="<?php echo Yii::app()->request->baseUrl; ?>/css/admin/images/icons/cross.png" alt="Delete"></a>
<a href="#" title="Edit Meta"><img
src="<?php echo Yii::app()->request->baseUrl; ?>/css/admin/images/icons/hammer_screwdriver.png"
alt="Edit Meta"></a>
</td>
</tr>
</tbody>
</table>
</div>
<!-- End #tab1 -->
<div class="tab-content" id="tab2" style="display: none;">
<form action="" method="post">
<fieldset> <!-- Set class to "column-left" or "column-right" on fieldsets to divide the form into columns -->
<p>
<label>Title</label>
<input class="text-input medium-input" type="text" id="medium-input" name="medium-input"> <span class="input-notification error png_bg">Error message</span>
</p>
<p>
<label>Checkboxes</label>
<label for="checkbox1"> <input type="checkbox" id="checkbox1" name="checkbox1"> Hot</label>
<label for="checkbox2"> <input type="checkbox" id="checkbox2" name="checkbox2"> New</label>
</p>
<p>
<label>Category</label>
<select name="dropdown" class="small-input">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
</select>
</p>
<p>
<label>Textarea with WYSIWYG</label>
<textarea class="text-input textarea wysiwyg" id="textarea" name="textfield" cols="79" rows="15"></textarea>
</p>
<p>
<input class="button" type="submit" value="Submit">
</p>
</fieldset>
<div class="clear"></div><!-- End .clear -->
</form>
</div>
<!-- End #tab2 -->
</div>
</div>
|
hahalulu/yii
|
demo/protected/views/admin/adminarticle/index.php
|
PHP
|
bsd-3-clause
| 7,002 |
<?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 27.04.2016
*/
namespace skeeks\cms\backend\assets;
use skeeks\cms\base\AssetBundle;
use yii\bootstrap\BootstrapAsset;
/**
* Class SelectLanguage
* @package common\widgets\selectLanguage
*/
class BackendAsset extends AssetBundle
{
public $sourcePath = '@skeeks/cms/backend/assets/src';
public $css = [
'backend.css',
];
public $js = [
'backend.js',
];
public $depends =
[
'yii\web\YiiAsset',
'skeeks\sx\assets\Custom',
'skeeks\sx\assets\ComponentAjaxLoader',
];
}
|
skeeks-cms/cms-backend
|
src/assets/BackendAsset.php
|
PHP
|
bsd-3-clause
| 679 |
/*******************************************************************************
* Copyright (C) 2001-2004 Vintela, Inc. 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 Vintela, Inc. 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 Vintela, Inc. 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.
*******************************************************************************/
/**
* @author Jon Carey
* @author Dan Nuffer
*/
#include "OW_config.h"
#include "OW_ConfigOpts.hpp"
#include "OW_FileSystem.hpp"
#include "OW_BinaryRequestHandler.hpp"
#include "OW_BinarySerialization.hpp"
#include "OW_Format.hpp"
#include "OW_CIMOMHandleIFC.hpp"
#include "OW_CIMFeatures.hpp"
#include "OW_CIMParamValue.hpp"
#include "OW_SocketUtils.hpp"
#include "OW_CIMException.hpp"
#include "OW_CIMProperty.hpp"
#include "OW_CIMQualifier.hpp"
#include "OW_Mutex.hpp"
#include "OW_MutexLock.hpp"
#include "OW_SocketException.hpp"
#include "OW_ThreadCancelledException.hpp"
#include "OW_Logger.hpp"
#include "OW_OperationContext.hpp"
#include "OW_UserUtils.hpp"
#include "OW_ServiceIFCNames.hpp"
#include "OW_ResultHandlerIFC.hpp"
#include <exception>
namespace OW_NAMESPACE
{
namespace
{
const String COMPONENT_NAME("ow.requesthandler.owbinary");
}
using namespace WBEMFlags;
//////////////////////////////////////////////////////////////////////////////
BinaryRequestHandler::BinaryRequestHandler()
: RequestHandlerIFC()
, m_userId(UserId(-1))
{
}
//////////////////////////////////////////////////////////////////////////////
RequestHandlerIFC*
BinaryRequestHandler::clone() const
{
return new BinaryRequestHandler(*this);
}
//////////////////////////////////////////////////////////////////////////////
String
BinaryRequestHandler::getName() const
{
return ServiceIFCNames::BinaryRequestHandler;
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::setEnvironment(const ServiceEnvironmentIFCRef& env)
{
RequestHandlerIFC::setEnvironment(env);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::doOptions(CIMFeatures& cf,
OperationContext&)
{
cf.cimom = "openwbem";
cf.cimProduct = CIMFeatures::SERVER;
cf.extURL = "local_binary";
cf.protocolVersion = OW_VERSION;
cf.supportedGroups.clear();
cf.supportedQueryLanguages.clear();
cf.supportedQueryLanguages.append("WQL");
cf.supportsBatch = false;
cf.validation.erase();
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::doProcess(std::istream* istrm, std::ostream *ostrm,
std::ostream* ostrError, OperationContext& context)
{
clearError();
String userName = context.getStringDataWithDefault(OperationContext::USER_NAME);
if (!userName.empty())
{
bool validUserName = false;
m_userId = UserUtils::getUserId(userName, validUserName);
if (!validUserName)
{
m_userId = UserId(-1);
}
}
UInt8 funcNo = 0;
LoggerRef lgr = getEnvironment()->getLogger(COMPONENT_NAME);
try
{
CIMOMHandleIFCRef chdl = getEnvironment()->getCIMOMHandle(context);
UInt32 version = 0;
BinarySerialization::read(*istrm, version);
if (version < MinBinaryProtocolVersion || version > BinaryProtocolVersion)
{
OW_THROWCIMMSG(CIMException::FAILED, "Incompatible version");
}
BinarySerialization::read(*istrm, funcNo);
try
{
switch (funcNo)
{
case BIN_GETQUAL:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler get qualifier"
" request");
getQual(chdl, *ostrm, *istrm);
break;
#ifndef OW_DISABLE_QUALIFIER_DECLARATION
case BIN_SETQUAL:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler set qualifier"
" request");
setQual(chdl, *ostrm, *istrm);
break;
case BIN_DELETEQUAL:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler delete qualifier"
" request");
deleteQual(chdl, *ostrm, *istrm);
break;
case BIN_ENUMQUALS:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler enum qualifiers"
" request");
enumQualifiers(chdl, *ostrm, *istrm);
break;
#endif // #ifndef OW_DISABLE_QUALIFIER_DECLARATION
case BIN_GETCLS:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler get class"
" request");
getClass(chdl, *ostrm, *istrm);
break;
#ifndef OW_DISABLE_SCHEMA_MANIPULATION
case BIN_CREATECLS:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler create class"
" request");
createClass(chdl, *ostrm, *istrm);
break;
case BIN_MODIFYCLS:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler modify class"
" request");
modifyClass(chdl, *ostrm, *istrm);
break;
case BIN_DELETECLS:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler delete class"
" request");
deleteClass(chdl, *ostrm, *istrm);
break;
#endif // #ifndef OW_DISABLE_SCHEMA_MANIPULATION
case BIN_ENUMCLSS:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler enum classes"
" request");
enumClasses(chdl, *ostrm, *istrm);
break;
case BIN_GETINST:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler get instance"
" request");
getInstance(chdl, *ostrm, *istrm);
break;
#ifndef OW_DISABLE_INSTANCE_MANIPULATION
case BIN_CREATEINST:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler create instance"
" request");
createInstance(chdl, *ostrm, *istrm);
break;
case BIN_MODIFYINST:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler get instance"
" request");
modifyInstance(chdl, *ostrm, *istrm);
break;
case BIN_DELETEINST:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler delete instance"
" request");
deleteInstance(chdl, *ostrm, *istrm);
break;
#if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
case BIN_SETPROP:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler set property"
" request");
setProperty(chdl, *ostrm, *istrm);
break;
#endif // #if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
#endif // #ifndef OW_DISABLE_INSTANCE_MANIPULATION
#if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
case BIN_GETPROP:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler get property"
" request");
getProperty(chdl, *ostrm, *istrm);
break;
#endif // #if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
case BIN_ENUMCLSNAMES:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler enum class names"
" request");
enumClassNames(chdl, *ostrm, *istrm);
break;
case BIN_ENUMINSTS:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler enum instances"
" request");
enumInstances(chdl, *ostrm, *istrm);
break;
case BIN_ENUMINSTNAMES:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler enum instance"
" names request");
enumInstanceNames(chdl, *ostrm, *istrm);
break;
case BIN_INVMETH:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler invoke method"
" request");
invokeMethod(chdl, *ostrm, *istrm);
break;
case BIN_EXECQUERY:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler exec query"
" request");
execQuery(chdl, *ostrm, *istrm);
break;
#ifndef OW_DISABLE_ASSOCIATION_TRAVERSAL
case BIN_ASSOCIATORS:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler associators"
" request");
associators(chdl, *ostrm, *istrm);
break;
case BIN_ASSOCNAMES:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler associator names"
" request");
associatorNames(chdl, *ostrm, *istrm);
break;
case BIN_REFERENCES:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler references"
" request");
references(chdl, *ostrm, *istrm);
break;
case BIN_REFNAMES:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler reference names"
" request");
referenceNames(chdl, *ostrm, *istrm);
break;
#endif
case BIN_GETSVRFEATURES:
OW_LOG_DEBUG(lgr, "BinaryRequestHandler get server"
" features request");
getServerFeatures(chdl, *ostrm, *istrm);
break;
default:
OW_LOG_DEBUG(lgr, Format("BinaryRequestHandler: Received"
" invalid function number: %1", funcNo));
writeError(*ostrError, "Invalid function number");
break;
}
}
catch(CIMException& e)
{
OW_LOG_INFO(lgr, Format("CIM Exception caught in"
" BinaryRequestHandler: %1", e));
BinarySerialization::write(*ostrError, BIN_EXCEPTION);
BinarySerialization::write(*ostrError, UInt16(e.getErrNo()));
BinarySerialization::write(*ostrError, e.getMessage());
setError(e.getErrNo(), e.getDescription());
}
}
catch(Exception& e)
{
OW_LOG_ERROR(lgr, "Exception caught in BinaryRequestHandler");
OW_LOG_ERROR(lgr, Format("Type: %1", e.type()));
OW_LOG_ERROR(lgr, Format("File: %1", e.getFile()));
OW_LOG_ERROR(lgr, Format("Line: %1", e.getLine()));
OW_LOG_ERROR(lgr, Format("Msg: %1", e.getMessage()));
writeError(*ostrError, Format("BinaryRequestHandler caught exception: %1", e).c_str());
setError(CIMException::FAILED, e.getMessage());
}
catch(std::exception& e)
{
OW_LOG_ERROR(lgr, Format("Caught %1 exception in BinaryRequestHandler",
e.what()));
writeError(*ostrError, Format("BinaryRequestHandler caught exception: %1", e.what()).c_str());
setError(CIMException::FAILED, e.what());
}
catch (ThreadCancelledException&)
{
OW_LOG_ERROR(lgr, "Thread cancelled in BinaryRequestHandler");
writeError(*ostrError, "Thread cancelled");
setError(CIMException::FAILED, "Thread cancelled");
throw;
}
catch(...)
{
OW_LOG_ERROR(lgr, "Unknown exception caught in BinaryRequestHandler");
writeError(*ostrError, "BinaryRequestHandler caught unknown exception");
setError(CIMException::FAILED, "Caught unknown exception");
}
}
#ifndef OW_DISABLE_SCHEMA_MANIPULATION
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::createClass(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMClass cc(BinarySerialization::readClass(istrm));
chdl->createClass(ns, cc);
BinarySerialization::write(ostrm, BIN_OK);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::modifyClass(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMClass cc(BinarySerialization::readClass(istrm));
chdl->modifyClass(ns, cc);
BinarySerialization::write(ostrm, BIN_OK);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::deleteClass(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
String className(BinarySerialization::readString(istrm));
chdl->deleteClass(ns, className);
BinarySerialization::write(ostrm, BIN_OK);
}
#endif // #ifndef OW_DISABLE_SCHEMA_MANIPULATION
//////////////////////////////////////////////////////////////////////////////
namespace
{
class BinaryCIMClassWriter : public CIMClassResultHandlerIFC
{
public:
BinaryCIMClassWriter(std::ostream& ostrm_)
: ostrm(ostrm_)
{}
protected:
virtual void doHandle(const CIMClass &c)
{
BinarySerialization::writeClass(ostrm, c);
}
private:
std::ostream& ostrm;
};
class BinaryCIMObjectPathWriter : public CIMObjectPathResultHandlerIFC
{
public:
BinaryCIMObjectPathWriter(std::ostream& ostrm_, const String& host_)
: ostrm(ostrm_)
, m_host(host_)
{}
protected:
virtual void doHandle(const CIMObjectPath &cop_)
{
// Make sure all outgoing object paths have our host name, instead of 127.0.0.1
CIMObjectPath cop(cop_);
if (cop.getFullNameSpace().isLocal())
{
try
{
cop.setHost(m_host);
}
catch (const SocketException& e)
{
}
}
BinarySerialization::writeObjectPath(ostrm, cop);
}
private:
std::ostream& ostrm;
String m_host;
};
class BinaryCIMInstanceWriter : public CIMInstanceResultHandlerIFC
{
public:
BinaryCIMInstanceWriter(std::ostream& ostrm_, const String& ns_)
: ostrm(ostrm_)
, ns(ns_)
{}
protected:
virtual void doHandle(const CIMInstance &cop)
{
if (cop.getNameSpace().empty())
{
CIMInstance ci(cop);
ci.setNameSpace(ns);
BinarySerialization::writeInstance(ostrm, ci);
}
else
{
BinarySerialization::writeInstance(ostrm, cop);
}
}
private:
std::ostream& ostrm;
String ns;
};
class BinaryCIMQualifierTypeWriter : public CIMQualifierTypeResultHandlerIFC
{
public:
BinaryCIMQualifierTypeWriter(std::ostream& ostrm_)
: ostrm(ostrm_)
{}
protected:
virtual void doHandle(const CIMQualifierType &cqt)
{
BinarySerialization::writeQualType(ostrm, cqt);
}
private:
std::ostream& ostrm;
};
class BinaryStringWriter : public StringResultHandlerIFC
{
public:
BinaryStringWriter(std::ostream& ostrm_)
: ostrm(ostrm_)
{}
protected:
virtual void doHandle(const String &name)
{
BinarySerialization::writeString(ostrm, name);
}
private:
std::ostream& ostrm;
String ns;
};
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::enumClasses(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
String className(BinarySerialization::readString(istrm));
EDeepFlag deep(BinarySerialization::readBool(istrm) ? E_DEEP : E_SHALLOW);
ELocalOnlyFlag localOnly(BinarySerialization::readBool(istrm) ? E_LOCAL_ONLY : E_NOT_LOCAL_ONLY);
EIncludeQualifiersFlag includeQualifiers(BinarySerialization::readBool(istrm) ? E_INCLUDE_QUALIFIERS : E_EXCLUDE_QUALIFIERS);
EIncludeClassOriginFlag includeClassOrigin(BinarySerialization::readBool(istrm) ? E_INCLUDE_CLASS_ORIGIN : E_EXCLUDE_CLASS_ORIGIN);
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, BINSIG_CLSENUM);
BinaryCIMClassWriter handler(ostrm);
chdl->enumClass(ns, className, handler, deep, localOnly,
includeQualifiers, includeClassOrigin);
BinarySerialization::write(ostrm, END_CLSENUM);
BinarySerialization::write(ostrm, END_CLSENUM);
}
#ifndef OW_DISABLE_QUALIFIER_DECLARATION
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::deleteQual(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
String qualName(BinarySerialization::readString(istrm));
chdl->deleteQualifierType(ns, qualName);
BinarySerialization::write(ostrm, BIN_OK);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::setQual(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMQualifierType qt(BinarySerialization::readQualType(istrm));
chdl->setQualifierType(ns, qt);
BinarySerialization::write(ostrm, BIN_OK);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::enumQualifiers(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, BINSIG_QUAL_TYPEENUM);
BinaryCIMQualifierTypeWriter handler(ostrm);
chdl->enumQualifierTypes(ns, handler);
BinarySerialization::write(ostrm, END_QUALENUM);
BinarySerialization::write(ostrm, END_QUALENUM);
}
#endif // #ifndef OW_DISABLE_QUALIFIER_DECLARATION
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::getClass(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
StringArray propList;
StringArray* propListPtr = 0;
String ns(BinarySerialization::readString(istrm));
String className(BinarySerialization::readString(istrm));
ELocalOnlyFlag localOnly(BinarySerialization::readBool(istrm) ? E_LOCAL_ONLY : E_NOT_LOCAL_ONLY);
EIncludeQualifiersFlag includeQualifiers(BinarySerialization::readBool(istrm) ? E_INCLUDE_QUALIFIERS : E_EXCLUDE_QUALIFIERS);
EIncludeClassOriginFlag includeClassOrigin(BinarySerialization::readBool(istrm) ? E_INCLUDE_CLASS_ORIGIN : E_EXCLUDE_CLASS_ORIGIN);
Bool nullPropertyList(BinarySerialization::readBool(istrm));
if (!nullPropertyList)
{
propList = BinarySerialization::readStringArray(istrm);
propListPtr = &propList;
}
CIMClass cc = chdl->getClass(ns, className, localOnly, includeQualifiers,
includeClassOrigin, propListPtr);
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::writeClass(ostrm, cc);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::getInstance(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMObjectPath op(BinarySerialization::readObjectPath(istrm));
ELocalOnlyFlag localOnly(BinarySerialization::readBool(istrm) ? E_LOCAL_ONLY : E_NOT_LOCAL_ONLY);
EIncludeQualifiersFlag includeQualifiers(BinarySerialization::readBool(istrm) ? E_INCLUDE_QUALIFIERS : E_EXCLUDE_QUALIFIERS);
EIncludeClassOriginFlag includeClassOrigin(BinarySerialization::readBool(istrm) ? E_INCLUDE_CLASS_ORIGIN : E_EXCLUDE_CLASS_ORIGIN);
StringArray propList;
StringArray* propListPtr = 0;
Bool nullPropertyList(BinarySerialization::readBool(istrm));
if (!nullPropertyList)
{
propList = BinarySerialization::readStringArray(istrm);
propListPtr = &propList;
}
CIMInstance cimInstance = chdl->getInstance(ns, op, localOnly,
includeQualifiers, includeClassOrigin, propListPtr);
if (cimInstance.getNameSpace().empty())
cimInstance.setNameSpace(ns);
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::writeInstance(ostrm, cimInstance);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::getQual(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
String qualifierName(BinarySerialization::readString(istrm));
CIMQualifierType qt = chdl->getQualifierType(ns, qualifierName);
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::writeQualType(ostrm, qt);
}
#ifndef OW_DISABLE_INSTANCE_MANIPULATION
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::createInstance(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMInstance cimInstance(BinarySerialization::readInstance(istrm));
CIMName className = cimInstance.getClassName();
//CIMObjectPath realPath(className, path.getNameSpace());
// Special treatment for __Namespace class
if (className == "__Namespace")
{
CIMProperty prop = cimInstance.getProperty(
CIMProperty::NAME_PROPERTY);
// Need the name property since it contains the name of the new
// name space
if (!prop)
{
OW_THROWCIMMSG(CIMException::INVALID_PARAMETER,
"Name property not specified for new namespace");
}
// If the name property didn't come acrossed as a key, then
// set the name property as the key
if (!prop.isKey())
{
prop.addQualifier(CIMQualifier::createKeyQualifier());
}
cimInstance.setProperty(prop);
}
/* This should be done in the CIM Server
CIMPropertyArray keys = cimInstance.getKeyValuePairs();
if (keys.size() == 0)
{
OW_THROWCIMMSG(CIMException::FAILED,"Instance doesn't have keys");
}
for (size_t i = 0; i < keys.size(); ++i)
{
CIMProperty key = keys[i];
if (!key.getValue())
{
OW_THROWCIMMSG(CIMException::FAILED,
Format("Key must be provided! Property \"%1\" does not have a "
"valid value.", key.getName()).c_str());
}
}
realPath.setKeys(keys);
*/
CIMObjectPath newPath = chdl->createInstance(ns, cimInstance);
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::writeObjectPath(ostrm, newPath);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::deleteInstance(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMObjectPath op(BinarySerialization::readObjectPath(istrm));
chdl->deleteInstance(ns, op);
BinarySerialization::write(ostrm, BIN_OK);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::modifyInstance(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMInstance ci(BinarySerialization::readInstance(istrm));
EIncludeQualifiersFlag includeQualifiers(BinarySerialization::readBool(istrm) ? E_INCLUDE_QUALIFIERS : E_EXCLUDE_QUALIFIERS);
StringArray propList;
StringArray* propListPtr = 0;
Bool nullPropertyList(BinarySerialization::readBool(istrm));
if (!nullPropertyList)
{
propList = BinarySerialization::readStringArray(istrm);
propListPtr = &propList;
}
chdl->modifyInstance(ns, ci, includeQualifiers, propListPtr);
BinarySerialization::write(ostrm, BIN_OK);
}
#if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::setProperty(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMObjectPath op(BinarySerialization::readObjectPath(istrm));
String propName(BinarySerialization::readString(istrm));
Bool isValue(BinarySerialization::readBool(istrm));
CIMValue cv(CIMNULL);
if (isValue)
{
cv = BinarySerialization::readValue(istrm);
}
chdl->setProperty(ns, op, propName, cv);
BinarySerialization::write(ostrm, BIN_OK);
}
#endif // #if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
#endif // #ifndef OW_DISABLE_INSTANCE_MANIPULATION
#if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::getProperty(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns (BinarySerialization::readString(istrm));
CIMObjectPath op(BinarySerialization::readObjectPath(istrm));
String propName(BinarySerialization::readString(istrm));
CIMValue cv = chdl->getProperty(ns, op, propName);
BinarySerialization::write(ostrm, BIN_OK);
Bool isValue = (cv) ? true : false;
BinarySerialization::writeBool(ostrm, isValue);
if (isValue)
{
BinarySerialization::writeValue(ostrm, cv);
}
}
#endif // #if !defined(OW_DISABLE_PROPERTY_OPERATIONS)
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::enumClassNames(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
String className(BinarySerialization::readString(istrm));
EDeepFlag deep(BinarySerialization::readBool(istrm) ? E_DEEP : E_SHALLOW);
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, BINSIG_STRINGENUM);
BinaryStringWriter handler(ostrm);
chdl->enumClassNames(ns, className, handler, deep);
BinarySerialization::write(ostrm, END_STRINGENUM);
BinarySerialization::write(ostrm, END_STRINGENUM);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::enumInstances(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
StringArray propList;
StringArray* propListPtr = 0;
String ns(BinarySerialization::readString(istrm));
String className(BinarySerialization::readString(istrm));
EDeepFlag deep(BinarySerialization::readBool(istrm) ? E_DEEP : E_SHALLOW);
ELocalOnlyFlag localOnly(BinarySerialization::readBool(istrm) ? E_LOCAL_ONLY : E_NOT_LOCAL_ONLY);
EIncludeQualifiersFlag includeQualifiers(BinarySerialization::readBool(istrm) ? E_INCLUDE_QUALIFIERS : E_EXCLUDE_QUALIFIERS);
EIncludeClassOriginFlag includeClassOrigin(BinarySerialization::readBool(istrm) ? E_INCLUDE_CLASS_ORIGIN : E_EXCLUDE_CLASS_ORIGIN);
Bool nullPropertyList(BinarySerialization::readBool(istrm));
if (!nullPropertyList)
{
propList = BinarySerialization::readStringArray(istrm);
propListPtr = &propList;
}
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, BINSIG_INSTENUM);
BinaryCIMInstanceWriter handler(ostrm, ns);
chdl->enumInstances(ns, className, handler, deep, localOnly,
includeQualifiers, includeClassOrigin, propListPtr);
BinarySerialization::write(ostrm, END_INSTENUM);
BinarySerialization::write(ostrm, END_INSTENUM);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::enumInstanceNames(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
String className(BinarySerialization::readString(istrm));
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, BINSIG_OPENUM);
BinaryCIMObjectPathWriter handler(ostrm, getHost());
chdl->enumInstanceNames(ns, className, handler);
BinarySerialization::write(ostrm, END_OPENUM);
BinarySerialization::write(ostrm, END_OPENUM);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::invokeMethod(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns (BinarySerialization::readString(istrm));
CIMObjectPath path(BinarySerialization::readObjectPath(istrm));
String methodName(BinarySerialization::readString(istrm));
CIMParamValueArray inparms;
CIMParamValueArray outparms;
// Get input params
BinarySerialization::verifySignature(istrm, BINSIG_PARAMVALUEARRAY);
BinarySerialization::readArray(istrm, inparms);
CIMValue cv = chdl->invokeMethod(ns, path, methodName, inparms, outparms);
BinarySerialization::write(ostrm, BIN_OK);
if (cv)
{
BinarySerialization::writeBool(ostrm, Bool(true));
BinarySerialization::writeValue(ostrm, cv);
}
else
{
BinarySerialization::writeBool(ostrm, Bool(false));
}
BinarySerialization::write(ostrm, BINSIG_PARAMVALUEARRAY);
BinarySerialization::writeArray(ostrm, outparms);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::execQuery(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
String query(BinarySerialization::readString(istrm));
String queryLang(BinarySerialization::readString(istrm));
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, BINSIG_INSTENUM);
BinaryCIMInstanceWriter handler(ostrm, ns);
chdl->execQuery(ns, handler, query, queryLang);
BinarySerialization::write(ostrm, END_INSTENUM);
BinarySerialization::write(ostrm, END_INSTENUM);
}
#ifndef OW_DISABLE_ASSOCIATION_TRAVERSAL
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::associators(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
StringArray propList;
StringArray* propListPtr = 0;
String ns(BinarySerialization::readString(istrm));
CIMObjectPath op(BinarySerialization::readObjectPath(istrm));
String assocClass(BinarySerialization::readString(istrm));
String resultClass(BinarySerialization::readString(istrm));
String role(BinarySerialization::readString(istrm));
String resultRole(BinarySerialization::readString(istrm));
EIncludeQualifiersFlag includeQualifiers(BinarySerialization::readBool(istrm) ? E_INCLUDE_QUALIFIERS : E_EXCLUDE_QUALIFIERS);
EIncludeClassOriginFlag includeClassOrigin(BinarySerialization::readBool(istrm) ? E_INCLUDE_CLASS_ORIGIN : E_EXCLUDE_CLASS_ORIGIN);
Bool nullPropertyList(BinarySerialization::readBool(istrm));
if (!nullPropertyList)
{
propList = BinarySerialization::readStringArray(istrm);
propListPtr = &propList;
}
BinarySerialization::write(ostrm, BIN_OK);
if (op.isClassPath())
{
// class path
BinarySerialization::write(ostrm, BINSIG_CLSENUM);
BinaryCIMClassWriter handler(ostrm);
op.setNameSpace(ns);
chdl->associatorsClasses(ns, op, handler, assocClass, resultClass,
role, resultRole, includeQualifiers, includeClassOrigin, propListPtr);
BinarySerialization::write(ostrm, END_CLSENUM);
BinarySerialization::write(ostrm, END_CLSENUM);
}
else
{
// instance path
BinarySerialization::write(ostrm, BINSIG_INSTENUM);
BinaryCIMInstanceWriter handler(ostrm, ns);
chdl->associators(ns, op, handler, assocClass, resultClass,
role, resultRole, includeQualifiers, includeClassOrigin, propListPtr);
BinarySerialization::write(ostrm, END_INSTENUM);
BinarySerialization::write(ostrm, END_INSTENUM);
}
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::associatorNames(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMObjectPath op(BinarySerialization::readObjectPath(istrm));
String assocClass(BinarySerialization::readString(istrm));
String resultClass(BinarySerialization::readString(istrm));
String role(BinarySerialization::readString(istrm));
String resultRole(BinarySerialization::readString(istrm));
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, BINSIG_OPENUM);
BinaryCIMObjectPathWriter handler(ostrm, getHost());
chdl->associatorNames(ns, op, handler, assocClass,
resultClass, role, resultRole);
BinarySerialization::write(ostrm, END_OPENUM);
BinarySerialization::write(ostrm, END_OPENUM);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::references(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
StringArray propList;
StringArray* propListPtr = 0;
String ns(BinarySerialization::readString(istrm));
CIMObjectPath op(BinarySerialization::readObjectPath(istrm));
String resultClass(BinarySerialization::readString(istrm));
String role(BinarySerialization::readString(istrm));
EIncludeQualifiersFlag includeQualifiers(BinarySerialization::readBool(istrm) ? E_INCLUDE_QUALIFIERS : E_EXCLUDE_QUALIFIERS);
EIncludeClassOriginFlag includeClassOrigin(BinarySerialization::readBool(istrm) ? E_INCLUDE_CLASS_ORIGIN : E_EXCLUDE_CLASS_ORIGIN);
Bool nullPropertyList(BinarySerialization::readBool(istrm));
if (!nullPropertyList)
{
propList = BinarySerialization::readStringArray(istrm);
propListPtr = &propList;
}
BinarySerialization::write(ostrm, BIN_OK);
if (op.isClassPath())
{
// class path
BinarySerialization::write(ostrm, BINSIG_CLSENUM);
BinaryCIMClassWriter handler(ostrm);
chdl->referencesClasses(ns, op, handler, resultClass,
role, includeQualifiers, includeClassOrigin, propListPtr);
BinarySerialization::write(ostrm, END_CLSENUM);
BinarySerialization::write(ostrm, END_CLSENUM);
}
else
{
// instance path
BinarySerialization::write(ostrm, BINSIG_INSTENUM);
BinaryCIMInstanceWriter handler(ostrm, ns);
chdl->references(ns, op, handler, resultClass,
role, includeQualifiers, includeClassOrigin, propListPtr);
BinarySerialization::write(ostrm, END_INSTENUM);
BinarySerialization::write(ostrm, END_INSTENUM);
}
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::referenceNames(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& istrm)
{
String ns(BinarySerialization::readString(istrm));
CIMObjectPath op(BinarySerialization::readObjectPath(istrm));
String resultClass(BinarySerialization::readString(istrm));
String role(BinarySerialization::readString(istrm));
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, BINSIG_OPENUM);
BinaryCIMObjectPathWriter handler(ostrm, getHost());
chdl->referenceNames(ns, op, handler, resultClass, role);
BinarySerialization::write(ostrm, END_OPENUM);
BinarySerialization::write(ostrm, END_OPENUM);
}
#endif
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::getServerFeatures(const CIMOMHandleIFCRef& chdl,
std::ostream& ostrm, std::istream& /*istrm*/)
{
CIMFeatures f = chdl->getServerFeatures();
BinarySerialization::write(ostrm, BIN_OK);
BinarySerialization::write(ostrm, Int32(f.cimProduct));
BinarySerialization::writeString(ostrm, f.extURL);
BinarySerialization::writeStringArray(ostrm, f.supportedGroups);
BinarySerialization::writeBool(ostrm, f.supportsBatch);
BinarySerialization::writeStringArray(ostrm, f.supportedQueryLanguages);
BinarySerialization::writeString(ostrm, f.validation);
BinarySerialization::writeString(ostrm, f.cimom);
BinarySerialization::writeString(ostrm, f.protocolVersion);
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::writeError(std::ostream& ostrm, const char* msg)
{
BinarySerialization::write(ostrm, BIN_ERROR);
BinarySerialization::write(ostrm, msg);
}
//////////////////////////////////////////////////////////////////////////////
bool
BinaryRequestHandler::writeFileName(std::ostream& ostrm,
const String& fname)
{
LoggerRef lgr = getEnvironment()->getLogger(COMPONENT_NAME);
if (m_userId == UserId(-1))
{
OW_LOG_ERROR(lgr, "Binary request handler cannot change file ownership:"
" Owner unknown");
return false;
}
try
{
if (FileSystem::changeFileOwner(fname, m_userId) != 0)
{
OW_LOG_ERROR(lgr, Format("Binary request handler failed changing"
" ownership on file %1", fname));
return false;
}
// Write -1 to indicate file name follows
BinarySerialization::write(ostrm, Int32(-1));
// Write file name
BinarySerialization::writeString(ostrm, fname);
}
catch(...)
{
FileSystem::removeFile(fname);
throw;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
StringArray
BinaryRequestHandler::getSupportedContentTypes() const
{
StringArray rval;
rval.push_back("application/x-owbinary");
return rval;
}
//////////////////////////////////////////////////////////////////////////////
String
BinaryRequestHandler::getContentType() const
{
return String("application/x-owbinary");
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::init(const ServiceEnvironmentIFCRef& env)
{
}
//////////////////////////////////////////////////////////////////////////////
void
BinaryRequestHandler::shutdown()
{
}
} // end namespace OW_NAMESPACE
//////////////////////////////////////////////////////////////////////////////
OW_REQUEST_HANDLER_FACTORY(OW_NAMESPACE::BinaryRequestHandler,BinaryRequest);
|
kkaempf/openwbem
|
src/requesthandlers/binary/OW_BinaryRequestHandler.cpp
|
C++
|
bsd-3-clause
| 35,938 |
require_relative '../concepts/board'
class NodesController < ApplicationController
before_action :load_nodes, only: :index
before_action :load_routes, only: :index
before_action :load_board, only: :index
respond_to :json
caches_page :index
def index
render json: @nodes, board: @board
end
private
def load_nodes
@nodes = Node.all
end
def load_routes
@routes = Route.all
end
def load_board
@board = Board.new(nodes: @nodes, routes: @routes)
end
end
|
hjwylde/scotland-yard
|
app/controllers/nodes_controller.rb
|
Ruby
|
bsd-3-clause
| 500 |
$(function() {
JQTWEET = {
// Set twitter hash/user, number of tweets & id/class to append tweets
// You need to clear tweet-date.txt before toggle between hash and user
// for multiple hashtags, you can separate the hashtag with OR, eg:
search: '', //leave this blank if you want to show user's tweet
hash: '',
user: '', //username
numTweets:500, //number of tweets
appendTo: '',
useGridalicious: false,
template: '<div class="item"> <div class="time"><p>{AGO}</p></div>\
<div class="tweet-wrapper">\
<div class="profile"><img href="{PHO}" src="{PHOP}"/></div>\
<div class="user">{USER}</div>\
<div class="text">{TEXT}</div><div class="img">{IMG}</div></div></div>',
// core function of jqtweet
// https://dev.twitter.com/docs/using-search
loadTweets: function() {
//console.log("We Made it here");
var request;
// different JSON request {hash|user}
if (JQTWEET.search) {
request = {
q: JQTWEET.search,
count: JQTWEET.numTweets,
api: 'search_tweets'
}
} else {
request = {
q: JQTWEET.user,
count: JQTWEET.numTweets,
api: 'statuses_userTimeline'
}
}
$.ajax({
url: 'grabtweets.php',
type: 'POST',
dataType: 'json',
data: request,
success: function(data, textStatus, xhr) {
if (data.httpstatus == 200) {
if (JQTWEET.search) data = data.statuses;
var text, name, img;
try {
// append tweets into page
for (var i = 0; i < JQTWEET.numTweets; i++) {
img = '';
url = 'http://twitter.com/' + data[i].user.screen_name + '/status/' + data[i].id_str;
try {
if (data[i].entities['media']) {
img = '<img src="' + data[i].entities['media'][0].media_url + '" />';
}
} catch (e) {
//no media
}
$(JQTWEET.appendTo).append( JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) )
.replace('{USER}', data[i].user.screen_name)
.replace('{PHO}', data[i].user.profile_image_url)
.replace('{PHOP}', data[i].user.profile_image_url)
.replace('{IMG}', img)
.replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) )
.replace('{URL}', url )
);
}
} catch (e) {
//item is less than item count
}
if (JQTWEET.useGridalicious) {
//run grid-a-licious
$(JQTWEET.appendTo).gridalicious({
gutter: 13,
width: 1080,
animate: true
});
}
} else alert('no data returned');
}
});
},
/**
* relative time calculator FROM TWITTER
* @param {string} twitter date string returned from Twitter API
* @return {string} relative time like "2 minutes ago"
*/
timeAgo: function(dateString) {
var rightNow = new Date();
var then = new Date(dateString);
if ($.browser.msie) {
// IE can't parse these crazy Ruby dates
then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
}
var diff = rightNow - then;
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
if (isNaN(diff) || diff < 0) {
return ""; // return blank string if unknown
}
if (diff < second * 2) {
// within 2 seconds
return "right now";
}
if (diff < minute) {
return Math.floor(diff / second) + " seconds ago";
}
if (diff < minute * 2) {
return "about 1 minute ago";
}
if (diff < hour) {
return Math.floor(diff / minute) + " minutes ago";
}
if (diff < hour * 2) {
return "about 1 hour ago";
}
if (diff < day) {
return Math.floor(diff / hour) + " hours ago";
}
if (diff > day && diff < day * 2) {
return "yesterday";
}
if (diff < day * 365) {
return Math.floor(diff / day) + " days ago";
}
else {
return "over a year ago";
}
}, // timeAgo()
/**
* The Twitalinkahashifyer!
* http://www.dustindiaz.com/basement/ify.html
* Eg:
* ify.clean('your tweet text');
*/
ify: {
link: function(tweet) {
return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
var http = m2.match(/w/) ? 'http://' : '';
return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
});
},
at: function(tweet) {
return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>';
});
},
list: function(tweet) {
return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) {
return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>';
});
},
hash: function(tweet) {
return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
});
},
clean: function(tweet) {
return this.hash(this.at(this.list(this.link(tweet))));
}
} // ify
};
});
|
Amaceika/TowerWall
|
twitter-oauth/jquery.jstwitter.js
|
JavaScript
|
bsd-3-clause
| 6,798 |
// 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 "content/renderer/input/input_handler_proxy.h"
#include "base/auto_reset.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/trace_event/trace_event.h"
#include "content/common/input/did_overscroll_params.h"
#include "content/common/input/web_input_event_traits.h"
#include "content/public/common/content_switches.h"
#include "content/renderer/input/input_handler_proxy_client.h"
#include "content/renderer/input/input_scroll_elasticity_controller.h"
#include "third_party/WebKit/public/platform/Platform.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "ui/events/latency_info.h"
#include "ui/gfx/frame_time.h"
#include "ui/gfx/geometry/point_conversions.h"
using blink::WebFloatPoint;
using blink::WebFloatSize;
using blink::WebGestureEvent;
using blink::WebInputEvent;
using blink::WebMouseEvent;
using blink::WebMouseWheelEvent;
using blink::WebPoint;
using blink::WebTouchEvent;
using blink::WebTouchPoint;
namespace {
// Maximum time between a fling event's timestamp and the first |Animate| call
// for the fling curve to use the fling timestamp as the initial animation time.
// Two frames allows a minor delay between event creation and the first animate.
const double kMaxSecondsFromFlingTimestampToFirstAnimate = 2. / 60.;
// Threshold for determining whether a fling scroll delta should have caused the
// client to scroll.
const float kScrollEpsilon = 0.1f;
// Minimum fling velocity required for the active fling and new fling for the
// two to accumulate.
const double kMinBoostFlingSpeedSquare = 350. * 350.;
// Minimum velocity for the active touch scroll to preserve (boost) an active
// fling for which cancellation has been deferred.
const double kMinBoostTouchScrollSpeedSquare = 150 * 150.;
// Timeout window after which the active fling will be cancelled if no scrolls
// or flings of sufficient velocity relative to the current fling are received.
// The default value on Android native views is 40ms, but we use a slightly
// increased value to accomodate small IPC message delays.
const double kFlingBoostTimeoutDelaySeconds = 0.045;
gfx::Vector2dF ToClientScrollIncrement(const WebFloatSize& increment) {
return gfx::Vector2dF(-increment.width, -increment.height);
}
double InSecondsF(const base::TimeTicks& time) {
return (time - base::TimeTicks()).InSecondsF();
}
bool ShouldSuppressScrollForFlingBoosting(
const gfx::Vector2dF& current_fling_velocity,
const WebGestureEvent& scroll_update_event,
double time_since_last_boost_event) {
DCHECK_EQ(WebInputEvent::GestureScrollUpdate, scroll_update_event.type);
gfx::Vector2dF dx(scroll_update_event.data.scrollUpdate.deltaX,
scroll_update_event.data.scrollUpdate.deltaY);
if (gfx::DotProduct(current_fling_velocity, dx) <= 0)
return false;
if (time_since_last_boost_event < 0.001)
return true;
// TODO(jdduke): Use |scroll_update_event.data.scrollUpdate.velocity{X,Y}|.
// The scroll must be of sufficient velocity to maintain the active fling.
const gfx::Vector2dF scroll_velocity =
gfx::ScaleVector2d(dx, 1. / time_since_last_boost_event);
if (scroll_velocity.LengthSquared() < kMinBoostTouchScrollSpeedSquare)
return false;
return true;
}
bool ShouldBoostFling(const gfx::Vector2dF& current_fling_velocity,
const WebGestureEvent& fling_start_event) {
DCHECK_EQ(WebInputEvent::GestureFlingStart, fling_start_event.type);
gfx::Vector2dF new_fling_velocity(
fling_start_event.data.flingStart.velocityX,
fling_start_event.data.flingStart.velocityY);
if (gfx::DotProduct(current_fling_velocity, new_fling_velocity) <= 0)
return false;
if (current_fling_velocity.LengthSquared() < kMinBoostFlingSpeedSquare)
return false;
if (new_fling_velocity.LengthSquared() < kMinBoostFlingSpeedSquare)
return false;
return true;
}
WebGestureEvent ObtainGestureScrollBegin(const WebGestureEvent& event) {
WebGestureEvent scroll_begin_event = event;
scroll_begin_event.type = WebInputEvent::GestureScrollBegin;
scroll_begin_event.data.scrollBegin.deltaXHint = 0;
scroll_begin_event.data.scrollBegin.deltaYHint = 0;
return scroll_begin_event;
}
void ReportInputEventLatencyUma(const WebInputEvent& event,
const ui::LatencyInfo& latency_info) {
if (!(event.type == WebInputEvent::GestureScrollBegin ||
event.type == WebInputEvent::GestureScrollUpdate ||
event.type == WebInputEvent::GesturePinchBegin ||
event.type == WebInputEvent::GesturePinchUpdate ||
event.type == WebInputEvent::GestureFlingStart)) {
return;
}
ui::LatencyInfo::LatencyMap::const_iterator it =
latency_info.latency_components.find(std::make_pair(
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, 0));
if (it == latency_info.latency_components.end())
return;
base::TimeDelta delta = base::TimeTicks::Now() - it->second.event_time;
for (size_t i = 0; i < it->second.event_count; ++i) {
switch (event.type) {
case blink::WebInputEvent::GestureScrollBegin:
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Event.Latency.RendererImpl.GestureScrollBegin",
delta.InMicroseconds(), 1, 1000000, 100);
break;
case blink::WebInputEvent::GestureScrollUpdate:
UMA_HISTOGRAM_CUSTOM_COUNTS(
// So named for historical reasons.
"Event.Latency.RendererImpl.GestureScroll2",
delta.InMicroseconds(), 1, 1000000, 100);
break;
case blink::WebInputEvent::GesturePinchBegin:
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Event.Latency.RendererImpl.GesturePinchBegin",
delta.InMicroseconds(), 1, 1000000, 100);
break;
case blink::WebInputEvent::GesturePinchUpdate:
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Event.Latency.RendererImpl.GesturePinchUpdate",
delta.InMicroseconds(), 1, 1000000, 100);
break;
case blink::WebInputEvent::GestureFlingStart:
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Event.Latency.RendererImpl.GestureFlingStart",
delta.InMicroseconds(), 1, 1000000, 100);
break;
default:
NOTREACHED();
break;
}
}
}
} // namespace
namespace content {
InputHandlerProxy::InputHandlerProxy(cc::InputHandler* input_handler,
InputHandlerProxyClient* client)
: client_(client),
input_handler_(input_handler),
deferred_fling_cancel_time_seconds_(0),
#ifndef NDEBUG
expect_scroll_update_end_(false),
#endif
gesture_scroll_on_impl_thread_(false),
gesture_pinch_on_impl_thread_(false),
fling_may_be_active_on_main_thread_(false),
disallow_horizontal_fling_scroll_(false),
disallow_vertical_fling_scroll_(false),
has_fling_animation_started_(false),
uma_latency_reporting_enabled_(base::TimeTicks::IsHighResolution()) {
DCHECK(client);
input_handler_->BindToClient(this);
smooth_scroll_enabled_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableSmoothScrolling);
cc::ScrollElasticityHelper* scroll_elasticity_helper =
input_handler_->CreateScrollElasticityHelper();
if (scroll_elasticity_helper) {
scroll_elasticity_controller_.reset(
new InputScrollElasticityController(scroll_elasticity_helper));
}
}
InputHandlerProxy::~InputHandlerProxy() {}
void InputHandlerProxy::WillShutdown() {
scroll_elasticity_controller_.reset();
input_handler_ = NULL;
client_->WillShutdown();
}
InputHandlerProxy::EventDisposition
InputHandlerProxy::HandleInputEventWithLatencyInfo(
const WebInputEvent& event,
ui::LatencyInfo* latency_info) {
DCHECK(input_handler_);
if (uma_latency_reporting_enabled_)
ReportInputEventLatencyUma(event, *latency_info);
TRACE_EVENT_FLOW_STEP0("input,benchmark",
"LatencyInfo.Flow",
TRACE_ID_DONT_MANGLE(latency_info->trace_id),
"HandleInputEventImpl");
scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor =
input_handler_->CreateLatencyInfoSwapPromiseMonitor(latency_info);
InputHandlerProxy::EventDisposition disposition = HandleInputEvent(event);
return disposition;
}
InputHandlerProxy::EventDisposition InputHandlerProxy::HandleInputEvent(
const WebInputEvent& event) {
DCHECK(input_handler_);
TRACE_EVENT1("input,benchmark", "InputHandlerProxy::HandleInputEvent",
"type", WebInputEventTraits::GetName(event.type));
client_->DidReceiveInputEvent(event);
if (FilterInputEventForFlingBoosting(event))
return DID_HANDLE;
switch (event.type) {
case WebInputEvent::MouseWheel:
return HandleMouseWheel(static_cast<const WebMouseWheelEvent&>(event));
case WebInputEvent::GestureScrollBegin:
return HandleGestureScrollBegin(
static_cast<const WebGestureEvent&>(event));
case WebInputEvent::GestureScrollUpdate:
return HandleGestureScrollUpdate(
static_cast<const WebGestureEvent&>(event));
case WebInputEvent::GestureScrollEnd:
return HandleGestureScrollEnd(static_cast<const WebGestureEvent&>(event));
case WebInputEvent::GesturePinchBegin: {
DCHECK(!gesture_pinch_on_impl_thread_);
const WebGestureEvent& gesture_event =
static_cast<const WebGestureEvent&>(event);
if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad &&
input_handler_->HaveWheelEventHandlersAt(
gfx::Point(gesture_event.x, gesture_event.y))) {
return DID_NOT_HANDLE;
} else {
input_handler_->PinchGestureBegin();
gesture_pinch_on_impl_thread_ = true;
return DID_HANDLE;
}
}
case WebInputEvent::GesturePinchEnd:
if (gesture_pinch_on_impl_thread_) {
gesture_pinch_on_impl_thread_ = false;
input_handler_->PinchGestureEnd();
return DID_HANDLE;
} else {
return DID_NOT_HANDLE;
}
case WebInputEvent::GesturePinchUpdate: {
if (gesture_pinch_on_impl_thread_) {
const WebGestureEvent& gesture_event =
static_cast<const WebGestureEvent&>(event);
if (gesture_event.data.pinchUpdate.zoomDisabled)
return DROP_EVENT;
input_handler_->PinchGestureUpdate(
gesture_event.data.pinchUpdate.scale,
gfx::Point(gesture_event.x, gesture_event.y));
return DID_HANDLE;
} else {
return DID_NOT_HANDLE;
}
}
case WebInputEvent::GestureFlingStart:
return HandleGestureFlingStart(
*static_cast<const WebGestureEvent*>(&event));
case WebInputEvent::GestureFlingCancel:
if (CancelCurrentFling())
return DID_HANDLE;
else if (!fling_may_be_active_on_main_thread_)
return DROP_EVENT;
return DID_NOT_HANDLE;
case WebInputEvent::TouchStart:
return HandleTouchStart(static_cast<const WebTouchEvent&>(event));
case WebInputEvent::MouseMove: {
const WebMouseEvent& mouse_event =
static_cast<const WebMouseEvent&>(event);
// TODO(tony): Ignore when mouse buttons are down?
// TODO(davemoore): This should never happen, but bug #326635 showed some
// surprising crashes.
CHECK(input_handler_);
input_handler_->MouseMoveAt(gfx::Point(mouse_event.x, mouse_event.y));
return DID_NOT_HANDLE;
}
default:
if (WebInputEvent::isKeyboardEventType(event.type)) {
// Only call |CancelCurrentFling()| if a fling was active, as it will
// otherwise disrupt an in-progress touch scroll.
if (fling_curve_)
CancelCurrentFling();
}
break;
}
return DID_NOT_HANDLE;
}
InputHandlerProxy::EventDisposition InputHandlerProxy::HandleMouseWheel(
const WebMouseWheelEvent& wheel_event) {
InputHandlerProxy::EventDisposition result = DID_NOT_HANDLE;
cc::InputHandlerScrollResult scroll_result;
// TODO(ccameron): The rail information should be pushed down into
// InputHandler.
gfx::Vector2dF scroll_delta(
wheel_event.railsMode != WebInputEvent::RailsModeVertical
? -wheel_event.deltaX
: 0,
wheel_event.railsMode != WebInputEvent::RailsModeHorizontal
? -wheel_event.deltaY
: 0);
if (wheel_event.scrollByPage) {
// TODO(jamesr): We don't properly handle scroll by page in the compositor
// thread, so punt it to the main thread. http://crbug.com/236639
result = DID_NOT_HANDLE;
} else if (!wheel_event.canScroll) {
// Wheel events with |canScroll| == false will not trigger scrolling,
// only event handlers. Forward to the main thread.
result = DID_NOT_HANDLE;
} else if (smooth_scroll_enabled_) {
cc::InputHandler::ScrollStatus scroll_status =
input_handler_->ScrollAnimated(gfx::Point(wheel_event.x, wheel_event.y),
scroll_delta);
switch (scroll_status) {
case cc::InputHandler::SCROLL_STARTED:
result = DID_HANDLE;
break;
case cc::InputHandler::SCROLL_IGNORED:
result = DROP_EVENT;
default:
result = DID_NOT_HANDLE;
break;
}
} else {
cc::InputHandler::ScrollStatus scroll_status = input_handler_->ScrollBegin(
gfx::Point(wheel_event.x, wheel_event.y), cc::InputHandler::WHEEL);
switch (scroll_status) {
case cc::InputHandler::SCROLL_STARTED: {
TRACE_EVENT_INSTANT2("input",
"InputHandlerProxy::handle_input wheel scroll",
TRACE_EVENT_SCOPE_THREAD, "deltaX",
scroll_delta.x(), "deltaY", scroll_delta.y());
gfx::Point scroll_point(wheel_event.x, wheel_event.y);
scroll_result = input_handler_->ScrollBy(scroll_point, scroll_delta);
HandleOverscroll(scroll_point, scroll_result);
input_handler_->ScrollEnd();
result = scroll_result.did_scroll ? DID_HANDLE : DROP_EVENT;
break;
}
case cc::InputHandler::SCROLL_IGNORED:
// TODO(jamesr): This should be DROP_EVENT, but in cases where we fail
// to properly sync scrollability it's safer to send the event to the
// main thread. Change back to DROP_EVENT once we have synchronization
// bugs sorted out.
result = DID_NOT_HANDLE;
break;
case cc::InputHandler::SCROLL_UNKNOWN:
case cc::InputHandler::SCROLL_ON_MAIN_THREAD:
result = DID_NOT_HANDLE;
break;
case cc::InputHandler::ScrollStatusCount:
NOTREACHED();
break;
}
}
// Send the event and its disposition to the elasticity controller to update
// the over-scroll animation. If the event is to be handled on the main
// thread, the event and its disposition will be sent to the elasticity
// controller after being handled on the main thread.
if (scroll_elasticity_controller_ && result != DID_NOT_HANDLE) {
// Note that the call to the elasticity controller is made asynchronously,
// to minimize divergence between main thread and impl thread event
// handling paths.
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&InputScrollElasticityController::ObserveWheelEventAndResult,
scroll_elasticity_controller_->GetWeakPtr(), wheel_event,
scroll_result));
}
return result;
}
InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureScrollBegin(
const WebGestureEvent& gesture_event) {
DCHECK(!gesture_scroll_on_impl_thread_);
#ifndef NDEBUG
DCHECK(!expect_scroll_update_end_);
expect_scroll_update_end_ = true;
#endif
cc::InputHandler::ScrollStatus scroll_status = input_handler_->ScrollBegin(
gfx::Point(gesture_event.x, gesture_event.y), cc::InputHandler::GESTURE);
UMA_HISTOGRAM_ENUMERATION("Renderer4.CompositorScrollHitTestResult",
scroll_status,
cc::InputHandler::ScrollStatusCount);
switch (scroll_status) {
case cc::InputHandler::SCROLL_STARTED:
TRACE_EVENT_INSTANT0("input",
"InputHandlerProxy::handle_input gesture scroll",
TRACE_EVENT_SCOPE_THREAD);
gesture_scroll_on_impl_thread_ = true;
return DID_HANDLE;
case cc::InputHandler::SCROLL_UNKNOWN:
case cc::InputHandler::SCROLL_ON_MAIN_THREAD:
return DID_NOT_HANDLE;
case cc::InputHandler::SCROLL_IGNORED:
return DROP_EVENT;
case cc::InputHandler::ScrollStatusCount:
NOTREACHED();
break;
}
return DID_NOT_HANDLE;
}
InputHandlerProxy::EventDisposition
InputHandlerProxy::HandleGestureScrollUpdate(
const WebGestureEvent& gesture_event) {
#ifndef NDEBUG
DCHECK(expect_scroll_update_end_);
#endif
if (!gesture_scroll_on_impl_thread_ && !gesture_pinch_on_impl_thread_)
return DID_NOT_HANDLE;
gfx::Point scroll_point(gesture_event.x, gesture_event.y);
gfx::Vector2dF scroll_delta(-gesture_event.data.scrollUpdate.deltaX,
-gesture_event.data.scrollUpdate.deltaY);
cc::InputHandlerScrollResult scroll_result = input_handler_->ScrollBy(
scroll_point, scroll_delta);
HandleOverscroll(scroll_point, scroll_result);
return scroll_result.did_scroll ? DID_HANDLE : DROP_EVENT;
}
InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureScrollEnd(
const WebGestureEvent& gesture_event) {
#ifndef NDEBUG
DCHECK(expect_scroll_update_end_);
expect_scroll_update_end_ = false;
#endif
input_handler_->ScrollEnd();
if (!gesture_scroll_on_impl_thread_)
return DID_NOT_HANDLE;
gesture_scroll_on_impl_thread_ = false;
return DID_HANDLE;
}
InputHandlerProxy::EventDisposition InputHandlerProxy::HandleGestureFlingStart(
const WebGestureEvent& gesture_event) {
cc::InputHandler::ScrollStatus scroll_status;
if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad) {
scroll_status = input_handler_->ScrollBegin(
gfx::Point(gesture_event.x, gesture_event.y),
cc::InputHandler::NON_BUBBLING_GESTURE);
} else {
if (!gesture_scroll_on_impl_thread_)
scroll_status = cc::InputHandler::SCROLL_ON_MAIN_THREAD;
else
scroll_status = input_handler_->FlingScrollBegin();
}
#ifndef NDEBUG
expect_scroll_update_end_ = false;
#endif
switch (scroll_status) {
case cc::InputHandler::SCROLL_STARTED: {
if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad)
input_handler_->ScrollEnd();
const float vx = gesture_event.data.flingStart.velocityX;
const float vy = gesture_event.data.flingStart.velocityY;
current_fling_velocity_ = gfx::Vector2dF(vx, vy);
DCHECK(!current_fling_velocity_.IsZero());
fling_curve_.reset(client_->CreateFlingAnimationCurve(
gesture_event.sourceDevice,
WebFloatPoint(vx, vy),
blink::WebSize()));
disallow_horizontal_fling_scroll_ = !vx;
disallow_vertical_fling_scroll_ = !vy;
TRACE_EVENT_ASYNC_BEGIN2("input",
"InputHandlerProxy::HandleGestureFling::started",
this,
"vx",
vx,
"vy",
vy);
// Note that the timestamp will only be used to kickstart the animation if
// its sufficiently close to the timestamp of the first call |Animate()|.
has_fling_animation_started_ = false;
fling_parameters_.startTime = gesture_event.timeStampSeconds;
fling_parameters_.delta = WebFloatPoint(vx, vy);
fling_parameters_.point = WebPoint(gesture_event.x, gesture_event.y);
fling_parameters_.globalPoint =
WebPoint(gesture_event.globalX, gesture_event.globalY);
fling_parameters_.modifiers = gesture_event.modifiers;
fling_parameters_.sourceDevice = gesture_event.sourceDevice;
input_handler_->SetNeedsAnimate();
return DID_HANDLE;
}
case cc::InputHandler::SCROLL_UNKNOWN:
case cc::InputHandler::SCROLL_ON_MAIN_THREAD: {
TRACE_EVENT_INSTANT0("input",
"InputHandlerProxy::HandleGestureFling::"
"scroll_on_main_thread",
TRACE_EVENT_SCOPE_THREAD);
gesture_scroll_on_impl_thread_ = false;
fling_may_be_active_on_main_thread_ = true;
return DID_NOT_HANDLE;
}
case cc::InputHandler::SCROLL_IGNORED: {
TRACE_EVENT_INSTANT0(
"input",
"InputHandlerProxy::HandleGestureFling::ignored",
TRACE_EVENT_SCOPE_THREAD);
gesture_scroll_on_impl_thread_ = false;
if (gesture_event.sourceDevice == blink::WebGestureDeviceTouchpad) {
// We still pass the curve to the main thread if there's nothing
// scrollable, in case something
// registers a handler before the curve is over.
return DID_NOT_HANDLE;
}
return DROP_EVENT;
}
case cc::InputHandler::ScrollStatusCount:
NOTREACHED();
break;
}
return DID_NOT_HANDLE;
}
InputHandlerProxy::EventDisposition InputHandlerProxy::HandleTouchStart(
const blink::WebTouchEvent& touch_event) {
for (size_t i = 0; i < touch_event.touchesLength; ++i) {
if (touch_event.touches[i].state != WebTouchPoint::StatePressed)
continue;
if (input_handler_->DoTouchEventsBlockScrollAt(
gfx::Point(touch_event.touches[i].position.x,
touch_event.touches[i].position.y))) {
// TODO(rbyers): We should consider still sending the touch events to
// main asynchronously (crbug.com/455539).
return DID_NOT_HANDLE;
}
}
return DROP_EVENT;
}
bool InputHandlerProxy::FilterInputEventForFlingBoosting(
const WebInputEvent& event) {
if (!WebInputEvent::isGestureEventType(event.type))
return false;
if (!fling_curve_) {
DCHECK(!deferred_fling_cancel_time_seconds_);
return false;
}
const WebGestureEvent& gesture_event =
static_cast<const WebGestureEvent&>(event);
if (gesture_event.type == WebInputEvent::GestureFlingCancel) {
if (gesture_event.data.flingCancel.preventBoosting)
return false;
if (current_fling_velocity_.LengthSquared() < kMinBoostFlingSpeedSquare)
return false;
TRACE_EVENT_INSTANT0("input",
"InputHandlerProxy::FlingBoostStart",
TRACE_EVENT_SCOPE_THREAD);
deferred_fling_cancel_time_seconds_ =
event.timeStampSeconds + kFlingBoostTimeoutDelaySeconds;
return true;
}
// A fling is either inactive or is "free spinning", i.e., has yet to be
// interrupted by a touch gesture, in which case there is nothing to filter.
if (!deferred_fling_cancel_time_seconds_)
return false;
// Gestures from a different source should immediately interrupt the fling.
if (gesture_event.sourceDevice != fling_parameters_.sourceDevice) {
CancelCurrentFling();
return false;
}
switch (gesture_event.type) {
case WebInputEvent::GestureTapCancel:
case WebInputEvent::GestureTapDown:
return false;
case WebInputEvent::GestureScrollBegin:
if (!input_handler_->IsCurrentlyScrollingLayerAt(
gfx::Point(gesture_event.x, gesture_event.y),
fling_parameters_.sourceDevice == blink::WebGestureDeviceTouchpad
? cc::InputHandler::NON_BUBBLING_GESTURE
: cc::InputHandler::GESTURE)) {
CancelCurrentFling();
return false;
}
// TODO(jdduke): Use |gesture_event.data.scrollBegin.delta{X,Y}Hint| to
// determine if the ScrollBegin should immediately cancel the fling.
ExtendBoostedFlingTimeout(gesture_event);
return true;
case WebInputEvent::GestureScrollUpdate: {
const double time_since_last_boost_event =
event.timeStampSeconds - last_fling_boost_event_.timeStampSeconds;
if (ShouldSuppressScrollForFlingBoosting(current_fling_velocity_,
gesture_event,
time_since_last_boost_event)) {
ExtendBoostedFlingTimeout(gesture_event);
return true;
}
CancelCurrentFling();
return false;
}
case WebInputEvent::GestureScrollEnd:
// Clear the last fling boost event *prior* to fling cancellation,
// preventing insertion of a synthetic GestureScrollBegin.
last_fling_boost_event_ = WebGestureEvent();
CancelCurrentFling();
return true;
case WebInputEvent::GestureFlingStart: {
DCHECK_EQ(fling_parameters_.sourceDevice, gesture_event.sourceDevice);
bool fling_boosted =
fling_parameters_.modifiers == gesture_event.modifiers &&
ShouldBoostFling(current_fling_velocity_, gesture_event);
gfx::Vector2dF new_fling_velocity(
gesture_event.data.flingStart.velocityX,
gesture_event.data.flingStart.velocityY);
DCHECK(!new_fling_velocity.IsZero());
if (fling_boosted)
current_fling_velocity_ += new_fling_velocity;
else
current_fling_velocity_ = new_fling_velocity;
WebFloatPoint velocity(current_fling_velocity_.x(),
current_fling_velocity_.y());
deferred_fling_cancel_time_seconds_ = 0;
disallow_horizontal_fling_scroll_ = !velocity.x;
disallow_vertical_fling_scroll_ = !velocity.y;
last_fling_boost_event_ = WebGestureEvent();
fling_curve_.reset(client_->CreateFlingAnimationCurve(
gesture_event.sourceDevice,
velocity,
blink::WebSize()));
fling_parameters_.startTime = gesture_event.timeStampSeconds;
fling_parameters_.delta = velocity;
fling_parameters_.point = WebPoint(gesture_event.x, gesture_event.y);
fling_parameters_.globalPoint =
WebPoint(gesture_event.globalX, gesture_event.globalY);
TRACE_EVENT_INSTANT2("input",
fling_boosted ? "InputHandlerProxy::FlingBoosted"
: "InputHandlerProxy::FlingReplaced",
TRACE_EVENT_SCOPE_THREAD,
"vx",
current_fling_velocity_.x(),
"vy",
current_fling_velocity_.y());
// The client expects balanced calls between a consumed GestureFlingStart
// and |DidStopFlinging()|. TODO(jdduke): Provide a count parameter to
// |DidStopFlinging()| and only send after the accumulated fling ends.
client_->DidStopFlinging();
return true;
}
default:
// All other types of gestures (taps, presses, etc...) will complete the
// deferred fling cancellation.
CancelCurrentFling();
return false;
}
}
void InputHandlerProxy::ExtendBoostedFlingTimeout(
const blink::WebGestureEvent& event) {
TRACE_EVENT_INSTANT0("input",
"InputHandlerProxy::ExtendBoostedFlingTimeout",
TRACE_EVENT_SCOPE_THREAD);
deferred_fling_cancel_time_seconds_ =
event.timeStampSeconds + kFlingBoostTimeoutDelaySeconds;
last_fling_boost_event_ = event;
}
void InputHandlerProxy::Animate(base::TimeTicks time) {
if (scroll_elasticity_controller_)
scroll_elasticity_controller_->Animate(time);
if (!fling_curve_)
return;
double monotonic_time_sec = InSecondsF(time);
if (deferred_fling_cancel_time_seconds_ &&
monotonic_time_sec > deferred_fling_cancel_time_seconds_) {
CancelCurrentFling();
return;
}
client_->DidAnimateForInput();
if (!has_fling_animation_started_) {
has_fling_animation_started_ = true;
// Guard against invalid, future or sufficiently stale start times, as there
// are no guarantees fling event and animation timestamps are compatible.
if (!fling_parameters_.startTime ||
monotonic_time_sec <= fling_parameters_.startTime ||
monotonic_time_sec >= fling_parameters_.startTime +
kMaxSecondsFromFlingTimestampToFirstAnimate) {
fling_parameters_.startTime = monotonic_time_sec;
input_handler_->SetNeedsAnimate();
return;
}
}
bool fling_is_active =
fling_curve_->apply(monotonic_time_sec - fling_parameters_.startTime,
this);
if (disallow_vertical_fling_scroll_ && disallow_horizontal_fling_scroll_)
fling_is_active = false;
if (fling_is_active) {
input_handler_->SetNeedsAnimate();
} else {
TRACE_EVENT_INSTANT0("input",
"InputHandlerProxy::animate::flingOver",
TRACE_EVENT_SCOPE_THREAD);
CancelCurrentFling();
}
}
void InputHandlerProxy::MainThreadHasStoppedFlinging() {
fling_may_be_active_on_main_thread_ = false;
client_->DidStopFlinging();
}
void InputHandlerProxy::ReconcileElasticOverscrollAndRootScroll() {
if (scroll_elasticity_controller_)
scroll_elasticity_controller_->ReconcileStretchAndScroll();
}
void InputHandlerProxy::HandleOverscroll(
const gfx::Point& causal_event_viewport_point,
const cc::InputHandlerScrollResult& scroll_result) {
DCHECK(client_);
if (!scroll_result.did_overscroll_root)
return;
TRACE_EVENT2("input",
"InputHandlerProxy::DidOverscroll",
"dx",
scroll_result.unused_scroll_delta.x(),
"dy",
scroll_result.unused_scroll_delta.y());
DidOverscrollParams params;
params.accumulated_overscroll = scroll_result.accumulated_root_overscroll;
params.latest_overscroll_delta = scroll_result.unused_scroll_delta;
params.current_fling_velocity =
ToClientScrollIncrement(current_fling_velocity_);
params.causal_event_viewport_point = causal_event_viewport_point;
if (fling_curve_) {
static const int kFlingOverscrollThreshold = 1;
disallow_horizontal_fling_scroll_ |=
std::abs(params.accumulated_overscroll.x()) >=
kFlingOverscrollThreshold;
disallow_vertical_fling_scroll_ |=
std::abs(params.accumulated_overscroll.y()) >=
kFlingOverscrollThreshold;
}
client_->DidOverscroll(params);
}
bool InputHandlerProxy::CancelCurrentFling() {
if (CancelCurrentFlingWithoutNotifyingClient()) {
client_->DidStopFlinging();
return true;
}
return false;
}
bool InputHandlerProxy::CancelCurrentFlingWithoutNotifyingClient() {
bool had_fling_animation = fling_curve_;
if (had_fling_animation &&
fling_parameters_.sourceDevice == blink::WebGestureDeviceTouchscreen) {
input_handler_->ScrollEnd();
TRACE_EVENT_ASYNC_END0(
"input",
"InputHandlerProxy::HandleGestureFling::started",
this);
}
TRACE_EVENT_INSTANT1("input",
"InputHandlerProxy::CancelCurrentFling",
TRACE_EVENT_SCOPE_THREAD,
"had_fling_animation",
had_fling_animation);
fling_curve_.reset();
has_fling_animation_started_ = false;
gesture_scroll_on_impl_thread_ = false;
current_fling_velocity_ = gfx::Vector2dF();
fling_parameters_ = blink::WebActiveWheelFlingParameters();
if (deferred_fling_cancel_time_seconds_) {
deferred_fling_cancel_time_seconds_ = 0;
WebGestureEvent last_fling_boost_event = last_fling_boost_event_;
last_fling_boost_event_ = WebGestureEvent();
if (last_fling_boost_event.type == WebInputEvent::GestureScrollBegin ||
last_fling_boost_event.type == WebInputEvent::GestureScrollUpdate) {
// Synthesize a GestureScrollBegin, as the original was suppressed.
HandleInputEvent(ObtainGestureScrollBegin(last_fling_boost_event));
}
}
return had_fling_animation;
}
bool InputHandlerProxy::TouchpadFlingScroll(
const WebFloatSize& increment) {
WebMouseWheelEvent synthetic_wheel;
synthetic_wheel.type = WebInputEvent::MouseWheel;
synthetic_wheel.deltaX = increment.width;
synthetic_wheel.deltaY = increment.height;
synthetic_wheel.hasPreciseScrollingDeltas = true;
synthetic_wheel.x = fling_parameters_.point.x;
synthetic_wheel.y = fling_parameters_.point.y;
synthetic_wheel.globalX = fling_parameters_.globalPoint.x;
synthetic_wheel.globalY = fling_parameters_.globalPoint.y;
synthetic_wheel.modifiers = fling_parameters_.modifiers;
InputHandlerProxy::EventDisposition disposition =
HandleInputEvent(synthetic_wheel);
switch (disposition) {
case DID_HANDLE:
return true;
case DROP_EVENT:
break;
case DID_NOT_HANDLE:
TRACE_EVENT_INSTANT0("input",
"InputHandlerProxy::scrollBy::AbortFling",
TRACE_EVENT_SCOPE_THREAD);
// If we got a DID_NOT_HANDLE, that means we need to deliver wheels on the
// main thread. In this case we need to schedule a commit and transfer the
// fling curve over to the main thread and run the rest of the wheels from
// there. This can happen when flinging a page that contains a scrollable
// subarea that we can't scroll on the thread if the fling starts outside
// the subarea but then is flung "under" the pointer.
client_->TransferActiveWheelFlingAnimation(fling_parameters_);
fling_may_be_active_on_main_thread_ = true;
CancelCurrentFlingWithoutNotifyingClient();
break;
}
return false;
}
bool InputHandlerProxy::scrollBy(const WebFloatSize& increment,
const WebFloatSize& velocity) {
WebFloatSize clipped_increment;
WebFloatSize clipped_velocity;
if (!disallow_horizontal_fling_scroll_) {
clipped_increment.width = increment.width;
clipped_velocity.width = velocity.width;
}
if (!disallow_vertical_fling_scroll_) {
clipped_increment.height = increment.height;
clipped_velocity.height = velocity.height;
}
current_fling_velocity_ = clipped_velocity;
// Early out if the increment is zero, but avoid early terimination if the
// velocity is still non-zero.
if (clipped_increment == WebFloatSize())
return clipped_velocity != WebFloatSize();
TRACE_EVENT2("input",
"InputHandlerProxy::scrollBy",
"x",
clipped_increment.width,
"y",
clipped_increment.height);
bool did_scroll = false;
switch (fling_parameters_.sourceDevice) {
case blink::WebGestureDeviceTouchpad:
did_scroll = TouchpadFlingScroll(clipped_increment);
break;
case blink::WebGestureDeviceTouchscreen: {
clipped_increment = ToClientScrollIncrement(clipped_increment);
cc::InputHandlerScrollResult scroll_result = input_handler_->ScrollBy(
fling_parameters_.point, clipped_increment);
HandleOverscroll(fling_parameters_.point, scroll_result);
did_scroll = scroll_result.did_scroll;
} break;
}
if (did_scroll) {
fling_parameters_.cumulativeScroll.width += clipped_increment.width;
fling_parameters_.cumulativeScroll.height += clipped_increment.height;
}
// It's possible the provided |increment| is sufficiently small as to not
// trigger a scroll, e.g., with a trivial time delta between fling updates.
// Return true in this case to prevent early fling termination.
if (std::abs(clipped_increment.width) < kScrollEpsilon &&
std::abs(clipped_increment.height) < kScrollEpsilon)
return true;
return did_scroll;
}
} // namespace content
|
fujunwei/chromium-crosswalk
|
content/renderer/input/input_handler_proxy.cc
|
C++
|
bsd-3-clause
| 35,811 |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Auxilios;
/**
* AuxiliosSearch represents the model behind the search form about `app\models\Auxilios`.
*/
class AuxiliosSearch extends Auxilios
{
public $documento_cliente;
public $nombre_cliente;
public $apellido_cliente;
public $tipoAuxilio;
public $familiar;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id_auxilio', 'tipo', 'num_meses', 'estado', 'id_cliente', 'tipo_auxilio', 'id_familiar'], 'integer'],
[['porcentaje_aux', 'monto'], 'number'],
[['fecha_auxilio', 'proveedor'], 'safe'],
[['documento_cliente', 'nombre_cliente', 'apellido_cliente', 'tipoAuxilio'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params,$tipo, $id)
{
if($id == 0){
$query = Auxilios::find()->where('auxilios.tipo=:tipo');
}else{
$query = Auxilios::find()->where('auxilios.tipo=:tipo AND auxilios.id_cliente =:id');
$query->addParams([':id' => $id]);
}
$query->addParams([':tipo' => $tipo]);
$query->joinWith(['idCliente', 'idFamiliar', 'tipoAuxilio']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['documento_cliente'] =[
'asc'=>['clientes.num_id'=>SORT_ASC],
'desc'=>['clientes.num_id'=>SORT_DESC],
];
$dataProvider->sort->attributes['nombre_cliente'] =[
'asc'=>['clientes.nombres'=>SORT_ASC],
'desc'=>['clientes.nombres'=>SORT_DESC],
];
$dataProvider->sort->attributes['apellido_cliente'] =[
'asc'=>['clientes.apellidos'=>SORT_ASC],
'desc'=>['clientes.apellidos'=>SORT_DESC],
];
$dataProvider->sort->attributes['tipoAuxilio'] =[
'asc'=>['tipo_auxilio.tipo_auxilio'=>SORT_ASC],
'desc'=>['tipo_auxilio.tipo_auxilio'=>SORT_DESC],
];
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'id_auxilio' => $this->id_auxilio,
'tipo' => $this->tipo,
'porcentaje_aux' => $this->porcentaje_aux,
'monto' => $this->monto,
'num_meses' => $this->num_meses,
'fecha_auxilio' => $this->fecha_auxilio,
'estado' => $this->estado,
'id_cliente' => $this->id_cliente,
'tipo_auxilio' => $this->tipo_auxilio,
'id_familiar' => $this->id_familiar,
]);
$query->andFilterWhere(['like', 'proveedor', $this->proveedor]);
$query->andFilterWhere(['like', 'clientes.num_id', $this->documento_cliente]);
$query->andFilterWhere(['like', 'clientes.nombres', $this->nombre_cliente]);
$query->andFilterWhere(['like', 'clientes.apellidos', $this->apellido_cliente]);
$query->andFilterWhere(['like', 'tipo_auxilio.tipo_auxilio', $this->tipoAuxilio]);
return $dataProvider;
}
}
|
oswen244/proserpaz
|
models/AuxiliosSearch.php
|
PHP
|
bsd-3-clause
| 3,499 |
<?php
/**
* Rebuilds the search indexes for the documentation pages.
*
* For the hourly cron rebuild use RebuildLuceneDocusIndex_Hourly
*
* @package docsviewer
* @subpackage tasks
*/
class RebuildLuceneDocsIndex extends BuildTask {
protected $title = "Rebuild Documentation Search Indexes";
protected $description = "
Rebuilds the indexes used for the search engine in the docsviewer.";
function run($request) {
$this->rebuildIndexes();
}
function rebuildIndexes($quiet = false) {
require_once(DOCSVIEWER_PATH .'/thirdparty/markdown/markdown.php');
require_once 'Zend/Search/Lucene.php';
ini_set("memory_limit", -1);
ini_set('max_execution_time', 0);
Filesystem::makeFolder(DocumentationSearch::get_index_location());
// only rebuild the index if we have to. Check for either flush or the time write.lock.file
// was last altered
$lock = DocumentationSearch::get_index_location() .'/write.lock.file';
$lockFileFresh = (file_exists($lock) && filemtime($lock) > (time() - (60 * 60 * 24)));
echo "Building index in ". DocumentationSearch::get_index_location() . PHP_EOL;
if($lockFileFresh && !isset($_REQUEST['flush'])) {
if(!$quiet) {
echo "Index recently rebuilt. If you want to force reindex use ?flush=1";
}
return true;
}
try {
$index = Zend_Search_Lucene::open(DocumentationSearch::get_index_location());
$index->removeReference();
}
catch (Zend_Search_Lucene_Exception $e) {
// user_error($e);
}
try {
$index = Zend_Search_Lucene::create(DocumentationSearch::get_index_location());
}
catch(Zend_Search_Lucene_Exception $c) {
user_error($c);
}
// includes registration
$pages = DocumentationSearch::get_all_documentation_pages();
if($pages) {
$count = 0;
// iconv complains about all the markdown formatting
// turn off notices while we parse
$error = error_reporting();
error_reporting('E_ALL ^ E_NOTICE');
foreach($pages as $page) {
$count++;
if(!is_dir($page->getPath())) {
$doc = new Zend_Search_Lucene_Document();
$content = $page->getMarkdown();
if($content) $content = Markdown($content);
$entity = ($entity = $page->getEntity()) ? $entity->getTitle() : "";
$doc->addField(Zend_Search_Lucene_Field::Text('content', $content));
$doc->addField($titleField = Zend_Search_Lucene_Field::Text('Title', $page->getTitle()));
$doc->addField($breadcrumbField = Zend_Search_Lucene_Field::Text('BreadcrumbTitle', $page->getBreadcrumbTitle()));
$doc->addField(Zend_Search_Lucene_Field::Keyword('Version', $page->getVersion()));
$doc->addField(Zend_Search_Lucene_Field::Keyword('Language', $page->getLang()));
$doc->addField(Zend_Search_Lucene_Field::Keyword('Entity', $entity));
$doc->addField(Zend_Search_Lucene_Field::Keyword('Link', $page->getLink(false)));
// custom boosts
$titleField->boost = 3;
$breadcrumbField->boost = 1.5;
foreach(DocumentationSearch::$boost_by_path as $pathExpr => $boost) {
if(preg_match($pathExpr, $page->getRelativePath())) $doc->boost = $boost;
}
$index->addDocument($doc);
}
if(!$quiet) echo "adding ". $page->getPath() ."\n";
}
error_reporting($error);
}
$index->commit();
if(!$quiet) echo "complete.";
}
}
/**
* @package docsviewer
* @subpackage tasks
*/
class RebuildLuceneDocusIndex_Hourly extends HourlyTask {
function process() {
$reindex = new RebuildLuceneDocusIndex();
$reindex->rebuildIndexes(true);
}
}
|
unclecheese/silverstripe-docsviewer
|
code/tasks/RebuildLuceneDocsIndex.php
|
PHP
|
bsd-3-clause
| 3,556 |
/////////////////////////////////////////////////////////////////////////////
// Program: wxWidgets Widgets Sample
// Name: checkbox.cpp
// Purpose: Part of the widgets sample showing wxCheckBox
// Author: Dimitri Schoolwerth, Vadim Zeitlin
// Created: 27 Sep 2003
// Copyright: (c) 2003 wxWindows team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
// for all others, include the necessary headers
#ifndef WX_PRECOMP
#include "wx/app.h"
#include "wx/log.h"
#include "wx/bitmap.h"
#include "wx/button.h"
#include "wx/checkbox.h"
#include "wx/radiobox.h"
#include "wx/statbox.h"
#include "wx/textctrl.h"
#include "wx/sizer.h"
#endif
#include "widgets.h"
#include "icons/checkbox.xpm"
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// control ids
enum
{
CheckboxPage_Reset = wxID_HIGHEST,
CheckboxPage_ChangeLabel,
CheckboxPage_Check,
CheckboxPage_Uncheck,
CheckboxPage_PartCheck,
CheckboxPage_ChkRight,
CheckboxPage_Checkbox
};
enum
{
CheckboxKind_2State,
CheckboxKind_3State,
CheckboxKind_3StateUser
};
// ----------------------------------------------------------------------------
// CheckBoxWidgetsPage
// ----------------------------------------------------------------------------
class CheckBoxWidgetsPage : public WidgetsPage
{
public:
CheckBoxWidgetsPage(WidgetsBookCtrl *book, wxImageList *imaglist);
virtual wxWindow *GetWidget() const wxOVERRIDE { return m_checkbox; }
virtual void RecreateWidget() wxOVERRIDE { CreateCheckbox(); }
// lazy creation of the content
virtual void CreateContent() wxOVERRIDE;
protected:
// event handlers
void OnCheckBox(wxCommandEvent& event);
void OnStyleChange(wxCommandEvent& event);
void OnButtonReset(wxCommandEvent& event);
void OnButtonChangeLabel(wxCommandEvent& event);
void OnButtonCheck(wxCommandEvent&) { m_checkbox->SetValue(true); }
void OnButtonUncheck(wxCommandEvent&) { m_checkbox->SetValue(false); }
void OnButtonPartCheck(wxCommandEvent&)
{
m_checkbox->Set3StateValue(wxCHK_UNDETERMINED);
}
void Is3State(wxUpdateUIEvent& event)
{
event.Enable( m_checkbox->Is3State() );
}
// reset the wxCheckBox parameters
void Reset();
// (re)create the wxCheckBox
void CreateCheckbox();
// the controls
// ------------
// the controls to choose the checkbox style
wxCheckBox *m_chkRight;
wxRadioBox *m_radioKind;
// the checkbox itself and the sizer it is in
wxCheckBox *m_checkbox;
wxSizer *m_sizerCheckbox;
// the text entries for command parameters
wxTextCtrl *m_textLabel;
private:
wxDECLARE_EVENT_TABLE();
DECLARE_WIDGETS_PAGE(CheckBoxWidgetsPage)
};
// ----------------------------------------------------------------------------
// event tables
// ----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(CheckBoxWidgetsPage, WidgetsPage)
EVT_CHECKBOX(CheckboxPage_Checkbox, CheckBoxWidgetsPage::OnCheckBox)
EVT_BUTTON(CheckboxPage_Reset, CheckBoxWidgetsPage::OnButtonReset)
EVT_BUTTON(CheckboxPage_ChangeLabel, CheckBoxWidgetsPage::OnButtonChangeLabel)
EVT_BUTTON(CheckboxPage_Check, CheckBoxWidgetsPage::OnButtonCheck)
EVT_BUTTON(CheckboxPage_Uncheck, CheckBoxWidgetsPage::OnButtonUncheck)
EVT_BUTTON(CheckboxPage_PartCheck, CheckBoxWidgetsPage::OnButtonPartCheck)
EVT_UPDATE_UI(CheckboxPage_PartCheck, CheckBoxWidgetsPage::Is3State)
EVT_RADIOBOX(wxID_ANY, CheckBoxWidgetsPage::OnStyleChange)
EVT_CHECKBOX(CheckboxPage_ChkRight, CheckBoxWidgetsPage::OnStyleChange)
wxEND_EVENT_TABLE()
// ============================================================================
// implementation
// ============================================================================
#if defined(__WXUNIVERSAL__)
#define FAMILY_CTRLS UNIVERSAL_CTRLS
#else
#define FAMILY_CTRLS NATIVE_CTRLS
#endif
IMPLEMENT_WIDGETS_PAGE(CheckBoxWidgetsPage, "CheckBox", FAMILY_CTRLS );
CheckBoxWidgetsPage::CheckBoxWidgetsPage(WidgetsBookCtrl *book,
wxImageList *imaglist)
: WidgetsPage(book, imaglist, checkbox_xpm)
{
}
void CheckBoxWidgetsPage::CreateContent()
{
wxSizer *sizerTop = new wxBoxSizer(wxHORIZONTAL);
// left pane
wxStaticBox *box = new wxStaticBox(this, wxID_ANY, "&Set style");
wxSizer *sizerLeft = new wxStaticBoxSizer(box, wxVERTICAL);
m_chkRight = CreateCheckBoxAndAddToSizer
(
sizerLeft,
"&Right aligned",
CheckboxPage_ChkRight
);
sizerLeft->Add(5, 5, 0, wxGROW | wxALL, 5); // spacer
static const wxString kinds[] =
{
"usual &2-state checkbox",
"&3rd state settable by program",
"&user-settable 3rd state",
};
m_radioKind = new wxRadioBox(this, wxID_ANY, "&Kind",
wxDefaultPosition, wxDefaultSize,
WXSIZEOF(kinds), kinds,
1);
sizerLeft->Add(m_radioKind, 0, wxGROW | wxALL, 5);
wxButton *btn = new wxButton(this, CheckboxPage_Reset, "&Reset");
sizerLeft->Add(btn, 0, wxALIGN_CENTRE_HORIZONTAL | wxALL, 15);
// middle pane
wxStaticBox *box2 = new wxStaticBox(this, wxID_ANY, "&Operations");
wxSizer *sizerMiddle = new wxStaticBoxSizer(box2, wxVERTICAL);
sizerMiddle->Add(CreateSizerWithTextAndButton(CheckboxPage_ChangeLabel,
"Change label",
wxID_ANY,
&m_textLabel),
0, wxALL | wxGROW, 5);
sizerMiddle->Add(new wxButton(this, CheckboxPage_Check, "&Check it"),
0, wxALL | wxGROW, 5);
sizerMiddle->Add(new wxButton(this, CheckboxPage_Uncheck, "&Uncheck it"),
0, wxALL | wxGROW, 5);
sizerMiddle->Add(new wxButton(this, CheckboxPage_PartCheck,
"Put in &3rd state"),
0, wxALL | wxGROW, 5);
// right pane
wxSizer *sizerRight = new wxBoxSizer(wxHORIZONTAL);
m_checkbox = new wxCheckBox(this, CheckboxPage_Checkbox, "&Check me!");
sizerRight->Add(0, 0, 1, wxCENTRE);
sizerRight->Add(m_checkbox, 1, wxCENTRE);
sizerRight->Add(0, 0, 1, wxCENTRE);
sizerRight->SetMinSize(150, 0);
m_sizerCheckbox = sizerRight; // save it to modify it later
// the 3 panes panes compose the window
sizerTop->Add(sizerLeft, 0, wxGROW | (wxALL & ~wxLEFT), 10);
sizerTop->Add(sizerMiddle, 1, wxGROW | wxALL, 10);
sizerTop->Add(sizerRight, 1, wxGROW | (wxALL & ~wxRIGHT), 10);
// final initializations
Reset();
SetSizer(sizerTop);
}
void CheckBoxWidgetsPage::Reset()
{
m_chkRight->SetValue(false);
m_radioKind->SetSelection(CheckboxKind_2State);
}
void CheckBoxWidgetsPage::CreateCheckbox()
{
wxString label = m_checkbox->GetLabel();
size_t count = m_sizerCheckbox->GetChildren().GetCount();
for ( size_t n = 0; n < count; n++ )
{
m_sizerCheckbox->Remove(0);
}
delete m_checkbox;
int flags = GetAttrs().m_defaultFlags;
if ( m_chkRight->IsChecked() )
flags |= wxALIGN_RIGHT;
switch ( m_radioKind->GetSelection() )
{
default:
wxFAIL_MSG("unexpected radiobox selection");
wxFALLTHROUGH;
case CheckboxKind_2State:
flags |= wxCHK_2STATE;
break;
case CheckboxKind_3StateUser:
flags |= wxCHK_ALLOW_3RD_STATE_FOR_USER;
wxFALLTHROUGH;
case CheckboxKind_3State:
flags |= wxCHK_3STATE;
break;
}
m_checkbox = new wxCheckBox(this, CheckboxPage_Checkbox, label,
wxDefaultPosition, wxDefaultSize,
flags);
m_sizerCheckbox->Add(0, 0, 1, wxCENTRE);
m_sizerCheckbox->Add(m_checkbox, 1, wxCENTRE);
m_sizerCheckbox->Add(0, 0, 1, wxCENTRE);
m_sizerCheckbox->Layout();
}
// ----------------------------------------------------------------------------
// event handlers
// ----------------------------------------------------------------------------
void CheckBoxWidgetsPage::OnButtonReset(wxCommandEvent& WXUNUSED(event))
{
Reset();
CreateCheckbox();
}
void CheckBoxWidgetsPage::OnStyleChange(wxCommandEvent& WXUNUSED(event))
{
CreateCheckbox();
}
void CheckBoxWidgetsPage::OnButtonChangeLabel(wxCommandEvent& WXUNUSED(event))
{
m_checkbox->SetLabel(m_textLabel->GetValue());
}
void CheckBoxWidgetsPage::OnCheckBox(wxCommandEvent& event)
{
wxLogMessage("Test checkbox %schecked (value = %d).",
event.IsChecked() ? "" : "un",
(int)m_checkbox->Get3StateValue());
}
|
ric2b/Vivaldi-browser
|
update_notifier/thirdparty/wxWidgets/samples/widgets/checkbox.cpp
|
C++
|
bsd-3-clause
| 9,600 |
"""
Set of utility programs for IRIS.
"""
import os
import re
import io
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from glob import glob
# pylint: disable=F0401,E0611,E1103
from urllib.request import urlopen
from urllib.parse import urljoin, urlparse
from urllib.error import HTTPError, URLError
def iris_timeline_parse(timeline_file):
"""
Parses an IRIS timeline file (SCI format) into a structured array. This
version outputs a strucured array instead of a pandas DataSet.
Parameters
----------
timeline_file - string
Filename with timeline file, or URL to the file.
Returns
-------
result - pandas.DataFrame
DataFrame with timeline.
"""
from sunpy.time import parse_time
data = []
slews = []
curr_slew = np.array([np.nan, np.nan])
line_pat = re.compile('.+OBSID=.+rpt.+endtime', re.IGNORECASE)
slew_pat = re.compile('.+I_EVENT_MESSAGE.+MSG="SLEW*', re.IGNORECASE)
if urlparse(timeline_file).netloc == '': # local file
file_obj = open(timeline_file, 'r')
else: # network location
try:
tmp = urlopen(timeline_file).read()
file_obj = io.StringIO(tmp)
except (HTTPError, URLError):
raise EOFError(('iris_timeline_parse: could not open the '
'following file:\n' + timeline_file))
for line in file_obj:
if slew_pat.match(line):
tmp = line.split('=')[1].replace('"', '').strip('SLEW_').split('_')
curr_slew = np.array(tmp).astype('f')
if line_pat.match(line):
data.append(line.replace('//', '').replace(' x ', ', ').strip())
slews.append(curr_slew) # include most up to date slew
file_obj.close()
if len(data) == 0:
raise EOFError(('iris_timeline_parse: could not find any'
' observations in:\n' + str(timeline_file)))
arr_type = [('date_obs', 'datetime64[us]'), ('date_end', 'datetime64[us]'),
('obsid', 'i8'), ('repeats', 'i4'), ('duration', 'f'),
('size', 'f'), ('description', '|S200'), ('xpos', 'f'),
('ypos', 'f'), ('timeline_name', '|S200')]
result = np.zeros(len(data), dtype=arr_type)
result['timeline_name'] = timeline_file
for i, line in enumerate(data):
date_tmp = line.split()[0]
if date_tmp[-2:] == '60': # deal with non-compliant second formats
date_tmp = date_tmp[:-2] + '59.999999'
result[i]['date_obs'] = parse_time(date_tmp)
tmp = line.replace(' Mbits, end', ', end') # Remove new Mbits size str
tmp = tmp.split('desc=')
result[i]['description'] = tmp[1]
tmp = tmp[0]
tmp = [k.split('=')[-1] for k in ' '.join(tmp.split()[1:]).split(',')]
result[i]['obsid'] = int(tmp[0])
result[i]['repeats'] = int(tmp[1])
result[i]['duration'] = float(tmp[2][:-1])
result[i]['size'] = float(tmp[3])
tmp = tmp[4].split()
result[i]['date_end'] = parse_time(date_tmp[:9] + tmp[-1]) + \
timedelta(days=int(tmp[0].strip('+')))
result[i]['xpos'] = slews[i][0]
result[i]['ypos'] = slews[i][1]
return pd.DataFrame(result) # order by date_obs
def get_iris_timeline(date_start, date_end, path=None, fmt='%Y/%m/%d',
pattern='.*IRIS_science_timeline.+txt'):
"""
Gets IRIS timelines for a given time period.
"""
if path is None:
path = ('http://iris.lmsal.com/health-safety/timeline/'
'iris_tim_archive/')
print('Locating files...')
file_obj = FileCrawler(date_start, date_end, path, pattern, fmt)
result = pd.DataFrame()
for tfile in file_obj.files:
try:
print('Parsing:\n' + tfile)
timeline = iris_timeline_parse(tfile)
result = result.append(timeline)
except EOFError:
print('get_iris_timeline: could not read timeline data from:\n' +
tfile)
return result
def get_iris_files(date_start, date_end, pattern='iris.*.fits', base='level1',
path='/Users/tiago/data/IRIS/data/'):
"""
Gets list of IRIS observations for a given time period.
Parameters
----------
date_start : str or datetime object
Starting date to search
date_end : str or datetime object
Ending date to search
path : str
Base path to look into
pattern : str
Regular expression used to match file names.
Returns
-------
files : list
List of strings with matching file names.
"""
file_path = os.path.join(path, base)
file_obj = FileCrawler(date_start, date_end, file_path, pattern,
fmt='%Y/%m/%d/H%H%M')
return file_obj.files
class FileCrawler(object):
"""
Crawls through file names in a local or remote (http) path.
Parameters
----------
date_start : str or datetime object
Starting date to search
date_end : str or datetime object
Ending date to search
path : str
Base path to look into
pattern : str
Regular expression used to match file names.
recursive: bool
If True, will recursively search subdirectories of dates.
Attributes
----------
date_start : str or datetime object
Starting date given as input
date_end : str or datetime object
Ending date given as input
paths : list
List of file paths given the supplied dates
files : list
List of file names given the supplied path, dates, and pattern
Methods
-------
get_remote_paths(date_start, date_end, path, fmt='%Y%m%d')
Finds existing remote paths within specified dates in path, given fmt.
get_remote_files(path, pattern)
Finds existing remote files within specified path matching pattern.
"""
def __init__(self, date_start, date_end, path, pattern, fmt='%Y%m%d',
verbose=False):
self.date_start = date_start
self.date_end = date_end
self.paths = self.get_paths(date_start, date_end, path, fmt)
if verbose:
print('Found the following paths:')
for item in self.paths:
print(item)
self.files = []
for item in self.paths:
self.files += self.get_files(item, pattern)
if verbose:
print('Found the following files:')
for item in self.files:
print(item)
@classmethod
def get_paths(cls, date_start, date_end, path, fmt='%Y%m%d'):
"""
Gets paths within specified date range.
Parameters
----------
date_start : str or datetime object
Starting date to search
date_end : str or datetime object
Ending date to search
path : str
Base path where to look for locations (if starts with http,
remote search will be done)
format : str
datetime format string for date in directories.
Returns
-------
dates - list
List with path locations (local directories or remote paths)
"""
from sunpy.time import parse_time
dates = []
date_start = parse_time(date_start)
date_end = parse_time(date_end)
curr = date_start
if '%H' in fmt:
incr = [0, 1] # increment only hours
else:
incr = [1, 0] # increment only days
if urlparse(path).netloc == '': # local file
while curr <= date_end:
curr_path = os.path.join(path, datetime.strftime(curr, fmt))
curr += timedelta(days=incr[0], hours=incr[1])
if os.path.isdir(curr_path):
dates.append(curr_path)
else: # network location
while curr <= date_end:
curr_path = urljoin(path, datetime.strftime(curr, fmt) + '/')
curr += timedelta(days=incr[0], hours=incr[1])
try:
urlopen(curr_path)
dates.append(curr_path)
except (HTTPError, URLError):
continue
return dates
@classmethod
def get_files(cls, path, pattern):
"""
Obtains local or remote files patching a pattern.
Parameters
----------
path : str
Local directory or remote URL (e.g. 'http://www.google.com/test/')
pattern : str
Regular expression to be matched in href link names.
Returns
-------
files : list
List of strings. Each string has the path for the files matching
the pattern (and are made sure exist).
.. todo:: add recursive option, add option for FTP
"""
from bs4 import BeautifulSoup
files = []
pat_re = re.compile(pattern, re.IGNORECASE)
if urlparse(path).scheme == '': # local file
all_files = glob(path + '/*')
for item in all_files:
if pat_re.match(item) and os.path.isfile(item):
files.append(item)
elif urlparse(path).scheme == 'http':
soup = BeautifulSoup(urlopen(path).read())
for link in soup.find_all('a'):
if pat_re.match(link.get('href')):
file_url = urljoin(path, link.get('href'))
try: # Add only links that exist
urlopen(file_url)
files.append(file_url)
except (HTTPError, URLError):
pass
elif urlparse(path).scheme == 'ftp':
raise NotImplementedError('ftp not yet supported...')
return files
|
ITA-Solar/helita
|
helita/obs/iris_util.py
|
Python
|
bsd-3-clause
| 9,925 |
#include "AudioListenerSystem.h"
#include "AudioBackendSystem.h"
#include "AudioListener.h"
#include "Transform.h"
#include "SoundOrientation.h"
#include "MeshOffsetTransform.h"
AudioListenerSystem::AudioListenerSystem(AudioBackendSystem* p_audioBackend) :
EntitySystem(SystemType::AudioListenerSystem, 2,
ComponentType::Transform, ComponentType::AudioListener)
{
m_audioBackend = p_audioBackend;
m_listener = SoundOrientation();
}
AudioListenerSystem::~AudioListenerSystem()
{
}
void AudioListenerSystem::processEntities( const vector<Entity*>& p_entities )
{
if(!p_entities.empty())
{
AudioListener* audioListener = static_cast<AudioListener*>(
p_entities[0]->getComponent( ComponentType::AudioListener));
Transform* trans = static_cast<Transform*>(
p_entities[0]->getComponent( ComponentType::Transform ) );
MeshOffsetTransform* offsetTrans = static_cast<MeshOffsetTransform*>(
p_entities[0]->getComponent( ComponentType::MeshOffsetTransform ));
if(offsetTrans){
AglMatrix worldTransform = offsetTrans->offset.inverse()*trans->getMatrix();
m_listener.listenerOrientFront = worldTransform.GetForward();
m_listener.listenerOrientTop = worldTransform.GetUp();
m_listener.listenerPos = worldTransform.GetTranslation();
}
else{
m_listener.listenerPos = trans->getTranslation();
m_listener.listenerOrientFront = trans->getMatrix().GetForward();
m_listener.listenerOrientTop = trans->getMatrix().GetUp();
}
/************************************************************************/
/* HACK:!!!THERE IS NO VELOCITY!!! */
/************************************************************************/
m_listener.listenerVelocity = AglVector3::zero();
m_audioBackend->updateListener( m_listener );
m_audioBackend->updateListenerVolume( audioListener->getListenerVolume() );
}
}
SoundOrientation* AudioListenerSystem::getListenerOrientation()
{
return &m_listener;
}
void AudioListenerSystem::initialize()
{
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(AntTweakBarWrapper::OVERALL,
"ListenerPosX", TwType::TW_TYPE_FLOAT, &m_listener.listenerPos.x, "group=Ship");
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(AntTweakBarWrapper::OVERALL,
"ListenerPosY", TwType::TW_TYPE_FLOAT, &m_listener.listenerPos.y, "group=Ship");
AntTweakBarWrapper::getInstance()->addReadOnlyVariable(AntTweakBarWrapper::OVERALL,
"ListenerPosZ", TwType::TW_TYPE_FLOAT, &m_listener.listenerPos.z, "group=Ship");
}
void AudioListenerSystem::inserted( Entity* p_entity )
{
AudioListener* audioListener = static_cast<AudioListener*>(
p_entity->getComponent( ComponentType::AudioListener));
AntTweakBarWrapper::getInstance()->modifyTheRefreshRate(AntTweakBarWrapper::SOUND,0.1f);
AntTweakBarWrapper::getInstance()->addWriteVariable(AntTweakBarWrapper::SOUND,
"MasterVolume", TwType::TW_TYPE_FLOAT, audioListener->getMasterVolumeRef(),
"step=0.01f min=0 max=1");
}
|
MattiasLiljeson/Amalgamation
|
Projects/Gameplay/Src/AudioListenerSystem.cpp
|
C++
|
bsd-3-clause
| 2,950 |
from __future__ import absolute_import, division, print_function
_TRIGGERS = {}
def register(tpe, start, stop, join):
def decorator(f):
_TRIGGERS[tpe] = {
"parser": f,
"start": start,
"stop": stop,
"join": join,
"threads": []
}
return f
return decorator
def lookup(tpe):
assert tpe in _TRIGGERS
return _TRIGGERS[tpe]["parser"]
def start():
for trigger in _TRIGGERS.values():
trigger["threads"].append(trigger["start"]())
def stop():
for trigger in _TRIGGERS.values():
for thread in trigger["threads"]:
if thread is not None:
trigger["stop"](thread)
else:
trigger["stop"]()
def join():
for trigger in _TRIGGERS.values():
for thread in trigger["threads"]:
if thread is not None:
trigger["join"](thread)
else:
trigger["join"]()
|
stcorp/legato
|
legato/registry.py
|
Python
|
bsd-3-clause
| 987 |
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.references :parent, :polymorphic => true
t.timestamps
end
end
end
|
breunigs/keks
|
db/migrate/20130217083354_create_questions.rb
|
Ruby
|
isc
| 182 |