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
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 ReportLab Europe Ltd. 2000-2004 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/rl_config.py __version__=''' $Id$ ''' __doc__='''Configuration file. You may edit this if you wish.''' allowTableBoundsErrors = 1 # set to 0 to die on too large elements in tables in debug (recommend 1 for production use) shapeChecking = 1 defaultEncoding = 'WinAnsiEncoding' # 'WinAnsi' or 'MacRoman' defaultGraphicsFontName= 'Times-Roman' #initializer for STATE_DEFAULTS in shapes.py pageCompression = 1 # default page compression mode defaultPageSize = 'A4' #default page size defaultImageCaching = 0 #set to zero to remove those annoying cached images ZLIB_WARNINGS = 1 warnOnMissingFontGlyphs = 0 #if 1, warns of each missing glyph verbose = 0 showBoundary = 0 # turns on and off boundary behaviour in Drawing emptyTableAction= 'error' # one of 'error', 'indicate', 'ignore' invariant= 0 #produces repeatable,identical PDFs with same timestamp info (for regression testing) eps_preview_transparent= None #set to white etc eps_preview= 1 #set to False to disable eps_ttf_embed= 1 #set to False to disable eps_ttf_embed_uid= 0 #set to 1 to enable overlapAttachedSpace= 1 #if set non false then adajacent flowable space after #and space before are merged (max space is used). longTableOptimize = 0 #default don't use Henning von Bargen's long table optimizations autoConvertEncoding = 0 #convert internally as needed (experimental) _FUZZ= 1e-6 #fuzz for layout arithmetic wrapA85= 0 #set to 1 to get old wrapped line behaviour fsEncodings=('utf8','cp1252','cp430') #encodings to attempt utf8 conversion with odbc_driver= 'odbc' #default odbc driver platypus_link_underline= 0 #paragraph links etc underlined if true canvas_basefontname= 'Helvetica' #this is used to initialize the canvas; if you override to make #something else you are responsible for ensuring the font is registered etc etc allowShortTableRows=1 #allows some rows in a table to be short imageReaderFlags=0 #attempt to convert images into internal memory files to reduce #the number of open files (see lib.utils.ImageReader) #if imageReaderFlags&2 then attempt autoclosing of those files #if imageReaderFlags&4 then cache data #if imageReaderFlags==-1 then use Ralf Schmitt's re-opening approach # places to look for T1Font information T1SearchPath = ( 'c:/Program Files/Adobe/Acrobat 9.0/Resource/Font', 'c:/Program Files/Adobe/Acrobat 8.0/Resource/Font', 'c:/Program Files/Adobe/Acrobat 7.0/Resource/Font', 'c:/Program Files/Adobe/Acrobat 6.0/Resource/Font', #Win32, Acrobat 6 'c:/Program Files/Adobe/Acrobat 5.0/Resource/Font', #Win32, Acrobat 5 'c:/Program Files/Adobe/Acrobat 4.0/Resource/Font', #Win32, Acrobat 4 '%(disk)s/Applications/Python %(sys_version)s/reportlab/fonts', #Mac? '/usr/lib/Acrobat9/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat8/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat7/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat6/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat5/Resource/Font', #Linux, Acrobat 5? '/usr/lib/Acrobat4/Resource/Font', #Linux, Acrobat 4 '/usr/local/Acrobat9/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat8/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat7/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat6/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat5/Resource/Font', #Linux, Acrobat 5? '/usr/local/Acrobat4/Resource/Font', #Linux, Acrobat 4 '%(REPORTLAB_DIR)s/fonts', #special '%(REPORTLAB_DIR)s/../fonts', #special '%(REPORTLAB_DIR)s/../../fonts', #special '%(HOME)s/fonts', #special ) # places to look for TT Font information TTFSearchPath = ( 'c:/winnt/fonts', 'c:/windows/fonts', '/usr/lib/X11/fonts/TrueType/', '%(REPORTLAB_DIR)s/fonts', #special '%(REPORTLAB_DIR)s/../fonts', #special '%(REPORTLAB_DIR)s/../../fonts',#special '%(HOME)s/fonts', #special #mac os X - from #http://developer.apple.com/technotes/tn/tn2024.html '~/Library/Fonts', '/Library/Fonts', '/Network/Library/Fonts', '/System/Library/Fonts', ) # places to look for CMap files - should ideally merge with above CMapSearchPath = ( '/usr/lib/Acrobat9/Resource/CMap', '/usr/lib/Acrobat8/Resource/CMap', '/usr/lib/Acrobat7/Resource/CMap', '/usr/lib/Acrobat6/Resource/CMap', '/usr/lib/Acrobat5/Resource/CMap', '/usr/lib/Acrobat4/Resource/CMap', '/usr/local/Acrobat9/Resource/CMap', '/usr/local/Acrobat8/Resource/CMap', '/usr/local/Acrobat7/Resource/CMap', '/usr/local/Acrobat6/Resource/CMap', '/usr/local/Acrobat5/Resource/CMap', '/usr/local/Acrobat4/Resource/CMap', 'C:\\Program Files\\Adobe\\Acrobat\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 9.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 8.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 7.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 6.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 5.0\\Resource\\CMap', 'C:\\Program Files\\Adobe\\Acrobat 4.0\\Resource\\CMap', '%(REPORTLAB_DIR)s/fonts/CMap', #special '%(REPORTLAB_DIR)s/../fonts/CMap', #special '%(REPORTLAB_DIR)s/../../fonts/CMap', #special '%(HOME)s/fonts/CMap', #special ) #### Normally don't need to edit below here #### try: from local_rl_config import * except: pass _SAVED = {} sys_version=None def _setOpt(name, value, conv=None): '''set a module level value from environ/default''' from os import environ ename = 'RL_'+name if environ.has_key(ename): value = environ[ename] if conv: value = conv(value) globals()[name] = value def _startUp(): '''This function allows easy resetting to the global defaults If the environment contains 'RL_xxx' then we use the value else we use the given default''' V='''T1SearchPath CMapSearchPath TTFSearchPath allowTableBoundsErrors shapeChecking defaultEncoding defaultGraphicsFontName pageCompression defaultPageSize defaultImageCaching ZLIB_WARNINGS warnOnMissingFontGlyphs verbose showBoundary emptyTableAction invariant eps_preview_transparent eps_preview eps_ttf_embed eps_ttf_embed_uid overlapAttachedSpace longTableOptimize autoConvertEncoding _FUZZ wrapA85 fsEncodings odbc_driver platypus_link_underline canvas_basefontname allowShortTableRows imageReaderFlags'''.split() import os, sys global sys_version, _unset_ sys_version = sys.version.split()[0] #strip off the other garbage from reportlab.lib import pagesizes from reportlab.lib.utils import rl_isdir if _SAVED=={}: _unset_ = getattr(sys,'_rl_config__unset_',None) if _unset_ is None: class _unset_: pass sys._rl_config__unset_ = _unset_ = _unset_() for k in V: _SAVED[k] = globals()[k] #places to search for Type 1 Font files import reportlab D = {'REPORTLAB_DIR': os.path.abspath(os.path.dirname(reportlab.__file__)), 'HOME': os.environ.get('HOME',os.getcwd()), 'disk': os.getcwd().split(':')[0], 'sys_version': sys_version, } for name in ('T1SearchPath','TTFSearchPath','CMapSearchPath'): P=[] for p in _SAVED[name]: d = (p % D).replace('/',os.sep) if rl_isdir(d): P.append(d) _setOpt(name,P) for k in V[3:]: v = _SAVED[k] if isinstance(v,(int,float)): conv = type(v) elif k=='defaultPageSize': conv = lambda v,M=pagesizes: getattr(M,v) else: conv = None _setOpt(k,v,conv) _registered_resets=[] def register_reset(func): _registered_resets[:] = [x for x in _registered_resets if x()] L = [x for x in _registered_resets if x() is func] if L: return from weakref import ref _registered_resets.append(ref(func)) def _reset(): #attempt to reset reportlab and friends _startUp() #our reset for f in _registered_resets[:]: c = f() if c: c() else: _registered_resets.remove(f) _startUp()
makinacorpus/reportlab-ecomobile
src/reportlab/rl_config.py
Python
bsd-3-clause
10,215
/*================================================================================ 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 j2x import ( "encoding/json" "fmt" "testing" ) func TestMashalIndent(t *testing.T) { var s = `{ "head":[ "one", 2, true, { "key":"value" } ] }` fmt.Println("\nTestMashalIndent ... list :", s) v, err := MarshalIndent(s," "," ") if err != nil { fmt.Println("err:",err.Error()) } fmt.Printf("v:\n%s",string(v)) s = `{ "head":{ "line":[ "one", 2, true, { "key":"value" } ] } }` m := make(map[string]interface{},0) err = json.Unmarshal([]byte(s), &m) type mystruct struct { S string F float64 } ms := mystruct{ S:"now's the time", F:3.14159625 } m["mystruct"] = interface{}(ms) fmt.Println("\nTestMarshalIndent ... mystruct", m) v, err = MarshalIndent(m," "," ") if err != nil { fmt.Println("err:",err.Error()) } fmt.Printf("v:\n%s",string(v)) }
clbanning/j2x
j2xindent_test.go
GO
bsd-3-clause
788
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
import os from google.appengine.api import memcache from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from twimonial.models import Twimonial, User from twimonial.ui import render_write import config class HomePage(webapp.RequestHandler): def get(self): if config.CACHE: # Check cache first cached_page = memcache.get('homepage') if cached_page: self.response.out.write(cached_page) return # Get latest five testimonials latest_twimonials = [t.dictize() for t in Twimonial.all().order('-created_at').fetch(5)] tmpl_values = { 'latest_twimonials': latest_twimonials, 'pop_users_twimonials': User.get_popular_users_testimonials(), } # Send out and cache it rendered_page = render_write(tmpl_values, 'home.html', self.request, self.response) if config.CACHE: memcache.set('homepage', rendered_page, config.CACHE_TIME_HOMEPAGE) def head(self): pass class NotFoundPage(webapp.RequestHandler): def get(self): self.error(404) tmpl_values = { } render_write(tmpl_values, '404.html', self.request, self.response) def head(self): self.error(404) class StaticPage(webapp.RequestHandler): def get(self, pagename): render_write({}, pagename + '.html', self.request, self.response) def head(self): pass class ListPage(webapp.RequestHandler): def get(self, screen_names_string): limit = 10 screen_names = [name for name in screen_names_string.split('-') if name][:limit] screen_names.sort() screen_names_string = '-'.join(screen_names) # Check cache first cached_page = memcache.get(screen_names_string, 'listpage') if cached_page: self.response.out.write(cached_page) return twimonials = [t.dictize() for t in Twimonial.get_tos(screen_names)] missings = [] t_screen_names = [t['to_user']['screen_name'].lower() for t in twimonials] for name in screen_names: if name.lower() not in t_screen_names: missings.append(name) tmpl_values = { 'twimonials': twimonials, 'missings': ', '.join(missings), } # Send out and cache it rendered_page = render_write(tmpl_values, 'list.html', self.request, self.response) memcache.set(screen_names_string, rendered_page, config.CACHE_TIME_LISTPAGE, namespace='listpage') application = webapp.WSGIApplication([ ('/', HomePage), ('/(about|terms|faq)', StaticPage), ('/list/([-_a-zA-Z0-9]+)', ListPage), ('/.*', NotFoundPage), ], debug=config.DEBUG) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
livibetter-backup/twimonial
src/index.py
Python
bsd-3-clause
2,779
using HtmlRenderer.TestLib.Dom; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HtmlRenderer.DomParseTester.DomComparing.ViewModels { public sealed class Comment : CharacterData<ReferenceComment> { public Comment(Context context, ReferenceComment model) : base(context, model) { } } }
todor-dk/HTML-Renderer
Source/Testing/HtmlRenderer.DomParseTester/DomComparing/ViewModels/Comment.cs
C#
bsd-3-clause
403
// 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
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using CodeGenTest.CodeGenExtension; namespace CodeGenTest { sealed class TestApp : C.ConsoleApplication { protected override void Init() { base.Init(); var source = this.CreateCSourceCollection("$(packagedir)/source/testapp/main.c"); /*var generatedSourceTuple = */source.GenerateSource(); } } }
markfinal/BuildAMation
tests/CodeGenTest/bam/Scripts/TestApp.cs
C#
bsd-3-clause
1,985
<?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
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-82a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: malloc Allocate data using malloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #include "std_testcase.h" #include "CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82 { #ifndef OMITBAD void bad() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (int64_t *)malloc(100*sizeof(int64_t)); if (data == NULL) {exit(-1);} CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_base* baseObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_bad; baseObject->action(data); delete baseObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int64_t * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using new */ data = new int64_t; CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_base* baseObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_goodG2B; baseObject->action(data); delete baseObject; } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (int64_t *)malloc(100*sizeof(int64_t)); if (data == NULL) {exit(-1);} CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_base* baseObject = new CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82_goodB2G; baseObject->action(data); delete baseObject; } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s03/CWE762_Mismatched_Memory_Management_Routines__delete_int64_t_malloc_82a.cpp
C++
bsd-3-clause
3,366
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\">&#9632;</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
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/page_load_metrics/browser/metrics_web_contents_observer.h" #include <memory> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/process/kill.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/time/time.h" #include "base/timer/mock_timer.h" #include "components/page_load_metrics/browser/page_load_metrics_test_content_browser_client.h" #include "components/page_load_metrics/browser/page_load_tracker.h" #include "components/page_load_metrics/browser/test_metrics_web_contents_observer_embedder.h" #include "content/public/browser/back_forward_cache.h" #include "content/public/browser/navigation_handle.h" #include "content/public/common/content_client.h" #include "content/public/common/content_features.h" #include "content/public/test/navigation_simulator.h" #include "content/public/test/render_frame_host_test_support.h" #include "content/public/test/test_renderer_host.h" #include "net/base/net_errors.h" #include "net/cert/cert_status_flags.h" #include "services/network/public/mojom/fetch_api.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/use_counter/use_counter_feature.h" #include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h" #include "third_party/blink/public/mojom/use_counter/use_counter_feature.mojom-shared.h" #include "url/url_constants.h" using content::NavigationSimulator; namespace page_load_metrics { namespace { const char kDefaultTestUrl[] = "https://google.com/"; const char kDefaultTestUrlAnchor[] = "https://google.com/#samedocument"; const char kDefaultTestUrl2[] = "https://whatever.com/"; const char kFilteredStartUrl[] = "https://whatever.com/ignore-on-start"; const char kFilteredCommitUrl[] = "https://whatever.com/ignore-on-commit"; void PopulatePageLoadTiming(mojom::PageLoadTiming* timing) { page_load_metrics::InitPageLoadTimingForTest(timing); timing->navigation_start = base::Time::FromDoubleT(1); timing->response_start = base::Milliseconds(10); timing->parse_timing->parse_start = base::Milliseconds(20); } blink::mojom::ResourceLoadInfoPtr CreateResourceLoadInfo( const GURL& url, network::mojom::RequestDestination request_destination) { blink::mojom::ResourceLoadInfoPtr resource_load_info = blink::mojom::ResourceLoadInfo::New(); resource_load_info->final_url = url; resource_load_info->original_url = url; resource_load_info->request_destination = request_destination; resource_load_info->was_cached = false; resource_load_info->raw_body_bytes = 0; resource_load_info->net_error = net::OK; resource_load_info->network_info = blink::mojom::CommonNetworkInfo::New(); resource_load_info->network_info->remote_endpoint = net::IPEndPoint(); resource_load_info->load_timing_info.request_start = base::TimeTicks::Now(); return resource_load_info; } } // namespace class MetricsWebContentsObserverTest : public content::RenderViewHostTestHarness { public: MetricsWebContentsObserverTest() { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); previous_timing_ = timing.Clone(); } MetricsWebContentsObserverTest(const MetricsWebContentsObserverTest&) = delete; MetricsWebContentsObserverTest& operator=( const MetricsWebContentsObserverTest&) = delete; void SetUp() override { content::RenderViewHostTestHarness::SetUp(); original_browser_client_ = content::SetBrowserClientForTesting(&browser_client_); AttachObserver(); } void TearDown() override { content::SetBrowserClientForTesting(original_browser_client_); RenderViewHostTestHarness::TearDown(); } void NavigateToUntrackedUrl() { content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(url::kAboutBlankURL)); } // Returns the mock timer used for buffering updates in the // PageLoadMetricsUpdateDispatcher. base::MockOneShotTimer* GetMostRecentTimer() { return embedder_interface_->GetMockTimer(); } void SimulateTimingUpdate(const mojom::PageLoadTiming& timing) { SimulateTimingUpdate(timing, web_contents()->GetMainFrame()); } void SimulateCpuTimingUpdate(const mojom::CpuTiming& timing, content::RenderFrameHost* render_frame_host) { observer()->OnTimingUpdated( render_frame_host, previous_timing_->Clone(), mojom::FrameMetadataPtr(base::in_place), std::vector<blink::UseCounterFeature>(), std::vector<mojom::ResourceDataUpdatePtr>(), mojom::FrameRenderDataUpdatePtr(base::in_place), timing.Clone(), mojom::DeferredResourceCountsPtr(base::in_place), mojom::InputTimingPtr(base::in_place), blink::MobileFriendliness()); } void SimulateTimingUpdate(const mojom::PageLoadTiming& timing, content::RenderFrameHost* render_frame_host) { SimulateTimingUpdateWithoutFiringDispatchTimer(timing, render_frame_host); // If sending the timing update caused the PageLoadMetricsUpdateDispatcher // to schedule a buffering timer, then fire it now so metrics are dispatched // to observers. base::MockOneShotTimer* mock_timer = GetMostRecentTimer(); if (mock_timer && mock_timer->IsRunning()) mock_timer->Fire(); } void SimulateTimingUpdateWithoutFiringDispatchTimer( const mojom::PageLoadTiming& timing, content::RenderFrameHost* render_frame_host) { previous_timing_ = timing.Clone(); observer()->OnTimingUpdated( render_frame_host, timing.Clone(), mojom::FrameMetadataPtr(base::in_place), std::vector<blink::UseCounterFeature>(), std::vector<mojom::ResourceDataUpdatePtr>(), mojom::FrameRenderDataUpdatePtr(base::in_place), mojom::CpuTimingPtr(base::in_place), mojom::DeferredResourceCountsPtr(base::in_place), mojom::InputTimingPtr(base::in_place), blink::MobileFriendliness()); } virtual std::unique_ptr<TestMetricsWebContentsObserverEmbedder> CreateEmbedder() { return std::make_unique<TestMetricsWebContentsObserverEmbedder>(); } void AttachObserver() { auto embedder_interface = CreateEmbedder(); embedder_interface_ = embedder_interface.get(); MetricsWebContentsObserver* observer = MetricsWebContentsObserver::CreateForWebContents( web_contents(), std::move(embedder_interface)); observer->OnVisibilityChanged(content::Visibility::VISIBLE); } void CheckErrorEvent(InternalErrorLoadEvent error, int count) { histogram_tester_.ExpectBucketCount(internal::kErrorEvents, error, count); num_errors_ += count; } void CheckTotalErrorEvents() { histogram_tester_.ExpectTotalCount(internal::kErrorEvents, num_errors_); } void CheckNoErrorEvents() { histogram_tester_.ExpectTotalCount(internal::kErrorEvents, 0); } int CountEmptyCompleteTimingReported() { int empty = 0; for (const auto& timing : embedder_interface_->complete_timings()) { if (page_load_metrics::IsEmpty(*timing)) ++empty; } return empty; } void CheckErrorNoIPCsReceivedIfNeeded(int count) { // With BackForwardCache, page is kept alive after navigation. // ERR_NO_IPCS_RECEIVED isn't recorded as it is reported during destruction // of page after navigation which doesn't happen with BackForwardCache. if (!content::BackForwardCache::IsBackForwardCacheFeatureEnabled()) CheckErrorEvent(ERR_NO_IPCS_RECEIVED, count); } const std::vector<mojom::PageLoadTimingPtr>& updated_timings() const { return embedder_interface_->updated_timings(); } const std::vector<mojom::CpuTimingPtr>& updated_cpu_timings() const { return embedder_interface_->updated_cpu_timings(); } const std::vector<mojom::PageLoadTimingPtr>& complete_timings() const { return embedder_interface_->complete_timings(); } const std::vector<mojom::PageLoadTimingPtr>& updated_subframe_timings() const { return embedder_interface_->updated_subframe_timings(); } int CountCompleteTimingReported() { return complete_timings().size(); } int CountUpdatedTimingReported() { return updated_timings().size(); } int CountUpdatedCpuTimingReported() { return updated_cpu_timings().size(); } int CountUpdatedSubFrameTimingReported() { return updated_subframe_timings().size(); } int CountOnBackForwardCacheEntered() const { return embedder_interface_->count_on_enter_back_forward_cache(); } const std::vector<GURL>& observed_committed_urls_from_on_start() const { return embedder_interface_->observed_committed_urls_from_on_start(); } const std::vector<GURL>& observed_aborted_urls() const { return embedder_interface_->observed_aborted_urls(); } const std::vector<blink::UseCounterFeature>& observed_features() const { return embedder_interface_->observed_features(); } const absl::optional<bool>& is_first_navigation_in_web_contents() const { return embedder_interface_->is_first_navigation_in_web_contents(); } const std::vector<GURL>& completed_filtered_urls() const { return embedder_interface_->completed_filtered_urls(); } const std::vector<ExtraRequestCompleteInfo>& loaded_resources() const { return embedder_interface_->loaded_resources(); } protected: MetricsWebContentsObserver* observer() { return MetricsWebContentsObserver::FromWebContents(web_contents()); } base::HistogramTester histogram_tester_; raw_ptr<TestMetricsWebContentsObserverEmbedder> embedder_interface_; private: int num_errors_ = 0; // Since we have two types of updates, both CpuTiming and PageLoadTiming, and // these feed into a singular OnTimingUpdated, we need to pass in an unchanged // PageLoadTiming structure to this function, so we need to keep track of the // previous structure that was passed when updating the PageLoadTiming. mojom::PageLoadTimingPtr previous_timing_; PageLoadMetricsTestContentBrowserClient browser_client_; raw_ptr<content::ContentBrowserClient> original_browser_client_ = nullptr; }; TEST_F(MetricsWebContentsObserverTest, SuccessfulMainFrameNavigation) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(1); ASSERT_TRUE(observed_committed_urls_from_on_start().empty()); ASSERT_FALSE(is_first_navigation_in_web_contents().has_value()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(1u, observed_committed_urls_from_on_start().size()); ASSERT_TRUE(observed_committed_urls_from_on_start().at(0).is_empty()); ASSERT_TRUE(is_first_navigation_in_web_contents().has_value()); ASSERT_TRUE(is_first_navigation_in_web_contents().value()); ASSERT_EQ(0, CountUpdatedTimingReported()); SimulateTimingUpdate(timing); ASSERT_EQ(1, CountUpdatedTimingReported()); ASSERT_EQ(0, CountCompleteTimingReported()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_FALSE(is_first_navigation_in_web_contents().value()); ASSERT_EQ(1, CountCompleteTimingReported()); ASSERT_EQ(0, CountEmptyCompleteTimingReported()); ASSERT_EQ(2u, observed_committed_urls_from_on_start().size()); ASSERT_EQ(kDefaultTestUrl, observed_committed_urls_from_on_start().at(1).spec()); ASSERT_EQ(1, CountUpdatedTimingReported()); ASSERT_EQ(0, CountUpdatedSubFrameTimingReported()); CheckNoErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, DISABLED_MainFrameNavigationInternalAbort) { auto navigation = content::NavigationSimulator::CreateBrowserInitiated( GURL(kDefaultTestUrl), web_contents()); navigation->Fail(net::ERR_ABORTED); ASSERT_EQ(1u, observed_aborted_urls().size()); ASSERT_EQ(kDefaultTestUrl, observed_aborted_urls().front().spec()); } TEST_F(MetricsWebContentsObserverTest, SubFrame) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(1); timing.response_start = base::Milliseconds(10); timing.parse_timing->parse_start = base::Milliseconds(20); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); ASSERT_EQ(1, CountUpdatedTimingReported()); EXPECT_TRUE(timing.Equals(*updated_timings().back())); content::RenderFrameHostTester* rfh_tester = content::RenderFrameHostTester::For(main_rfh()); content::RenderFrameHost* subframe = rfh_tester->AppendChild("subframe"); // Dispatch a timing update for the child frame that includes a first paint. mojom::PageLoadTiming subframe_timing; page_load_metrics::InitPageLoadTimingForTest(&subframe_timing); subframe_timing.navigation_start = base::Time::FromDoubleT(2); subframe_timing.response_start = base::Milliseconds(10); subframe_timing.parse_timing->parse_start = base::Milliseconds(20); subframe_timing.paint_timing->first_paint = base::Milliseconds(40); subframe = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe); SimulateTimingUpdate(subframe_timing, subframe); ASSERT_EQ(1, CountUpdatedSubFrameTimingReported()); EXPECT_TRUE(subframe_timing.Equals(*updated_subframe_timings().back())); // The subframe update which included a paint should have also triggered // a main frame update, which includes a first paint. ASSERT_EQ(2, CountUpdatedTimingReported()); EXPECT_FALSE(timing.Equals(*updated_timings().back())); EXPECT_TRUE(updated_timings().back()->paint_timing->first_paint); // Navigate again to see if the timing updated for a subframe message. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(1, CountCompleteTimingReported()); ASSERT_EQ(2, CountUpdatedTimingReported()); ASSERT_EQ(0, CountEmptyCompleteTimingReported()); ASSERT_EQ(1, CountUpdatedSubFrameTimingReported()); EXPECT_TRUE(subframe_timing.Equals(*updated_subframe_timings().back())); CheckNoErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, SameDocumentNoTrigger) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(1); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(0, CountUpdatedTimingReported()); SimulateTimingUpdate(timing); ASSERT_EQ(1, CountUpdatedTimingReported()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrlAnchor)); // Send the same timing update. The original tracker for kDefaultTestUrl // should dedup the update, and the tracker for kDefaultTestUrlAnchor should // have been destroyed as a result of its being a same page navigation, so // CountUpdatedTimingReported() should continue to return 1. SimulateTimingUpdate(timing); ASSERT_EQ(1, CountUpdatedTimingReported()); ASSERT_EQ(0, CountCompleteTimingReported()); // Navigate again to force histogram logging. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); // A same page navigation shouldn't trigger logging UMA for the original. ASSERT_EQ(1, CountUpdatedTimingReported()); ASSERT_EQ(1, CountCompleteTimingReported()); ASSERT_EQ(0, CountEmptyCompleteTimingReported()); CheckNoErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, DontLogNewTabPage) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(1); embedder_interface_->set_is_ntp(true); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(0, CountUpdatedTimingReported()); ASSERT_EQ(0, CountCompleteTimingReported()); // Ensure that NTP and other untracked loads are still accounted for as part // of keeping track of the first navigation in the WebContents. embedder_interface_->set_is_ntp(false); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_TRUE(is_first_navigation_in_web_contents().has_value()); ASSERT_FALSE(is_first_navigation_in_web_contents().value()); CheckErrorEvent(ERR_IPC_WITH_NO_RELEVANT_LOAD, 1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, DontLogIrrelevantNavigation) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(10); GURL about_blank_url = GURL("about:blank"); content::NavigationSimulator::NavigateAndCommitFromBrowser(web_contents(), about_blank_url); SimulateTimingUpdate(timing); ASSERT_EQ(0, CountUpdatedTimingReported()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(0, CountUpdatedTimingReported()); ASSERT_EQ(0, CountCompleteTimingReported()); // Ensure that NTP and other untracked loads are still accounted for as part // of keeping track of the first navigation in the WebContents. ASSERT_TRUE(is_first_navigation_in_web_contents().has_value()); ASSERT_FALSE(is_first_navigation_in_web_contents().value()); CheckErrorEvent(ERR_IPC_FROM_BAD_URL_SCHEME, 0); CheckErrorEvent(ERR_IPC_WITH_NO_RELEVANT_LOAD, 1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, EmptyTimingError) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); ASSERT_EQ(0, CountUpdatedTimingReported()); NavigateToUntrackedUrl(); ASSERT_EQ(0, CountUpdatedTimingReported()); ASSERT_EQ(1, CountCompleteTimingReported()); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorEvent(ERR_NO_IPCS_RECEIVED, 1); CheckTotalErrorEvents(); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal::INVALID_EMPTY_TIMING, 1); } TEST_F(MetricsWebContentsObserverTest, NullNavigationStartError) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.parse_timing->parse_start = base::Milliseconds(1); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); ASSERT_EQ(0, CountUpdatedTimingReported()); NavigateToUntrackedUrl(); ASSERT_EQ(0, CountUpdatedTimingReported()); ASSERT_EQ(1, CountCompleteTimingReported()); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorEvent(ERR_NO_IPCS_RECEIVED, 1); CheckTotalErrorEvents(); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal::INVALID_NULL_NAVIGATION_START, 1); } TEST_F(MetricsWebContentsObserverTest, TimingOrderError) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(1); timing.parse_timing->parse_stop = base::Milliseconds(1); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); ASSERT_EQ(0, CountUpdatedTimingReported()); NavigateToUntrackedUrl(); ASSERT_EQ(0, CountUpdatedTimingReported()); ASSERT_EQ(1, CountCompleteTimingReported()); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorEvent(ERR_NO_IPCS_RECEIVED, 1); CheckTotalErrorEvents(); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal::INVALID_ORDER_PARSE_START_PARSE_STOP, 1); } TEST_F(MetricsWebContentsObserverTest, BadIPC) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(10); mojom::PageLoadTiming timing2; page_load_metrics::InitPageLoadTimingForTest(&timing2); timing2.navigation_start = base::Time::FromDoubleT(100); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); ASSERT_EQ(1, CountUpdatedTimingReported()); SimulateTimingUpdate(timing2); ASSERT_EQ(1, CountUpdatedTimingReported()); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING_DESCENDENT, 1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, ObservePartialNavigation) { // Reset the state of the tests, and attach the MetricsWebContentsObserver in // the middle of a navigation. This tests that the class is robust to only // observing some of a navigation. DeleteContents(); SetContents(CreateTestWebContents()); mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(10); // Start the navigation, then start observing the web contents. This used to // crash us. Make sure we bail out and don't log histograms. std::unique_ptr<NavigationSimulator> navigation = NavigationSimulator::CreateBrowserInitiated(GURL(kDefaultTestUrl), web_contents()); navigation->Start(); AttachObserver(); navigation->Commit(); SimulateTimingUpdate(timing); // Navigate again to force histogram logging. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(0, CountCompleteTimingReported()); ASSERT_EQ(0, CountUpdatedTimingReported()); CheckErrorEvent(ERR_IPC_WITH_NO_RELEVANT_LOAD, 1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, DontLogAbortChains) { NavigateAndCommit(GURL(kDefaultTestUrl)); NavigateAndCommit(GURL(kDefaultTestUrl2)); NavigateAndCommit(GURL(kDefaultTestUrl)); histogram_tester_.ExpectTotalCount(internal::kAbortChainSizeNewNavigation, 0); CheckErrorNoIPCsReceivedIfNeeded(2); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, LogAbortChains) { // Start and abort three loads before one finally commits. NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl), net::ERR_ABORTED); NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl2), net::ERR_ABORTED); NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl), net::ERR_ABORTED); NavigationSimulator::NavigateAndCommitFromBrowser(web_contents(), GURL(kDefaultTestUrl2)); histogram_tester_.ExpectTotalCount(internal::kAbortChainSizeNewNavigation, 1); histogram_tester_.ExpectBucketCount(internal::kAbortChainSizeNewNavigation, 3, 1); CheckNoErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, LogAbortChainsSameURL) { // Start and abort three loads before one finally commits. NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl), net::ERR_ABORTED); NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl), net::ERR_ABORTED); NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl), net::ERR_ABORTED); NavigationSimulator::NavigateAndCommitFromBrowser(web_contents(), GURL(kDefaultTestUrl)); histogram_tester_.ExpectTotalCount(internal::kAbortChainSizeNewNavigation, 1); histogram_tester_.ExpectBucketCount(internal::kAbortChainSizeNewNavigation, 3, 1); histogram_tester_.ExpectTotalCount(internal::kAbortChainSizeSameURL, 1); histogram_tester_.ExpectBucketCount(internal::kAbortChainSizeSameURL, 3, 1); } TEST_F(MetricsWebContentsObserverTest, LogAbortChainsNoCommit) { // Start and abort three loads before one finally commits. NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl), net::ERR_ABORTED); NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl2), net::ERR_ABORTED); NavigationSimulator::NavigateAndFailFromBrowser( web_contents(), GURL(kDefaultTestUrl), net::ERR_ABORTED); web_contents()->Stop(); histogram_tester_.ExpectTotalCount(internal::kAbortChainSizeNoCommit, 1); histogram_tester_.ExpectBucketCount(internal::kAbortChainSizeNoCommit, 3, 1); } TEST_F(MetricsWebContentsObserverTest, FlushMetricsOnAppEnterBackground) { content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); histogram_tester_.ExpectTotalCount( internal::kPageLoadCompletedAfterAppBackground, 0); observer()->FlushMetricsOnAppEnterBackground(); histogram_tester_.ExpectTotalCount( internal::kPageLoadCompletedAfterAppBackground, 1); histogram_tester_.ExpectBucketCount( internal::kPageLoadCompletedAfterAppBackground, false, 1); histogram_tester_.ExpectBucketCount( internal::kPageLoadCompletedAfterAppBackground, true, 0); // Navigate again, which forces completion callbacks on the previous // navigation to be invoked. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); // Verify that, even though the page load completed, no complete timings were // reported, because the TestPageLoadMetricsObserver's // FlushMetricsOnAppEnterBackground implementation returned STOP_OBSERVING, // thus preventing OnComplete from being invoked. ASSERT_EQ(0, CountCompleteTimingReported()); DeleteContents(); histogram_tester_.ExpectTotalCount( internal::kPageLoadCompletedAfterAppBackground, 2); histogram_tester_.ExpectBucketCount( internal::kPageLoadCompletedAfterAppBackground, false, 1); histogram_tester_.ExpectBucketCount( internal::kPageLoadCompletedAfterAppBackground, true, 1); } TEST_F(MetricsWebContentsObserverTest, StopObservingOnCommit) { ASSERT_TRUE(completed_filtered_urls().empty()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_TRUE(completed_filtered_urls().empty()); // kFilteredCommitUrl should stop observing in OnCommit, and thus should not // reach OnComplete(). content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kFilteredCommitUrl)); ASSERT_EQ(std::vector<GURL>({GURL(kDefaultTestUrl)}), completed_filtered_urls()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(std::vector<GURL>({GURL(kDefaultTestUrl)}), completed_filtered_urls()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(std::vector<GURL>({GURL(kDefaultTestUrl), GURL(kDefaultTestUrl2)}), completed_filtered_urls()); } TEST_F(MetricsWebContentsObserverTest, StopObservingOnStart) { ASSERT_TRUE(completed_filtered_urls().empty()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_TRUE(completed_filtered_urls().empty()); // kFilteredCommitUrl should stop observing in OnStart, and thus should not // reach OnComplete(). content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kFilteredStartUrl)); ASSERT_EQ(std::vector<GURL>({GURL(kDefaultTestUrl)}), completed_filtered_urls()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(std::vector<GURL>({GURL(kDefaultTestUrl)}), completed_filtered_urls()); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(std::vector<GURL>({GURL(kDefaultTestUrl), GURL(kDefaultTestUrl2)}), completed_filtered_urls()); } // We buffer cross frame timings in order to provide a consistent view of // timing data to observers. See crbug.com/722860 for more. TEST_F(MetricsWebContentsObserverTest, OutOfOrderCrossFrameTiming) { mojom::PageLoadTiming timing; page_load_metrics::InitPageLoadTimingForTest(&timing); timing.navigation_start = base::Time::FromDoubleT(1); timing.response_start = base::Milliseconds(10); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); ASSERT_EQ(1, CountUpdatedTimingReported()); EXPECT_TRUE(timing.Equals(*updated_timings().back())); content::RenderFrameHostTester* rfh_tester = content::RenderFrameHostTester::For(main_rfh()); content::RenderFrameHost* subframe = rfh_tester->AppendChild("subframe"); // Dispatch a timing update for the child frame that includes a first paint. mojom::PageLoadTiming subframe_timing; PopulatePageLoadTiming(&subframe_timing); subframe_timing.paint_timing->first_paint = base::Milliseconds(40); subframe = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe); SimulateTimingUpdate(subframe_timing, subframe); // Though a first paint was dispatched in the child, it should not yet be // reflected as an updated timing in the main frame, since the main frame // hasn't received updates for required earlier events such as parse_start. ASSERT_EQ(1, CountUpdatedSubFrameTimingReported()); EXPECT_TRUE(subframe_timing.Equals(*updated_subframe_timings().back())); ASSERT_EQ(1, CountUpdatedTimingReported()); EXPECT_TRUE(timing.Equals(*updated_timings().back())); // Dispatch the parse_start event in the parent. We should now unbuffer the // first paint main frame update and receive a main frame update with a first // paint value. timing.parse_timing->parse_start = base::Milliseconds(20); SimulateTimingUpdate(timing); ASSERT_EQ(2, CountUpdatedTimingReported()); EXPECT_FALSE(timing.Equals(*updated_timings().back())); EXPECT_TRUE( updated_timings().back()->parse_timing->Equals(*timing.parse_timing)); EXPECT_TRUE(updated_timings().back()->document_timing->Equals( *timing.document_timing)); EXPECT_FALSE( updated_timings().back()->paint_timing->Equals(*timing.paint_timing)); EXPECT_TRUE(updated_timings().back()->paint_timing->first_paint); // Navigate again to see if the timing updated for a subframe message. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(1, CountCompleteTimingReported()); ASSERT_EQ(2, CountUpdatedTimingReported()); ASSERT_EQ(0, CountEmptyCompleteTimingReported()); ASSERT_EQ(1, CountUpdatedSubFrameTimingReported()); EXPECT_TRUE(subframe_timing.Equals(*updated_subframe_timings().back())); CheckNoErrorEvents(); } // We buffer cross-frame paint updates to account for paint timings from // different frames arriving out of order. TEST_F(MetricsWebContentsObserverTest, OutOfOrderCrossFrameTiming2) { // Dispatch a timing update for the main frame that includes a first // paint. This should be buffered, with the dispatch timer running. mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); // Ensure this is much bigger than the subframe first paint below. We // currently can't inject the navigation start offset, so we must ensure that // subframe first paint + navigation start offset < main frame first paint. timing.paint_timing->first_paint = base::Milliseconds(100000); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdateWithoutFiringDispatchTimer(timing, main_rfh()); EXPECT_TRUE(GetMostRecentTimer()->IsRunning()); ASSERT_EQ(0, CountUpdatedTimingReported()); content::RenderFrameHostTester* rfh_tester = content::RenderFrameHostTester::For(main_rfh()); // Dispatch a timing update for a child frame that includes a first paint. mojom::PageLoadTiming subframe_timing; PopulatePageLoadTiming(&subframe_timing); subframe_timing.paint_timing->first_paint = base::Milliseconds(500); content::RenderFrameHost* subframe = rfh_tester->AppendChild("subframe"); subframe = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe); SimulateTimingUpdateWithoutFiringDispatchTimer(subframe_timing, subframe); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kHistogramOutOfOrderTiming, 1); EXPECT_TRUE(GetMostRecentTimer()->IsRunning()); ASSERT_EQ(0, CountUpdatedTimingReported()); // At this point, the timing update is buffered, waiting for the timer to // fire. GetMostRecentTimer()->Fire(); // Firing the timer should produce a timing update. The update should be a // merged view of the main frame timing, with a first paint timestamp from the // subframe. ASSERT_EQ(1, CountUpdatedTimingReported()); EXPECT_FALSE(timing.Equals(*updated_timings().back())); EXPECT_TRUE( updated_timings().back()->parse_timing->Equals(*timing.parse_timing)); EXPECT_TRUE(updated_timings().back()->document_timing->Equals( *timing.document_timing)); EXPECT_FALSE( updated_timings().back()->paint_timing->Equals(*timing.paint_timing)); EXPECT_TRUE(updated_timings().back()->paint_timing->first_paint); // The first paint value should be the min of all received first paints, which // in this case is the first paint from the subframe. Since it is offset by // the subframe's navigation start, the received value should be >= the first // paint value specified in the subframe. EXPECT_GE(updated_timings().back()->paint_timing->first_paint, subframe_timing.paint_timing->first_paint); EXPECT_LT(updated_timings().back()->paint_timing->first_paint, timing.paint_timing->first_paint); base::TimeDelta initial_first_paint = updated_timings().back()->paint_timing->first_paint.value(); // Dispatch a timing update for an additional child frame, with an earlier // first paint time. This should cause an immediate update, without a timer // delay. subframe_timing.paint_timing->first_paint = base::Milliseconds(50); content::RenderFrameHost* subframe2 = rfh_tester->AppendChild("subframe"); subframe2 = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe2); SimulateTimingUpdateWithoutFiringDispatchTimer(subframe_timing, subframe2); base::TimeDelta updated_first_paint = updated_timings().back()->paint_timing->first_paint.value(); EXPECT_FALSE(GetMostRecentTimer()->IsRunning()); ASSERT_EQ(2, CountUpdatedTimingReported()); EXPECT_LT(updated_first_paint, initial_first_paint); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kHistogramOutOfOrderTimingBuffered, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kHistogramOutOfOrderTimingBuffered, (initial_first_paint - updated_first_paint).InMilliseconds(), 1); CheckNoErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, FlushBufferOnAppBackground) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.paint_timing->first_paint = base::Milliseconds(100000); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdateWithoutFiringDispatchTimer(timing, main_rfh()); ASSERT_EQ(0, CountUpdatedTimingReported()); observer()->FlushMetricsOnAppEnterBackground(); ASSERT_EQ(1, CountUpdatedTimingReported()); } TEST_F(MetricsWebContentsObserverTest, FirstInputDelayMissingFirstInputTimestamp) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.interactive_timing->first_input_delay = base::Milliseconds(10); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; // Won't have been set, as we're missing the first_input_timestamp. EXPECT_FALSE(interactive_timing.first_input_delay.has_value()); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal::INVALID_NULL_FIRST_INPUT_TIMESTAMP, 1); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorNoIPCsReceivedIfNeeded(1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, FirstInputTimestampMissingFirstInputDelay) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.interactive_timing->first_input_timestamp = base::Milliseconds(10); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; // Won't have been set, as we're missing the first_input_delay. EXPECT_FALSE(interactive_timing.first_input_timestamp.has_value()); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal::INVALID_NULL_FIRST_INPUT_DELAY, 1); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorNoIPCsReceivedIfNeeded(1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, LongestInputDelayMissingLongestInputTimestamp) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.interactive_timing->longest_input_delay = base::Milliseconds(10); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; // Won't have been set, as we're missing the longest_input_timestamp. EXPECT_FALSE(interactive_timing.longest_input_delay.has_value()); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal::INVALID_NULL_LONGEST_INPUT_TIMESTAMP, 1); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorNoIPCsReceivedIfNeeded(1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, LongestInputTimestampMissingLongestInputDelay) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.interactive_timing->longest_input_timestamp = base::Milliseconds(10); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; // Won't have been set, as we're missing the longest_input_delay. EXPECT_FALSE(interactive_timing.longest_input_timestamp.has_value()); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal::INVALID_NULL_LONGEST_INPUT_DELAY, 1); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorNoIPCsReceivedIfNeeded(1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, LongestInputDelaySmallerThanFirstInputDelay) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.interactive_timing->first_input_delay = base::Milliseconds(50); timing.interactive_timing->first_input_timestamp = base::Milliseconds(1000); timing.interactive_timing->longest_input_delay = base::Milliseconds(10); timing.interactive_timing->longest_input_timestamp = base::Milliseconds(2000); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; // Won't have been set, as it's invalid. EXPECT_FALSE(interactive_timing.longest_input_delay.has_value()); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal:: INVALID_LONGEST_INPUT_DELAY_LESS_THAN_FIRST_INPUT_DELAY, 1); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorNoIPCsReceivedIfNeeded(1); CheckTotalErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, LongestInputTimestampEarlierThanFirstInputTimestamp) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.interactive_timing->first_input_delay = base::Milliseconds(50); timing.interactive_timing->first_input_timestamp = base::Milliseconds(1000); timing.interactive_timing->longest_input_delay = base::Milliseconds(60); timing.interactive_timing->longest_input_timestamp = base::Milliseconds(500); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; // Won't have been set, as it's invalid. EXPECT_FALSE(interactive_timing.longest_input_delay.has_value()); histogram_tester_.ExpectTotalCount( page_load_metrics::internal::kPageLoadTimingStatus, 1); histogram_tester_.ExpectBucketCount( page_load_metrics::internal::kPageLoadTimingStatus, page_load_metrics::internal:: INVALID_LONGEST_INPUT_TIMESTAMP_LESS_THAN_FIRST_INPUT_TIMESTAMP, 1); CheckErrorEvent(ERR_BAD_TIMING_IPC_INVALID_TIMING, 1); CheckErrorNoIPCsReceivedIfNeeded(1); CheckTotalErrorEvents(); } // Main frame delivers an input notification. Subsequently, a subframe delivers // an input notification, where the input occurred first. Verify that // FirstInputDelay and FirstInputTimestamp come from the subframe. TEST_F(MetricsWebContentsObserverTest, FirstInputDelayAndTimingSubframeFirstDeliveredSecond) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.interactive_timing->first_input_delay = base::Milliseconds(10); // Set this far in the future. We currently can't control the navigation start // offset, so we ensure that the subframe timestamp + the unknown offset is // less than the main frame timestamp. timing.interactive_timing->first_input_timestamp = base::Minutes(100); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); content::RenderFrameHostTester* rfh_tester = content::RenderFrameHostTester::For(main_rfh()); content::RenderFrameHost* subframe = rfh_tester->AppendChild("subframe"); // Dispatch a timing update for the child frame that includes a first input // earlier than the one for the main frame. mojom::PageLoadTiming subframe_timing; PopulatePageLoadTiming(&subframe_timing); subframe_timing.interactive_timing->first_input_delay = base::Milliseconds(15); subframe_timing.interactive_timing->first_input_timestamp = base::Milliseconds(90); subframe = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe); SimulateTimingUpdate(subframe_timing, subframe); // Navigate again to confirm the timing updated for a subframe message. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; EXPECT_EQ(base::Milliseconds(15), interactive_timing.first_input_delay); // Ensure the timestamp is from the subframe. The main frame timestamp was 100 // minutes. EXPECT_LT(interactive_timing.first_input_timestamp, base::Minutes(10)); CheckNoErrorEvents(); } // A subframe delivers an input notification. Subsequently, the mainframe // delivers an input notification, where the input occurred first. Verify that // FirstInputDelay and FirstInputTimestamp come from the main frame. TEST_F(MetricsWebContentsObserverTest, FirstInputDelayAndTimingMainframeFirstDeliveredSecond) { // We need to navigate before we can navigate the subframe. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); content::RenderFrameHostTester* rfh_tester = content::RenderFrameHostTester::For(main_rfh()); content::RenderFrameHost* subframe = rfh_tester->AppendChild("subframe"); mojom::PageLoadTiming subframe_timing; PopulatePageLoadTiming(&subframe_timing); subframe_timing.interactive_timing->first_input_delay = base::Milliseconds(10); subframe_timing.interactive_timing->first_input_timestamp = base::Minutes(100); subframe = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe); SimulateTimingUpdate(subframe_timing, subframe); mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); // Dispatch a timing update for the main frame that includes a first input // earlier than the one for the subframe. timing.interactive_timing->first_input_delay = base::Milliseconds(15); // Set this far in the future. We currently can't control the navigation start // offset, so we ensure that the main frame timestamp + the unknown offset is // less than the subframe timestamp. timing.interactive_timing->first_input_timestamp = base::Milliseconds(90); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(timing); // Navigate again to confirm the timing updated for the mainframe message. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; EXPECT_EQ(base::Milliseconds(15), interactive_timing.first_input_delay); // Ensure the timestamp is from the main frame. The subframe timestamp was 100 // minutes. EXPECT_LT(interactive_timing.first_input_timestamp, base::Minutes(10)); CheckNoErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, DISABLED_LongestInputInMainFrame) { // We need to navigate before we can navigate the subframe. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); content::RenderFrameHostTester* rfh_tester = content::RenderFrameHostTester::For(main_rfh()); content::RenderFrameHost* subframe = rfh_tester->AppendChild("subframe"); mojom::PageLoadTiming subframe_timing; PopulatePageLoadTiming(&subframe_timing); subframe_timing.interactive_timing->longest_input_delay = base::Milliseconds(70); subframe_timing.interactive_timing->longest_input_timestamp = base::Milliseconds(1000); subframe = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe); SimulateTimingUpdate(subframe_timing, subframe); mojom::PageLoadTiming main_frame_timing; PopulatePageLoadTiming(&main_frame_timing); // Dispatch a timing update for the main frame that includes a longest input // delay longer than the one for the subframe. main_frame_timing.interactive_timing->longest_input_delay = base::Milliseconds(100); main_frame_timing.interactive_timing->longest_input_timestamp = base::Milliseconds(2000); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(main_frame_timing); // Second subframe. content::RenderFrameHost* subframe2 = rfh_tester->AppendChild("subframe2"); mojom::PageLoadTiming subframe2_timing; PopulatePageLoadTiming(&subframe2_timing); subframe2_timing.interactive_timing->longest_input_delay = base::Milliseconds(80); subframe2_timing.interactive_timing->longest_input_timestamp = base::Milliseconds(3000); subframe2 = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe2); SimulateTimingUpdate(subframe2_timing, subframe2); // Navigate again to confirm all timings are updated. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; EXPECT_EQ(base::Milliseconds(100), interactive_timing.longest_input_delay); EXPECT_EQ(base::Milliseconds(2000), interactive_timing.longest_input_timestamp); CheckNoErrorEvents(); } // ----------------------------------------------------------------------------- // | | | // 1s 2s 3s // Subframe1 Main Frame Subframe2 // LID (15ms) LID (100ms) LID (200ms) // // Delivery order: Main Frame -> Subframe1 -> Subframe2. TEST_F(MetricsWebContentsObserverTest, LongestInputInSubframe) { mojom::PageLoadTiming main_frame_timing; PopulatePageLoadTiming(&main_frame_timing); main_frame_timing.interactive_timing->longest_input_delay = base::Milliseconds(100); main_frame_timing.interactive_timing->longest_input_timestamp = base::Milliseconds(2000); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdate(main_frame_timing); content::RenderFrameHostTester* rfh_tester = content::RenderFrameHostTester::For(main_rfh()); // First subframe. content::RenderFrameHost* subframe1 = rfh_tester->AppendChild("subframe1"); mojom::PageLoadTiming subframe_timing; PopulatePageLoadTiming(&subframe_timing); subframe_timing.interactive_timing->longest_input_delay = base::Milliseconds(15); subframe_timing.interactive_timing->longest_input_timestamp = base::Milliseconds(1000); subframe1 = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe1); SimulateTimingUpdate(subframe_timing, subframe1); // Second subframe. content::RenderFrameHost* subframe2 = rfh_tester->AppendChild("subframe2"); mojom::PageLoadTiming subframe2_timing; PopulatePageLoadTiming(&subframe2_timing); subframe2_timing.interactive_timing->longest_input_delay = base::Milliseconds(200); subframe2_timing.interactive_timing->longest_input_timestamp = base::Milliseconds(3000); // TODO: Make this url3. subframe2 = content::NavigationSimulator::NavigateAndCommitFromDocument( GURL(kDefaultTestUrl2), subframe2); SimulateTimingUpdate(subframe2_timing, subframe2); // Navigate again to confirm all timings are updated. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); const mojom::InteractiveTiming& interactive_timing = *complete_timings().back()->interactive_timing; EXPECT_EQ(base::Milliseconds(200), interactive_timing.longest_input_delay); // Actual LID timestamp includes the delta between navigation start in // subframe2 and navigation time in the main frame. That delta varies with // different runs, so we only check here that the timestamp is greater than // 3s. EXPECT_GT(interactive_timing.longest_input_timestamp.value(), base::Milliseconds(3000)); CheckNoErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, DispatchDelayedMetricsOnPageClose) { mojom::PageLoadTiming timing; PopulatePageLoadTiming(&timing); timing.paint_timing->first_paint = base::Milliseconds(1000); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); SimulateTimingUpdateWithoutFiringDispatchTimer(timing, main_rfh()); // Throw in a cpu timing update, shouldn't affect the page timing results. mojom::CpuTiming cpu_timing; cpu_timing.task_time = base::Milliseconds(1000); SimulateCpuTimingUpdate(cpu_timing, main_rfh()); EXPECT_TRUE(GetMostRecentTimer()->IsRunning()); ASSERT_EQ(0, CountUpdatedTimingReported()); ASSERT_EQ(0, CountCompleteTimingReported()); // Navigate to a new page. This should force dispatch of the buffered timing // update. NavigateToUntrackedUrl(); ASSERT_EQ(1, CountUpdatedTimingReported()); ASSERT_EQ(1, CountUpdatedCpuTimingReported()); ASSERT_EQ(1, CountCompleteTimingReported()); EXPECT_TRUE(timing.Equals(*updated_timings().back())); EXPECT_TRUE(timing.Equals(*complete_timings().back())); EXPECT_TRUE(cpu_timing.Equals(*updated_cpu_timings().back())); CheckNoErrorEvents(); } // Make sure the dispatch of CPU occurs immediately. TEST_F(MetricsWebContentsObserverTest, DispatchCpuMetricsImmediately) { content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); mojom::CpuTiming timing; timing.task_time = base::Milliseconds(1000); SimulateCpuTimingUpdate(timing, main_rfh()); ASSERT_EQ(1, CountUpdatedCpuTimingReported()); EXPECT_TRUE(timing.Equals(*updated_cpu_timings().back())); // Navigate to a new page. This should force dispatch of the buffered timing // update. NavigateToUntrackedUrl(); ASSERT_EQ(1, CountUpdatedCpuTimingReported()); EXPECT_TRUE(timing.Equals(*updated_cpu_timings().back())); CheckNoErrorEvents(); } TEST_F(MetricsWebContentsObserverTest, OnLoadedResource_MainFrame) { GURL main_resource_url(kDefaultTestUrl); content::NavigationSimulator::NavigateAndCommitFromBrowser(web_contents(), main_resource_url); auto navigation_simulator = content::NavigationSimulator::CreateRendererInitiated( main_resource_url, web_contents()->GetMainFrame()); navigation_simulator->Start(); navigation_simulator->Commit(); const auto request_id = navigation_simulator->GetGlobalRequestID(); observer()->ResourceLoadComplete( web_contents()->GetMainFrame(), request_id, *CreateResourceLoadInfo(main_resource_url, network::mojom::RequestDestination::kFrame)); EXPECT_EQ(1u, loaded_resources().size()); EXPECT_EQ(url::Origin::Create(main_resource_url), loaded_resources().back().origin_of_final_url); NavigateToUntrackedUrl(); // Deliver a second main frame resource. This one should be ignored, since the // specified |request_id| is no longer associated with any tracked page loads. observer()->ResourceLoadComplete( web_contents()->GetMainFrame(), request_id, *CreateResourceLoadInfo(main_resource_url, network::mojom::RequestDestination::kFrame)); EXPECT_EQ(1u, loaded_resources().size()); EXPECT_EQ(url::Origin::Create(main_resource_url), loaded_resources().back().origin_of_final_url); } TEST_F(MetricsWebContentsObserverTest, OnLoadedResource_Subresource) { content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); GURL loaded_resource_url("http://www.other.com/"); observer()->ResourceLoadComplete( web_contents()->GetMainFrame(), content::GlobalRequestID(), *CreateResourceLoadInfo(loaded_resource_url, network::mojom::RequestDestination::kScript)); EXPECT_EQ(1u, loaded_resources().size()); EXPECT_EQ(url::Origin::Create(loaded_resource_url), loaded_resources().back().origin_of_final_url); } TEST_F(MetricsWebContentsObserverTest, OnLoadedResource_ResourceFromOtherRFHIgnored) { content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); content::RenderFrameHost* old_rfh = web_contents()->GetMainFrame(); content::LeaveInPendingDeletionState(old_rfh); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); DCHECK(!old_rfh->IsActive()); observer()->ResourceLoadComplete( old_rfh, content::GlobalRequestID(), *CreateResourceLoadInfo(GURL("http://www.other.com/"), network::mojom::RequestDestination::kScript)); EXPECT_TRUE(loaded_resources().empty()); } TEST_F(MetricsWebContentsObserverTest, OnLoadedResource_IgnoreNonHttpOrHttpsScheme) { content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); GURL loaded_resource_url("data:text/html,Hello world"); observer()->ResourceLoadComplete( web_contents()->GetMainFrame(), content::GlobalRequestID(), *CreateResourceLoadInfo(loaded_resource_url, network::mojom::RequestDestination::kScript)); EXPECT_TRUE(loaded_resources().empty()); } TEST_F(MetricsWebContentsObserverTest, RecordFeatureUsage) { content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(main_rfh()->GetLastCommittedURL().spec(), GURL(kDefaultTestUrl)); MetricsWebContentsObserver::RecordFeatureUsage( main_rfh(), {blink::mojom::WebFeature::kHTMLMarqueeElement, blink::mojom::WebFeature::kFormAttribute}); blink::UseCounterFeature feature1 = { blink::mojom::UseCounterFeatureType::kWebFeature, static_cast<uint32_t>(blink::mojom::WebFeature::kHTMLMarqueeElement), }; blink::UseCounterFeature feature2 = { blink::mojom::UseCounterFeatureType::kWebFeature, static_cast<uint32_t>(blink::mojom::WebFeature::kFormAttribute), }; ASSERT_EQ(observed_features().size(), 2ul); EXPECT_EQ(observed_features()[0], feature1); EXPECT_EQ(observed_features()[1], feature2); } TEST_F(MetricsWebContentsObserverTest, RecordFeatureUsageNoObserver) { // Reset the state of the tests, and don't add an observer. DeleteContents(); SetContents(CreateTestWebContents()); // This call should just do nothing, and should not crash - if that happens, // we are good. MetricsWebContentsObserver::RecordFeatureUsage( main_rfh(), {blink::mojom::WebFeature::kHTMLMarqueeElement, blink::mojom::WebFeature::kFormAttribute}); } class MetricsWebContentsObserverBackForwardCacheTest : public MetricsWebContentsObserverTest, public content::WebContentsDelegate { class CreatedPageLoadTrackerObserver : public MetricsWebContentsObserver::TestingObserver { public: explicit CreatedPageLoadTrackerObserver(content::WebContents* web_contents) : MetricsWebContentsObserver::TestingObserver(web_contents) {} int tracker_committed_count() const { return tracker_committed_count_; } void OnCommit(PageLoadTracker* tracker) override { tracker_committed_count_++; } private: int tracker_committed_count_ = 0; }; public: MetricsWebContentsObserverBackForwardCacheTest() { feature_list_.InitWithFeaturesAndParameters( {{features::kBackForwardCache, {{"TimeToLiveInBackForwardCacheInSeconds", "3600"}}}}, // Allow BackForwardCache for all devices regardless of their memory. {features::kBackForwardCacheMemoryControls}); } ~MetricsWebContentsObserverBackForwardCacheTest() override = default; int tracker_committed_count() const { return created_page_load_tracker_observer_->tracker_committed_count(); } void SetUp() override { MetricsWebContentsObserverTest::SetUp(); created_page_load_tracker_observer_ = std::make_unique<CreatedPageLoadTrackerObserver>(web_contents()); observer()->AddTestingObserver(created_page_load_tracker_observer_.get()); web_contents()->SetDelegate(this); } // content::WebContentsDelegate: bool IsBackForwardCacheSupported() override { return true; } private: base::test::ScopedFeatureList feature_list_; std::unique_ptr<CreatedPageLoadTrackerObserver> created_page_load_tracker_observer_; }; TEST_F(MetricsWebContentsObserverBackForwardCacheTest, RecordFeatureUsageWithBackForwardCache) { content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(main_rfh()->GetLastCommittedURL().spec(), GURL(kDefaultTestUrl)); MetricsWebContentsObserver::RecordFeatureUsage( main_rfh(), blink::mojom::WebFeature::kHTMLMarqueeElement); content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); content::NavigationSimulator::GoBack(web_contents()); MetricsWebContentsObserver::RecordFeatureUsage( main_rfh(), blink::mojom::WebFeature::kFormAttribute); // For now back-forward cached navigations are not tracked and the events // after the history navigation are not tracked. blink::UseCounterFeature feature = { blink::mojom::UseCounterFeatureType::kWebFeature, static_cast<uint32_t>(blink::mojom::WebFeature::kHTMLMarqueeElement), }; EXPECT_THAT(observed_features(), testing::ElementsAre(feature)); } // Checks OnEnterBackForwardCache is called appropriately with back-forward // cache enabled. TEST_F(MetricsWebContentsObserverBackForwardCacheTest, EnterBackForwardCache) { // Go to the URL1. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(main_rfh()->GetLastCommittedURL().spec(), GURL(kDefaultTestUrl)); ASSERT_EQ(0, CountCompleteTimingReported()); EXPECT_EQ(0, CountOnBackForwardCacheEntered()); EXPECT_EQ(1, tracker_committed_count()); // Go to the URL2. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(main_rfh()->GetLastCommittedURL().spec(), GURL(kDefaultTestUrl2)); // With the default implementation of PageLoadMetricsObserver, // OnEnteringBackForwardCache invokes OnComplete and returns STOP_OBSERVING. ASSERT_EQ(1, CountCompleteTimingReported()); EXPECT_EQ(1, CountOnBackForwardCacheEntered()); EXPECT_EQ(2, tracker_committed_count()); // Go back. content::NavigationSimulator::GoBack(web_contents()); EXPECT_EQ(2, CountOnBackForwardCacheEntered()); // Again, OnComplete is assured to be called. ASSERT_EQ(2, CountCompleteTimingReported()); // A new page load tracker is not created or committed. A page load tracker in // the cache is used instead. EXPECT_EQ(2, tracker_committed_count()); } // TODO(hajimehoshi): Detect the document eviction so that PageLoadTracker in // the cache is destroyed. This would call PageLoadMetricsObserver::OnComplete. // This test can be implemented after a PageLoadMetricsObserver's // OnEnterBackForwardCache returns CONTINUE_OBSERVING. class MetricsWebContentsObserverBackForwardCacheDisabledTest : public MetricsWebContentsObserverTest { public: MetricsWebContentsObserverBackForwardCacheDisabledTest() { feature_list_.InitWithFeaturesAndParameters({}, {features::kBackForwardCache}); } ~MetricsWebContentsObserverBackForwardCacheDisabledTest() override = default; private: base::test::ScopedFeatureList feature_list_; }; // Checks OnEnterBackForwardCache is NOT called without back-forward cache // enabled. TEST_F(MetricsWebContentsObserverBackForwardCacheDisabledTest, EnterBackForwardCacheNotCalled) { // Go to the URL1. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(main_rfh()->GetLastCommittedURL().spec(), GURL(kDefaultTestUrl)); ASSERT_EQ(0, CountCompleteTimingReported()); // Go to the URL2. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(main_rfh()->GetLastCommittedURL().spec(), GURL(kDefaultTestUrl2)); ASSERT_EQ(1, CountCompleteTimingReported()); EXPECT_EQ(0, CountOnBackForwardCacheEntered()); // Go back. content::NavigationSimulator::GoBack(web_contents()); EXPECT_EQ(0, CountOnBackForwardCacheEntered()); ASSERT_EQ(2, CountCompleteTimingReported()); } class MetricsWebContentsObserverNonPrimaryPageTest : public MetricsWebContentsObserverBackForwardCacheTest { public: class MetricsObserver : public PageLoadMetricsObserver { public: explicit MetricsObserver( MetricsWebContentsObserverNonPrimaryPageTest* owner) : owner_(owner) {} ObservePolicy OnCommit(content::NavigationHandle* handle, ukm::SourceId source_id) override { committed_url_ = handle->GetURL(); return CONTINUE_OBSERVING; } ObservePolicy OnEnterBackForwardCache( const mojom::PageLoadTiming& timing) override { return CONTINUE_OBSERVING; } void OnV8MemoryChanged( const std::vector<MemoryUpdate>& memory_updates) override { owner_->OnV8MemoryChanged(committed_url_, memory_updates); } private: raw_ptr<MetricsWebContentsObserverNonPrimaryPageTest> owner_; GURL committed_url_; }; class Embedder : public TestMetricsWebContentsObserverEmbedder { public: explicit Embedder(MetricsWebContentsObserverNonPrimaryPageTest* owner) : owner_(owner) {} void RegisterObservers(PageLoadTracker* tracker) override { TestMetricsWebContentsObserverEmbedder::RegisterObservers(tracker); tracker->AddObserver(std::make_unique<MetricsObserver>(owner_)); } private: raw_ptr<MetricsWebContentsObserverNonPrimaryPageTest> owner_; }; std::unique_ptr<TestMetricsWebContentsObserverEmbedder> CreateEmbedder() override { return std::make_unique<Embedder>(this); } void OnV8MemoryChanged(const GURL& url, const std::vector<MemoryUpdate>& memory_updates) { std::vector<MemoryUpdate>& updates_for_url = observed_memory_updates_[url]; updates_for_url.insert(updates_for_url.end(), memory_updates.begin(), memory_updates.end()); } protected: std::map<GURL, std::vector<MemoryUpdate>> observed_memory_updates_; }; TEST_F(MetricsWebContentsObserverNonPrimaryPageTest, MemoryUpdates) { // Go to the URL1. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl)); ASSERT_EQ(main_rfh()->GetLastCommittedURL().spec(), GURL(kDefaultTestUrl)); content::GlobalRenderFrameHostId rfh1_id = main_rfh()->GetGlobalId(); ASSERT_EQ(0, CountCompleteTimingReported()); EXPECT_EQ(0, CountOnBackForwardCacheEntered()); EXPECT_EQ(1, tracker_committed_count()); // Go to the URL2. content::NavigationSimulator::NavigateAndCommitFromBrowser( web_contents(), GURL(kDefaultTestUrl2)); ASSERT_EQ(main_rfh()->GetLastCommittedURL().spec(), GURL(kDefaultTestUrl2)); content::GlobalRenderFrameHostId rfh2_id = main_rfh()->GetGlobalId(); ASSERT_EQ(1, CountCompleteTimingReported()); EXPECT_EQ(1, CountOnBackForwardCacheEntered()); EXPECT_EQ(2, tracker_committed_count()); std::vector<MemoryUpdate> memory_updates = {{rfh1_id, 100}, {rfh2_id, 200}}; observer()->OnV8MemoryChanged(memory_updates); // Verify that memory updates are observed both in primary URL2 and // non-primary URL1. ASSERT_EQ(2u, observed_memory_updates_.size()); ASSERT_EQ(1u, observed_memory_updates_[GURL(kDefaultTestUrl)].size()); EXPECT_EQ(100, observed_memory_updates_[GURL(kDefaultTestUrl)][0].delta_bytes); ASSERT_EQ(1u, observed_memory_updates_[GURL(kDefaultTestUrl2)].size()); EXPECT_EQ(200, observed_memory_updates_[GURL(kDefaultTestUrl2)][0].delta_bytes); } } // namespace page_load_metrics
ric2b/Vivaldi-browser
chromium/components/page_load_metrics/browser/metrics_web_contents_observer_unittest.cc
C++
bsd-3-clause
69,984
<?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
// Copyright 2020 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.autofill_assistant; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import androidx.preference.Preference; import androidx.preference.PreferenceCategory; import androidx.test.filters.LargeTest; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; import org.chromium.chrome.browser.preferences.SharedPreferencesManager; import org.chromium.chrome.browser.settings.SettingsActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.browser.Features.DisableFeatures; import org.chromium.chrome.test.util.browser.Features.EnableFeatures; import org.chromium.components.browser_ui.settings.ChromeSwitchPreference; import org.chromium.content_public.browser.test.util.TestThreadUtils; /** * Tests for AutofillAssistantPreferenceFragment. */ @RunWith(ChromeJUnit4ClassRunner.class) public class AutofillAssistantPreferenceFragmentTest { private final SettingsActivityTestRule<AutofillAssistantPreferenceFragment> mSettingsActivityTestRule = new SettingsActivityTestRule<>(AutofillAssistantPreferenceFragment.class); private final SharedPreferencesManager mSharedPreferencesManager = SharedPreferencesManager.getInstance(); /** * Test: if the onboarding was never shown or it was shown and not accepted, the AA chrome * preference should not exist. * * Note: the presence of the {@link AutofillAssistantPreferenceFragment.PREF_AUTOFILL_ASSISTANT} * shared preference indicates whether the onboarding was accepted or not. */ @Test @LargeTest @Feature({"Sync"}) @EnableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_NAME) public void testAutofillAssistantNoPreferenceIfOnboardingNeverShown() { final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { assertFalse(prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_AUTOFILL_ASSISTANT) .isVisible()); }); } /** * Test: if the onboarding was accepted, the AA chrome preference should also exist. * * Note: the presence of the {@link AutofillAssistantPreferenceFragment.PREF_AUTOFILL_ASSISTANT} * shared preference indicates whether the onboarding was accepted or not. */ @Test @LargeTest @Feature({"Sync"}) @EnableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_NAME) public void testAutofillAssistantPreferenceShownIfOnboardingShown() { setAutofillAssistantSwitchValue(true); final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { assertTrue(prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_AUTOFILL_ASSISTANT) .isVisible()); }); } /** * Ensure that the "Autofill Assistant" setting is not shown when the feature is disabled. */ @Test @LargeTest @Feature({"Sync"}) @DisableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_NAME) public void testAutofillAssistantNoPreferenceIfFeatureDisabled() { setAutofillAssistantSwitchValue(true); final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { assertFalse(prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_AUTOFILL_ASSISTANT) .isVisible()); }); } /** * Ensure that the "Autofill Assistant" on/off switch works. */ @Test @LargeTest @Feature({"Sync"}) @EnableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_NAME) public void testAutofillAssistantSwitchOn() { TestThreadUtils.runOnUiThreadBlocking(() -> { setAutofillAssistantSwitchValue(true); }); final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { ChromeSwitchPreference autofillAssistantSwitch = (ChromeSwitchPreference) prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_AUTOFILL_ASSISTANT); assertTrue(autofillAssistantSwitch.isChecked()); autofillAssistantSwitch.performClick(); assertFalse(mSharedPreferencesManager.readBoolean( ChromePreferenceKeys.AUTOFILL_ASSISTANT_ENABLED, true)); autofillAssistantSwitch.performClick(); assertTrue(mSharedPreferencesManager.readBoolean( ChromePreferenceKeys.AUTOFILL_ASSISTANT_ENABLED, false)); }); } @Test @LargeTest @Feature({"Sync"}) @EnableFeatures({AssistantFeatures.AUTOFILL_ASSISTANT_NAME, AssistantFeatures.AUTOFILL_ASSISTANT_PROACTIVE_HELP_NAME}) @DisableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_DISABLE_PROACTIVE_HELP_TIED_TO_MSBB_NAME) public void testProactiveHelpDisabledIfMsbbDisabled() { final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { ChromeSwitchPreference proactiveHelpSwitch = (ChromeSwitchPreference) prefs.findPreference( AutofillAssistantPreferenceFragment .PREF_ASSISTANT_PROACTIVE_HELP_SWITCH); assertFalse(proactiveHelpSwitch.isEnabled()); Preference syncAndServicesLink = prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_GOOGLE_SERVICES_SETTINGS_LINK); assertNotNull(syncAndServicesLink); assertTrue(syncAndServicesLink.isVisible()); }); } @Test @LargeTest @Feature({"Sync"}) @EnableFeatures({AssistantFeatures.AUTOFILL_ASSISTANT_NAME, AssistantFeatures.AUTOFILL_ASSISTANT_PROACTIVE_HELP_NAME, AssistantFeatures.AUTOFILL_ASSISTANT_DISABLE_PROACTIVE_HELP_TIED_TO_MSBB_NAME}) public void testProactiveHelpNotLinkedToMsbbIfLinkDisabled() { final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { ChromeSwitchPreference proactiveHelpSwitch = (ChromeSwitchPreference) prefs.findPreference( AutofillAssistantPreferenceFragment .PREF_ASSISTANT_PROACTIVE_HELP_SWITCH); assertTrue(proactiveHelpSwitch.isEnabled()); Preference syncAndServicesLink = prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_GOOGLE_SERVICES_SETTINGS_LINK); assertNotNull(syncAndServicesLink); assertFalse(syncAndServicesLink.isVisible()); }); } @Test @LargeTest @Feature({"Sync"}) @EnableFeatures({AssistantFeatures.AUTOFILL_ASSISTANT_NAME, AssistantFeatures.AUTOFILL_ASSISTANT_PROACTIVE_HELP_NAME}) @DisableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_DISABLE_PROACTIVE_HELP_TIED_TO_MSBB_NAME) public void testProactiveHelpDisabledIfAutofillAssistantDisabled() { TestThreadUtils.runOnUiThreadBlocking(() -> { setAutofillAssistantSwitchValue(true); }); final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { ChromeSwitchPreference proactiveHelpSwitch = (ChromeSwitchPreference) prefs.findPreference( AutofillAssistantPreferenceFragment .PREF_ASSISTANT_PROACTIVE_HELP_SWITCH); Preference syncAndServicesLink = prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_GOOGLE_SERVICES_SETTINGS_LINK); assertFalse(proactiveHelpSwitch.isEnabled()); assertTrue(syncAndServicesLink.isVisible()); ChromeSwitchPreference autofillAssistantSwitch = (ChromeSwitchPreference) prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_AUTOFILL_ASSISTANT); autofillAssistantSwitch.performClick(); assertFalse(proactiveHelpSwitch.isEnabled()); assertFalse(syncAndServicesLink.isVisible()); }); } @Test @LargeTest @Feature({"Sync"}) @DisableFeatures(AssistantFeatures.AUTOFILL_ASSISTANT_PROACTIVE_HELP_NAME) public void testProactiveHelpInvisibleIfProactiveHelpDisabled() { final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { ChromeSwitchPreference proactiveHelpSwitch = (ChromeSwitchPreference) prefs.findPreference( AutofillAssistantPreferenceFragment .PREF_ASSISTANT_PROACTIVE_HELP_SWITCH); assertFalse(proactiveHelpSwitch.isVisible()); }); } @Test @LargeTest @Feature({"Sync"}) @DisableFeatures({AssistantFeatures.AUTOFILL_ASSISTANT_NAME, AssistantFeatures.AUTOFILL_ASSISTANT_PROACTIVE_HELP_NAME}) public void testWebAssistanceInvisibleIfAutofillAssistantCompletelyDisabled() { final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { PreferenceCategory webAssistanceCateogory = prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_WEB_ASSISTANCE_CATEGORY); assertFalse(webAssistanceCateogory.isVisible()); }); } @Test @LargeTest @Feature({"AssistantVoiceSearch"}) @EnableFeatures(ChromeFeatureList.OMNIBOX_ASSISTANT_VOICE_SEARCH) public void testEnhancedVoiceSearch_Enabled() { final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { PreferenceCategory assistantVoiceSearchCategory = prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_ASSISTANT_VOICE_SEARCH_CATEGORY); assertTrue(assistantVoiceSearchCategory.isVisible()); ChromeSwitchPreference assistantVoiceSearchEnabledSwitch = (ChromeSwitchPreference) prefs.findPreference( AutofillAssistantPreferenceFragment .PREF_ASSISTANT_VOICE_SEARCH_ENABLED_SWTICH); assertTrue(assistantVoiceSearchEnabledSwitch.isVisible()); assistantVoiceSearchEnabledSwitch.performClick(); assertTrue(mSharedPreferencesManager.readBoolean( ChromePreferenceKeys.ASSISTANT_VOICE_SEARCH_ENABLED, /* default= */ false)); }); } @Test @LargeTest @Feature({"AssistantVoiceSearch"}) @DisableFeatures(ChromeFeatureList.OMNIBOX_ASSISTANT_VOICE_SEARCH) public void testEnhancedVoiceSearch_Disabled() { final AutofillAssistantPreferenceFragment prefs = startAutofillAssistantPreferenceFragment(); TestThreadUtils.runOnUiThreadBlocking(() -> { PreferenceCategory assistantVoiceSearchCategory = prefs.findPreference( AutofillAssistantPreferenceFragment.PREF_ASSISTANT_VOICE_SEARCH_CATEGORY); assertFalse(assistantVoiceSearchCategory.isVisible()); ChromeSwitchPreference assistantVoiceSearchEnabledSwitch = (ChromeSwitchPreference) prefs.findPreference( AutofillAssistantPreferenceFragment .PREF_ASSISTANT_VOICE_SEARCH_ENABLED_SWTICH); assertFalse(assistantVoiceSearchEnabledSwitch.isVisible()); }); } private void setAutofillAssistantSwitchValue(boolean newValue) { SharedPreferencesManager.getInstance().writeBoolean( ChromePreferenceKeys.AUTOFILL_ASSISTANT_ENABLED, newValue); } private AutofillAssistantPreferenceFragment startAutofillAssistantPreferenceFragment() { mSettingsActivityTestRule.startSettingsActivity(); return mSettingsActivityTestRule.getFragment(); } public boolean isAutofillAssistantSwitchOn() { return mSharedPreferencesManager.readBoolean( ChromePreferenceKeys.AUTOFILL_ASSISTANT_ENABLED, false); } }
ric2b/Vivaldi-browser
chromium/chrome/android/javatests/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantPreferenceFragmentTest.java
Java
bsd-3-clause
13,445
""" 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
package main import ( "os" "os/exec" "testing" ) // TestMainSuccess tests main function in a separate process using a trick from // https://talks.golang.org/2014/testing.slide#1 func TestMainSuccess(t *testing.T) { if os.Getenv("TEST_MAIN_FUNC") == "1" { os.Args = []string{"", "nop"} main() return } cmd := exec.Command(os.Args[0], "-test.run=TestMainSuccess") cmd.Env = append(os.Environ(), "TEST_MAIN_FUNC=1") err := cmd.Run() if e, ok := err.(*exec.ExitError); ok && !e.Success() { t.Fatalf("process ran with err %v, want exit status 0", err) } } // TestMainFailure tests main function in a separate process using a trick from // https://talks.golang.org/2014/testing.slide#1 func TestMainFailure(t *testing.T) { if os.Getenv("TEST_MAIN_FUNC") == "1" { os.Args = []string{"", "fail"} main() return } cmd := exec.Command(os.Args[0], "-test.run=TestMainFailure") cmd.Env = append(os.Environ(), "TEST_MAIN_FUNC=1") err := cmd.Run() if err == nil { t.Fatalf("process ran with err %v, want exit status 1", err) } }
juhovuori/builder
main_test.go
GO
bsd-3-clause
1,050
#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
/// <reference types="draft-js" /> declare module 'draft-js-export-html' { import draftjs = require("draft-js"); type BlockStyleFn = (block: draftjs.ContentBlock) => RenderConfig|undefined; type EntityStyleFn = (entity: draftjs.EntityInstance) => RenderConfig|undefined; type BlockRenderer = (block: draftjs.ContentBlock) => string; type RenderConfig = { element?: string; attributes?: any; style?: any; }; export interface Options { defaultBlockTag?: string | null; inlineStyles?: { [styleName: string]: RenderConfig }; blockRenderers?: { [blockType: string]: BlockRenderer }; blockStyleFn?: BlockStyleFn; entityStyleFn?: EntityStyleFn; } export function stateToHTML(content: draftjs.ContentState, options?: Options): string; }
sstur/draft-js-export-html
packages/draft-js-export-html/typings/index.d.ts
TypeScript
isc
833
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
import sublime, sublime_plugin, os class ExpandTabsOnSave(sublime_plugin.EventListener): def on_pre_save(self, view): if view.settings().get('expand_tabs_on_save') == 1: view.window().run_command('expand_tabs')
edonet/package
Edoner/expand_tabs_on_save.py
Python
isc
236
// Copyright 2012-2015 Apcera Inc. All rights reserved. package server import ( "bufio" "encoding/json" "fmt" "math/rand" "net" "sync" "sync/atomic" "time" "github.com/nats-io/gnatsd/hashmap" "github.com/nats-io/gnatsd/sublist" ) const ( // The size of the bufio reader/writer on top of the socket. defaultBufSize = 32768 // Scratch buffer size for the processMsg() calls. msgScratchSize = 512 msgHeadProto = "MSG " ) // Type of client const ( // CLIENT is an end user. CLIENT = iota // ROUTER is another router in the cluster. ROUTER ) type client struct { mu sync.Mutex typ int cid uint64 lang string opts clientOpts nc net.Conn mpay int ncs string bw *bufio.Writer srv *Server subs *hashmap.HashMap pcd map[*client]struct{} atmr *time.Timer ptmr *time.Timer pout int msgb [msgScratchSize]byte parseState stats route *route } func (c *client) String() (id string) { return c.ncs } func (c *client) GetOpts() *clientOpts { return &c.opts } type subscription struct { client *client subject []byte queue []byte sid []byte nm int64 max int64 } type clientOpts struct { Verbose bool `json:"verbose"` Pedantic bool `json:"pedantic"` SslRequired bool `json:"ssl_required"` Authorization string `json:"auth_token"` Username string `json:"user"` Password string `json:"pass"` Name string `json:"name"` Lang string `json:"lang"` Version string `json:"version"` } var defaultOpts = clientOpts{Verbose: true, Pedantic: true} func init() { rand.Seed(time.Now().UnixNano()) } // Lock should be held func (c *client) initClient() { s := c.srv c.cid = atomic.AddUint64(&s.gcid, 1) c.bw = bufio.NewWriterSize(c.nc, defaultBufSize) c.subs = hashmap.New() // This is a scratch buffer used for processMsg() // The msg header starts with "MSG ", // in bytes that is [77 83 71 32]. c.msgb = [msgScratchSize]byte{77, 83, 71, 32} // This is to track pending clients that have data to be flushed // after we process inbound msgs from our own connection. c.pcd = make(map[*client]struct{}) // snapshot the string version of the connection conn := "-" if ip, ok := c.nc.(*net.TCPConn); ok { addr := ip.RemoteAddr().(*net.TCPAddr) conn = fmt.Sprintf("%s:%d", addr.IP, addr.Port) } switch c.typ { case CLIENT: c.ncs = fmt.Sprintf("%s - cid:%d", conn, c.cid) case ROUTER: c.ncs = fmt.Sprintf("%s - rid:%d", conn, c.cid) } // No clue why, but this stalls and kills performance on Mac (Mavericks). // // if ip, ok := c.nc.(*net.TCPConn); ok { // ip.SetReadBuffer(defaultBufSize) // ip.SetWriteBuffer(2 * defaultBufSize) // } // Set the Ping timer c.setPingTimer() // Spin up the read loop. go c.readLoop() } func (c *client) readLoop() { // Grab the connection off the client, it will be cleared on a close. // We check for that after the loop, but want to avoid a nil dereference c.mu.Lock() nc := c.nc c.mu.Unlock() if nc == nil { return } b := make([]byte, defaultBufSize) for { n, err := nc.Read(b) if err != nil { c.closeConnection() return } if err := c.parse(b[:n]); err != nil { // handled inline if err != ErrMaxPayload && err != ErrAuthorization { c.Errorf("Error reading from client: %s", err.Error()) c.sendErr("Parser Error") c.closeConnection() } return } // Check pending clients for flush. for cp := range c.pcd { // Flush those in the set cp.mu.Lock() if cp.nc != nil { cp.nc.SetWriteDeadline(time.Now().Add(DEFAULT_FLUSH_DEADLINE)) err := cp.bw.Flush() cp.nc.SetWriteDeadline(time.Time{}) if err != nil { c.Debugf("Error flushing: %v", err) cp.mu.Unlock() cp.closeConnection() cp.mu.Lock() } } cp.mu.Unlock() delete(c.pcd, cp) } // Check to see if we got closed, e.g. slow consumer c.mu.Lock() nc := c.nc c.mu.Unlock() if nc == nil { return } } } func (c *client) traceMsg(msg []byte) { if trace == 0 { return } // FIXME(dlc), allow limits to printable payload c.Tracef("->> MSG_PAYLOAD: [%s]", string(msg[:len(msg)-LEN_CR_LF])) } func (c *client) traceInOp(op string, arg []byte) { c.traceOp("->> %s", op, arg) } func (c *client) traceOutOp(op string, arg []byte) { c.traceOp("<<- %s", op, arg) } func (c *client) traceOp(format, op string, arg []byte) { if trace == 0 { return } opa := []interface{}{} if op != "" { opa = append(opa, op) } if arg != nil { opa = append(opa, string(arg)) } c.Tracef(format, opa) } // Process the info message if we are a route. func (c *client) processRouteInfo(info *Info) { c.mu.Lock() if c.route == nil { c.mu.Unlock() return } c.route.remoteID = info.ID // Check to see if we have this remote already registered. // This can happen when both servers have routes to each other. s := c.srv c.mu.Unlock() if s.addRoute(c) { c.Debugf("Registering remote route %q", info.ID) // Send our local subscriptions to this route. s.sendLocalSubsToRoute(c) } else { c.Debugf("Detected duplicate remote route %q", info.ID) c.closeConnection() } } // Process the information messages from Clients and other routes. func (c *client) processInfo(arg []byte) error { info := Info{} if err := json.Unmarshal(arg, &info); err != nil { return err } if c.typ == ROUTER { c.processRouteInfo(&info) } return nil } func (c *client) processErr(errStr string) { c.Errorf("Client error %s", errStr) c.closeConnection() } func (c *client) processConnect(arg []byte) error { c.traceInOp("CONNECT", arg) // This will be resolved regardless before we exit this func, // so we can just clear it here. c.clearAuthTimer() if err := json.Unmarshal(arg, &c.opts); err != nil { return err } if c.srv != nil { // Check for Auth if ok := c.srv.checkAuth(c); !ok { c.authViolation() return ErrAuthorization } } // Grab connection name of remote route. if c.typ == ROUTER && c.route != nil { c.route.remoteID = c.opts.Name } if c.opts.Verbose { c.sendOK() } return nil } func (c *client) authTimeout() { c.sendErr("Authorization Timeout") c.closeConnection() } func (c *client) authViolation() { c.Errorf(ErrAuthorization.Error()) c.sendErr("Authorization Violation") c.closeConnection() } func (c *client) maxPayloadViolation(sz int) { c.Errorf("%s: %d vs %d", ErrMaxPayload.Error(), sz, c.mpay) c.sendErr("Maximum Payload Violation") c.closeConnection() } func (c *client) sendErr(err string) { c.mu.Lock() if c.bw != nil { c.bw.WriteString(fmt.Sprintf("-ERR '%s'\r\n", err)) c.pcd[c] = needFlush } c.mu.Unlock() } func (c *client) sendOK() { c.mu.Lock() c.bw.WriteString("+OK\r\n") c.pcd[c] = needFlush c.mu.Unlock() } func (c *client) processPing() { c.traceInOp("PING", nil) if c.nc == nil { return } c.traceOutOp("PONG", nil) c.mu.Lock() c.bw.WriteString("PONG\r\n") err := c.bw.Flush() if err != nil { c.clearConnection() c.Debugf("Error on Flush, error %s", err.Error()) } c.mu.Unlock() } func (c *client) processPong() { c.traceInOp("PONG", nil) c.mu.Lock() c.pout -= 1 c.mu.Unlock() } func (c *client) processMsgArgs(arg []byte) error { if trace == 1 { c.traceInOp("MSG", arg) } // Unroll splitArgs to avoid runtime/heap issues a := [MAX_MSG_ARGS][]byte{} args := a[:0] start := -1 for i, b := range arg { switch b { case ' ', '\t', '\r', '\n': if start >= 0 { args = append(args, arg[start:i]) start = -1 } default: if start < 0 { start = i } } } if start >= 0 { args = append(args, arg[start:]) } c.pa.subject = args[0] c.pa.sid = args[1] switch len(args) { case 3: c.pa.reply = nil c.pa.szb = args[2] c.pa.size = parseSize(args[2]) case 4: c.pa.reply = args[2] c.pa.szb = args[3] c.pa.size = parseSize(args[3]) default: return fmt.Errorf("processMsgArgs Parse Error: '%s'", arg) } if c.pa.size < 0 { return fmt.Errorf("processMsgArgs Bad or Missing Size: '%s'", arg) } return nil } func (c *client) processPub(arg []byte) error { if trace == 1 { c.traceInOp("PUB", arg) } // Unroll splitArgs to avoid runtime/heap issues a := [MAX_PUB_ARGS][]byte{} args := a[:0] start := -1 for i, b := range arg { switch b { case ' ', '\t', '\r', '\n': if start >= 0 { args = append(args, arg[start:i]) start = -1 } default: if start < 0 { start = i } } } if start >= 0 { args = append(args, arg[start:]) } switch len(args) { case 2: c.pa.subject = args[0] c.pa.reply = nil c.pa.size = parseSize(args[1]) c.pa.szb = args[1] case 3: c.pa.subject = args[0] c.pa.reply = args[1] c.pa.size = parseSize(args[2]) c.pa.szb = args[2] default: return fmt.Errorf("processPub Parse Error: '%s'", arg) } if c.pa.size < 0 { return fmt.Errorf("processPub Bad or Missing Size: '%s'", arg) } if c.mpay > 0 && c.pa.size > c.mpay { c.maxPayloadViolation(c.pa.size) return ErrMaxPayload } if c.opts.Pedantic && !sublist.IsValidLiteralSubject(c.pa.subject) { c.sendErr("Invalid Subject") } return nil } func splitArg(arg []byte) [][]byte { a := [MAX_MSG_ARGS][]byte{} args := a[:0] start := -1 for i, b := range arg { switch b { case ' ', '\t', '\r', '\n': if start >= 0 { args = append(args, arg[start:i]) start = -1 } default: if start < 0 { start = i } } } if start >= 0 { args = append(args, arg[start:]) } return args } func (c *client) processSub(argo []byte) (err error) { c.traceInOp("SUB", argo) // Copy so we do not reference a potentially large buffer arg := make([]byte, len(argo)) copy(arg, argo) args := splitArg(arg) sub := &subscription{client: c} switch len(args) { case 2: sub.subject = args[0] sub.queue = nil sub.sid = args[1] case 3: sub.subject = args[0] sub.queue = args[1] sub.sid = args[2] default: return fmt.Errorf("processSub Parse Error: '%s'", arg) } c.mu.Lock() if c.nc == nil { c.mu.Unlock() return nil } c.subs.Set(sub.sid, sub) if c.srv != nil { err = c.srv.sl.Insert(sub.subject, sub) } shouldForward := c.typ != ROUTER && c.srv != nil c.mu.Unlock() if err != nil { c.sendErr("Invalid Subject") } else if c.opts.Verbose { c.sendOK() } if shouldForward { c.srv.broadcastSubscribe(sub) } return nil } func (c *client) unsubscribe(sub *subscription) { c.mu.Lock() defer c.mu.Unlock() if sub.max > 0 && sub.nm < sub.max { c.Debugf( "Deferring actual UNSUB(%s): %d max, %d received\n", string(sub.subject), sub.max, sub.nm) return } c.traceOp("<-> %s", "DELSUB", sub.sid) c.subs.Remove(sub.sid) if c.srv != nil { c.srv.sl.Remove(sub.subject, sub) } } func (c *client) processUnsub(arg []byte) error { c.traceInOp("UNSUB", arg) args := splitArg(arg) var sid []byte max := -1 switch len(args) { case 1: sid = args[0] case 2: sid = args[0] max = parseSize(args[1]) default: return fmt.Errorf("processUnsub Parse Error: '%s'", arg) } if sub, ok := (c.subs.Get(sid)).(*subscription); ok { if max > 0 { sub.max = int64(max) } else { // Clear it here to override sub.max = 0 } c.unsubscribe(sub) if shouldForward := c.typ != ROUTER && c.srv != nil; shouldForward { c.srv.broadcastUnSubscribe(sub) } } if c.opts.Verbose { c.sendOK() } return nil } func (c *client) msgHeader(mh []byte, sub *subscription) []byte { mh = append(mh, sub.sid...) mh = append(mh, ' ') if c.pa.reply != nil { mh = append(mh, c.pa.reply...) mh = append(mh, ' ') } mh = append(mh, c.pa.szb...) mh = append(mh, "\r\n"...) return mh } // Used to treat maps as efficient set var needFlush = struct{}{} var routeSeen = struct{}{} func (c *client) deliverMsg(sub *subscription, mh, msg []byte) { if sub.client == nil { return } client := sub.client client.mu.Lock() sub.nm++ // Check if we should auto-unsubscribe. if sub.max > 0 { // For routing.. shouldForward := client.typ != ROUTER && client.srv != nil // If we are at the exact number, unsubscribe but // still process the message in hand, otherwise // unsubscribe and drop message on the floor. if sub.nm == sub.max { c.Debugf("Auto-unsubscribe limit of %d reached for sid '%s'\n", sub.max, string(sub.sid)) defer client.unsubscribe(sub) if shouldForward { defer client.srv.broadcastUnSubscribe(sub) } } else if sub.nm > sub.max { c.Debugf("Auto-unsubscribe limit [%d] exceeded\n", sub.max) client.mu.Unlock() client.unsubscribe(sub) if shouldForward { client.srv.broadcastUnSubscribe(sub) } return } } if client.nc == nil { client.mu.Unlock() return } // Update statistics // The msg includes the CR_LF, so pull back out for accounting. msgSize := int64(len(msg) - LEN_CR_LF) client.outMsgs++ client.outBytes += msgSize atomic.AddInt64(&c.srv.outMsgs, 1) atomic.AddInt64(&c.srv.outBytes, msgSize) // Check to see if our writes will cause a flush // in the underlying bufio. If so limit time we // will wait for flush to complete. deadlineSet := false if client.bw.Available() < (len(mh) + len(msg) + len(CR_LF)) { client.nc.SetWriteDeadline(time.Now().Add(DEFAULT_FLUSH_DEADLINE)) deadlineSet = true } // Deliver to the client. _, err := client.bw.Write(mh) if err != nil { goto writeErr } _, err = client.bw.Write(msg) if err != nil { goto writeErr } if trace == 1 { client.traceOutOp(string(mh[:len(mh)-LEN_CR_LF]), nil) } // TODO(dlc) - Do we need this or can we just call always? if deadlineSet { client.nc.SetWriteDeadline(time.Time{}) } client.mu.Unlock() c.pcd[client] = needFlush return writeErr: if deadlineSet { client.nc.SetWriteDeadline(time.Time{}) } client.mu.Unlock() if ne, ok := err.(net.Error); ok && ne.Timeout() { atomic.AddInt64(&client.srv.slowConsumers, 1) client.Noticef("Slow Consumer Detected") client.closeConnection() } else { c.Debugf("Error writing msg: %v", err) } } // processMsg is called to process an inbound msg from a client. func (c *client) processMsg(msg []byte) { // Update statistics // The msg includes the CR_LF, so pull back out for accounting. msgSize := int64(len(msg) - LEN_CR_LF) c.inMsgs++ c.inBytes += msgSize // Snapshot server. srv := c.srv if srv != nil { atomic.AddInt64(&srv.inMsgs, 1) atomic.AddInt64(&srv.inBytes, msgSize) } if trace == 1 { c.traceMsg(msg) } if c.opts.Verbose { c.sendOK() } if srv == nil { return } r := srv.sl.Match(c.pa.subject) if len(r) <= 0 { return } // Scratch buffer.. msgh := c.msgb[:len(msgHeadProto)] // msg header msgh = append(msgh, c.pa.subject...) msgh = append(msgh, ' ') si := len(msgh) var qmap map[string][]*subscription var qsubs []*subscription isRoute := c.typ == ROUTER var rmap map[string]struct{} // If we are a route and we have a queue subscription, deliver direct // since they are sent direct via L2 semantics. If the match is a queue // subscription, we will return from here regardless if we find a sub. if isRoute { if sub, ok := srv.routeSidQueueSubscriber(c.pa.sid); ok { if sub != nil { mh := c.msgHeader(msgh[:si], sub) c.deliverMsg(sub, mh, msg) } return } } // Loop over all subscriptions that match. for _, v := range r { sub := v.(*subscription) // Process queue group subscriptions by gathering them all up // here. We will pick the winners when we are done processing // all of the subscriptions. if sub.queue != nil { // Queue subscriptions handled from routes directly above. if isRoute { continue } // FIXME(dlc), this can be more efficient if qmap == nil { qmap = make(map[string][]*subscription) } qname := string(sub.queue) qsubs = qmap[qname] if qsubs == nil { qsubs = make([]*subscription, 0, 4) } qsubs = append(qsubs, sub) qmap[qname] = qsubs continue } // Process normal, non-queue group subscriptions. // If this is a send to a ROUTER, make sure we only send it // once. The other side will handle the appropriate re-processing. // Also enforce 1-Hop. if sub.client.typ == ROUTER { // Skip if sourced from a ROUTER and going to another ROUTER. // This is 1-Hop semantics for ROUTERs. if isRoute { continue } // Check to see if we have already sent it here. if rmap == nil { rmap = make(map[string]struct{}, srv.numRoutes()) } sub.client.mu.Lock() if sub.client.nc == nil || sub.client.route == nil || sub.client.route.remoteID == "" { c.Debugf("Bad or Missing ROUTER Identity, not processing msg") sub.client.mu.Unlock() continue } if _, ok := rmap[sub.client.route.remoteID]; ok { c.Debugf("Ignoring route, already processed") sub.client.mu.Unlock() continue } rmap[sub.client.route.remoteID] = routeSeen sub.client.mu.Unlock() } mh := c.msgHeader(msgh[:si], sub) c.deliverMsg(sub, mh, msg) } if qmap != nil { for _, qsubs := range qmap { index := rand.Int() % len(qsubs) sub := qsubs[index] mh := c.msgHeader(msgh[:si], sub) c.deliverMsg(sub, mh, msg) } } } func (c *client) processPingTimer() { c.mu.Lock() defer c.mu.Unlock() c.ptmr = nil // Check if we are ready yet.. if _, ok := c.nc.(*net.TCPConn); !ok { return } c.Debugf("%s Ping Timer", c.typeString()) // Check for violation c.pout += 1 if c.pout > c.srv.opts.MaxPingsOut { c.Debugf("Stale Client Connection - Closing") if c.bw != nil { c.bw.WriteString(fmt.Sprintf("-ERR '%s'\r\n", "Stale Connection")) c.bw.Flush() } c.clearConnection() return } c.traceOutOp("PING", nil) // Send PING c.bw.WriteString("PING\r\n") err := c.bw.Flush() if err != nil { c.Debugf("Error on Client Ping Flush, error %s", err) c.clearConnection() } else { // Reset to fire again if all OK. c.setPingTimer() } } func (c *client) setPingTimer() { if c.srv == nil { return } d := c.srv.opts.PingInterval c.ptmr = time.AfterFunc(d, c.processPingTimer) } // Lock should be held func (c *client) clearPingTimer() { if c.ptmr == nil { return } c.ptmr.Stop() c.ptmr = nil } // Lock should be held func (c *client) setAuthTimer(d time.Duration) { c.atmr = time.AfterFunc(d, func() { c.authTimeout() }) } // Lock should be held func (c *client) clearAuthTimer() { if c.atmr == nil { return } c.atmr.Stop() c.atmr = nil } func (c *client) isAuthTimerSet() bool { c.mu.Lock() isSet := c.atmr != nil c.mu.Unlock() return isSet } // Lock should be held func (c *client) clearConnection() { if c.nc == nil { return } c.bw.Flush() c.nc.Close() } func (c *client) typeString() string { switch c.typ { case CLIENT: return "Client" case ROUTER: return "Router" } return "Unknown Type" } func (c *client) closeConnection() { c.mu.Lock() if c.nc == nil { c.mu.Unlock() return } c.Debugf("%s connection closed", c.typeString()) c.clearAuthTimer() c.clearPingTimer() c.clearConnection() c.nc = nil // Snapshot for use. subs := c.subs.All() srv := c.srv c.mu.Unlock() if srv != nil { // Unregister srv.removeClient(c) // Remove clients subscriptions. for _, s := range subs { if sub, ok := s.(*subscription); ok { srv.sl.Remove(sub.subject, sub) // Forward on unsubscribes if we are not // a router ourselves. if c.typ != ROUTER { srv.broadcastUnSubscribe(sub) } } } } // Check for a solicited route. If it was, start up a reconnect unless // we are already connected to the other end. if c.isSolicitedRoute() { srv.mu.Lock() defer srv.mu.Unlock() rid := c.route.remoteID if rid != "" && srv.remotes[rid] != nil { Debugf("Not attempting reconnect for solicited route, already connected to \"%s\"", rid) return } else { Debugf("Attempting reconnect for solicited route \"%s\"", c.route.url) go srv.reConnectToRoute(c.route.url) } } } // Logging functionality scoped to a client or route. func (c *client) Errorf(format string, v ...interface{}) { format = fmt.Sprintf("%s - %s", c, format) Errorf(format, v...) } func (c *client) Debugf(format string, v ...interface{}) { format = fmt.Sprintf("%s - %s", c, format) Debugf(format, v...) } func (c *client) Noticef(format string, v ...interface{}) { format = fmt.Sprintf("%s - %s", c, format) Noticef(format, v...) } func (c *client) Tracef(format string, v ...interface{}) { format = fmt.Sprintf("%s - %s", c, format) Tracef(format, v...) }
dockbiz/gnatsd
server/client.go
GO
mit
20,486
/** */ package gluemodel.CIM.IEC61970.impl; import gluemodel.CIM.IEC61970.IEC61970CIMVersion; import gluemodel.CIM.IEC61970.IEC61970Package; import gluemodel.CIM.impl.ElementImpl; import java.util.Date; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>CIM Version</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link gluemodel.CIM.IEC61970.impl.IEC61970CIMVersionImpl#getDate <em>Date</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.impl.IEC61970CIMVersionImpl#getVersion <em>Version</em>}</li> * </ul> * * @generated */ public class IEC61970CIMVersionImpl extends ElementImpl implements IEC61970CIMVersion { /** * The default value of the '{@link #getDate() <em>Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDate() * @generated * @ordered */ protected static final Date DATE_EDEFAULT = null; /** * The cached value of the '{@link #getDate() <em>Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDate() * @generated * @ordered */ protected Date date = DATE_EDEFAULT; /** * The default value of the '{@link #getVersion() <em>Version</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVersion() * @generated * @ordered */ protected static final String VERSION_EDEFAULT = null; /** * The cached value of the '{@link #getVersion() <em>Version</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVersion() * @generated * @ordered */ protected String version = VERSION_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IEC61970CIMVersionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return IEC61970Package.Literals.IEC61970_CIM_VERSION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Date getDate() { return date; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDate(Date newDate) { Date oldDate = date; date = newDate; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, IEC61970Package.IEC61970_CIM_VERSION__DATE, oldDate, date)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getVersion() { return version; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setVersion(String newVersion) { String oldVersion = version; version = newVersion; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, IEC61970Package.IEC61970_CIM_VERSION__VERSION, oldVersion, version)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case IEC61970Package.IEC61970_CIM_VERSION__DATE: return getDate(); case IEC61970Package.IEC61970_CIM_VERSION__VERSION: return getVersion(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case IEC61970Package.IEC61970_CIM_VERSION__DATE: setDate((Date)newValue); return; case IEC61970Package.IEC61970_CIM_VERSION__VERSION: setVersion((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case IEC61970Package.IEC61970_CIM_VERSION__DATE: setDate(DATE_EDEFAULT); return; case IEC61970Package.IEC61970_CIM_VERSION__VERSION: setVersion(VERSION_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case IEC61970Package.IEC61970_CIM_VERSION__DATE: return DATE_EDEFAULT == null ? date != null : !DATE_EDEFAULT.equals(date); case IEC61970Package.IEC61970_CIM_VERSION__VERSION: return VERSION_EDEFAULT == null ? version != null : !VERSION_EDEFAULT.equals(version); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (date: "); result.append(date); result.append(", version: "); result.append(version); result.append(')'); return result.toString(); } } //IEC61970CIMVersionImpl
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/impl/IEC61970CIMVersionImpl.java
Java
mit
5,104
<?php /** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup Protean Protean template * @ingroup UnaModules * * @{ */ $aConfig = array( /** * Main Section. */ 'type' => BX_DOL_MODULE_TYPE_TEMPLATE, 'name' => 'bx_protean', 'title' => 'Protean', 'note' => 'Design template', 'version' => '9.0.10', 'vendor' => 'Boonex', 'help_url' => 'http://feed.una.io/?section={module_name}', 'compatible_with' => array( '9.0.0-RC10' ), /** * 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars. */ 'home_dir' => 'boonex/protean/', 'home_uri' => 'protean', 'db_prefix' => 'bx_protean_', 'class_prefix' => 'BxProtean', /** * Category for language keys. */ 'language_category' => 'Boonex Protean Template', /** * Installation/Uninstallation Section. */ 'install' => array( 'execute_sql' => 1, 'update_languages' => 1, 'clear_db_cache' => 1 ), 'uninstall' => array ( 'execute_sql' => 1, 'update_languages' => 1, 'clear_db_cache' => 1 ), 'enable' => array( 'execute_sql' => 1 ), 'disable' => array( 'execute_sql' => 1 ), /** * Dependencies Section */ 'dependencies' => array(), ); /** @} */
unaio/una
modules/boonex/protean/updates/9.0.9_9.0.10/source/install/config.php
PHP
mit
1,429
CodeMirror.ternLint = function(cm, updateLinting, options) { function addAnnotation(error, found) { var startLine = error.startLine; var startChar = error.startChar; var endLine = error.endLine; var endChar = error.endChar; var message = error.message; found.push({ from : error.start, to : error.end, message : message }); } var getServer = (typeof options.server == "function") ? options.server : function(cm) {return options.server}; var query = { type : "lint", file : "#0", lineCharPositions : true }; var files = []; files.push({ type : "full", name : "[doc]", text : cm.getValue() }); var doc = { query : query, files : files }; getServer(cm).server.request(doc, function(error, response) { if (error) { updateLinting(cm, []); } else { var messages = response.messages; updateLinting(cm, messages); } }); };
daniel-lundin/tern-snabbt
demos/resources/tern-lint/codemirror/addon/lint/tern-lint.js
JavaScript
mit
952
import { D2ManifestDefinitions } from 'app/destiny2/d2-definitions'; import { PluggableInventoryItemDefinition } from 'app/inventory/item-types'; import { startWordRegexp } from './search-filters/freeform'; export function createPlugSearchPredicate( query: string, language: string, defs: D2ManifestDefinitions ) { if (!query.length) { return (_plug: PluggableInventoryItemDefinition) => true; } const regexp = startWordRegexp(query, language); return (plug: PluggableInventoryItemDefinition) => regexp.test(plug.displayProperties.name) || regexp.test(plug.displayProperties.description) || regexp.test(plug.itemTypeDisplayName) || plug.perks.some((perk) => { const perkDef = defs.SandboxPerk.get(perk.perkHash); return ( perkDef && (regexp.test(perkDef.displayProperties.name) || regexp.test(perkDef.displayProperties.description) || regexp.test(perk.requirementDisplayString)) ); }); }
DestinyItemManager/DIM
src/app/search/plug-search.ts
TypeScript
mit
982
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {animate, animation, AnimationMetadata, AnimationMetadataType, AnimationOptions, AUTO_STYLE, group, keyframes, query, sequence, state, style, transition, trigger, useAnimation, ɵStyleDataMap} from '@angular/animations'; import {Animation} from '../../src/dsl/animation'; import {buildAnimationAst} from '../../src/dsl/animation_ast_builder'; import {AnimationTimelineInstruction} from '../../src/dsl/animation_timeline_instruction'; import {ElementInstructionMap} from '../../src/dsl/element_instruction_map'; import {MockAnimationDriver} from '../../testing'; function createDiv() { return document.createElement('div'); } { describe('Animation', () => { // these tests are only meant to be run within the DOM (for now) if (isNode) return; let rootElement: any; let subElement1: any; let subElement2: any; beforeEach(() => { rootElement = createDiv(); subElement1 = createDiv(); subElement2 = createDiv(); document.body.appendChild(rootElement); rootElement.appendChild(subElement1); rootElement.appendChild(subElement2); }); afterEach(() => { document.body.removeChild(rootElement); }); describe('validation', () => { it('should throw an error if one or more but not all keyframes() styles contain offsets', () => { const steps = animate(1000, keyframes([ style({opacity: 0}), style({opacity: 1, offset: 1}), ])); expect(() => { validateAndThrowAnimationSequence(steps); }) .toThrowError( /Not all style\(\) steps within the declared keyframes\(\) contain offsets/); }); it('should throw an error if not all offsets are between 0 and 1', () => { let steps = animate(1000, keyframes([ style({opacity: 0, offset: -1}), style({opacity: 1, offset: 1}), ])); expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Please ensure that all keyframe offsets are between 0 and 1/); steps = animate(1000, keyframes([ style({opacity: 0, offset: 0}), style({opacity: 1, offset: 1.1}), ])); expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Please ensure that all keyframe offsets are between 0 and 1/); }); it('should throw an error if a smaller offset shows up after a bigger one', () => { let steps = animate(1000, keyframes([ style({opacity: 0, offset: 1}), style({opacity: 1, offset: 0}), ])); expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Please ensure that all keyframe offsets are in order/); }); it('should throw an error if any styles overlap during parallel animations', () => { const steps = group([ sequence([ // 0 -> 2000ms style({opacity: 0}), animate('500ms', style({opacity: .25})), animate('500ms', style({opacity: .5})), animate('500ms', style({opacity: .75})), animate('500ms', style({opacity: 1})) ]), animate('1s 500ms', keyframes([ // 0 -> 1500ms style({width: 0}), style({opacity: 1, width: 1000}), ])) ]); expect(() => { validateAndThrowAnimationSequence(steps); }) .toThrowError( /The CSS property "opacity" that exists between the times of "0ms" and "2000ms" is also being animated in a parallel animation between the times of "0ms" and "1500ms"/); }); it('should not throw an error if animations overlap in different query levels within different transitions', () => { const steps = trigger('myAnimation', [ transition('a => b', group([ query('h1', animate('1s', style({opacity: 0}))), query('h2', animate('1s', style({opacity: 1}))), ])), transition('b => a', group([ query('h1', animate('1s', style({opacity: 0}))), query('h2', animate('1s', style({opacity: 1}))), ])), ]); expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow(); }); it('should not allow triggers to be defined with a prefixed `@` symbol', () => { const steps = trigger('@foo', []); expect(() => validateAndThrowAnimationSequence(steps)) .toThrowError( /animation triggers cannot be prefixed with an `@` sign \(e\.g\. trigger\('@foo', \[...\]\)\)/); }); it('should throw an error if an animation time is invalid', () => { const steps = [animate('500xs', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/The provided timing value "500xs" is invalid/); const steps2 = [animate('500ms 500ms 500ms ease-out', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps2); }).toThrowError(/The provided timing value "500ms 500ms 500ms ease-out" is invalid/); }); it('should throw if negative durations are used', () => { const steps = [animate(-1000, style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Duration values below 0 are not allowed for this animation step/); const steps2 = [animate('-1s', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps2); }).toThrowError(/Duration values below 0 are not allowed for this animation step/); }); it('should throw if negative delays are used', () => { const steps = [animate('1s -500ms', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Delay values below 0 are not allowed for this animation step/); const steps2 = [animate('1s -0.5s', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps2); }).toThrowError(/Delay values below 0 are not allowed for this animation step/); }); it('should throw if keyframes() is not used inside of animate()', () => { const steps = [keyframes([])]; expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/keyframes\(\) must be placed inside of a call to animate\(\)/); const steps2 = [group([keyframes([])])]; expect(() => { validateAndThrowAnimationSequence(steps2); }).toThrowError(/keyframes\(\) must be placed inside of a call to animate\(\)/); }); it('should throw if dynamic style substitutions are used without defaults within state() definitions', () => { const steps = [ state('final', style({ 'width': '{{ one }}px', 'borderRadius': '{{ two }}px {{ three }}px', })), ]; expect(() => { validateAndThrowAnimationSequence(steps); }) .toThrowError( /state\("final", ...\) must define default values for all the following style substitutions: one, two, three/); const steps2 = [state( 'panfinal', style({ 'color': '{{ greyColor }}', 'borderColor': '1px solid {{ greyColor }}', 'backgroundColor': '{{ redColor }}', }), {params: {redColor: 'maroon'}})]; expect(() => { validateAndThrowAnimationSequence(steps2); }) .toThrowError( /state\("panfinal", ...\) must define default values for all the following style substitutions: greyColor/); }); it('should throw an error if an invalid CSS property is used in the animation', () => { const steps = [animate(1000, style({abc: '500px'}))]; expect(() => { validateAndThrowAnimationSequence(steps); }) .toThrowError( /The provided animation property "abc" is not a supported CSS property for animations/); }); it('should allow a vendor-prefixed property to be used in an animation sequence without throwing an error', () => { const steps = [ style({webkitTransform: 'translateX(0px)'}), animate(1000, style({webkitTransform: 'translateX(100px)'})) ]; expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow(); }); it('should allow for old CSS properties (like transform) to be auto-prefixed by webkit', () => { const steps = [ style({transform: 'translateX(-100px)'}), animate(1000, style({transform: 'translateX(500px)'})) ]; expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow(); }); }); describe('keyframe building', () => { describe('style() / animate()', () => { it('should produce a balanced series of keyframes given a sequence of animate steps', () => { const steps = [ style({width: 0}), animate(1000, style({height: 50})), animate(1000, style({width: 100})), animate(1000, style({height: 150})), animate(1000, style({width: 200})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players[0].keyframes).toEqual([ new Map<string, string|number>( [['height', AUTO_STYLE], ['width', 0], ['offset', 0]]), new Map<string, string|number>([['height', 50], ['width', 0], ['offset', .25]]), new Map<string, string|number>([['height', 50], ['width', 100], ['offset', .5]]), new Map<string, string|number>([['height', 150], ['width', 100], ['offset', .75]]), new Map<string, string|number>([['height', 150], ['width', 200], ['offset', 1]]), ]); }); it('should fill in missing starting steps when a starting `style()` value is not used', () => { const steps = [animate(1000, style({width: 999}))]; const players = invokeAnimationSequence(rootElement, steps); expect(players[0].keyframes).toEqual([ new Map<string, string|number>([['width', AUTO_STYLE], ['offset', 0]]), new Map<string, string|number>([['width', 999], ['offset', 1]]), ]); }); it('should merge successive style() calls together before an animate() call', () => { const steps = [ style({width: 0}), style({height: 0}), style({width: 200}), style({opacity: 0}), animate(1000, style({width: 100, height: 400, opacity: 1})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players[0].keyframes).toEqual([ new Map<string, string|number>( [['width', 200], ['height', 0], ['opacity', 0], ['offset', 0]]), new Map<string, string|number>( [['width', 100], ['height', 400], ['opacity', 1], ['offset', 1]]) ]); }); it('should not merge in successive style() calls to the previous animate() keyframe', () => { const steps = [ style({opacity: 0}), animate(1000, style({opacity: .5})), style({opacity: .6}), animate(1000, style({opacity: 1})) ]; const players = invokeAnimationSequence(rootElement, steps); const keyframes = humanizeOffsets(players[0].keyframes, 4); expect(keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>([['opacity', .5], ['offset', .4998]]), new Map<string, string|number>([['opacity', .6], ['offset', .5002]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); }); it('should support an easing value that uses cubic-bezier(...)', () => { const steps = [ style({opacity: 0}), animate('1s cubic-bezier(.29, .55 ,.53 ,1.53)', style({opacity: 1})) ]; const player = invokeAnimationSequence(rootElement, steps)[0]; const firstKeyframe = player.keyframes[0]; const firstKeyframeEasing = firstKeyframe.get('easing') as string; expect(firstKeyframeEasing.replace(/\s+/g, '')).toEqual('cubic-bezier(.29,.55,.53,1.53)'); }); }); describe('sequence()', () => { it('should not produce extra timelines when multiple sequences are used within each other', () => { const steps = [ style({width: 0}), animate(1000, style({width: 100})), sequence([ animate(1000, style({width: 200})), sequence([ animate(1000, style({width: 300})), ]), ]), animate(1000, style({width: 400})), sequence([ animate(1000, style({width: 500})), ]), ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['width', 0], ['offset', 0]]), new Map<string, string|number>([['width', 100], ['offset', .2]]), new Map<string, string|number>([['width', 200], ['offset', .4]]), new Map<string, string|number>([['width', 300], ['offset', .6]]), new Map<string, string|number>([['width', 400], ['offset', .8]]), new Map<string, string|number>([['width', 500], ['offset', 1]]) ]); }); it('should create a new timeline after a sequence if group() or keyframe() commands are used within', () => { const steps = [ style({width: 100, height: 100}), animate(1000, style({width: 150, height: 150})), sequence([ group([ animate(1000, style({height: 200})), ]), animate(1000, keyframes([style({width: 180}), style({width: 200})])) ]), animate(1000, style({width: 500, height: 500})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(4); const finalPlayer = players[players.length - 1]; expect(finalPlayer.keyframes).toEqual([ new Map<string, string|number>([['width', 200], ['height', 200], ['offset', 0]]), new Map<string, string|number>([['width', 500], ['height', 500], ['offset', 1]]) ]); }); it('should push the start of a sequence if a delay option is provided', () => { const steps = [ style({width: '0px'}), animate(1000, style({width: '100px'})), sequence( [ animate(1000, style({width: '200px'})), ], {delay: 500}) ]; const players = invokeAnimationSequence(rootElement, steps); const finalPlayer = players[players.length - 1]; expect(finalPlayer.keyframes).toEqual([ new Map<string, string|number>([['width', '100px'], ['offset', 0]]), new Map<string, string|number>([['width', '200px'], ['offset', 1]]), ]); expect(finalPlayer.delay).toEqual(1500); }); it('should allow a float-based delay value to be used', () => { let steps: any[] = [ animate('.75s 0.75s', style({width: '300px'})), ]; let players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); let p1 = players.pop()!; expect(p1.duration).toEqual(1500); expect(p1.keyframes).toEqual([ new Map<string, string|number>([['width', '*'], ['offset', 0]]), new Map<string, string|number>([['width', '*'], ['offset', 0.5]]), new Map<string, string|number>([['width', '300px'], ['offset', 1]]), ]); steps = [ style({width: '100px'}), animate('.5s .5s', style({width: '200px'})), ]; players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); p1 = players.pop()!; expect(p1.duration).toEqual(1000); expect(p1.keyframes).toEqual([ new Map<string, string|number>([['width', '100px'], ['offset', 0]]), new Map<string, string|number>([['width', '100px'], ['offset', 0.5]]), new Map<string, string|number>([['width', '200px'], ['offset', 1]]), ]); }); }); describe('substitutions', () => { it('should allow params to be substituted even if they are not defaulted in a reusable animation', () => { const myAnimation = animation([ style({left: '{{ start }}'}), animate(1000, style({left: '{{ end }}'})), ]); const steps = [ useAnimation(myAnimation, {params: {start: '0px', end: '100px'}}), ]; const players = invokeAnimationSequence(rootElement, steps, {}); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['left', '0px'], ['offset', 0]]), new Map<string, string|number>([['left', '100px'], ['offset', 1]]), ]); }); it('should substitute in timing values', () => { function makeAnimation(exp: string, options: {[key: string]: any}) { const steps = [style({opacity: 0}), animate(exp, style({opacity: 1}))]; return invokeAnimationSequence(rootElement, steps, options); } let players = makeAnimation('{{ duration }}', buildParams({duration: '1234ms'})); expect(players[0].duration).toEqual(1234); players = makeAnimation('{{ duration }}', buildParams({duration: '9s 2s'})); expect(players[0].duration).toEqual(11000); players = makeAnimation('{{ duration }} 1s', buildParams({duration: '1.5s'})); expect(players[0].duration).toEqual(2500); players = makeAnimation( '{{ duration }} {{ delay }}', buildParams({duration: '1s', delay: '2s'})); expect(players[0].duration).toEqual(3000); }); it('should allow multiple substitutions to occur within the same style value', () => { const steps = [ style({borderRadius: '100px 100px'}), animate(1000, style({borderRadius: '{{ one }}px {{ two }}'})), ]; const players = invokeAnimationSequence(rootElement, steps, buildParams({one: '200', two: '400px'})); expect(players[0].keyframes).toEqual([ new Map<string, string|number>([['offset', 0], ['borderRadius', '100px 100px']]), new Map<string, string|number>([['offset', 1], ['borderRadius', '200px 400px']]) ]); }); it('should substitute in values that are defined as parameters for inner areas of a sequence', () => { const steps = sequence( [ sequence( [ sequence( [ style({height: '{{ x0 }}px'}), animate(1000, style({height: '{{ x2 }}px'})), ], buildParams({x2: '{{ x1 }}3'})), ], buildParams({x1: '{{ x0 }}2'})), ], buildParams({x0: '1'})); const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const [player] = players; expect(player.keyframes).toEqual([ new Map<string, string|number>([['offset', 0], ['height', '1px']]), new Map<string, string|number>([['offset', 1], ['height', '123px']]) ]); }); it('should substitute in values that are defined as parameters for reusable animations', () => { const anim = animation([ style({height: '{{ start }}'}), animate(1000, style({height: '{{ end }}'})), ]); const steps = sequence( [ sequence( [ useAnimation(anim, buildParams({start: '{{ a }}', end: '{{ b }}'})), ], buildParams({a: '100px', b: '200px'})), ], buildParams({a: '0px'})); const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const [player] = players; expect(player.keyframes).toEqual([ new Map<string, string|number>([['offset', 0], ['height', '100px']]), new Map<string, string|number>([['offset', 1], ['height', '200px']]), ]); }); it('should throw an error when an input variable is not provided when invoked and is not a default value', () => { expect(() => invokeAnimationSequence(rootElement, [style({color: '{{ color }}'})])) .toThrowError(/Please provide a value for the animation param color/); expect( () => invokeAnimationSequence( rootElement, [ style({color: '{{ start }}'}), animate('{{ time }}', style({color: '{{ end }}'})), ], buildParams({start: 'blue', end: 'red'}))) .toThrowError(/Please provide a value for the animation param time/); }); }); describe('keyframes()', () => { it('should produce a sub timeline when `keyframes()` is used within a sequence', () => { const steps = [ animate(1000, style({opacity: .5})), animate(1000, style({opacity: 1})), animate( 1000, keyframes([style({height: 0}), style({height: 100}), style({height: 50})])), animate(1000, style({height: 0, opacity: 0})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(3); const player0 = players[0]; expect(player0.delay).toEqual(0); expect(player0.keyframes).toEqual([ new Map<string, string|number>([['opacity', AUTO_STYLE], ['offset', 0]]), new Map<string, string|number>([['opacity', .5], ['offset', .5]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); const subPlayer = players[1]; expect(subPlayer.delay).toEqual(2000); expect(subPlayer.keyframes).toEqual([ new Map<string, string|number>([['height', 0], ['offset', 0]]), new Map<string, string|number>([['height', 100], ['offset', .5]]), new Map<string, string|number>([['height', 50], ['offset', 1]]), ]); const player1 = players[2]; expect(player1.delay).toEqual(3000); expect(player1.keyframes).toEqual([ new Map<string, string|number>([['opacity', 1], ['height', 50], ['offset', 0]]), new Map<string, string|number>([['opacity', 0], ['height', 0], ['offset', 1]]) ]); }); it('should propagate inner keyframe style data to the parent timeline if used afterwards', () => { const steps = [ style({opacity: 0}), animate(1000, style({opacity: .5})), animate(1000, style({opacity: 1})), animate(1000, keyframes([ style({color: 'red'}), style({color: 'blue'}), ])), animate(1000, style({color: 'green', opacity: 0})) ]; const players = invokeAnimationSequence(rootElement, steps); const finalPlayer = players[players.length - 1]; expect(finalPlayer.keyframes).toEqual([ new Map<string, string|number>([['opacity', 1], ['color', 'blue'], ['offset', 0]]), new Map<string, string|number>([['opacity', 0], ['color', 'green'], ['offset', 1]]) ]); }); it('should feed in starting data into inner keyframes if used in an style step beforehand', () => { const steps = [ animate(1000, style({opacity: .5})), animate(1000, keyframes([ style({opacity: .8, offset: .5}), style({opacity: 1, offset: 1}), ])) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(2); const topPlayer = players[0]; expect(topPlayer.keyframes).toEqual([ new Map<string, string|number>([['opacity', AUTO_STYLE], ['offset', 0]]), new Map<string, string|number>([['opacity', .5], ['offset', 1]]) ]); const subPlayer = players[1]; expect(subPlayer.keyframes).toEqual([ new Map<string, string|number>([['opacity', .5], ['offset', 0]]), new Map<string, string|number>([['opacity', .8], ['offset', 0.5]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]) ]); }); it('should set the easing value as an easing value for the entire timeline', () => { const steps = [ style({opacity: 0}), animate(1000, style({opacity: .5})), animate( '1s ease-out', keyframes([style({opacity: .8, offset: .5}), style({opacity: 1, offset: 1})])) ]; const player = invokeAnimationSequence(rootElement, steps)[1]; expect(player.easing).toEqual('ease-out'); }); it('should combine the starting time + the given delay as the delay value for the animated keyframes', () => { const steps = [ style({opacity: 0}), animate(500, style({opacity: .5})), animate( '1s 2s ease-out', keyframes([style({opacity: .8, offset: .5}), style({opacity: 1, offset: 1})])) ]; const player = invokeAnimationSequence(rootElement, steps)[1]; expect(player.delay).toEqual(2500); }); it('should not leak in additional styles used later on after keyframe styles have already been declared', () => { const steps = [ animate(1000, style({height: '50px'})), animate(2000, keyframes([ style({left: '0', top: '0', offset: 0}), style({left: '40%', top: '50%', offset: .33}), style({left: '60%', top: '80%', offset: .66}), style({left: 'calc(100% - 100px)', top: '100%', offset: 1}), ])), group([animate('2s', style({width: '200px'}))]), animate('2s', style({height: '300px'})), group([animate('2s', style({height: '500px', width: '500px'}))]) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(5); const firstPlayerKeyframes = players[0].keyframes; expect(firstPlayerKeyframes[0].get('width')).toBeFalsy(); expect(firstPlayerKeyframes[1].get('width')).toBeFalsy(); expect(firstPlayerKeyframes[0].get('height')).toEqual(AUTO_STYLE); expect(firstPlayerKeyframes[1].get('height')).toEqual('50px'); const keyframePlayerKeyframes = players[1].keyframes; expect(keyframePlayerKeyframes[0].get('width')).toBeFalsy(); expect(keyframePlayerKeyframes[0].get('height')).toBeFalsy(); const groupPlayerKeyframes = players[2].keyframes; expect(groupPlayerKeyframes[0].get('width')).toEqual(AUTO_STYLE); expect(groupPlayerKeyframes[1].get('width')).toEqual('200px'); expect(groupPlayerKeyframes[0].get('height')).toBeFalsy(); expect(groupPlayerKeyframes[1].get('height')).toBeFalsy(); const secondToFinalAnimatePlayerKeyframes = players[3].keyframes; expect(secondToFinalAnimatePlayerKeyframes[0].get('width')).toBeFalsy(); expect(secondToFinalAnimatePlayerKeyframes[1].get('width')).toBeFalsy(); expect(secondToFinalAnimatePlayerKeyframes[0].get('height')).toEqual('50px'); expect(secondToFinalAnimatePlayerKeyframes[1].get('height')).toEqual('300px'); const finalAnimatePlayerKeyframes = players[4].keyframes; expect(finalAnimatePlayerKeyframes[0].get('width')).toEqual('200px'); expect(finalAnimatePlayerKeyframes[1].get('width')).toEqual('500px'); expect(finalAnimatePlayerKeyframes[0].get('height')).toEqual('300px'); expect(finalAnimatePlayerKeyframes[1].get('height')).toEqual('500px'); }); it('should respect offsets if provided directly within the style data', () => { const steps = animate(1000, keyframes([ style({opacity: 0, offset: 0}), style({opacity: .6, offset: .6}), style({opacity: 1, offset: 1}) ])); const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>([['opacity', .6], ['offset', .6]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); }); it('should respect offsets if provided directly within the style metadata type', () => { const steps = animate(1000, keyframes([ {type: AnimationMetadataType.Style, offset: 0, styles: {opacity: 0}}, {type: AnimationMetadataType.Style, offset: .4, styles: {opacity: .4}}, {type: AnimationMetadataType.Style, offset: 1, styles: {opacity: 1}}, ])); const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>([['opacity', .4], ['offset', .4]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); }); }); describe('group()', () => { it('should properly tally style data within a group() for use in a follow-up animate() step', () => { const steps = [ style({width: 0, height: 0}), animate(1000, style({width: 20, height: 50})), group([animate('1s 1s', style({width: 200})), animate('1s', style({height: 500}))]), animate(1000, style({width: 1000, height: 1000})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(4); const player0 = players[0]; expect(player0.duration).toEqual(1000); expect(player0.keyframes).toEqual([ new Map<string, string|number>([['width', 0], ['height', 0], ['offset', 0]]), new Map<string, string|number>([['width', 20], ['height', 50], ['offset', 1]]) ]); const gPlayer1 = players[1]; expect(gPlayer1.duration).toEqual(2000); expect(gPlayer1.delay).toEqual(1000); expect(gPlayer1.keyframes).toEqual([ new Map<string, string|number>([['width', 20], ['offset', 0]]), new Map<string, string|number>([['width', 20], ['offset', .5]]), new Map<string, string|number>([['width', 200], ['offset', 1]]) ]); const gPlayer2 = players[2]; expect(gPlayer2.duration).toEqual(1000); expect(gPlayer2.delay).toEqual(1000); expect(gPlayer2.keyframes).toEqual([ new Map<string, string|number>([['height', 50], ['offset', 0]]), new Map<string, string|number>([['height', 500], ['offset', 1]]) ]); const player1 = players[3]; expect(player1.duration).toEqual(1000); expect(player1.delay).toEqual(3000); expect(player1.keyframes).toEqual([ new Map<string, string|number>([['width', 200], ['height', 500], ['offset', 0]]), new Map<string, string|number>([['width', 1000], ['height', 1000], ['offset', 1]]) ]); }); it('should support groups with nested sequences', () => { const steps = [group([ sequence([ style({opacity: 0}), animate(1000, style({opacity: 1})), ]), sequence([ style({width: 0}), animate(1000, style({width: 200})), ]) ])]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(2); const gPlayer1 = players[0]; expect(gPlayer1.delay).toEqual(0); expect(gPlayer1.keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); const gPlayer2 = players[1]; expect(gPlayer1.delay).toEqual(0); expect(gPlayer2.keyframes).toEqual([ new Map<string, string|number>([['width', 0], ['offset', 0]]), new Map<string, string|number>([['width', 200], ['offset', 1]]) ]); }); it('should respect delays after group entries', () => { const steps = [ style({width: 0, height: 0}), animate(1000, style({width: 50, height: 50})), group([ animate(1000, style({width: 100})), animate(1000, style({height: 100})), ]), animate('1s 1s', style({height: 200, width: 200})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(4); const finalPlayer = players[players.length - 1]; expect(finalPlayer.delay).toEqual(2000); expect(finalPlayer.duration).toEqual(2000); expect(finalPlayer.keyframes).toEqual([ new Map<string, string|number>([['width', 100], ['height', 100], ['offset', 0]]), new Map<string, string|number>([['width', 100], ['height', 100], ['offset', .5]]), new Map<string, string|number>([['width', 200], ['height', 200], ['offset', 1]]), ]); }); it('should respect delays after multiple calls to group()', () => { const steps = [ group([animate('2s', style({opacity: 1})), animate('2s', style({width: '100px'}))]), animate(2000, style({width: 0, opacity: 0})), group([animate('2s', style({opacity: 1})), animate('2s', style({width: '200px'}))]), animate(2000, style({width: 0, opacity: 0})) ]; const players = invokeAnimationSequence(rootElement, steps); const middlePlayer = players[2]; expect(middlePlayer.delay).toEqual(2000); expect(middlePlayer.duration).toEqual(2000); const finalPlayer = players[players.length - 1]; expect(finalPlayer.delay).toEqual(6000); expect(finalPlayer.duration).toEqual(2000); }); it('should push the start of a group if a delay option is provided', () => { const steps = [ style({width: '0px', height: '0px'}), animate(1500, style({width: '100px', height: '100px'})), group( [ animate(1000, style({width: '200px'})), animate(2000, style({height: '200px'})), ], {delay: 300}) ]; const players = invokeAnimationSequence(rootElement, steps); const finalWidthPlayer = players[players.length - 2]; const finalHeightPlayer = players[players.length - 1]; expect(finalWidthPlayer.delay).toEqual(1800); expect(finalWidthPlayer.keyframes).toEqual([ new Map<string, string|number>([['width', '100px'], ['offset', 0]]), new Map<string, string|number>([['width', '200px'], ['offset', 1]]), ]); expect(finalHeightPlayer.delay).toEqual(1800); expect(finalHeightPlayer.keyframes).toEqual([ new Map<string, string|number>([['height', '100px'], ['offset', 0]]), new Map<string, string|number>([['height', '200px'], ['offset', 1]]), ]); }); }); describe('query()', () => { it('should delay the query operation if a delay option is provided', () => { const steps = [ style({opacity: 0}), animate(1000, style({opacity: 1})), query( 'div', [ style({width: 0}), animate(500, style({width: 200})), ], {delay: 200}) ]; const players = invokeAnimationSequence(rootElement, steps); const finalPlayer = players[players.length - 1]; expect(finalPlayer.delay).toEqual(1200); }); it('should throw an error when an animation query returns zero elements', () => { const steps = [query('somethingFake', [style({opacity: 0}), animate(1000, style({opacity: 1}))])]; expect(() => { invokeAnimationSequence(rootElement, steps); }) .toThrowError( /`query\("somethingFake"\)` returned zero elements\. \(Use `query\("somethingFake", \{ optional: true \}\)` if you wish to allow this\.\)/); }); it('should allow a query to be skipped if it is set as optional and returns zero elements', () => { const steps = [query( 'somethingFake', [style({opacity: 0}), animate(1000, style({opacity: 1}))], {optional: true})]; expect(() => { invokeAnimationSequence(rootElement, steps); }).not.toThrow(); const steps2 = [query( 'fakeSomethings', [style({opacity: 0}), animate(1000, style({opacity: 1}))], {optional: true})]; expect(() => { invokeAnimationSequence(rootElement, steps2); }).not.toThrow(); }); it('should delay the query operation if a delay option is provided', () => { const steps = [ style({opacity: 0}), animate(1300, style({opacity: 1})), query( 'div', [ style({width: 0}), animate(500, style({width: 200})), ], {delay: 300}) ]; const players = invokeAnimationSequence(rootElement, steps); const fp1 = players[players.length - 2]; const fp2 = players[players.length - 1]; expect(fp1.delay).toEqual(1600); expect(fp2.delay).toEqual(1600); }); }); describe('timing values', () => { it('should properly combine an easing value with a delay into a set of three keyframes', () => { const steps: AnimationMetadata[] = [style({opacity: 0}), animate('3s 1s ease-out', style({opacity: 1}))]; const player = invokeAnimationSequence(rootElement, steps)[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>( [['opacity', 0], ['offset', .25], ['easing', 'ease-out']]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]) ]); }); it('should allow easing values to exist for each animate() step', () => { const steps: AnimationMetadata[] = [ style({width: 0}), animate('1s linear', style({width: 10})), animate('2s ease-out', style({width: 20})), animate('1s ease-in', style({width: 30})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['width', 0], ['offset', 0], ['easing', 'linear']]), new Map<string, string|number>( [['width', 10], ['offset', .25], ['easing', 'ease-out']]), new Map<string, string|number>([['width', 20], ['offset', .75], ['easing', 'ease-in']]), new Map<string, string|number>([['width', 30], ['offset', 1]]) ]); }); it('should produce a top-level timeline only for the duration that is set as before a group kicks in', () => { const steps: AnimationMetadata[] = [ style({width: 0, height: 0, opacity: 0}), animate('1s', style({width: 100, height: 100, opacity: .2})), group([ animate('500ms 1s', style({width: 500})), animate('1s', style({height: 500})), sequence([ animate(500, style({opacity: .5})), animate(500, style({opacity: .6})), animate(500, style({opacity: .7})), animate(500, style({opacity: 1})), ]) ]) ]; const player = invokeAnimationSequence(rootElement, steps)[0]; expect(player.duration).toEqual(1000); expect(player.delay).toEqual(0); }); it('should offset group() and keyframe() timelines with a delay which is the current time of the previous player when called', () => { const steps: AnimationMetadata[] = [ style({width: 0, height: 0}), animate('1500ms linear', style({width: 10, height: 10})), group([ animate(1000, style({width: 500, height: 500})), animate(2000, style({width: 500, height: 500})) ]), animate(1000, keyframes([ style({width: 200}), style({width: 500}), ])) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players[0].delay).toEqual(0); // top-level animation expect(players[1].delay).toEqual(1500); // first entry in group() expect(players[2].delay).toEqual(1500); // second entry in group() expect(players[3].delay).toEqual(3500); // animate(...keyframes()) }); }); describe('state based data', () => { it('should create an empty animation if there are zero animation steps', () => { const steps: AnimationMetadata[] = []; const fromStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'blue'], ['height', 100]])]; const toStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'red']])]; const player = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles)[0]; expect(player.duration).toEqual(0); expect(player.keyframes).toEqual([]); }); it('should produce an animation from start to end between the to and from styles if there are animate steps in between', () => { const steps: AnimationMetadata[] = [animate(1000)]; const fromStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'blue'], ['height', 100]])]; const toStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'red']])]; const players = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles); expect(players[0].keyframes).toEqual([ new Map<string, string|number>( [['background', 'blue'], ['height', 100], ['offset', 0]]), new Map<string, string|number>( [['background', 'red'], ['height', AUTO_STYLE], ['offset', 1]]) ]); }); it('should produce an animation from start to end between the to and from styles if there are animate steps in between with an easing value', () => { const steps: AnimationMetadata[] = [animate('1s ease-out')]; const fromStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'blue']])]; const toStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'red']])]; const players = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles); expect(players[0].keyframes).toEqual([ new Map<string, string|number>( [['background', 'blue'], ['offset', 0], ['easing', 'ease-out']]), new Map<string, string|number>([['background', 'red'], ['offset', 1]]) ]); }); }); }); }); } function humanizeOffsets( keyframes: Array<ɵStyleDataMap>, digits: number = 3): Array<ɵStyleDataMap> { return keyframes.map(keyframe => { keyframe.set('offset', Number(parseFloat(<any>keyframe.get('offset')).toFixed(digits))); return keyframe; }); } function invokeAnimationSequence( element: any, steps: AnimationMetadata|AnimationMetadata[], locals: {[key: string]: any} = {}, startingStyles: Array<ɵStyleDataMap> = [], destinationStyles: Array<ɵStyleDataMap> = [], subInstructions?: ElementInstructionMap): AnimationTimelineInstruction[] { const driver = new MockAnimationDriver(); return new Animation(driver, steps) .buildTimelines(element, startingStyles, destinationStyles, locals, subInstructions); } function validateAndThrowAnimationSequence(steps: AnimationMetadata|AnimationMetadata[]) { const driver = new MockAnimationDriver(); const errors: string[] = []; const ast = buildAnimationAst(driver, steps, errors); if (errors.length) { throw new Error(errors.join('\n')); } } function buildParams(params: {[name: string]: any}): AnimationOptions { return <AnimationOptions>{params}; }
shairez/angular
packages/animations/browser/test/dsl/animation_spec.ts
TypeScript
mit
48,978
/* * Copyright 2015 the original author or phly. * 未经正式书面同意,其他任何个人、团体不得使用、复制、修改或发布本软件. */ package com.phly.ttw.manage.supplier.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.directwebremoting.annotations.RemoteProxy; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.phly.common.base.action.BaseAction; import com.phly.common.exceptionhandler.annotation.ExceptionMessage; import com.phly.ttw.manage.order.facade.OrderFacade; import com.phly.ttw.manage.order.model.OrderVO; /** * 订单Action类(供应商使用) * * @author LGP */ @Controller @RemoteProxy public class SupplierOrderAction extends BaseAction { @Resource private OrderFacade orderFacade; /** * 查询订单列表 * * @param orderVO * @return 订单集合 */ @ExceptionMessage("查询订单列表失败,请联系管理员") @RequestMapping("/page/ttw/manage/supplier/order") @ResponseBody public ModelMap queryOrderList(HttpServletRequest request, OrderVO orderVO) { String method = request.getParameter("m"); String[] orders = null; if (method.equals("finish")) { orders = new String[1]; orders[0] = "7"; } if (method.equals("unfinish")) { orders = new String[5]; orders[0] = "2"; orders[1] = "3"; orders[2] = "4"; orders[3] = "5"; orders[4] = "6"; } if (method.equals("all")) { orders = new String[6]; orders[0] = "2"; orders[1] = "3"; orders[2] = "4"; orders[3] = "5"; orders[4] = "6"; orders[4] = "7"; } orderVO.setInOrderStatus(orders); return this.orderFacade.queryOrderList(orderVO); } }
linmuxi/ttw
src/com/phly/ttw/manage/supplier/action/SupplierOrderAction.java
Java
mit
1,854
import $ from 'cafy'; import ID from '../../../../misc/cafy-id'; import Note from '../../../../models/note'; import Mute from '../../../../models/mute'; import { pack } from '../../../../models/note'; import UserList from '../../../../models/user-list'; import { ILocalUser } from '../../../../models/user'; import getParams from '../../get-params'; export const meta = { desc: { ja: '指定したユーザーリストのタイムラインを取得します。', en: 'Get timeline of a user list.' }, requireCredential: true, params: { listId: $.type(ID).note({ desc: { ja: 'リストのID' } }), limit: $.num.optional.range(1, 100).note({ default: 10, desc: { ja: '最大数' } }), sinceId: $.type(ID).optional.note({ desc: { ja: '指定すると、この投稿を基点としてより新しい投稿を取得します' } }), untilId: $.type(ID).optional.note({ desc: { ja: '指定すると、この投稿を基点としてより古い投稿を取得します' } }), sinceDate: $.num.optional.note({ desc: { ja: '指定した時間を基点としてより新しい投稿を取得します。数値は、1970年1月1日 00:00:00 UTC から指定した日時までの経過時間をミリ秒単位で表します。' } }), untilDate: $.num.optional.note({ desc: { ja: '指定した時間を基点としてより古い投稿を取得します。数値は、1970年1月1日 00:00:00 UTC から指定した日時までの経過時間をミリ秒単位で表します。' } }), includeMyRenotes: $.bool.optional.note({ default: true, desc: { ja: '自分の行ったRenoteを含めるかどうか' } }), includeRenotedMyNotes: $.bool.optional.note({ default: true, desc: { ja: 'Renoteされた自分の投稿を含めるかどうか' } }), includeLocalRenotes: $.bool.optional.note({ default: true, desc: { ja: 'Renoteされたローカルの投稿を含めるかどうか' } }), mediaOnly: $.bool.optional.note({ desc: { ja: 'true にすると、メディアが添付された投稿だけ取得します' } }), } }; export default async (params: any, user: ILocalUser) => { const [ps, psErr] = getParams(meta, params); if (psErr) throw psErr; const [list, mutedUserIds] = await Promise.all([ // リストを取得 // Fetch the list UserList.findOne({ _id: ps.listId, userId: user._id }), // ミュートしているユーザーを取得 Mute.find({ muterId: user._id }).then(ms => ms.map(m => m.muteeId)) ]); if (list.userIds.length == 0) { return []; } //#region Construct query const sort = { _id: -1 }; const listQuery = list.userIds.map(u => ({ userId: u, // リプライは含めない(ただし投稿者自身の投稿へのリプライ、自分の投稿へのリプライ、自分のリプライは含める) $or: [{ // リプライでない replyId: null }, { // または // リプライだが返信先が投稿者自身の投稿 $expr: { $eq: ['$_reply.userId', '$userId'] } }, { // または // リプライだが返信先が自分(フォロワー)の投稿 '_reply.userId': user._id }, { // または // 自分(フォロワー)が送信したリプライ userId: user._id }] })); const query = { $and: [{ // リストに入っている人のタイムラインへの投稿 $or: listQuery, // mute userId: { $nin: mutedUserIds }, '_reply.userId': { $nin: mutedUserIds }, '_renote.userId': { $nin: mutedUserIds }, }] } as any; // MongoDBではトップレベルで否定ができないため、De Morganの法則を利用してクエリします。 // つまり、「『自分の投稿かつRenote』ではない」を「『自分の投稿ではない』または『Renoteではない』」と表現します。 // for details: https://en.wikipedia.org/wiki/De_Morgan%27s_laws if (ps.includeMyRenotes === false) { query.$and.push({ $or: [{ userId: { $ne: user._id } }, { renoteId: null }, { text: { $ne: null } }, { mediaIds: { $ne: [] } }, { poll: { $ne: null } }] }); } if (ps.includeRenotedMyNotes === false) { query.$and.push({ $or: [{ '_renote.userId': { $ne: user._id } }, { renoteId: null }, { text: { $ne: null } }, { mediaIds: { $ne: [] } }, { poll: { $ne: null } }] }); } if (ps.includeLocalRenotes === false) { query.$and.push({ $or: [{ '_renote.user.host': { $ne: null } }, { renoteId: null }, { text: { $ne: null } }, { mediaIds: { $ne: [] } }, { poll: { $ne: null } }] }); } if (ps.mediaOnly) { query.$and.push({ mediaIds: { $exists: true, $ne: [] } }); } if (ps.sinceId) { sort._id = 1; query._id = { $gt: ps.sinceId }; } else if (ps.untilId) { query._id = { $lt: ps.untilId }; } else if (ps.sinceDate) { sort._id = 1; query.createdAt = { $gt: new Date(ps.sinceDate) }; } else if (ps.untilDate) { query.createdAt = { $lt: new Date(ps.untilDate) }; } //#endregion // Issue query const timeline = await Note .find(query, { limit: ps.limit, sort: sort }); // Serialize return await Promise.all(timeline.map(note => pack(note, user))); };
ha-dai/Misskey
src/server/api/endpoints/notes/user-list-timeline.ts
TypeScript
mit
5,368
require 'spec_helper' feature 'as entry publisher, publishing an entry', js: true do scenario 'without depublication date' do entry = create(:entry, title: 'Test Entry') Dom::Admin::Page.sign_in_as(:publisher, on: entry) visit(pageflow.editor_entry_path(entry)) editor_sidebar = Dom::Editor::Sidebar.find! editor_sidebar.publish_button.click Dom::Editor::PublishEntryPanel.find!.publish Dom::Admin::EntryPage.visit_revisions(entry) expect(Dom::Admin::EntryRevision.published).to be_present end scenario 'with depublication date' do entry = create(:entry, title: 'Test Entry') Dom::Admin::Page.sign_in_as(:publisher, on: entry) visit(pageflow.editor_entry_path(entry)) editor_sidebar = Dom::Editor::Sidebar.find! editor_sidebar.publish_button.click Dom::Editor::PublishEntryPanel.find!.publish_until(1.month.from_now) Dom::Admin::EntryPage.visit_revisions(entry) expect(Dom::Admin::EntryRevision.published_until_date).to be_present end scenario 'with invalid depublication time' do entry = create(:entry, title: 'Test Entry') Dom::Admin::Page.sign_in_as(:publisher, on: entry) visit(pageflow.editor_entry_path(entry)) editor_sidebar = Dom::Editor::Sidebar.find! editor_sidebar.publish_button.click publish_panel = Dom::Editor::PublishEntryPanel.find! publish_panel.activate_publish_until publish_panel.set_depublication_date(1.month.from_now.strftime('%d.%m.%Y'), '40:30') expect(publish_panel.save_button).to be_disabled end scenario 'with password' do entry = create(:entry, title: 'Test Entry') Dom::Admin::Page.sign_in_as(:publisher, on: entry) visit(pageflow.editor_entry_path(entry)) editor_sidebar = Dom::Editor::Sidebar.find! editor_sidebar.publish_button.click publish_panel = Dom::Editor::PublishEntryPanel.find! publish_panel.activate_password_protection('abc213') publish_panel.publish Dom::Admin::EntryPage.visit_revisions(entry) published_revision = Dom::Admin::EntryRevision.published.first expect(published_revision).to be_password_protected end end
tf/pageflow
spec/features/entry_publisher/publishing_an_entry_spec.rb
Ruby
mit
2,140
using System; namespace SharpCompress.Compressors.Xz { public class XZIndexMarkerReachedException : Exception { } }
adamhathcock/sharpcompress
src/SharpCompress/Compressors/Xz/XZIndexMarkerReachedException.cs
C#
mit
132
package com.benromberg.cordonbleu.data.migration.change0015; import static org.assertj.core.api.Assertions.assertThat; import com.benromberg.cordonbleu.data.migration.ChangeRule; import com.benromberg.cordonbleu.data.migration.TestCollection; import org.junit.Rule; import org.junit.Test; import com.benromberg.cordonbleu.data.migration.change0015.Change0015; public class Change0015Test { private static final String COMMIT_COLLECTION = "commit"; private static final String OTHER_FIELD = "other field"; private static final String COMMIT_ID = "commit-id"; @Rule public ChangeRule changeRule = new ChangeRule(Change0015.class); @Test public void convertUniqueFields_CanReadValues() throws Exception { TestCollection<CommitBefore> collectionBefore = changeRule.getCollection(COMMIT_COLLECTION, CommitBefore.class); CommitBefore commitBefore = new CommitBefore(COMMIT_ID, OTHER_FIELD); collectionBefore.insert(commitBefore); changeRule.runChanges(); TestCollection<CommitAfter> collectionAfter = changeRule.getCollection(COMMIT_COLLECTION, CommitAfter.class); CommitAfter userAfter = collectionAfter.findOneById(COMMIT_ID); assertThat(userAfter.getOtherField()).isEqualTo(OTHER_FIELD); assertThat(userAfter.isRemoved()).isFalse(); } }
BenRomberg/cordonbleu
cordonbleu-data/src/test/java/com/benromberg/cordonbleu/data/migration/change0015/Change0015Test.java
Java
mit
1,339
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014-2019 British Columbia Institute of Technology * Copyright (c) 2019 CodeIgniter Foundation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author CodeIgniter Dev Team * @copyright 2019 CodeIgniter Foundation * @license https://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 4.0.0 * @filesource */ namespace CodeIgniter\HTTP; use CodeIgniter\HTTP\Exceptions\HTTPException; /** * Class Negotiate * * Provides methods to negotiate with the HTTP headers to determine the best * type match between what the application supports and what the requesting * getServer wants. * * @see http://tools.ietf.org/html/rfc7231#section-5.3 * @package CodeIgniter\HTTP */ class Negotiate { /** * Request * * @var \CodeIgniter\HTTP\RequestInterface|\CodeIgniter\HTTP\IncomingRequest */ protected $request; //-------------------------------------------------------------------- /** * Constructor * * @param \CodeIgniter\HTTP\RequestInterface $request */ public function __construct(RequestInterface $request = null) { if (! is_null($request)) { $this->request = $request; } } //-------------------------------------------------------------------- /** * Stores the request instance to grab the headers from. * * @param RequestInterface $request * * @return $this */ public function setRequest(RequestInterface $request) { $this->request = $request; return $this; } //-------------------------------------------------------------------- /** * Determines the best content-type to use based on the $supported * types the application says it supports, and the types requested * by the client. * * If no match is found, the first, highest-ranking client requested * type is returned. * * @param array $supported * @param boolean $strictMatch If TRUE, will return an empty string when no match found. * If FALSE, will return the first supported element. * * @return string */ public function media(array $supported, bool $strictMatch = false): string { return $this->getBestMatch($supported, $this->request->getHeaderLine('accept'), true, $strictMatch); } //-------------------------------------------------------------------- /** * Determines the best charset to use based on the $supported * types the application says it supports, and the types requested * by the client. * * If no match is found, the first, highest-ranking client requested * type is returned. * * @param array $supported * * @return string */ public function charset(array $supported): string { $match = $this->getBestMatch($supported, $this->request->getHeaderLine('accept-charset'), false, true); // If no charset is shown as a match, ignore the directive // as allowed by the RFC, and tell it a default value. if (empty($match)) { return 'utf-8'; } return $match; } //-------------------------------------------------------------------- /** * Determines the best encoding type to use based on the $supported * types the application says it supports, and the types requested * by the client. * * If no match is found, the first, highest-ranking client requested * type is returned. * * @param array $supported * * @return string */ public function encoding(array $supported = []): string { array_push($supported, 'identity'); return $this->getBestMatch($supported, $this->request->getHeaderLine('accept-encoding')); } //-------------------------------------------------------------------- /** * Determines the best language to use based on the $supported * types the application says it supports, and the types requested * by the client. * * If no match is found, the first, highest-ranking client requested * type is returned. * * @param array $supported * * @return string */ public function language(array $supported): string { return $this->getBestMatch($supported, $this->request->getHeaderLine('accept-language')); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // Utility Methods //-------------------------------------------------------------------- /** * Does the grunt work of comparing any of the app-supported values * against a given Accept* header string. * * Portions of this code base on Aura.Accept library. * * @param array $supported App-supported values * @param string $header header string * @param boolean $enforceTypes If TRUE, will compare media types and sub-types. * @param boolean $strictMatch If TRUE, will return empty string on no match. * If FALSE, will return the first supported element. * * @return string Best match */ protected function getBestMatch(array $supported, string $header = null, bool $enforceTypes = false, bool $strictMatch = false): string { if (empty($supported)) { throw HTTPException::forEmptySupportedNegotiations(); } if (empty($header)) { return $strictMatch ? '' : $supported[0]; } $acceptable = $this->parseHeader($header); foreach ($acceptable as $accept) { // if acceptable quality is zero, skip it. if ($accept['q'] === 0.0) { continue; } // if acceptable value is "anything", return the first available if ($accept['value'] === '*' || $accept['value'] === '*/*') { return $supported[0]; } // If an acceptable value is supported, return it foreach ($supported as $available) { if ($this->match($accept, $available, $enforceTypes)) { return $available; } } } // No matches? Return the first supported element. return $strictMatch ? '' : $supported[0]; } //-------------------------------------------------------------------- /** * Parses an Accept* header into it's multiple values. * * This is based on code from Aura.Accept library. * * @param string $header * * @return array */ public function parseHeader(string $header): array { $results = []; $acceptable = explode(',', $header); foreach ($acceptable as $value) { $pairs = explode(';', $value); $value = $pairs[0]; unset($pairs[0]); $parameters = []; foreach ($pairs as $pair) { $param = []; preg_match( '/^(?P<name>.+?)=(?P<quoted>"|\')?(?P<value>.*?)(?:\k<quoted>)?$/', $pair, $param ); $parameters[trim($param['name'])] = trim($param['value']); } $quality = 1.0; if (array_key_exists('q', $parameters)) { $quality = $parameters['q']; unset($parameters['q']); } $results[] = [ 'value' => trim($value), 'q' => (float) $quality, 'params' => $parameters, ]; } // Sort to get the highest results first usort($results, function ($a, $b) { if ($a['q'] === $b['q']) { $a_ast = substr_count($a['value'], '*'); $b_ast = substr_count($b['value'], '*'); // '*/*' has lower precedence than 'text/*', // and 'text/*' has lower priority than 'text/plain' // // This seems backwards, but needs to be that way // due to the way PHP7 handles ordering or array // elements created by reference. if ($a_ast > $b_ast) { return 1; } // If the counts are the same, but one element // has more params than another, it has higher precedence. // // This seems backwards, but needs to be that way // due to the way PHP7 handles ordering or array // elements created by reference. if ($a_ast === $b_ast) { return count($b['params']) - count($a['params']); } return 0; } // Still here? Higher q values have precedence. return ($a['q'] > $b['q']) ? -1 : 1; }); return $results; } //-------------------------------------------------------------------- /** * Match-maker * * @param array $acceptable * @param string $supported * @param boolean $enforceTypes * @return boolean */ protected function match(array $acceptable, string $supported, bool $enforceTypes = false): bool { $supported = $this->parseHeader($supported); if (is_array($supported) && count($supported) === 1) { $supported = $supported[0]; } // Is it an exact match? if ($acceptable['value'] === $supported['value']) { return $this->matchParameters($acceptable, $supported); } // Do we need to compare types/sub-types? Only used // by negotiateMedia(). if ($enforceTypes) { return $this->matchTypes($acceptable, $supported); } return false; } //-------------------------------------------------------------------- /** * Checks two Accept values with matching 'values' to see if their * 'params' are the same. * * @param array $acceptable * @param array $supported * * @return boolean */ protected function matchParameters(array $acceptable, array $supported): bool { if (count($acceptable['params']) !== count($supported['params'])) { return false; } foreach ($supported['params'] as $label => $value) { if (! isset($acceptable['params'][$label]) || $acceptable['params'][$label] !== $value) { return false; } } return true; } //-------------------------------------------------------------------- /** * Compares the types/subtypes of an acceptable Media type and * the supported string. * * @param array $acceptable * @param array $supported * * @return boolean */ public function matchTypes(array $acceptable, array $supported): bool { list($aType, $aSubType) = explode('/', $acceptable['value']); list($sType, $sSubType) = explode('/', $supported['value']); // If the types don't match, we're done. if ($aType !== $sType) { return false; } // If there's an asterisk, we're cool if ($aSubType === '*') { return true; } // Otherwise, subtypes must match also. return $aSubType === $sSubType; } //-------------------------------------------------------------------- }
jim-parry/CodeIgniter4
system/HTTP/Negotiate.php
PHP
mit
11,335
class CreateUsers < ActiveRecord::Migration[5.1] def change create_table :users do |t| t.string :first_name t.string :last_name t.string :spire t.string :email t.string :phone t.timestamps null: false end end end
umts/garrulous-garbanzo
db/migrate/20150909204238_create_users.rb
Ruby
mit
262
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpCodeSnippets { public class DoubleArrayCreation { public double[][] ScaleArrays(double[][] arrays, double scalingFactor) { var result = new double[arrays.Length][]; for (int i = 0; i < arrays.Length; i++) { result[i] = ScaleArray(arrays[i], scalingFactor); } return result; } public double[] ScaleArray(double[] array, double scalingFactor) { var result = new double[array.Length]; for (int i = 0; i < array.Length; i++) result[i] = array[i] * scalingFactor; return result; } private const int Zero = 0; private static readonly double[] Empty = new double[Zero]; private static readonly double[] Empty2 = new double[Zero2]; private const int Zero2 = 0; public void EmptyArray() { const int Two = 2; var result = new double[Two]; } } }
liebharc/VerifyBuffer
VerifyBuffering/CSharpCodeSnippets/DoubleArrayCreation.cs
C#
mit
1,190
//Copyright (C) <2012> <Jon Baker, Glenn Mariën and Lao Tszy> //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. //You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. //Copyright (C) <2012> Jon Baker(http://au70.net) using System; using System.Collections.Generic; namespace fCraft.Drawing { public sealed class WallsDrawOperation : DrawOperation { bool fillInner; public override string Name { get { return "Walls"; } } public override string Description { get { return Name; } } public WallsDrawOperation(Player player) : base(player){ } public override bool Prepare(Vector3I[] marks) { if (!base.Prepare(marks)) return false; fillInner = Brush.HasAlternateBlock && Bounds.Width > 2 && Bounds.Length > 2 && Bounds.Height > 2; BlocksTotalEstimate = Bounds.Volume; if (!fillInner) { BlocksTotalEstimate -= Math.Max(0, Bounds.Width - 2) * Math.Max(0, Bounds.Length - 2) * Math.Max(0, Bounds.Height - 2); } coordEnumerator = BlockEnumerator().GetEnumerator(); return true; } IEnumerator<Vector3I> coordEnumerator; public override int DrawBatch(int maxBlocksToDraw) { int blocksDone = 0; while (coordEnumerator.MoveNext()) { Coords = coordEnumerator.Current; if (DrawOneBlock()) { blocksDone++; if (blocksDone >= maxBlocksToDraw) return blocksDone; } } IsDone = true; return blocksDone; } //all works. Maybe look at Block estimation. IEnumerable<Vector3I> BlockEnumerator() { for (int x = Bounds.XMin; x <= Bounds.XMax; x++) { for (int z = Bounds.ZMin - 1; z < Bounds.ZMax; z++) { yield return new Vector3I(x, Bounds.YMin, z + 1); if (Bounds.YMin != Bounds.YMax) { yield return new Vector3I(x, Bounds.YMax, z + 1); } } for (int y = Bounds.YMin; y < Bounds.YMax; y++) { for (int z = Bounds.ZMin - 1; z < Bounds.ZMax; z++) { yield return new Vector3I(Bounds.XMin, y, z + 1); if (Bounds.XMin != Bounds.XMax) { yield return new Vector3I(Bounds.XMax, y, z + 1); } } } } if (fillInner) { UseAlternateBlock = true; for (int x = Bounds.XMin + 1; x < Bounds.XMax; x++) { for (int y = Bounds.YMin + 1; y < Bounds.YMax; y++) { for (int z = Bounds.ZMin; z < Bounds.ZMax + 1; z++) { yield return new Vector3I(x, y, z); } } } } } } }
LeChosenOne/LegendCraft
fCraft/Drawing/DrawOps/WallsOp.cs
C#
mit
3,853
import os import load_data import numpy as np from keras.backend import theano_backend as K from keras.callbacks import ModelCheckpoint, EarlyStopping from keras.utils.generic_utils import Progbar from keras.callbacks import Callback import generative_models as gm from common import CsvHistory from common import merge_result_batches import adverse_models as am from collections import Counter from scipy.stats import entropy def train(train, dev, model, model_dir, batch_size, glove, beam_size, samples_per_epoch, val_samples, cmodel, epochs): if not os.path.exists(model_dir): os.makedirs(model_dir) hypo_len = model.get_layer('hypo_input').input_shape[1] -1 ne = model.get_layer('noise_embeddings') vae = model.get_layer('vae_output') g_train = train_generator(train, batch_size, hypo_len, 'class_input' in model.input_names, ne, vae) saver = ModelCheckpoint(model_dir + '/weights.hdf5', monitor = 'hypo_loss', mode = 'min', save_best_only = True) #saver = ModelCheckpoint(model_dir + '/weights{epoch:02d}.hdf5') #es = EarlyStopping(patience = 4, monitor = 'hypo_loss', mode = 'min') csv = CsvHistory(model_dir + '/history.csv') gtest = gm.gen_test(model, glove, batch_size) noise_size = ne.output_shape[-1] if ne else model.get_layer('expansion').input_shape[-1] cb = ValidateGen(dev, gtest, beam_size, hypo_len, val_samples, noise_size, glove, cmodel, True, True) hist = model.fit_generator(g_train, samples_per_epoch = samples_per_epoch, nb_epoch = epochs, callbacks = [cb, saver, csv]) return hist def train_generator(train, batch_size, hypo_len, cinput, ninput, vae): while True: mb = load_data.get_minibatches_idx(len(train[0]), batch_size, shuffle=True) for i, train_index in mb: if len(train_index) != batch_size: continue padded_p = train[0][train_index] padded_h = train[1][train_index] label = train[2][train_index] hypo_input = np.concatenate([np.zeros((batch_size, 1)), padded_h], axis = 1) train_input = np.concatenate([padded_h, np.zeros((batch_size, 1))], axis = 1) inputs = [padded_p, hypo_input] + ([train_index[:, None]] if ninput else []) + [train_input] if cinput: inputs.append(label) outputs = [np.ones((batch_size, hypo_len + 1, 1))] if vae: outputs += [np.zeros(batch_size)] yield (inputs, outputs) def generative_predict_beam(test_model, premises, noise_batch, class_indices, return_best, hypo_len): core_model, premise_func, noise_func = test_model version = int(core_model.name[-1]) batch_size = core_model.input_layers[0].input_shape[0] beam_size = batch_size / len(premises) dup_premises = np.repeat(premises, beam_size, axis = 0) premise = premise_func(dup_premises) if version != 9 else None class_input = np.repeat(class_indices, beam_size, axis = 0) embed_vec = np.repeat(noise_batch, beam_size, axis = 0) if version == 8: noise = noise_func(embed_vec, class_input) elif version == 6 or version == 7: noise = noise_func(embed_vec[:,-1,:], class_input) elif version == 9: noise = noise_func(embed_vec, class_input, dup_premises) elif version == 5: noise = noise_func(embed_vec) core_model.reset_states() core_model.get_layer('attention').set_state(noise) word_input = np.zeros((batch_size, 1)) result_probs = np.zeros(batch_size) debug_probs = np.zeros((hypo_len, batch_size)) lengths = np.zeros(batch_size) words = None probs = None for i in range(hypo_len): data = [premise, word_input, noise, np.zeros((batch_size,1))] if version == 9: data = data[1:] preds = core_model.predict_on_batch(data) preds = np.log(preds) split_preds = np.array(np.split(preds, len(premises))) if probs is None: if beam_size == 1: word_input = np.argmax(split_preds[:, 0, 0], axis = 1)[:,None] else: word_input = np.argpartition(-split_preds[:, 0, 0], beam_size)[:,:beam_size] probs = split_preds[:,0,0][np.arange(len(premises))[:, np.newaxis],[word_input]].ravel() word_input= word_input.ravel()[:,None] words = np.array(word_input) debug_probs[0] = probs else: split_cprobs = (preds[:,-1,:] + probs[:, None]).reshape((len(premises), -1)) if beam_size == 1: max_indices = np.argmax(split_cprobs, axis = 1)[:,None] else: max_indices = np.argpartition(-split_cprobs, beam_size)[:,:beam_size] probs = split_cprobs[np.arange(len(premises))[:, np.newaxis],[max_indices]].ravel() word_input = (max_indices % preds.shape[-1]).ravel()[:,None] state_indices = (max_indices / preds.shape[-1]) + np.arange(0, batch_size, beam_size)[:, None] state_indices = state_indices.ravel() shuffle_states(core_model, state_indices) words = np.concatenate([words[state_indices], word_input], axis = -1) debug_probs = debug_probs[:, state_indices] debug_probs[i] = probs - np.sum(debug_probs, axis = 0) lengths += 1 * (word_input[:,0] > 0).astype('int') if (np.sum(word_input) == 0): words = np.concatenate([words, np.zeros((batch_size, hypo_len - words.shape[1]))], axis = -1) break result_probs = probs / -lengths if return_best: best_ind = np.argmin(np.array(np.split(result_probs, len(premises))), axis =1) + np.arange(0, batch_size, beam_size) return words[best_ind], result_probs[best_ind] else: return words, result_probs, debug_probs def shuffle_states(graph_model, indices): for l in graph_model.layers: if getattr(l, 'stateful', False): for s in l.states: K.set_value(s, s.get_value()[indices]) def val_generator(dev, gen_test, beam_size, hypo_len, noise_size): batch_size = gen_test[0].input_layers[0].input_shape[0] per_batch = batch_size / beam_size while True: mb = load_data.get_minibatches_idx(len(dev[0]), per_batch, shuffle=False) for i, train_index in mb: if len(train_index) != per_batch: continue premises = dev[0][train_index] noise_input = np.random.normal(scale=0.11, size=(per_batch, 1, noise_size)) class_indices = dev[2][train_index] words, loss = generative_predict_beam(gen_test, premises, noise_input, class_indices, True, hypo_len) yield premises, words, loss, noise_input, class_indices def single_generate(premise, label, gen_test, beam_size, hypo_len, noise_size, noise_input = None): batch_size = gen_test[0].input_layers[0].input_shape[0] per_batch = batch_size / beam_size premises = [premise] * per_batch if noise_input is None: noise_input = np.random.normal(scale=0.11, size=(per_batch, 1, noise_size)) class_indices = np.ones(per_batch) * label class_indices = load_data.convert_to_one_hot(class_indices, 3) words, loss = generative_predict_beam(gen_test, premises, noise_input, class_indices, True, hypo_len) return words def validate(dev, gen_test, beam_size, hypo_len, samples, noise_size, glove, cmodel = None, adverse = False, diverse = False): vgen = val_generator(dev, gen_test, beam_size, hypo_len, noise_size) p = Progbar(samples) batchez = [] while p.seen_so_far < samples: batch = next(vgen) preplexity = np.mean(np.power(2, batch[2])) loss = np.mean(batch[2]) losses = [('hypo_loss',loss),('perplexity', preplexity)] if cmodel is not None: ceval = cmodel.evaluate([batch[0], batch[1]], batch[4], verbose = 0) losses += [('class_loss', ceval[0]), ('class_acc', ceval[1])] probs = cmodel.predict([batch[0], batch[1]], verbose = 0) losses += [('class_entropy', np.mean(-np.sum(probs * np.log(probs), axis=1)))] p.add(len(batch[0]), losses) batchez.append(batch) batchez = merge_result_batches(batchez) res = {} if adverse: val_loss = adverse_validation(dev, batchez, glove) print 'adverse_loss:', val_loss res['adverse_loss'] = val_loss if diverse: div, _, _, _ = diversity(dev, gen_test, beam_size, hypo_len, noise_size, 64, 32) res['diversity'] = div print for val in p.unique_values: arr = p.sum_values[val] res[val] = arr[0] / arr[1] return res def adverse_validation(dev, batchez, glove): samples = len(batchez[1]) discriminator = am.discriminator(glove, 50) ad_model = am.adverse_model(discriminator) res = ad_model.fit([dev[1][:samples], batchez[1]], np.zeros(samples), validation_split=0.1, verbose = 0, nb_epoch = 20, callbacks = [EarlyStopping(patience=2)]) return np.min(res.history['val_loss']) def diversity(dev, gen_test, beam_size, hypo_len, noise_size, per_premise, samples): step = len(dev[0]) / samples sind = [i * step for i in range(samples)] p = Progbar(per_premise * samples) for i in sind: hypos = [] unique_words = [] hypo_list = [] premise = dev[0][i] prem_list = set(cut_zeros(list(premise))) while len(hypos) < per_premise: label = np.argmax(dev[2][i]) words = single_generate(premise, label, gen_test, beam_size, hypo_len, noise_size) hypos += [str(ex) for ex in words] unique_words += [int(w) for ex in words for w in ex if w > 0] hypo_list += [set(cut_zeros(list(ex))) for ex in words] jacks = [] prem_jacks = [] for u in range(len(hypo_list)): sim_prem = len(hypo_list[u] & prem_list)/float(len(hypo_list[u] | prem_list)) prem_jacks.append(sim_prem) for v in range(u+1, len(hypo_list)): sim = len(hypo_list[u] & hypo_list[v])/float(len(hypo_list[u] | hypo_list[v])) jacks.append(sim) avg_dist_hypo = 1 - np.mean(jacks) avg_dist_prem = 1 - np.mean(prem_jacks) d = entropy(Counter(hypos).values()) w = entropy(Counter(unique_words).values()) p.add(len(hypos), [('diversity', d),('word_entropy', w),('avg_dist_hypo', avg_dist_hypo), ('avg_dist_prem', avg_dist_prem)]) arrd = p.sum_values['diversity'] arrw = p.sum_values['word_entropy'] arrj = p.sum_values['avg_dist_hypo'] arrp = p.sum_values['avg_dist_prem'] return arrd[0] / arrd[1], arrw[0] / arrw[1], arrj[0] / arrj[1], arrp[0] / arrp[1] def cut_zeros(list): return [a for a in list if a > 0] class ValidateGen(Callback): def __init__(self, dev, gen_test, beam_size, hypo_len, samples, noise_size, glove, cmodel, adverse, diverse): self.dev = dev self.gen_test=gen_test self.beam_size = beam_size self.hypo_len = hypo_len self.samples = samples self.noise_size = noise_size self.cmodel= cmodel self.glove = glove self.adverse = adverse self.diverse = diverse def on_epoch_end(self, epoch, logs={}): gm.update_gen_weights(self.gen_test[0], self.model) val_log = validate(self.dev, self.gen_test, self.beam_size, self.hypo_len, self.samples, self.noise_size, self.glove, self.cmodel, self.adverse, self.diverse) logs.update(val_log)
jstarc/deep_reasoning
generative_alg.py
Python
mit
12,160
<?php // FILE: xtemplate.class (part of MiniMediaEducation, https://github.com/aleph3d/MiniMediaEducation.git) // TYPE: funciton/class Library (PHP5) // LICENSE: BSD and LGPL ////// Copyright (c) 2000-2001 Barnab�s Debreceni [cranx@users.sourceforge.net] XTemplate ////// Copyright (c) 2002-2007 Jeremy Coates [cocomp@users.sourceforge.net] XTemplate & CachingXTemplate // When developing uncomment the line below, re-comment before making public //error_reporting(E_ALL); /** * XTemplate PHP templating engine * * @package XTemplate * @author Barnabas Debreceni [cranx@users.sourceforge.net] * @copyright Barnabas Debreceni 2000-2001 * @author Jeremy Coates [cocomp@users.sourceforge.net] * @copyright Jeremy Coates 2002-2007 * @see license.txt LGPL / BSD license * @since PHP 5 * @link $HeadURL: https://xtpl.svn.sourceforge.net/svnroot/xtpl/trunk/xtemplate.class.php $ * @version $Id: xtemplate.class.php 21 2007-05-29 18:01:15Z cocomp $ * * * XTemplate class - http://www.phpxtemplate.org/ (x)html / xml generation with templates - fast & easy * Latest stable & Subversion versions available @ http://sourceforge.net/projects/xtpl/ * License: LGPL / BSD - see license.txt * Changelog: see changelog.txt */ proCheck() or die(); class XTemplate { /** * Properties */ /** * Raw contents of the template file * * @access public * @var string */ public $filecontents = ''; /** * Unparsed blocks * * @access public * @var array */ public $blocks = array(); /** * Parsed blocks * * @var unknown_type */ public $parsed_blocks = array(); /** * Preparsed blocks (for file includes) * * @access public * @var array */ public $preparsed_blocks = array(); /** * Block parsing order for recursive parsing * (Sometimes reverse :) * * @access public * @var array */ public $block_parse_order = array(); /** * Store sub-block names * (For fast resetting) * * @access public * @var array */ public $sub_blocks = array(); /** * Variables array * * @access public * @var array */ public $vars = array(); /** * File variables array * * @access public * @var array */ public $filevars = array(); /** * Filevars' parent block * * @access public * @var array */ public $filevar_parent = array(); /** * File caching during duration of script * e.g. files only cached to speed {FILE "filename"} repeats * * @access public * @var array */ public $filecache = array(); /** * Location of template files * * @access public * @var string */ public $tpldir = ''; /** * Filenames lookup table * * @access public * @var null */ public $files = null; /** * Template filename * * @access public * @var string */ public $filename = ''; // moved to setup method so uses the tag_start & end_delims /** * RegEx for file includes * * "/\{FILE\s*\"([^\"]+)\"\s*\}/m"; * * @access public * @var string */ public $file_delim = ''; /** * RegEx for file include variable * * "/\{FILE\s*\{([A-Za-z0-9\._]+?)\}\s*\}/m"; * * @access public * @var string */ public $filevar_delim = ''; /** * RegEx for file includes with newlines * * "/^\s*\{FILE\s*\{([A-Za-z0-9\._]+?)\}\s*\}\s*\n/m"; * * @access public * @var string */ public $filevar_delim_nl = ''; /** * Template block start delimiter * * @access public * @var string */ public $block_start_delim = '<!-- '; /** * Template block end delimiter * * @access public * @var string */ public $block_end_delim = '-->'; /** * Template block start word * * @access public * @var string */ public $block_start_word = 'BEGIN:'; /** * Template block end word * * The last 3 properties and this make the delimiters look like: * @example <!-- BEGIN: block_name --> * if you use the default syntax. * * @access public * @var string */ public $block_end_word = 'END:'; /** * Template tag start delimiter * * This makes the delimiters look like: * @example {tagname} * if you use the default syntax. * * @access public * @var string */ public $tag_start_delim = '{'; /** * Template tag end delimiter * * This makes the delimiters look like: * @example {tagname} * if you use the default syntax. * * @access public * @var string */ public $tag_end_delim = '}'; /* this makes the delimiters look like: {tagname} if you use my syntax. */ /** * Regular expression element for comments within tags and blocks * * @example {tagname#My Comment} * @example {tagname #My Comment} * @example <!-- BEGIN: blockname#My Comment --> * @example <!-- BEGIN: blockname #My Comment --> * * @access public * @var string */ public $comment_preg = '( ?#.*?)?'; /** * Default main template block name * * @access public * @var string */ public $mainblock = 'main'; /** * Script output type * * @access public * @var string */ public $output_type = 'HTML'; /** * Debug mode * * @access public * @var boolean */ public $debug = false; /** * Null string for unassigned vars * * @access protected * @var array */ protected $_null_string = array('' => ''); /** * Null string for unassigned blocks * * @access protected * @var array */ protected $_null_block = array('' => ''); /** * Errors * * @access protected * @var string */ protected $_error = ''; /** * Auto-reset sub blocks * * @access protected * @var boolean */ protected $_autoreset = true; /** * Set to FALSE to generate errors if a non-existant blocks is referenced * * @author NW * @since 2002/10/17 * @access protected * @var boolean */ protected $_ignore_missing_blocks = true; /** * PHP 5 Constructor - Instantiate the object * * @param string $file Template file to work on * @param string/array $tpldir Location of template files (useful for keeping files outside web server root) * @param array $files Filenames lookup * @param string $mainblock Name of main block in the template * @param boolean $autosetup If true, run setup() as part of constuctor * @return XTemplate */ public function __construct($file, $tpldir = '', $files = null, $mainblock = 'main', $autosetup = true) { $this->restart($file, $tpldir, $files, $mainblock, $autosetup, $this->tag_start_delim, $this->tag_end_delim); } /** * PHP 4 Constructor - Instantiate the object * * @deprecated Use PHP 5 constructor instead * @param string $file Template file to work on * @param string/array $tpldir Location of template files (useful for keeping files outside web server root) * @param array $files Filenames lookup * @param string $mainblock Name of main block in the template * @param boolean $autosetup If true, run setup() as part of constuctor * @return XTemplate */ public function XTemplate ($file, $tpldir = '', $files = null, $mainblock = 'main', $autosetup = true) { assert('Deprecated - use PHP 5 constructor'); } /***************************************************************************/ /***[ public stuff ]********************************************************/ /***************************************************************************/ /** * Restart the class - allows one instantiation with several files processed by restarting * e.g. $xtpl = new XTemplate('file1.xtpl'); * $xtpl->parse('main'); * $xtpl->out('main'); * $xtpl->restart('file2.xtpl'); * $xtpl->parse('main'); * $xtpl->out('main'); * (Added in response to sf:641407 feature request) * * @param string $file Template file to work on * @param string/array $tpldir Location of template files * @param array $files Filenames lookup * @param string $mainblock Name of main block in the template * @param boolean $autosetup If true, run setup() as part of restarting * @param string $tag_start { * @param string $tag_end } */ public function restart ($file, $tpldir = '', $files = null, $mainblock = 'main', $autosetup = true, $tag_start = '{', $tag_end = '}') { $this->filename = $file; // From SF Feature request 1202027 // Kenneth Kalmer $this->tpldir = $tpldir; if (defined('XTPL_DIR') && empty($this->tpldir)) { $this->tpldir = XTPL_DIR; } if (is_array($files)) { $this->files = $files; } $this->mainblock = $mainblock; $this->tag_start_delim = $tag_start; $this->tag_end_delim = $tag_end; // Start with fresh file contents $this->filecontents = ''; // Reset the template arrays $this->blocks = array(); $this->parsed_blocks = array(); $this->preparsed_blocks = array(); $this->block_parse_order = array(); $this->sub_blocks = array(); $this->vars = array(); $this->filevars = array(); $this->filevar_parent = array(); $this->filecache = array(); if ($autosetup) { $this->setup(); } } /** * setup - the elements that were previously in the constructor * * @access public * @param boolean $add_outer If true is passed when called, it adds an outer main block to the file */ public function setup ($add_outer = false) { $this->tag_start_delim = preg_quote($this->tag_start_delim); $this->tag_end_delim = preg_quote($this->tag_end_delim); // Setup the file delimiters // regexp for file includes $this->file_delim = "/" . $this->tag_start_delim . "FILE\s*\"([^\"]+)\"" . $this->comment_preg . $this->tag_end_delim . "/m"; // regexp for file includes $this->filevar_delim = "/" . $this->tag_start_delim . "FILE\s*" . $this->tag_start_delim . "([A-Za-z0-9\._]+?)" . $this->comment_preg . $this->tag_end_delim . $this->comment_preg . $this->tag_end_delim . "/m"; // regexp for file includes w/ newlines $this->filevar_delim_nl = "/^\s*" . $this->tag_start_delim . "FILE\s*" . $this->tag_start_delim . "([A-Za-z0-9\._]+?)" . $this->comment_preg . $this->tag_end_delim . $this->comment_preg . $this->tag_end_delim . "\s*\n/m"; if (empty($this->filecontents)) { // read in template file $this->filecontents = $this->_r_getfile($this->filename); } if ($add_outer) { $this->_add_outer_block(); } // preprocess some stuff $this->blocks = $this->_maketree($this->filecontents, ''); $this->filevar_parent = $this->_store_filevar_parents($this->blocks); $this->scan_globals(); } /** * assign a variable * * @example Simplest case: * @example $xtpl->assign('name', 'value'); * @example {name} in template * * @example Array assign: * @example $xtpl->assign(array('name' => 'value', 'name2' => 'value2')); * @example {name} {name2} in template * * @example Value as array assign: * @example $xtpl->assign('name', array('key' => 'value', 'key2' => 'value2')); * @example {name.key} {name.key2} in template * * @example Reset array: * @example $xtpl->assign('name', array('key' => 'value', 'key2' => 'value2')); * @example // Other code then: * @example $xtpl->assign('name', array('key3' => 'value3'), false); * @example {name.key} {name.key2} {name.key3} in template * * @access public * @param string $name Variable to assign $val to * @param string / array $val Value to assign to $name * @param boolean $reset_array Reset the variable array if $val is an array */ public function assign ($name, $val = '', $reset_array = true) { if (is_array($name)) { foreach ($name as $k => $v) { $this->vars[$k] = $v; } } elseif (is_array($val)) { // Clear the existing values if ($reset_array) { $this->vars[$name] = array(); } foreach ($val as $k => $v) { $this->vars[$name][$k] = $v; } } else { $this->vars[$name] = $val; } } /** * assign a file variable * * @access public * @param string $name Variable to assign $val to * @param string / array $val Values to assign to $name */ public function assign_file ($name, $val = '') { if (is_array($name)) { foreach ($name as $k => $v) { $this->_assign_file_sub($k, $v); } } else { $this->_assign_file_sub($name, $val); } } /** * parse a block * * @access public * @param string $bname Block name to parse */ public function parse ($bname) { if (isset($this->preparsed_blocks[$bname])) { $copy = $this->preparsed_blocks[$bname]; } elseif (isset($this->blocks[$bname])) { $copy = $this->blocks[$bname]; } elseif ($this->_ignore_missing_blocks) { // ------------------------------------------------------ // NW : 17 Oct 2002. Added default of ignore_missing_blocks // to allow for generalised processing where some // blocks may be removed from the HTML without the // processing code needing to be altered. // ------------------------------------------------------ // JRC: 3/1/2003 added set error to ignore missing functionality $this->_set_error("parse: blockname [$bname] does not exist"); return; } else { $this->_set_error("parse: blockname [$bname] does not exist"); } /* from there we should have no more {FILE } directives */ if (!isset($copy)) { die('Block: ' . $bname); } $copy = preg_replace($this->filevar_delim_nl, '', $copy); $var_array = array(); /* find & replace variables+blocks */ preg_match_all("|" . $this->tag_start_delim . "([A-Za-z0-9\._]+?" . $this->comment_preg . ")" . $this->tag_end_delim. "|", $copy, $var_array); $var_array = $var_array[1]; foreach ($var_array as $k => $v) { // Are there any comments in the tags {tag#a comment for documenting the template} $any_comments = explode('#', $v); $v = rtrim($any_comments[0]); if (sizeof($any_comments) > 1) { $comments = $any_comments[1]; } else { $comments = ''; } $sub = explode('.', $v); if ($sub[0] == '_BLOCK_') { unset($sub[0]); $bname2 = implode('.', $sub); // trinary operator eliminates assign error in E_ALL reporting $var = isset($this->parsed_blocks[$bname2]) ? $this->parsed_blocks[$bname2] : null; $nul = (!isset($this->_null_block[$bname2])) ? $this->_null_block[''] : $this->_null_block[$bname2]; if ($var === '') { if ($nul == '') { // ----------------------------------------------------------- // Removed requirement for blocks to be at the start of string // ----------------------------------------------------------- // $copy=preg_replace("/^\s*\{".$v."\}\s*\n*/m","",$copy); // Now blocks don't need to be at the beginning of a line, //$copy=preg_replace("/\s*" . $this->tag_start_delim . $v . $this->tag_end_delim . "\s*\n*/m","",$copy); $copy = preg_replace("|" . $this->tag_start_delim . $v . $this->tag_end_delim . "|m", '', $copy); } else { $copy = preg_replace("|" . $this->tag_start_delim . $v . $this->tag_end_delim . "|m", "$nul", $copy); } } else { //$var = trim($var); switch (true) { case preg_match('/^\n/', $var) && preg_match('/\n$/', $var): $var = substr($var, 1, -1); break; case preg_match('/^\n/', $var): $var = substr($var, 1); break; case preg_match('/\n$/', $var): $var = substr($var, 0, -1); break; } // SF Bug no. 810773 - thanks anonymous $var = str_replace('\\', '\\\\', $var); // Ensure dollars in strings are not evaluated reported by SadGeezer 31/3/04 $var = str_replace('$', '\\$', $var); // Replaced str_replaces with preg_quote //$var = preg_quote($var); $var = str_replace('\\|', '|', $var); $copy = preg_replace("|" . $this->tag_start_delim . $v . $this->tag_end_delim . "|m", "$var", $copy); if (preg_match('/^\n/', $copy) && preg_match('/\n$/', $copy)) { $copy = substr($copy, 1, -1); } } } else { $var = $this->vars; foreach ($sub as $v1) { // NW 4 Oct 2002 - Added isset and is_array check to avoid NOTICE messages // JC 17 Oct 2002 - Changed EMPTY to stlen=0 // if (empty($var[$v1])) { // this line would think that zeros(0) were empty - which is not true if (!isset($var[$v1]) || (!is_array($var[$v1]) && strlen($var[$v1]) == 0)) { // Check for constant, when variable not assigned if (defined($v1)) { $var[$v1] = constant($v1); } else { $var[$v1] = null; } } $var = $var[$v1]; } $nul = (!isset($this->_null_string[$v])) ? ($this->_null_string[""]) : ($this->_null_string[$v]); $var = (!isset($var)) ? $nul : $var; if ($var === '') { // ----------------------------------------------------------- // Removed requriement for blocks to be at the start of string // ----------------------------------------------------------- // $copy=preg_replace("|^\s*\{".$v." ?#?".$comments."\}\s*\n|m","",$copy); $copy = preg_replace("|" . $this->tag_start_delim . $v . "( ?#" . $comments . ")?" . $this->tag_end_delim . "|m", '', $copy); } $var = trim($var); // SF Bug no. 810773 - thanks anonymous $var = str_replace('\\', '\\\\', $var); // Ensure dollars in strings are not evaluated reported by SadGeezer 31/3/04 $var = str_replace('$', '\\$', $var); // Replace str_replaces with preg_quote //$var = preg_quote($var); $var = str_replace('\\|', '|', $var); $copy = preg_replace("|" . $this->tag_start_delim . $v . "( ?#" . $comments . ")?" . $this->tag_end_delim . "|m", "$var", $copy); if (preg_match('/^\n/', $copy) && preg_match('/\n$/', $copy)) { $copy = substr($copy, 1); } } } if (isset($this->parsed_blocks[$bname])) { $this->parsed_blocks[$bname] .= $copy; } else { $this->parsed_blocks[$bname] = $copy; } /* reset sub-blocks */ if ($this->_autoreset && (!empty($this->sub_blocks[$bname]))) { reset($this->sub_blocks[$bname]); foreach ($this->sub_blocks[$bname] as $k => $v) { $this->reset($v); } } } /** * returns the parsed text for a block, including all sub-blocks. * * @access public * @param string $bname Block name to parse */ public function rparse ($bname) { if (!empty($this->sub_blocks[$bname])) { reset($this->sub_blocks[$bname]); foreach ($this->sub_blocks[$bname] as $k => $v) { if (!empty($v)) { $this->rparse($v); } } } $this->parse($bname); } /** * inserts a loop ( call assign & parse ) * * @access public * @param string $bname Block name to assign * @param string $var Variable to assign values to * @param string / array $value Value to assign to $var */ public function insert_loop ($bname, $var, $value = '') { $this->assign($var, $value); $this->parse($bname); } /** * parses a block for every set of data in the values array * * @access public * @param string $bname Block name to loop * @param string $var Variable to assign values to * @param array $values Values to assign to $var */ public function array_loop ($bname, $var, &$values) { if (is_array($values)) { foreach($values as $v) { $this->insert_loop($bname, $var, $v); } } } /** * returns the parsed text for a block * * @access public * @param string $bname Block name to return * @return string */ public function text ($bname = '') { $text = ''; if ($this->debug && $this->output_type == 'HTML') { // JC 20/11/02 echo the template filename if in development as // html comment $text .= '<!-- XTemplate: ' . realpath($this->filename) . " -->\n"; } $bname = !empty($bname) ? $bname : $this->mainblock; $text .= isset($this->parsed_blocks[$bname]) ? $this->parsed_blocks[$bname] : $this->get_error(); return $text; } /** * prints the parsed text * * @access public * @param string $bname Block name to echo out */ public function out ($bname) { $out = $this->text($bname); // $length=strlen($out); //header("Content-Length: ".$length); // TODO: Comment this back in later echo $out; } public function VariableOut ($bname) { $out = $this->text($bname); // $length=strlen($out); //header("Content-Length: ".$length); // TODO: Comment this back in later return $out; } /** * prints the parsed text to a specified file * * @access public * @param string $bname Block name to write out * @param string $fname File name to write to */ public function out_file ($bname, $fname) { if (!empty($bname) && !empty($fname) && is_writeable($fname)) { $fp = fopen($fname, 'w'); fwrite($fp, $this->text($bname)); fclose($fp); } } /** * resets the parsed text * * @access public * @param string $bname Block to reset */ public function reset ($bname) { $this->parsed_blocks[$bname] = ''; } /** * returns true if block was parsed, false if not * * @access public * @param string $bname Block name to test * @return boolean */ public function parsed ($bname) { return (!empty($this->parsed_blocks[$bname])); } /** * sets the string to replace in case the var was not assigned * * @access public * @param string $str Display string for null block * @param string $varname Variable name to apply $str to */ public function set_null_string($str, $varname = '') { $this->_null_string[$varname] = $str; } /** * Backwards compatibility only * * @param string $str * @param string $varname * @deprecated Change to set_null_string to keep in with rest of naming convention */ public function SetNullString ($str, $varname = '') { $this->set_null_string($str, $varname); } /** * sets the string to replace in case the block was not parsed * * @access public * @param string $str Display string for null block * @param string $bname Block name to apply $str to */ public function set_null_block ($str, $bname = '') { $this->_null_block[$bname] = $str; } /** * Backwards compatibility only * * @param string $str * @param string $bname * @deprecated Change to set_null_block to keep in with rest of naming convention */ public function SetNullBlock ($str, $bname = '') { $this->set_null_block($str, $bname); } /** * sets AUTORESET to 1. (default is 1) * if set to 1, parse() automatically resets the parsed blocks' sub blocks * (for multiple level blocks) * * @access public */ public function set_autoreset () { $this->_autoreset = true; } /** * sets AUTORESET to 0. (default is 1) * if set to 1, parse() automatically resets the parsed blocks' sub blocks * (for multiple level blocks) * * @access public */ public function clear_autoreset () { $this->_autoreset = false; } /** * scans global variables and assigns to PHP array * * @access public */ public function scan_globals () { reset($GLOBALS); foreach ($GLOBALS as $k => $v) { $GLOB[$k] = $v; } /** * Access global variables as: * @example {PHP._SERVER.HTTP_HOST} * in your template! */ $this->assign('PHP', $GLOB); } /** * gets error condition / string * * @access public * @return boolean / string */ public function get_error () { // JRC: 3/1/2003 Added ouptut wrapper and detection of output type for error message output $retval = false; if ($this->_error != '') { switch ($this->output_type) { case 'HTML': case 'html': $retval = '<b>[XTemplate]</b><ul>' . nl2br(str_replace('* ', '<li>', str_replace(" *\n", "</li>\n", $this->_error))) . '</ul>'; break; default: $retval = '[XTemplate] ' . str_replace(' *\n', "\n", $this->_error); break; } } return $retval; } /***************************************************************************/ /***[ private stuff ]*******************************************************/ /***************************************************************************/ /** * generates the array containing to-be-parsed stuff: * $blocks["main"],$blocks["main.table"],$blocks["main.table.row"], etc. * also builds the reverse parse order. * * @access public - aiming for private * @param string $con content to be processed * @param string $parentblock name of the parent block in the block hierarchy */ public function _maketree ($con, $parentblock='') { $blocks = array(); $con2 = explode($this->block_start_delim, $con); if (!empty($parentblock)) { $block_names = explode('.', $parentblock); $level = sizeof($block_names); } else { $block_names = array(); $level = 0; } // JRC 06/04/2005 Added block comments (on BEGIN or END) <!-- BEGIN: block_name#Comments placed here --> //$patt = "($this->block_start_word|$this->block_end_word)\s*(\w+)\s*$this->block_end_delim(.*)"; $patt = "(" . $this->block_start_word . "|" . $this->block_end_word . ")\s*(\w+)" . $this->comment_preg . "\s*" . $this->block_end_delim . "(.*)"; foreach($con2 as $k => $v) { $res = array(); if (preg_match_all("/$patt/ims", $v, $res, PREG_SET_ORDER)) { // $res[0][1] = BEGIN or END // $res[0][2] = block name // $res[0][3] = comment // $res[0][4] = kinda content $block_word = $res[0][1]; $block_name = $res[0][2]; $comment = $res[0][3]; $content = $res[0][4]; if (strtoupper($block_word) == $this->block_start_word) { $parent_name = implode('.', $block_names); // add one level - array("main","table","row") $block_names[++$level] = $block_name; // make block name (main.table.row) $cur_block_name=implode('.', $block_names); // build block parsing order (reverse) $this->block_parse_order[] = $cur_block_name; //add contents. trinary operator eliminates assign error in E_ALL reporting $blocks[$cur_block_name] = isset($blocks[$cur_block_name]) ? $blocks[$cur_block_name] . $content : $content; // add {_BLOCK_.blockname} string to parent block $blocks[$parent_name] .= str_replace('\\', '', $this->tag_start_delim) . '_BLOCK_.' . $cur_block_name . str_replace('\\', '', $this->tag_end_delim); // store sub block names for autoresetting and recursive parsing $this->sub_blocks[$parent_name][] = $cur_block_name; // store sub block names for autoresetting $this->sub_blocks[$cur_block_name][] = ''; } else if (strtoupper($block_word) == $this->block_end_word) { unset($block_names[$level--]); $parent_name = implode('.', $block_names); // add rest of block to parent block $blocks[$parent_name] .= $content; } } else { // no block delimiters found // Saves doing multiple implodes - less overhead $tmp = implode('.', $block_names); if ($k) { $blocks[$tmp] .= $this->block_start_delim; } // trinary operator eliminates assign error in E_ALL reporting $blocks[$tmp] = isset($blocks[$tmp]) ? $blocks[$tmp] . $v : $v; } } return $blocks; } /** * Sub processing for assign_file method * * @access private * @param string $name * @param string $val */ private function _assign_file_sub ($name, $val) { if (isset($this->filevar_parent[$name])) { if ($val != '') { $val = $this->_r_getfile($val); foreach($this->filevar_parent[$name] as $parent) { if (isset($this->preparsed_blocks[$parent]) && !isset($this->filevars[$name])) { $copy = $this->preparsed_blocks[$parent]; } elseif (isset($this->blocks[$parent])) { $copy = $this->blocks[$parent]; } $res = array(); preg_match_all($this->filevar_delim, $copy, $res, PREG_SET_ORDER); if (is_array($res) && isset($res[0])) { // Changed as per solution in SF bug ID #1261828 foreach ($res as $v) { // Changed as per solution in SF bug ID #1261828 if ($v[1] == $name) { // Changed as per solution in SF bug ID #1261828 $copy = preg_replace("/" . preg_quote($v[0]) . "/", "$val", $copy); $this->preparsed_blocks = array_merge($this->preparsed_blocks, $this->_maketree($copy, $parent)); $this->filevar_parent = array_merge($this->filevar_parent, $this->_store_filevar_parents($this->preparsed_blocks)); } } } } } } $this->filevars[$name] = $val; } /** * store container block's name for file variables * * @access public - aiming for private * @param array $blocks * @return array */ public function _store_filevar_parents ($blocks){ $parents = array(); foreach ($blocks as $bname => $con) { $res = array(); preg_match_all($this->filevar_delim, $con, $res); foreach ($res[1] as $k => $v) { $parents[$v][] = $bname; } } return $parents; } /** * Set the error string * * @access private * @param string $str */ private function _set_error ($str) { // JRC: 3/1/2003 Made to append the error messages $this->_error .= '* ' . $str . " *\n"; // JRC: 3/1/2003 Removed trigger error, use this externally if you want it eg. trigger_error($xtpl->get_error()) //trigger_error($this->get_error()); } /** * returns the contents of a file * * @access protected * @param string $file * @return string */ protected function _getfile ($file) { if (!isset($file)) { // JC 19/12/02 added $file to error message $this->_set_error('!isset file name!' . $file); return ''; } // check if filename is mapped to other filename if (isset($this->files)) { if (isset($this->files[$file])) { $file = $this->files[$file]; } } // prepend template dir if (!empty($this->tpldir)) { /** * Support hierarchy of file locations to search * * @example Supply array of filepaths when instantiating * First path supplied that has the named file is prioritised * $xtpl = new XTemplate('myfile.xtpl', array('.','/mypath', '/mypath2')); * @since 29/05/2007 */ if (is_array($this->tpldir)) { foreach ($this->tpldir as $dir) { if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) { $file = $dir . DIRECTORY_SEPARATOR . $file; break; } } } else { $file = $this->tpldir. DIRECTORY_SEPARATOR . $file; } } $file_text = ''; if (isset($this->filecache[$file])) { $file_text .= $this->filecache[$file]; if ($this->debug) { $file_text = '<!-- XTemplate debug cached: ' . realpath($file) . ' -->' . "\n" . $file_text; } } else { if (is_file($file) && is_readable($file)) { if (filesize($file)) { if (!($fh = fopen($file, 'r'))) { $this->_set_error('Cannot open file: ' . realpath($file)); return ''; } $file_text .= fread($fh,filesize($file)); fclose($fh); } if ($this->debug) { $file_text = '<!-- XTemplate debug: ' . realpath($file) . ' -->' . "\n" . $file_text; } } elseif (str_replace('.', '', phpversion()) >= '430' && $file_text = @file_get_contents($file, true)) { // Enable use of include path by using file_get_contents // Implemented at suggestion of SF Feature Request ID #1529478 michaelgroh if ($file_text === false) { $this->_set_error("[" . realpath($file) . "] ($file) does not exist"); $file_text = "<b>__XTemplate fatal error: file [$file] does not exist in the include path__</b>"; } elseif ($this->debug) { $file_text = '<!-- XTemplate debug: ' . realpath($file) . ' (via include path) -->' . "\n" . $file_text; } } elseif (!is_file($file)) { // NW 17 Oct 2002 : Added realpath around the file name to identify where the code is searching. $this->_set_error("[" . realpath($file) . "] ($file) does not exist"); $file_text .= "<b>__XTemplate fatal error: file [$file] does not exist__</b>"; } elseif (!is_readable($file)) { $this->_set_error("[" . realpath($file) . "] ($file) is not readable"); $file_text .= "<b>__XTemplate fatal error: file [$file] is not readable__</b>"; } $this->filecache[$file] = $file_text; } return $file_text; } /** * recursively gets the content of a file with {FILE "filename.tpl"} directives * * @access public - aiming for private * @param string $file * @return string */ public function _r_getfile ($file) { $text = $this->_getfile($file); $res = array(); while (preg_match($this->file_delim,$text,$res)) { $text2 = $this->_getfile($res[1]); $text = preg_replace("'".preg_quote($res[0])."'",$text2,$text); } return $text; } /** * add an outer block delimiter set useful for rtfs etc - keeps them editable in word * * @access private */ private function _add_outer_block () { $before = $this->block_start_delim . $this->block_start_word . ' ' . $this->mainblock . ' ' . $this->block_end_delim; $after = $this->block_start_delim . $this->block_end_word . ' ' . $this->mainblock . ' ' . $this->block_end_delim; $this->filecontents = $before . "\n" . $this->filecontents . "\n" . $after; } /** * Debug function - var_dump wrapped in '<pre></pre>' tags * * @access private * @param multiple var_dumps all the supplied arguments */ private function _pre_var_dump ($args) { if ($this->debug) { echo '<pre>'; var_dump(func_get_args()); echo '</pre>'; } } } /* end of XTemplate class. */ ?>
aleph3d/MiniMediaEducation
MasterServer/MSmmc-ps/plugins/plg-template/lib/xtemplate.class.php
PHP
mit
35,089
module Sunspot #:nodoc: module Rails #:nodoc: # # This module adds an after_filter to ActionController::Base that commits # the Sunspot session if any documents have been added, changed, or removed # in the course of the request. # module RequestLifecycle class <<self def included(base) #:nodoc: subclasses = base.subclasses.map do |subclass| begin subclass.constantize rescue NameError end end.compact loaded_controllers = [base].concat(subclasses) # Depending on how Sunspot::Rails is loaded, there may already be # controllers loaded into memory that subclass this controller. In # this case, since after_filter uses the inheritable_attribute # structure, the already-loaded subclasses don't get the filters. So, # the below ensures that all loaded controllers have the filter. loaded_controllers.each do |controller| controller.after_filter do if Sunspot::Rails.configuration.auto_commit_after_request? Sunspot.commit_if_dirty elsif Sunspot::Rails.configuration.auto_commit_after_delete_request? Sunspot.commit_if_delete_dirty end end end end end end end end
omarramos/sunspot_rails-temp
lib/sunspot/rails/request_lifecycle.rb
Ruby
mit
1,373
--TEST-- ldap_search() - operation that should fail --CREDITS-- Davide Mendolia <idaf1er@gmail.com> Belgian PHP Testfest 2009 --SKIPIF-- <?php require_once dirname(__FILE__) .'/skipif.inc'; ?> <?php require_once dirname(__FILE__) .'/skipifbindfailure.inc'; ?> --FILE-- <?php include "connect.inc"; $link = ldap_connect($host, $port); $dn = "dc=not-found,$base"; $filter = "(dc=*)"; $result = ldap_search(); var_dump($result); $result = ldap_search($link, $dn, $filter); var_dump($result); $result = ldap_search($link, $dn, $filter, NULL); var_dump($result); $result = ldap_search($link, $dn, $filter, array(1 => 'top')); var_dump($result); $result = ldap_search(array(), $dn, $filter, array('top')); var_dump($result); $result = ldap_search(array($link, $link), array($dn), $filter, array('top')); var_dump($result); $result = ldap_search(array($link, $link), $dn, array($filter), array('top')); var_dump($result); ?> ===DONE=== --EXPECTF-- Warning: ldap_search() expects at least 3 parameters, 0 given in %s on line %d NULL Warning: ldap_search(): Search: No such object in %s on line %d bool(false) Warning: ldap_search() expects parameter 4 to be array, null given in %s on line %d NULL Warning: ldap_search(): Array initialization wrong in %s on line %d bool(false) Warning: ldap_search(): No links in link array in %s on line %d bool(false) Warning: ldap_search(): Base must either be a string, or an array with the same number of elements as the links array in %s on line %d bool(false) Warning: ldap_search(): Filter must either be a string, or an array with the same number of elements as the links array in %s on line %d bool(false) ===DONE===
lunaczp/learning
language/c/testPhpSrc/php-5.6.17/ext/ldap/tests/ldap_search_error.phpt
PHP
mit
1,668
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\View; class DesignLoader { /** * Request * * @var \Magento\Framework\App\RequestInterface */ protected $_request; /** * Application * * @var \Magento\Framework\App\AreaList */ protected $_areaList; /** * Layout * * @var \Magento\Framework\App\State */ protected $appState; /** * @param \Magento\Framework\App\RequestInterface $request * @param \Magento\Framework\App\AreaList $areaList * @param \Magento\Framework\App\State $appState */ public function __construct( \Magento\Framework\App\RequestInterface $request, \Magento\Framework\App\AreaList $areaList, \Magento\Framework\App\State $appState ) { $this->_request = $request; $this->_areaList = $areaList; $this->appState = $appState; } /** * Load design * * @return void */ public function load() { $area = $this->_areaList->getArea($this->appState->getAreaCode()); $area->load(\Magento\Framework\App\Area::PART_DESIGN); $area->load(\Magento\Framework\App\Area::PART_TRANSLATE); $area->detectDesign($this->_request); } }
j-froehlich/magento2_wk
vendor/magento/framework/View/DesignLoader.php
PHP
mit
1,360
/** * Fixes an issue with Bootstrap Date Picker * @see https://github.com/angular-ui/bootstrap/issues/2659 * * How does it work? AngularJS allows multiple directives with the same name, * and each is treated independently though they are instantiated based on the * same element/attribute/comment. * * So this directive goes along with ui.bootstrap's datepicker-popup directive. * @see http://angular-ui.github.io/bootstrap/versioned-docs/0.12.0/#/datepicker */ export default function datepickerPopup() { return { restrict: 'EAC', require: 'ngModel', link: function(scope, element, attr, controller) { //remove the default formatter from the input directive to prevent conflict controller.$formatters.shift(); } }; } datepickerPopup.$inject = [];
manekinekko/ng-admin
src/javascripts/ng-admin/Crud/field/datepickerPopup.js
JavaScript
mit
823
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datamigration.v2018_03_31_preview; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * Database specific information for SQL to SQL migration task inputs. */ public class MigrateSqlServerSqlServerDatabaseInput { /** * Name of the database. */ @JsonProperty(value = "name") private String name; /** * Name of the database at destination. */ @JsonProperty(value = "restoreDatabaseName") private String restoreDatabaseName; /** * Backup file share information for this database. */ @JsonProperty(value = "backupFileShare") private FileShare backupFileShare; /** * The list of database files. */ @JsonProperty(value = "databaseFiles") private List<DatabaseFileInput> databaseFiles; /** * Get name of the database. * * @return the name value */ public String name() { return this.name; } /** * Set name of the database. * * @param name the name value to set * @return the MigrateSqlServerSqlServerDatabaseInput object itself. */ public MigrateSqlServerSqlServerDatabaseInput withName(String name) { this.name = name; return this; } /** * Get name of the database at destination. * * @return the restoreDatabaseName value */ public String restoreDatabaseName() { return this.restoreDatabaseName; } /** * Set name of the database at destination. * * @param restoreDatabaseName the restoreDatabaseName value to set * @return the MigrateSqlServerSqlServerDatabaseInput object itself. */ public MigrateSqlServerSqlServerDatabaseInput withRestoreDatabaseName(String restoreDatabaseName) { this.restoreDatabaseName = restoreDatabaseName; return this; } /** * Get backup file share information for this database. * * @return the backupFileShare value */ public FileShare backupFileShare() { return this.backupFileShare; } /** * Set backup file share information for this database. * * @param backupFileShare the backupFileShare value to set * @return the MigrateSqlServerSqlServerDatabaseInput object itself. */ public MigrateSqlServerSqlServerDatabaseInput withBackupFileShare(FileShare backupFileShare) { this.backupFileShare = backupFileShare; return this; } /** * Get the list of database files. * * @return the databaseFiles value */ public List<DatabaseFileInput> databaseFiles() { return this.databaseFiles; } /** * Set the list of database files. * * @param databaseFiles the databaseFiles value to set * @return the MigrateSqlServerSqlServerDatabaseInput object itself. */ public MigrateSqlServerSqlServerDatabaseInput withDatabaseFiles(List<DatabaseFileInput> databaseFiles) { this.databaseFiles = databaseFiles; return this; } }
navalev/azure-sdk-for-java
sdk/datamigration/mgmt-v2018_03_31_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_03_31_preview/MigrateSqlServerSqlServerDatabaseInput.java
Java
mit
3,305
/* YUI 3.7.2 (build 5639) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('editor-base', function (Y, NAME) { /** * Base class for Editor. Handles the business logic of Editor, no GUI involved only utility methods and events. * * var editor = new Y.EditorBase({ * content: 'Foo' * }); * editor.render('#demo'); * * @class EditorBase * @extends Base * @module editor * @main editor * @submodule editor-base * @constructor */ var EditorBase = function() { EditorBase.superclass.constructor.apply(this, arguments); }, LAST_CHILD = ':last-child', BODY = 'body'; Y.extend(EditorBase, Y.Base, { /** * Internal reference to the Y.Frame instance * @property frame */ frame: null, initializer: function() { var frame = new Y.Frame({ designMode: true, title: EditorBase.STRINGS.title, use: EditorBase.USE, dir: this.get('dir'), extracss: this.get('extracss'), linkedcss: this.get('linkedcss'), defaultblock: this.get('defaultblock'), host: this }).plug(Y.Plugin.ExecCommand); frame.after('ready', Y.bind(this._afterFrameReady, this)); frame.addTarget(this); this.frame = frame; this.publish('nodeChange', { emitFacade: true, bubbles: true, defaultFn: this._defNodeChangeFn }); //this.plug(Y.Plugin.EditorPara); }, destructor: function() { this.frame.destroy(); this.detachAll(); }, /** * Copy certain styles from one node instance to another (used for new paragraph creation mainly) * @method copyStyles * @param {Node} from The Node instance to copy the styles from * @param {Node} to The Node instance to copy the styles to */ copyStyles: function(from, to) { if (from.test('a')) { //Don't carry the A styles return; } var styles = ['color', 'fontSize', 'fontFamily', 'backgroundColor', 'fontStyle' ], newStyles = {}; Y.each(styles, function(v) { newStyles[v] = from.getStyle(v); }); if (from.ancestor('b,strong')) { newStyles.fontWeight = 'bold'; } if (from.ancestor('u')) { if (!newStyles.textDecoration) { newStyles.textDecoration = 'underline'; } } to.setStyles(newStyles); }, /** * Holder for the selection bookmark in IE. * @property _lastBookmark * @private */ _lastBookmark: null, /** * Resolves the e.changedNode in the nodeChange event if it comes from the document. If * the event came from the document, it will get the last child of the last child of the document * and return that instead. * @method _resolveChangedNode * @param {Node} n The node to resolve * @private */ _resolveChangedNode: function(n) { var inst = this.getInstance(), lc, lc2, found; if (n && n.test(BODY)) { var sel = new inst.EditorSelection(); if (sel && sel.anchorNode) { n = sel.anchorNode; } } if (inst && n && n.test('html')) { lc = inst.one(BODY).one(LAST_CHILD); while (!found) { if (lc) { lc2 = lc.one(LAST_CHILD); if (lc2) { lc = lc2; } else { found = true; } } else { found = true; } } if (lc) { if (lc.test('br')) { if (lc.previous()) { lc = lc.previous(); } else { lc = lc.get('parentNode'); } } if (lc) { n = lc; } } } if (!n) { //Fallback to make sure a node is attached to the event n = inst.one(BODY); } return n; }, /** * The default handler for the nodeChange event. * @method _defNodeChangeFn * @param {Event} e The event * @private */ _defNodeChangeFn: function(e) { var startTime = (new Date()).getTime(); //Y.log('Default nodeChange function: ' + e.changedType, 'info', 'editor'); var inst = this.getInstance(), sel, cur, btag = inst.EditorSelection.DEFAULT_BLOCK_TAG; if (Y.UA.ie) { try { sel = inst.config.doc.selection.createRange(); if (sel.getBookmark) { this._lastBookmark = sel.getBookmark(); } } catch (ie) {} } e.changedNode = this._resolveChangedNode(e.changedNode); /* * @TODO * This whole method needs to be fixed and made more dynamic. * Maybe static functions for the e.changeType and an object bag * to walk through and filter to pass off the event to before firing.. */ switch (e.changedType) { case 'keydown': if (!Y.UA.gecko) { if (!EditorBase.NC_KEYS[e.changedEvent.keyCode] && !e.changedEvent.shiftKey && !e.changedEvent.ctrlKey && (e.changedEvent.keyCode !== 13)) { //inst.later(100, inst, inst.EditorSelection.cleanCursor); } } break; case 'tab': if (!e.changedNode.test('li, li *') && !e.changedEvent.shiftKey) { e.changedEvent.frameEvent.preventDefault(); Y.log('Overriding TAB key to insert HTML: HALTING', 'info', 'editor'); if (Y.UA.webkit) { this.execCommand('inserttext', '\t'); } else if (Y.UA.gecko) { this.frame.exec._command('inserthtml', EditorBase.TABKEY); } else if (Y.UA.ie) { this.execCommand('inserthtml', EditorBase.TABKEY); } } break; case 'backspace-up': // Fixes #2531090 - Joins text node strings so they become one for bidi if (Y.UA.webkit && e.changedNode) { e.changedNode.set('innerHTML', e.changedNode.get('innerHTML')); } break; } if (Y.UA.webkit && e.commands && (e.commands.indent || e.commands.outdent)) { /* * When executing execCommand 'indent or 'outdent' Webkit applies * a class to the BLOCKQUOTE that adds left/right margin to it * This strips that style so it is just a normal BLOCKQUOTE */ var bq = inst.all('.webkit-indent-blockquote, blockquote'); if (bq.size()) { bq.setStyle('margin', ''); } } var changed = this.getDomPath(e.changedNode, false), cmds = {}, family, fsize, classes = [], fColor = '', bColor = ''; if (e.commands) { cmds = e.commands; } var normal = false; Y.each(changed, function(el) { var tag = el.tagName.toLowerCase(), cmd = EditorBase.TAG2CMD[tag]; if (cmd) { cmds[cmd] = 1; } //Bold and Italic styles var s = el.currentStyle || el.style; if ((''+s.fontWeight) == 'normal') { normal = true; } if ((''+s.fontWeight) == 'bold') { //Cast this to a string cmds.bold = 1; } if (Y.UA.ie) { if (s.fontWeight > 400) { cmds.bold = 1; } } if (s.fontStyle == 'italic') { cmds.italic = 1; } if (s.textDecoration.indexOf('underline') > -1) { cmds.underline = 1; } if (s.textDecoration.indexOf('line-through') > -1) { cmds.strikethrough = 1; } var n = inst.one(el); if (n.getStyle('fontFamily')) { var family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase(); if (family2) { family = family2; } if (family) { family = family.replace(/'/g, '').replace(/"/g, ''); } } fsize = EditorBase.NORMALIZE_FONTSIZE(n); var cls = el.className.split(' '); Y.each(cls, function(v) { if (v !== '' && (v.substr(0, 4) !== 'yui_')) { classes.push(v); } }); fColor = EditorBase.FILTER_RGB(n.getStyle('color')); var bColor2 = EditorBase.FILTER_RGB(s.backgroundColor); if (bColor2 !== 'transparent') { if (bColor2 !== '') { bColor = bColor2; } } }); if (normal) { delete cmds.bold; delete cmds.italic; } e.dompath = inst.all(changed); e.classNames = classes; e.commands = cmds; //TODO Dont' like this, not dynamic enough.. if (!e.fontFamily) { e.fontFamily = family; } if (!e.fontSize) { e.fontSize = fsize; } if (!e.fontColor) { e.fontColor = fColor; } if (!e.backgroundColor) { e.backgroundColor = bColor; } var endTime = (new Date()).getTime(); Y.log('_defNodeChangeTimer 2: ' + (endTime - startTime) + 'ms', 'info', 'selection'); }, /** * Walk the dom tree from this node up to body, returning a reversed array of parents. * @method getDomPath * @param {Node} node The Node to start from */ getDomPath: function(node, nodeList) { var domPath = [], domNode, inst = this.frame.getInstance(); domNode = inst.Node.getDOMNode(node); //return inst.all(domNode); while (domNode !== null) { if ((domNode === inst.config.doc.documentElement) || (domNode === inst.config.doc) || !domNode.tagName) { domNode = null; break; } if (!inst.DOM.inDoc(domNode)) { domNode = null; break; } //Check to see if we get el.nodeName and nodeType if (domNode.nodeName && domNode.nodeType && (domNode.nodeType == 1)) { domPath.push(domNode); } if (domNode == inst.config.doc.body) { domNode = null; break; } domNode = domNode.parentNode; } /*{{{ Using Node while (node !== null) { if (node.test('html') || node.test('doc') || !node.get('tagName')) { node = null; break; } if (!node.inDoc()) { node = null; break; } //Check to see if we get el.nodeName and nodeType if (node.get('nodeName') && node.get('nodeType') && (node.get('nodeType') == 1)) { domPath.push(inst.Node.getDOMNode(node)); } if (node.test('body')) { node = null; break; } node = node.get('parentNode'); } }}}*/ if (domPath.length === 0) { domPath[0] = inst.config.doc.body; } if (nodeList) { return inst.all(domPath.reverse()); } else { return domPath.reverse(); } }, /** * After frame ready, bind mousedown & keyup listeners * @method _afterFrameReady * @private */ _afterFrameReady: function() { var inst = this.frame.getInstance(); this.frame.on('dom:mouseup', Y.bind(this._onFrameMouseUp, this)); this.frame.on('dom:mousedown', Y.bind(this._onFrameMouseDown, this)); this.frame.on('dom:keydown', Y.bind(this._onFrameKeyDown, this)); if (Y.UA.ie) { this.frame.on('dom:activate', Y.bind(this._onFrameActivate, this)); this.frame.on('dom:beforedeactivate', Y.bind(this._beforeFrameDeactivate, this)); } this.frame.on('dom:keyup', Y.bind(this._onFrameKeyUp, this)); this.frame.on('dom:keypress', Y.bind(this._onFrameKeyPress, this)); this.frame.on('dom:paste', Y.bind(this._onPaste, this)); inst.EditorSelection.filter(); this.fire('ready'); }, /** * Caches the current cursor position in IE. * @method _beforeFrameDeactivate * @private */ _beforeFrameDeactivate: function(e) { if (e.frameTarget.test('html')) { //Means it came from a scrollbar return; } var inst = this.getInstance(), sel = inst.config.doc.selection.createRange(); if (sel.compareEndPoints && !sel.compareEndPoints('StartToEnd', sel)) { sel.pasteHTML('<var id="yui-ie-cursor">'); } }, /** * Moves the cached selection bookmark back so IE can place the cursor in the right place. * @method _onFrameActivate * @private */ _onFrameActivate: function(e) { if (e.frameTarget.test('html')) { //Means it came from a scrollbar return; } var inst = this.getInstance(), sel = new inst.EditorSelection(), range = sel.createRange(), cur = inst.all('#yui-ie-cursor'); if (cur.size()) { cur.each(function(n) { n.set('id', ''); if (range.moveToElementText) { try { range.moveToElementText(n._node); var moved = range.move('character', -1); if (moved === -1) { //Only move up if we actually moved back. range.move('character', 1); } range.select(); range.text = ''; } catch (e) {} } n.remove(); }); } }, /** * Fires nodeChange event * @method _onPaste * @private */ _onPaste: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'paste', changedEvent: e.frameEvent }); }, /** * Fires nodeChange event * @method _onFrameMouseUp * @private */ _onFrameMouseUp: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent }); }, /** * Fires nodeChange event * @method _onFrameMouseDown * @private */ _onFrameMouseDown: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent }); }, /** * Caches a copy of the selection for key events. Only creating the selection on keydown * @property _currentSelection * @private */ _currentSelection: null, /** * Holds the timer for selection clearing * @property _currentSelectionTimer * @private */ _currentSelectionTimer: null, /** * Flag to determine if we can clear the selection or not. * @property _currentSelectionClear * @private */ _currentSelectionClear: null, /** * Fires nodeChange event * @method _onFrameKeyDown * @private */ _onFrameKeyDown: function(e) { var inst, sel; if (!this._currentSelection) { if (this._currentSelectionTimer) { this._currentSelectionTimer.cancel(); } this._currentSelectionTimer = Y.later(850, this, function() { this._currentSelectionClear = true; }); inst = this.frame.getInstance(); sel = new inst.EditorSelection(e); this._currentSelection = sel; } else { sel = this._currentSelection; } inst = this.frame.getInstance(); sel = new inst.EditorSelection(); this._currentSelection = sel; if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode], changedEvent: e.frameEvent }); this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-down', changedEvent: e.frameEvent }); } } }, /** * Fires nodeChange event * @method _onFrameKeyPress * @private */ _onFrameKeyPress: function(e) { var sel = this._currentSelection; if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-press', changedEvent: e.frameEvent }); } } }, /** * Fires nodeChange event for keyup on specific keys * @method _onFrameKeyUp * @private */ _onFrameKeyUp: function(e) { var inst = this.frame.getInstance(), sel = new inst.EditorSelection(e); if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keyup', selection: sel, changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-up', selection: sel, changedEvent: e.frameEvent }); } } if (this._currentSelectionClear) { this._currentSelectionClear = this._currentSelection = null; } }, /** * Pass through to the frame.execCommand method * @method execCommand * @param {String} cmd The command to pass: inserthtml, insertimage, bold * @param {String} val The optional value of the command: Helvetica * @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands. */ execCommand: function(cmd, val) { var ret = this.frame.execCommand(cmd, val), inst = this.frame.getInstance(), sel = new inst.EditorSelection(), cmds = {}, e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret }; switch (cmd) { case 'forecolor': e.fontColor = val; break; case 'backcolor': e.backgroundColor = val; break; case 'fontsize': e.fontSize = val; break; case 'fontname': e.fontFamily = val; break; } cmds[cmd] = 1; e.commands = cmds; this.fire('nodeChange', e); return ret; }, /** * Get the YUI instance of the frame * @method getInstance * @return {YUI} The YUI instance bound to the frame. */ getInstance: function() { return this.frame.getInstance(); }, /** * Renders the Y.Frame to the passed node. * @method render * @param {Selector/HTMLElement/Node} node The node to append the Editor to * @return {EditorBase} * @chainable */ render: function(node) { this.frame.set('content', this.get('content')); this.frame.render(node); return this; }, /** * Focus the contentWindow of the iframe * @method focus * @param {Function} fn Callback function to execute after focus happens * @return {EditorBase} * @chainable */ focus: function(fn) { this.frame.focus(fn); return this; }, /** * Handles the showing of the Editor instance. Currently only handles the iframe * @method show * @return {EditorBase} * @chainable */ show: function() { this.frame.show(); return this; }, /** * Handles the hiding of the Editor instance. Currently only handles the iframe * @method hide * @return {EditorBase} * @chainable */ hide: function() { this.frame.hide(); return this; }, /** * (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering * @method getContent * @return {String} The filtered content of the Editor */ getContent: function() { var html = '', inst = this.getInstance(); if (inst && inst.EditorSelection) { html = inst.EditorSelection.unfilter(); } //Removing the _yuid from the objects in IE html = html.replace(/ _yuid="([^>]*)"/g, ''); return html; } }, { /** * @static * @method NORMALIZE_FONTSIZE * @description Pulls the fontSize from a node, then checks for string values (x-large, x-small) * and converts them to pixel sizes. If the parsed size is different from the original, it calls * node.setStyle to update the node with a pixel size for normalization. */ NORMALIZE_FONTSIZE: function(n) { var size = n.getStyle('fontSize'), oSize = size; switch (size) { case '-webkit-xxx-large': size = '48px'; break; case 'xx-large': size = '32px'; break; case 'x-large': size = '24px'; break; case 'large': size = '18px'; break; case 'medium': size = '16px'; break; case 'small': size = '13px'; break; case 'x-small': size = '10px'; break; } if (oSize !== size) { n.setStyle('fontSize', size); } return size; }, /** * @static * @property TABKEY * @description The HTML markup to use for the tabkey */ TABKEY: '<span class="tab">&nbsp;&nbsp;&nbsp;&nbsp;</span>', /** * @static * @method FILTER_RGB * @param String css The CSS string containing rgb(#,#,#); * @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00 * @return String */ FILTER_RGB: function(css) { if (css.toLowerCase().indexOf('rgb') != -1) { var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"); var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','); if (rgb.length == 5) { var r = parseInt(rgb[1], 10).toString(16); var g = parseInt(rgb[2], 10).toString(16); var b = parseInt(rgb[3], 10).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; css = "#" + r + g + b; } } return css; }, /** * @static * @property TAG2CMD * @description A hash table of tags to their execcomand's */ TAG2CMD: { 'b': 'bold', 'strong': 'bold', 'i': 'italic', 'em': 'italic', 'u': 'underline', 'sup': 'superscript', 'sub': 'subscript', 'img': 'insertimage', 'a' : 'createlink', 'ul' : 'insertunorderedlist', 'ol' : 'insertorderedlist' }, /** * Hash table of keys to fire a nodeChange event for. * @static * @property NC_KEYS * @type Object */ NC_KEYS: { 8: 'backspace', 9: 'tab', 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 46: 'delete' }, /** * The default modules to use inside the Frame * @static * @property USE * @type Array */ USE: ['substitute', 'node', 'selector-css3', 'editor-selection', 'stylesheet'], /** * The Class Name: editorBase * @static * @property NAME */ NAME: 'editorBase', /** * Editor Strings. By default contains only the `title` property for the * Title of frame document (default "Rich Text Editor"). * * @static * @property STRINGS */ STRINGS: { title: 'Rich Text Editor' }, ATTRS: { /** * The content to load into the Editor Frame * @attribute content */ content: { value: '<br class="yui-cursor">', setter: function(str) { if (str.substr(0, 1) === "\n") { Y.log('Stripping first carriage return from content before injecting', 'warn', 'editor'); str = str.substr(1); } if (str === '') { str = '<br class="yui-cursor">'; } if (str === ' ') { if (Y.UA.gecko) { str = '<br class="yui-cursor">'; } } return this.frame.set('content', str); }, getter: function() { return this.frame.get('content'); } }, /** * The value of the dir attribute on the HTML element of the frame. Default: ltr * @attribute dir */ dir: { writeOnce: true, value: 'ltr' }, /** * @attribute linkedcss * @description An array of url's to external linked style sheets * @type String */ linkedcss: { value: '', setter: function(css) { if (this.frame) { this.frame.set('linkedcss', css); } return css; } }, /** * @attribute extracss * @description A string of CSS to add to the Head of the Editor * @type String */ extracss: { value: false, setter: function(css) { if (this.frame) { this.frame.set('extracss', css); } return css; } }, /** * @attribute defaultblock * @description The default tag to use for block level items, defaults to: p * @type String */ defaultblock: { value: 'p' } } }); Y.EditorBase = EditorBase; /** * @event nodeChange * @description Fired from several mouse/key/paste event points. * @param {Event.Facade} event An Event Facade object with the following specific properties added: * <dl> * <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd> * <dt>changedNode</dt><dd>The node that was interacted with</dd> * <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd> * <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd> * <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd> * <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd> * <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd> * <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd> * <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd> * <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd> * </dl> * @type {Event.Custom} */ /** * @event ready * @description Fired after the frame is ready. * @param {Event.Facade} event An Event Facade object. * @type {Event.Custom} */ }, '3.7.2', {"requires": ["base", "frame", "node", "exec-command", "editor-selection"]});
spadin/coverphoto
node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/editor-base/editor-base-debug.js
JavaScript
mit
32,357
// Copyright (c) The HLSL2GLSLFork Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE.txt file. #include "localintermediate.h" // // Two purposes: // 1. Show an example of how to iterate tree. Functions can // also directly call Traverse() on children themselves to // have finer grained control over the process than shown here. // See the last function for how to get started. // 2. Print out a text based description of the tree. // // // Use this class to carry along data from node to node in // the traversal // class TOutputTraverser : public TIntermTraverser { public: TOutputTraverser(TInfoSink& i) : infoSink(i) { } TInfoSink& infoSink; }; TString TType::getCompleteString() const { char buf[100]; char *p = &buf[0]; if (qualifier != EvqTemporary && qualifier != EvqGlobal) p += sprintf(p, "%s ", getQualifierString()); sprintf(p, "%s", getBasicString()); if (array) p += sprintf(p, " array"); if (matrix) p += sprintf(p, "matrix%dX%d", matcols, matrows); else if (matrows > 1) p += sprintf(p, "vec%d", matrows); return TString(buf); } // // Helper functions for printing, not part of traversing. // void OutputTreeText(TInfoSink& infoSink, TIntermNode* node, const int depth) { int i; infoSink.debug << node->getLine(); for (i = 0; i < depth; ++i) infoSink.debug << " "; } // // The rest of the file are the traversal functions. The last one // is the one that starts the traversal. // // Return true from interior nodes to have the external traversal // continue on to children. If you process children yourself, // return false. // void OutputSymbol(TIntermSymbol* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); OutputTreeText(oit->infoSink, node, oit->depth); char buf[100]; sprintf(buf, "'%s' (%s)\n", node->getSymbol().c_str(), node->getCompleteString().c_str()); oit->infoSink.debug << buf; } bool OutputBinary(bool, /* preVisit */ TIntermBinary* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); switch (node->getOp()) { case EOpAssign: out.debug << "="; break; case EOpAddAssign: out.debug << "+="; break; case EOpSubAssign: out.debug << "-="; break; case EOpMulAssign: out.debug << "*="; break; case EOpVectorTimesMatrixAssign: out.debug << "vec *= matrix"; break; case EOpVectorTimesScalarAssign: out.debug << "vec *= scalar"; break; case EOpMatrixTimesScalarAssign: out.debug << "matrix *= scalar"; break; case EOpMatrixTimesMatrixAssign: out.debug << "matrix *= matrix"; break; case EOpDivAssign: out.debug << "/="; break; case EOpModAssign: out.debug << "%="; break; case EOpAndAssign: out.debug << "&="; break; case EOpInclusiveOrAssign: out.debug << "|="; break; case EOpExclusiveOrAssign: out.debug << "^="; break; case EOpLeftShiftAssign: out.debug << "<<="; break; case EOpRightShiftAssign: out.debug << ">>="; break; case EOpIndexDirect: out.debug << "index"; break; case EOpIndexIndirect: out.debug << "indirect index"; break; case EOpIndexDirectStruct: out.debug << "struct index"; break; case EOpVectorSwizzle: out.debug << "swizzle"; break; case EOpAdd: out.debug << "+"; break; case EOpSub: out.debug << "-"; break; case EOpMul: out.debug << "*"; break; case EOpDiv: out.debug << "/"; break; case EOpMod: out.debug << "%"; break; case EOpRightShift: out.debug << ">>"; break; case EOpLeftShift: out.debug << "<<"; break; case EOpAnd: out.debug << "&"; break; case EOpInclusiveOr: out.debug << "|"; break; case EOpExclusiveOr: out.debug << "^"; break; case EOpEqual: out.debug << "=="; break; case EOpNotEqual: out.debug << "!="; break; case EOpLessThan: out.debug << "<"; break; case EOpGreaterThan: out.debug << ">"; break; case EOpLessThanEqual: out.debug << "<="; break; case EOpGreaterThanEqual: out.debug << ">="; break; case EOpVectorTimesScalar: out.debug << "vec*scalar"; break; case EOpVectorTimesMatrix: out.debug << "vec*matrix"; break; case EOpMatrixTimesVector: out.debug << "matrix*vec"; break; case EOpMatrixTimesScalar: out.debug << "matrix*scalar"; break; case EOpMatrixTimesMatrix: out.debug << "matrix*matrix"; break; case EOpLogicalOr: out.debug << "||"; break; case EOpLogicalXor: out.debug << "^^"; break; case EOpLogicalAnd: out.debug << "&&"; break; default: out.debug << "<unknown op>"; } out.debug << " (" << node->getCompleteString() << ")"; out.debug << "\n"; return true; } bool OutputUnary(bool, /* preVisit */ TIntermUnary* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); switch (node->getOp()) { case EOpNegative: out.debug << "Negate value"; break; case EOpVectorLogicalNot: case EOpLogicalNot: out.debug << "Negate conditional"; break; case EOpBitwiseNot: out.debug << "Bitwise not"; break; case EOpPostIncrement: out.debug << "Post-Increment"; break; case EOpPostDecrement: out.debug << "Post-Decrement"; break; case EOpPreIncrement: out.debug << "Pre-Increment"; break; case EOpPreDecrement: out.debug << "Pre-Decrement"; break; case EOpConvIntToBool: out.debug << "Convert int to bool"; break; case EOpConvFloatToBool:out.debug << "Convert float to bool";break; case EOpConvBoolToFloat:out.debug << "Convert bool to float";break; case EOpConvIntToFloat: out.debug << "Convert int to float"; break; case EOpConvFloatToInt: out.debug << "Convert float to int"; break; case EOpConvBoolToInt: out.debug << "Convert bool to int"; break; case EOpRadians: out.debug << "radians"; break; case EOpDegrees: out.debug << "degrees"; break; case EOpSin: out.debug << "sine"; break; case EOpCos: out.debug << "cosine"; break; case EOpTan: out.debug << "tangent"; break; case EOpAsin: out.debug << "arc sine"; break; case EOpAcos: out.debug << "arc cosine"; break; case EOpAtan: out.debug << "arc tangent"; break; case EOpAtan2: out.debug << "arc tangent 2"; break; case EOpExp: out.debug << "exp"; break; case EOpLog: out.debug << "log"; break; case EOpExp2: out.debug << "exp2"; break; case EOpLog2: out.debug << "log2"; break; case EOpLog10: out.debug << "log10"; break; case EOpSqrt: out.debug << "sqrt"; break; case EOpInverseSqrt: out.debug << "inverse sqrt"; break; case EOpAbs: out.debug << "Absolute value"; break; case EOpSign: out.debug << "Sign"; break; case EOpFloor: out.debug << "Floor"; break; case EOpCeil: out.debug << "Ceiling"; break; case EOpFract: out.debug << "Fraction"; break; case EOpLength: out.debug << "length"; break; case EOpNormalize: out.debug << "normalize"; break; case EOpDPdx: out.debug << "dPdx"; break; case EOpDPdy: out.debug << "dPdy"; break; case EOpFwidth: out.debug << "fwidth"; break; case EOpFclip: out.debug << "clip"; break; case EOpAny: out.debug << "any"; break; case EOpAll: out.debug << "all"; break; case EOpD3DCOLORtoUBYTE4: out.debug << "D3DCOLORtoUBYTE4"; break; default: out.debug.message(EPrefixError, "Bad unary op"); } out.debug << " (" << node->getCompleteString() << ")"; out.debug << "\n"; return true; } bool OutputAggregate(bool, /* preVisit */ TIntermAggregate* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; if (node->getOp() == EOpNull) { out.debug.message(EPrefixError, "node is still EOpNull!"); return true; } OutputTreeText(out, node, oit->depth); switch (node->getOp()) { case EOpSequence: out.debug << "Sequence\n"; return true; case EOpComma: out.debug << "Comma\n"; return true; case EOpFunction: out.debug << "Func Def: " << node->getName(); break; case EOpFunctionCall: out.debug << "Func Call: " << node->getName(); break; case EOpParameters: out.debug << "Func Params: "; break; case EOpConstructFloat: out.debug << "Construct float"; break; case EOpConstructVec2: out.debug << "Construct vec2"; break; case EOpConstructVec3: out.debug << "Construct vec3"; break; case EOpConstructVec4: out.debug << "Construct vec4"; break; case EOpConstructBool: out.debug << "Construct bool"; break; case EOpConstructBVec2: out.debug << "Construct bvec2"; break; case EOpConstructBVec3: out.debug << "Construct bvec3"; break; case EOpConstructBVec4: out.debug << "Construct bvec4"; break; case EOpConstructInt: out.debug << "Construct int"; break; case EOpConstructIVec2: out.debug << "Construct ivec2"; break; case EOpConstructIVec3: out.debug << "Construct ivec3"; break; case EOpConstructIVec4: out.debug << "Construct ivec4"; break; case EOpConstructMat2x2: out.debug << "Construct mat2x2"; break; case EOpConstructMat2x3: out.debug << "Construct mat2x3"; break; case EOpConstructMat2x4: out.debug << "Construct mat2x4"; break; case EOpConstructMat3x2: out.debug << "Construct mat3x2"; break; case EOpConstructMat3x3: out.debug << "Construct mat3x3"; break; case EOpConstructMat3x4: out.debug << "Construct mat3x4"; break; case EOpConstructMat4x2: out.debug << "Construct mat4x2"; break; case EOpConstructMat4x3: out.debug << "Construct mat4x3"; break; case EOpConstructMat4x4: out.debug << "Construct mat4x4"; break; case EOpConstructStruct: out.debug << "Construct struc"; break; case EOpConstructMat2x2FromMat: out.debug << "Construct mat2 from mat"; break; case EOpConstructMat3x3FromMat: out.debug << "Construct mat3 from mat"; break; case EOpMatrixIndex: out.debug << "Matrix index"; break; case EOpMatrixIndexDynamic: out.debug << "Matrix index dynamic"; break; case EOpLessThan: out.debug << "Compare Less Than"; break; case EOpGreaterThan: out.debug << "Compare Greater Than"; break; case EOpLessThanEqual: out.debug << "Compare Less Than or Equal"; break; case EOpGreaterThanEqual: out.debug << "Compare Greater Than or Equal"; break; case EOpVectorEqual: out.debug << "Equal"; break; case EOpVectorNotEqual: out.debug << "NotEqual"; break; case EOpMod: out.debug << "mod"; break; case EOpPow: out.debug << "pow"; break; case EOpAtan: out.debug << "atan"; break; case EOpAtan2: out.debug << "atan2"; break; case EOpSinCos: out.debug << "sincos"; break; case EOpMin: out.debug << "min"; break; case EOpMax: out.debug << "max"; break; case EOpClamp: out.debug << "clamp"; break; case EOpMix: out.debug << "mix"; break; case EOpStep: out.debug << "step"; break; case EOpSmoothStep: out.debug << "smoothstep"; break; case EOpLit: out.debug << "lit"; break; case EOpDistance: out.debug << "distance"; break; case EOpDot: out.debug << "dot"; break; case EOpCross: out.debug << "cross"; break; case EOpFaceForward: out.debug << "faceforward"; break; case EOpReflect: out.debug << "reflect"; break; case EOpRefract: out.debug << "refract"; break; case EOpMul: out.debug << "mul"; break; case EOpTex1D: out.debug << "tex1D"; break; case EOpTex1DProj: out.debug << "tex1Dproj"; break; case EOpTex1DLod: out.debug << "tex1Dlod"; break; case EOpTex1DBias: out.debug << "tex1Dbias"; break; case EOpTex1DGrad: out.debug << "tex1Dgrad"; break; case EOpTex2D: out.debug << "tex2D"; break; case EOpTex2DProj: out.debug << "tex2Dproj"; break; case EOpTex2DLod: out.debug << "tex2Dlod"; break; case EOpTex2DBias: out.debug << "tex2Dbias"; break; case EOpTex2DGrad: out.debug << "tex2Dgrad"; break; case EOpTex3D: out.debug << "tex3D"; break; case EOpTex3DProj: out.debug << "tex3Dproj"; break; case EOpTex3DLod: out.debug << "tex3Dlod"; break; case EOpTex3DBias: out.debug << "tex3Dbias"; break; case EOpTex3DGrad: out.debug << "tex3Dgrad"; break; case EOpTexCube: out.debug << "texCUBE"; break; case EOpTexCubeProj: out.debug << "texCUBEproj"; break; case EOpTexCubeLod: out.debug << "texCUBElod"; break; case EOpTexCubeBias: out.debug << "texCUBEbias"; break; case EOpTexCubeGrad: out.debug << "texCUBEgrad"; break; case EOpTexRect: out.debug << "texRECT"; break; case EOpTexRectProj: out.debug << "texRECTproj"; break; case EOpShadow2D: out.debug << "shadow2D"; break; case EOpShadow2DProj:out.debug << "shadow2Dproj"; break; case EOpTex2DArray: out.debug << "tex2DArray"; break; case EOpTex2DArrayLod: out.debug << "tex2DArrayLod"; break; case EOpTex2DArrayBias: out.debug << "tex2DArrayBias"; break; default: out.debug.message(EPrefixError, "Bad aggregation op"); } if (node->getOp() != EOpSequence && node->getOp() != EOpParameters) out.debug << " (" << node->getCompleteString() << ")"; out.debug << "\n"; return true; } bool OutputSelection(bool, /* preVisit */ TIntermSelection* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); out.debug << "ternary ?:"; out.debug << " (" << node->getCompleteString() << ")\n"; ++oit->depth; OutputTreeText(oit->infoSink, node, oit->depth); out.debug << "Condition\n"; node->getCondition()->traverse(it); OutputTreeText(oit->infoSink, node, oit->depth); if (node->getTrueBlock()) { out.debug << "true case\n"; node->getTrueBlock()->traverse(it); } else out.debug << "true case is null\n"; if (node->getFalseBlock()) { OutputTreeText(oit->infoSink, node, oit->depth); out.debug << "false case\n"; node->getFalseBlock()->traverse(it); } --oit->depth; return false; } void OutputConstant(TIntermConstant* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; int size = node->getCount(); for (int i = 0; i < size; i++) { OutputTreeText(out, node, oit->depth); switch (node->getValue(i).type) { case EbtBool: if (node->toBool(i)) out.debug << "true"; else out.debug << "false"; out.debug << " (" << "const bool" << ")"; out.debug << "\n"; break; case EbtFloat: { char buf[300]; sprintf(buf, "%f (%s)", node->toFloat(i), "const float"); out.debug << buf << "\n"; } break; case EbtInt: { char buf[300]; sprintf(buf, "%d (%s)", node->toInt(i), "const int"); out.debug << buf << "\n"; break; } default: out.info.message(EPrefixInternalError, "Unknown constant", node->getLine()); break; } } } bool OutputLoop(bool, /* preVisit */ TIntermLoop* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); out.debug << "Loop with condition "; if (node->getType() == ELoopDoWhile) out.debug << "not "; out.debug << "tested first\n"; ++oit->depth; OutputTreeText(oit->infoSink, node, oit->depth); if (node->getCondition()) { out.debug << "Loop Condition\n"; node->getCondition()->traverse(it); } else out.debug << "No loop condition\n"; OutputTreeText(oit->infoSink, node, oit->depth); if (node->getBody()) { out.debug << "Loop Body\n"; node->getBody()->traverse(it); } else out.debug << "No loop body\n"; if (node->getExpression()) { OutputTreeText(oit->infoSink, node, oit->depth); out.debug << "Loop Terminal Expression\n"; node->getExpression()->traverse(it); } --oit->depth; return false; } bool OutputBranch(bool, /* previsit*/ TIntermBranch* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); switch (node->getFlowOp()) { case EOpKill: out.debug << "Branch: Kill"; break; case EOpBreak: out.debug << "Branch: Break"; break; case EOpContinue: out.debug << "Branch: Continue"; break; case EOpReturn: out.debug << "Branch: Return"; break; default: out.debug << "Branch: Unknown Branch"; break; } if (node->getExpression()) { out.debug << " with expression\n"; ++oit->depth; node->getExpression()->traverse(it); --oit->depth; } else out.debug << "\n"; return false; } void ir_output_tree(TIntermNode* root, TInfoSink& infoSink) { if (root == 0) return; TOutputTraverser it(infoSink); it.visitAggregate = OutputAggregate; it.visitBinary = OutputBinary; it.visitConstant = OutputConstant; it.visitSelection = OutputSelection; it.visitSymbol = OutputSymbol; it.visitUnary = OutputUnary; it.visitLoop = OutputLoop; it.visitBranch = OutputBranch; root->traverse(&it); }
lriki/LNSL
src/hlsl2glslfork/hlslang/MachineIndependent/intermOut.cpp
C++
mit
18,856
/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { fail } from '../util/assert'; /** * PersistencePromise<> is essentially a re-implementation of Promise<> except * it has a .next() method instead of .then() and .next() and .catch() callbacks * are executed synchronously when a PersistencePromise resolves rather than * asynchronously (Promise<> implementations use setImmediate() or similar). * * This is necessary to interoperate with IndexedDB which will automatically * commit transactions if control is returned to the event loop without * synchronously initiating another operation on the transaction. * * NOTE: .then() and .catch() only allow a single consumer, unlike normal * Promises. */ var PersistencePromise = /** @class */ (function () { function PersistencePromise(callback) { var _this = this; // NOTE: next/catchCallback will always point to our own wrapper functions, // not the user's raw next() or catch() callbacks. this.nextCallback = null; this.catchCallback = null; // When the operation resolves, we'll set result or error and mark isDone. this.result = undefined; this.error = null; this.isDone = false; // Set to true when .then() or .catch() are called and prevents additional // chaining. this.callbackAttached = false; callback(function (value) { _this.isDone = true; _this.result = value; if (_this.nextCallback) { // value should be defined unless T is Void, but we can't express // that in the type system. _this.nextCallback(value); } }, function (error) { _this.isDone = true; _this.error = error; if (_this.catchCallback) { _this.catchCallback(error); } }); } PersistencePromise.prototype.catch = function (fn) { return this.next(undefined, fn); }; PersistencePromise.prototype.next = function (nextFn, catchFn) { var _this = this; if (this.callbackAttached) { fail('Called next() or catch() twice for PersistencePromise'); } this.callbackAttached = true; if (this.isDone) { if (!this.error) { return this.wrapSuccess(nextFn, this.result); } else { return this.wrapFailure(catchFn, this.error); } } else { return new PersistencePromise(function (resolve, reject) { _this.nextCallback = function (value) { _this.wrapSuccess(nextFn, value).next(resolve, reject); }; _this.catchCallback = function (error) { _this.wrapFailure(catchFn, error).next(resolve, reject); }; }); } }; PersistencePromise.prototype.toPromise = function () { var _this = this; return new Promise(function (resolve, reject) { _this.next(resolve, reject); }); }; PersistencePromise.prototype.wrapUserFunction = function (fn) { try { var result = fn(); if (result instanceof PersistencePromise) { return result; } else { return PersistencePromise.resolve(result); } } catch (e) { return PersistencePromise.reject(e); } }; PersistencePromise.prototype.wrapSuccess = function (nextFn, value) { if (nextFn) { return this.wrapUserFunction(function () { return nextFn(value); }); } else { // If there's no nextFn, then R must be the same as T but we // can't express that in the type system. return PersistencePromise.resolve(value); } }; PersistencePromise.prototype.wrapFailure = function (catchFn, error) { if (catchFn) { return this.wrapUserFunction(function () { return catchFn(error); }); } else { return PersistencePromise.reject(error); } }; PersistencePromise.resolve = function (result) { return new PersistencePromise(function (resolve, reject) { resolve(result); }); }; PersistencePromise.reject = function (error) { return new PersistencePromise(function (resolve, reject) { reject(error); }); }; PersistencePromise.waitFor = function (all) { return all.reduce(function (promise, nextPromise, idx) { return promise.next(function () { return nextPromise; }); }, PersistencePromise.resolve()); }; PersistencePromise.map = function (all) { var results = []; var first = true; // initial is ignored, so we can cheat on the type. var initial = PersistencePromise.resolve(null); return all .reduce(function (promise, nextPromise) { return promise.next(function (result) { if (!first) { results.push(result); } first = false; return nextPromise; }); }, initial) .next(function (result) { results.push(result); return results; }); }; return PersistencePromise; }()); export { PersistencePromise }; //# sourceMappingURL=persistence_promise.js.map
aggiedefenders/aggiedefenders.github.io
node_modules/@firebase/firestore/dist/esm/src/local/persistence_promise.js
JavaScript
mit
6,111
MainIndexEstablishmentsListView = Backbone.View.extend({ events: { 'click .nav': 'navigate' }, initialize: function () { this.listenTo(this.collection, 'reset', this.render); }, render: function (e) { this.$el.html(''); if (this.collection.length > 0) { this.collection.each(function (establishment) { this.renderEstablishment(establishment); }, this); } else { this.$el.html(''); this.$el.html(render('establishments/index_no_results')); } }, renderEstablishment: function (establishment) { var establishment_view = new EstablishmentsIndexEstablishmentView({ tagName: 'li', model: establishment }); this.$el.append(establishment_view.el); }, navigate: function (e) { e.preventDefault(); App.navigate(e.target.pathname, { trigger: true }); } });
sealocal/yumhacker
app/assets/javascripts/views/main/index_establishments_list_view.js
JavaScript
mit
825
/* * BOOOS.h * * Created on: Aug 14, 2014 */ #ifndef TASK_CC_ #define TASK_CC_ #include "BOOOS.h" #include <iostream> namespace BOOOS { BOOOS * BOOOS::__booos = 0; BOOOS::SchedulerType BOOOS::SCHED_POLICY = BOOOS::SCHED_FCFS; // ou outro escalonador. Ajustem como necessário bool BOOOS::SCHED_PREEMPT = false; // pode ser preemptivo ou não bool BOOOS::SCHED_AGING = false; // apenas alguns escalonadores usam aging. Ajustem como necessário BOOOS::BOOOS(bool verbose) : _verbose(verbose) { if(_verbose) std::cout << "Welcome to BOOOS - Basic Object Oriented Operating System!" << std::endl; // Call init routines of other components this->init(); } BOOOS::~BOOOS() { // Call finish routines of other components (if any) if(_verbose) std::cout << "BOOOS ended... Bye!" << std::endl; } void BOOOS::init() { Task::init(); Scheduler::init(); } void BOOOS::panic() { std::cerr << "BOOOSta! Panic!" << std::endl; while(true); } } /* namespace BOOOS */ #endif
paladini/UFSC-so1-2015-01
trabalhos/atividadePratica2/final/lib/BOOOS.cc
C++
mit
979
using System; using System.Linq; using System.Text; using Abp.Collections.Extensions; using Abp.Extensions; using Abp.Web.Api.Modeling; namespace Abp.Web.Api.ProxyScripting.Generators { internal static class ProxyScriptingJsFuncHelper { private const string ValidJsVariableNameChars = "abcdefghijklmnopqrstuxwvyzABCDEFGHIJKLMNOPQRSTUXWVYZ0123456789_"; public static string NormalizeJsVariableName(string name, string additionalChars = "") { var validChars = ValidJsVariableNameChars + additionalChars; var sb = new StringBuilder(name); sb.Replace('-', '_'); //Delete invalid chars foreach (var c in name) { if (!validChars.Contains(c)) { sb.Replace(c.ToString(), ""); } } if (sb.Length == 0) { return "_" + Guid.NewGuid().ToString("N").Left(8); } return sb.ToString(); } public static string GetParamNameInJsFunc(ParameterApiDescriptionModel parameterInfo) { return parameterInfo.Name == parameterInfo.NameOnMethod ? NormalizeJsVariableName(parameterInfo.Name.ToCamelCase(), ".") : NormalizeJsVariableName(parameterInfo.NameOnMethod.ToCamelCase()) + "." + NormalizeJsVariableName(parameterInfo.Name.ToCamelCase(), "."); } public static string CreateJsObjectLiteral(ParameterApiDescriptionModel[] parameters, int indent = 0) { var sb = new StringBuilder(); sb.AppendLine("{"); foreach (var prm in parameters) { sb.AppendLine($"{new string(' ', indent)} '{prm.Name}': {GetParamNameInJsFunc(prm)}"); } sb.Append(new string(' ', indent) + "}"); return sb.ToString(); } public static string GenerateJsFuncParameterList(ActionApiDescriptionModel action, string ajaxParametersName) { var methodParamNames = action.Parameters.Select(p => p.NameOnMethod).Distinct().ToList(); methodParamNames.Add(ajaxParametersName); return methodParamNames.Select(prmName => NormalizeJsVariableName(prmName.ToCamelCase())).JoinAsString(", "); } } }
liuxx001/BodeAbp
src/frame/Abp.Web.Common/Web/Api/ProxyScripting/Generators/ProxyScriptingJsFuncHelper.cs
C#
mit
2,365
/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights. #ifndef SAPI_VAR_STACK_HPP_ #define SAPI_VAR_STACK_HPP_ #include <new> #include <cstdio> #include <deque> #include "../arg/Argument.hpp" namespace var { /*! \brief Queue Class * \details The Queue class is a FIFO data structure * that allows data to be pushed on the back * and popped from the front. It is similar to the * std::queue container class. * */ template<typename T> class Stack : public api::WorkObject { public: /*! \details Constructs a new Queue. */ Stack(){} ~Stack(){ } /*! \details Returns a reference to the back item. * * The back item is the one that has most recently * been pushed using push(). * */ T & top(){ return m_deque.back(); } /*! \details Returns a read-only reference to the back item. * * The back item is the one that has most recently * been pushed using push(). * */ const T & top() const { return m_deque.back(); } /*! \details Pushes an item on the queue. * * @param value The item to push * */ Stack& push(const T & value){ m_deque.push_back(value); return *this; } /*! \details Pops an item from the front of the queue. */ Stack& pop(){ m_deque.pop_back(); return *this; } /*! \details Returns true if the queue is empty. */ bool is_empty() const { return m_deque.empty(); } /*! \details Returns the number of items in the queue. */ u32 count() const { return m_deque.size(); } /*! \details Clears the contents of the queue. * * This will empty the queue and free all the * resources associated with it. * */ Stack& clear(){ //deconstruct objects in the list using pop m_deque.clear(); return *this; } private: std::deque<T> m_deque; }; } #endif // SAPI_VAR_STACK_HPP_
StratifyLabs/StratifyAPI
include/var/Stack.hpp
C++
mit
1,819
using DataCloner.Core.Metadata; using System.Collections.Generic; using System.Linq; using System.Text; using System; namespace DataCloner.Core.Data.Generator { public class InsertWriter : IInsertWriter { private string IdentifierDelemiterStart { get; } private string IdentifierDelemiterEnd { get; } private string StringDelemiter { get; } private string NamedParameterPrefix { get; } private readonly StringBuilder _sb = new StringBuilder(); public InsertWriter(string identifierDelemiterStart, string identifierDelemiterEnd , string stringDelemiter, string namedParameterPrefix) { IdentifierDelemiterStart = identifierDelemiterStart; IdentifierDelemiterEnd = identifierDelemiterEnd; StringDelemiter = stringDelemiter; NamedParameterPrefix = namedParameterPrefix; } public IInsertWriter AppendColumns(TableIdentifier table, List<ColumnDefinition> columns) { _sb.Append("INSERT INTO ") .Append(IdentifierDelemiterStart).Append(table.Database).Append(IdentifierDelemiterEnd).Append("."); if (!String.IsNullOrWhiteSpace(table.Schema)) _sb.Append(IdentifierDelemiterStart).Append(table.Schema).Append(IdentifierDelemiterEnd).Append("."); _sb.Append(IdentifierDelemiterStart).Append(table.Table).Append(IdentifierDelemiterEnd) .Append("("); //Nom des colonnes for (var i = 0; i < columns.Count(); i++) { if (!columns[i].IsAutoIncrement) _sb.Append(IdentifierDelemiterStart).Append(columns[i].Name).Append(IdentifierDelemiterEnd).Append(","); } _sb.Remove(_sb.Length - 1, 1); _sb.Append(")VALUES("); return this; } public IInsertWriter Append(string value) { _sb.Append(value); return this; } public IInsertWriter AppendValue(object value) { _sb.Append(StringDelemiter).Append(value).Append(StringDelemiter).Append(","); return this; } public IInsertWriter AppendVariable(string varName) { _sb.Append(NamedParameterPrefix).Append(varName).Append(","); return this; } public IInsertWriter Complete() { _sb.Remove(_sb.Length - 1, 1); _sb.Append(");\r\n"); return this; } public StringBuilder ToStringBuilder() { return _sb; } } }
naster01/DataCloner
archive/DataCloner.Core/Data/Generator/InsertWriter.cs
C#
mit
2,629
var rules = module.exports = []; function Checker(name, rule) { this.name = name; this.rule = rule; this.check = function(results) { var violations = [], that = this; results.filter(function(result) { return result.shortName !== '[[code]]'; }).forEach(function (result) { var violation = that.rule(result); if (violation) { if (!result.violations) { result.violations = []; } result.violations.push({ message: violation, source: that.name }); } violations.push(result); }); return violations; }; } rules.Checker = Checker; rules.push( new Checker("FunctionLength", function(result) { var config = result.config || {}; var functionLength = config.functionLength || 30; if (result.shortName !== 'module.exports' && result.lines > functionLength) { return result.shortName + " is " + result.lines + " lines long, maximum allowed is " + functionLength; } return null; }) ); rules.push( new Checker("CyclomaticComplexity", function(result) { var config = result.config || {}; var cyclomaticComplexity = config.cyclomaticComplexity || 10; if (result.complexity > cyclomaticComplexity) { return result.shortName + " has a cyclomatic complexity of " + result.complexity + ", maximum should be " + cyclomaticComplexity; } return null; }) ); rules.push( new Checker("NumberOfArguments", function(result) { var config = result.config || {}; var numberOfArguments = config.numberOfArguments || 5; if (result.ins > numberOfArguments) { return result.shortName + " has " + result.ins + " arguments, maximum allowed is " + numberOfArguments; } return null; }) );
yubin-huang/jscheckstyle
lib/rules.js
JavaScript
mit
1,979
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test that the wallet resends transactions periodically.""" from collections import defaultdict import time from test_framework.blocktools import create_block, create_coinbase from test_framework.messages import ToHex from test_framework.mininode import P2PInterface, mininode_lock from test_framework.test_framework import GuldenTestFramework from test_framework.util import assert_equal, wait_until class P2PStoreTxInvs(P2PInterface): def __init__(self): super().__init__() self.tx_invs_received = defaultdict(int) def on_inv(self, message): # Store how many times invs have been received for each tx. for i in message.inv: if i.type == 1: # save txid self.tx_invs_received[i.hash] += 1 class ResendWalletTransactionsTest(GuldenTestFramework): def set_test_params(self): self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): node = self.nodes[0] # alias node.add_p2p_connection(P2PStoreTxInvs()) self.log.info("Create a new transaction and wait until it's broadcast") txid = int(node.sendtoaddress(node.getnewaddress(), 1), 16) # Can take a few seconds due to transaction trickling wait_until(lambda: node.p2p.tx_invs_received[txid] >= 1, lock=mininode_lock) # Add a second peer since txs aren't rebroadcast to the same peer (see filterInventoryKnown) node.add_p2p_connection(P2PStoreTxInvs()) self.log.info("Create a block") # Create and submit a block without the transaction. # Transactions are only rebroadcast if there has been a block at least five minutes # after the last time we tried to broadcast. Use mocktime and give an extra minute to be sure. block_time = int(time.time()) + 6 * 60 node.setmocktime(block_time) block = create_block(int(node.getbestblockhash(), 16), create_coinbase(node.getblockchaininfo()['blocks']), block_time) block.nVersion = 3 block.rehash() block.solve() node.submitblock(ToHex(block)) # Transaction should not be rebroadcast node.p2ps[1].sync_with_ping() assert_equal(node.p2ps[1].tx_invs_received[txid], 0) self.log.info("Transaction should be rebroadcast after 30 minutes") # Use mocktime and give an extra 5 minutes to be sure. rebroadcast_time = int(time.time()) + 41 * 60 node.setmocktime(rebroadcast_time) wait_until(lambda: node.p2ps[1].tx_invs_received[txid] >= 1, lock=mininode_lock) if __name__ == '__main__': ResendWalletTransactionsTest().main()
nlgcoin/guldencoin-official
test/functional/wallet_resendwallettransactions.py
Python
mit
2,912
const fs = require('fs'); const path = require('path'); const yoHelper = require('yeoman-test'); const yoAssert = require('yeoman-assert'); const generatorPath = '../packages/generator-emakinacee-react/generators/compute'; describe('Compute', () => { describe('without module', () => { before(() => { return yoHelper .run(path.join(__dirname, generatorPath)) .withArguments(['test-compute']); }); it('generates all files to shared location', () => { yoAssert.file([ './src/shared/computes/testCompute.js', './src/shared/computes/testCompute.spec.js', ]); }); it('compute file has valid content', (done) => { fs.readFile(path.join(__dirname, './snapshots/compute/compute.js'), 'utf8', (err, template) => { if (err) done(err); if (!template || template === '') done(new Error('Template snapshot does not exist or is empty')); yoAssert.fileContent( './src/shared/computes/testCompute.js', template ); done(); }); }); it('spec file has valid content', (done) => { fs.readFile(path.join(__dirname, './snapshots/compute/compute.spec.js'), 'utf8', (err, template) => { if (err) done(err); if (!template || template === '') done(new Error('Template snapshot does not exist or is empty')); yoAssert.fileContent( './src/shared/computes/testCompute.spec.js', template ); done(); }); }); }); describe('with module', () => { before(() => { return yoHelper .run(path.join(__dirname, generatorPath)) .withArguments(['test-compute', 'test-module']); }); it('generates all files to module location', () => { yoAssert.file([ './src/modules/TestModule/computes/testCompute.js', './src/modules/TestModule/computes/testCompute.spec.js', ]); }); it('compute file has valid content', (done) => { fs.readFile(path.join(__dirname, './snapshots/compute/compute.js'), 'utf8', (err, template) => { if (err) done(err); if (!template || template === '') done(new Error('Template snapshot does not exist or is empty')); yoAssert.fileContent( './src/modules/TestModule/computes/testCompute.js', template ); done(); }); }); it('spec file has valid content', (done) => { fs.readFile(path.join(__dirname, './snapshots/compute/compute.spec.js'), 'utf8', (err, template) => { if (err) done(err); if (!template || template === '') done(new Error('Template snapshot does not exist or is empty')); yoAssert.fileContent( './src/modules/TestModule/computes/testCompute.spec.js', template ); done(); }); }); }); });
emakina-cee-oss/generator-emakinacee-react
test/compute.test.js
JavaScript
mit
3,309
(function () { var KEY = { ENTER: 13, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }; function normalizeTokens(tokens) { return tokens.filter(function (token) { return !!token; }).map(function (token) { return token.toLowerCase(); }); } function newIndexNode() { return { ids: [], children: {} }; } function buildIndex(options) { var index = newIndexNode(); options.forEach(function (option, id) { var val = option.text || option.value, tokens = normalizeTokens(val.split(/\s+/)); tokens.forEach(function (token) { var ch, chars = token.split(''), node = index; while (ch = chars.shift()) { node = node.children[ch] || (node.children[ch] = newIndexNode()); node.ids.push(id); } }); }); return index; } function find(query, index, options) { var matches, tokens = normalizeTokens(query.split(/\s+/)); tokens.forEach(function (token) { var node = index, ch, chars = token.split(''); if (matches && matches.length === 0) { return false; } while (node && (ch = chars.shift())) { node = node.children[ch]; } if (node && chars.length === 0) { ids = node.ids.slice(0); matches = matches ? getIntersection(matches, ids) : ids; } else { matches = []; return false; } }); return matches ? unique(matches).map(function (id) { return options[id]; }) : []; } function unique(array) { var seen = {}, uniques = []; for (var i = 0; i < array.length; i++) { if (!seen[array[i]]) { seen[array[i]] = true; uniques.push(array[i]); } } return uniques; } function getIntersection(arrayA, arrayB) { var ai = 0, bi = 0, intersection = []; arrayA = arrayA.sort(compare); arrayB = arrayB.sort(compare); while (ai < arrayA.length && bi < arrayB.length) { if (arrayA[ai] < arrayB[bi]) { ai++; } else if (arrayA[ai] > arrayB[bi]) { bi++; } else { intersection.push(arrayA[ai]); ai++; bi++; } } return intersection; function compare(a, b) { return a - b; } } var BAutocompletePrototype = Object.create(HTMLElement.prototype, { options: { enumerable: true, get: function () { var list = document.querySelector('#' + this.getAttribute('list')); if (list && list.options) { CustomElements.upgrade(list); return Array.prototype.slice.call(list.options, 0); } return []; } }, index: { enumerable: true, get: function () { if (!this.__index) { this.__index = buildIndex(this.options); } return this.__index; } }, suggestionList: { enumerable: true, get: function () { return this.querySelector('ul'); } }, selectable: { enumerable: true, get: function () { return this.querySelector('b-selectable'); } }, input: { enumerable: true, get: function () { return this.querySelector('input[type=text]'); } }, createdCallback: { enumerable: true, value: function () { this.appendChild(this.template.content.cloneNode(true)); this.input.addEventListener('input', this.onInputChange.bind(this), false); this.input.addEventListener('focus', this.onInputFocus.bind(this), false); this.input.addEventListener('blur', this.onInputBlur.bind(this), false); this.selectable.addEventListener('mousedown', this.onSuggestionPick.bind(this), false); this.selectable.addEventListener('b-activate', this.pickSuggestion.bind(this), false); } }, handleAria: { enumerable: true, value: function () { this.setAttribute('role', 'combobox'); this.setAttribute('aria-autocomplete', 'list'); } }, onInputFocus: { enumerable: true, value: function (e) { this.keydownListener = this.keydownHandler.bind(this); this.input.addEventListener('keydown', this.keydownListener, false); } }, onInputBlur: { enumerable: true, value: function (e) { if (this.cancelBlur) { this.cancelBlur = false; return; } this.input.removeEventListener('keydown', this.keydownListener, false); this.hideSuggestionList(); } }, onSuggestionPick: { enumerable: true, value: function (e) { e.preventDefault(); this.cancelBlur = true; } }, keydownHandler: { enumerable: true, value: function (e) { e.stopPropagation(); switch (e.keyCode) { case KEY.ENTER: { this.selectable.activate(); break; } case KEY.DOWN: { if (!this.areSuggestionsVisible()) { this.showSuggestionList(); } else { this.selectable.selectNextItem(); } break; } case KEY.UP: { if (!this.areSuggestionsVisible()) { this.showSuggestionList(); } else { this.selectable.selectPreviousItem(); } break; } default: return; } e.preventDefault(); } }, onInputChange: { enumerable: true, value: function (e) { e.stopPropagation(); if (!this.areSuggestionsVisible()) { this.showSuggestionList(); this.input.focus(); } else { this.refreshSuggestionList(); } this.selectFirstSuggestion(); } }, filterOptions: { enumerable: true, value: function () { var query = this.input.value; if (!query) return this.options; return find(query, this.index, this.options); } }, paintSuggestionList: { enumerable: true, value: function () { this.selectable.unselect(); var list = this.suggestionList, options = this.filterOptions(); while (list.childNodes.length > 0) { list.removeChild(list.childNodes[0]); } options.forEach(function (option) { var li = document.createElement('li'); li.innerHTML = option.text || option.value; list.appendChild(li); }); } }, refreshSuggestionList: { enumerable: true, value: function () { this.paintSuggestionList(); } }, toggleSuggestionList: { enumerable: true, value: function (e) { if (e) { e.stopPropagation(); } this.areSuggestionsVisible() ? this.hideSuggestionList() : this.showSuggestionList(); this.input.focus(); } }, showSuggestionList: { enumerable: true, value: function () { this.paintSuggestionList(); this.selectable.setAttribute('visible', ''); } }, hideSuggestionList: { enumerable: true, value: function () { if (this.areSuggestionsVisible()) { this.selectable.removeAttribute('visible'); } } }, selectFirstSuggestion: { enumerable: true, value: function () { this.selectable.selectFirst(); } }, areSuggestionsVisible: { enumerable: true, value: function () { return this.selectable.hasAttribute('visible'); } }, pickSuggestion: { enumerable: true, value: function (e) { this.cancelBlur = false; this.input.value = this.getItemValue(e.detail.item); this.hideSuggestionList(); } }, getItemValue: { enumerable: true, value: function (itemIndex) { return this.querySelectorAll('li')[itemIndex].innerHTML; } } }); window.BAutocomplete = document.registerElement('b-autocomplete', { prototype: BAutocompletePrototype }); Object.defineProperty(BAutocompletePrototype, 'template', { get: function () { var fragment = document.createDocumentFragment(); var div = fragment.appendChild(document.createElement('div')); div.innerHTML = ' <input type="text" autocomplete="off" role="textbox" value=""> <b-selectable target="li"> <ul></ul> </b-selectable> '; while (child = div.firstChild) { fragment.insertBefore(child, div); } fragment.removeChild(div); return { content: fragment }; } }); }()); (function () { var BComboBoxPrototype = Object.create(BAutocomplete.prototype, { listToggle: { enumerable: true, get: function () { return this.querySelector('.b-combo-box-toggle'); } }, createdCallback: { enumerable: true, value: function () { this._super.createdCallback.call(this); this.listToggle.addEventListener('click', this.toggleSuggestionList.bind(this), false); } } }); window.BComboBox = document.registerElement('b-combo-box', { prototype: BComboBoxPrototype }); Object.defineProperty(BComboBox.prototype, '_super', { enumerable: false, writable: false, configurable: false, value: BAutocomplete.prototype }); Object.defineProperty(BComboBoxPrototype, 'template', { get: function () { var fragment = document.createDocumentFragment(); var div = fragment.appendChild(document.createElement('div')); div.innerHTML = ' <input type="text" autocomplete="off" role="textbox" value=""> <a class="b-combo-box-toggle"></a> <b-selectable target="li"> <ul></ul> </b-selectable> '; while (child = div.firstChild) { fragment.insertBefore(child, div); } fragment.removeChild(div); return { content: fragment }; } }); }());
bosonic-labs/b-autocomplete
dist/b-autocomplete.js
JavaScript
mit
12,927
<?php /** * Checkout.com * Authorised and regulated as an electronic money institution * by the UK Financial Conduct Authority (FCA) under number 900816. * * PHP version 7 * * @category SDK * @package Checkout.com * @author Platforms Development Team <platforms@checkout.com> * @copyright 2010-2019 Checkout.com * @license https://opensource.org/licenses/mit-license.html MIT License * @link https://docs.checkout.com/ */ namespace Checkout\Models\Payments; /** * Payment method Bancontact. * * @category SDK * @package Checkout.com * @author Platforms Development Team <platforms@checkout.com> * @license https://opensource.org/licenses/mit-license.html MIT License * @link https://docs.checkout.com/ */ class BancontactSource extends Source { /** * Qualified name of the class. * * @var string */ const QUALIFIED_NAME = __CLASS__; /** * Name of the model. * * @var string */ const MODEL_NAME = 'bancontact'; /** * Magic Methods */ /** * Initialise bancontact. * * @param string $name The account_holder_name * @param string $country The payment_country * @param string $descriptor The billing_descriptor */ public function __construct($name, $country, $descriptor = '') { $this->type = static::MODEL_NAME; $this->account_holder_name = $name; $this->payment_country = $country; $this->billing_descriptor = $descriptor; } }
checkout/checkout-woocommerce-plugin
woocommerce-gateway-checkout-com/includes/lib/checkout-sdk-php/src/Models/Payments/BancontactSource.php
PHP
mit
1,552