text
stringlengths
1
1.05M
; A337929: Numbers w such that (F(2*n-1)^2, -F(2*n)^2, w) are primitive solutions of the Diophantine equation 2*x^3 + 2*y^3 + z^3 = 1, where F(n) is the n-th Fibonacci number (A000045). ; 1,11,79,545,3739,25631,175681,1204139,8253295,56568929,387729211,2657535551,18215019649,124847601995,855718194319,5865179758241,40200540113371,275538601035359,1888569667134145,12944449068903659,88722573815191471,608113567637436641 mov $2,$0 mov $0,1 mov $1,1 lpb $2 add $0,$1 add $1,$0 sub $2,1 lpe mul $0,$1 mul $0,2 sub $0,1
// Copyright (C) 2012-2018 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. /// @file dhcp6_log.cc /// Contains the loggers used by the DHCPv6 server component. #include <config.h> #include <dhcp6/dhcp6_log.h> namespace isc { namespace dhcp { const int DBG_DHCP6_START = isc::log::DBGLVL_START_SHUT; const int DBG_DHCP6_SHUT = isc::log::DBGLVL_START_SHUT; const int DBG_DHCP6_COMMAND = isc::log::DBGLVL_COMMAND; const int DBG_DHCP6_BASIC = isc::log::DBGLVL_TRACE_BASIC; const int DBG_DHCP6_HOOKS = isc::log::DBGLVL_TRACE_BASIC; const int DBG_DHCP6_BASIC_DATA = isc::log::DBGLVL_TRACE_BASIC_DATA; const int DBG_DHCP6_DETAIL = isc::log::DBGLVL_TRACE_DETAIL; const int DBG_DHCP6_DETAIL_DATA = isc::log::DBGLVL_TRACE_DETAIL_DATA; const char* DHCP6_ROOT_LOGGER_NAME = "kea-dhcp6"; const char* DHCP6_APP_LOGGER_NAME = "dhcp6"; const char* DHCP6_BAD_PACKET_LOGGER_NAME = "bad-packets"; const char* DHCP6_PACKET_LOGGER_NAME = "packets"; const char* DHCP6_OPTIONS_LOGGER_NAME = "options"; const char* DHCP6_DDNS_LOGGER_NAME = "ddns"; const char* DHCP6_LEASE_LOGGER_NAME = "leases"; isc::log::Logger dhcp6_logger(DHCP6_APP_LOGGER_NAME); isc::log::Logger bad_packet6_logger(DHCP6_BAD_PACKET_LOGGER_NAME); isc::log::Logger packet6_logger(DHCP6_PACKET_LOGGER_NAME); isc::log::Logger options6_logger(DHCP6_OPTIONS_LOGGER_NAME); isc::log::Logger ddns6_logger(DHCP6_DDNS_LOGGER_NAME); isc::log::Logger lease6_logger(DHCP6_LEASE_LOGGER_NAME); } // namespace dhcp } // namespace isc
#include "SerialControlledRobot.h" #include "JointSensors.h" #include <KrisLibrary/utils/AnyCollection.h> SerialControlledRobot::SerialControlledRobot(const char* _host,double timeout) :host(_host),robotTime(0),timeStep(0),numOverruns(0),stopFlag(false),controllerMutex(NULL) { controllerPipe = new SocketPipeWorker(_host,false,timeout); } SerialControlledRobot::~SerialControlledRobot() { controllerPipe = NULL; } bool SerialControlledRobot::Init(Robot* _robot,RobotController* _controller) { if(!ControlledRobot::Init(_robot,_controller)) return false; if(!controllerPipe->Start()) { fprintf(stderr,"SerialControlledRobot: Error opening socket to %s\n",host.c_str()); return false; } return true; } bool SerialControlledRobot::Process(double timeout) { if(!controllerPipe->initialized) { fprintf(stderr,"SerialControlledRobot::Process(): did you forget to call Init?\n"); return false; } Timer timer; int iteration = 0; while(!stopFlag) { Real lastReadTime = timer.ElapsedTime(); if(lastReadTime > timeout) return false; timeStep = 0; if(controllerMutex) controllerMutex->lock(); ReadSensorData(sensors); if(timeStep == 0) { //first time, or failed to read -- //read next sensor data again to get timing info if(controllerMutex) controllerMutex->unlock(); if(iteration % 100 == 0) printf("SerialControlledRobot(): Error getting timestep? Waiting.\n"); ThreadSleep(0.01); } else { if(klamptController) { klamptController->sensors = &sensors; klamptController->command = &command; klamptController->Update(timeStep); } if(controllerMutex) controllerMutex->unlock(); WriteCommandData(command); Real time = timer.ElapsedTime(); if(time > lastReadTime + timeStep) { numOverruns ++; } return true; } iteration ++; } return false; } bool SerialControlledRobot::Run() { if(!controllerPipe->initialized) { fprintf(stderr,"SerialControlledRobot::Run(): did you forget to call Init?\n"); return false; } Timer timer; stopFlag = false; while(!stopFlag) { Real lastReadTime = timer.ElapsedTime(); timeStep = 0; if(controllerMutex) controllerMutex->lock(); ReadSensorData(sensors); if(timeStep == 0) { //first time, or failed to read -- //read next sensor data again to get timing info if(controllerMutex) controllerMutex->unlock(); ThreadSleep(0.01); } else { if(klamptController) { klamptController->sensors = &sensors; klamptController->command = &command; Real dt = robotTime-klamptController->time; if(klamptController->time == 0) //first update dt = timeStep; klamptController->Update(robotTime-klamptController->time); } if(controllerMutex) controllerMutex->unlock(); if(!controllerPipe->initialized) { fprintf(stderr,"SerialControlledRobot::Run(): killed by socket disconnect?\n"); return false; } WriteCommandData(command); Real time = timer.ElapsedTime(); if(time > lastReadTime + timeStep) { printf("Klamp't controller overrun, took time %g which exceeds time step %g\n",time-lastReadTime,timeStep); numOverruns ++; } else { ThreadSleep(Max(lastReadTime + timeStep - time,0.0)); } } } return true; } void SerialControlledRobot::Stop() { stopFlag = true; } void SerialControlledRobot::SetMutex(Mutex* mutex) { controllerMutex = mutex; } void SerialControlledRobot::ReadSensorData(RobotSensors& sensors) { if(controllerPipe && controllerPipe->UnreadCount() > 0) { if(controllerPipe->UnreadCount() > 1) { fprintf(stderr,"SerialControlledRobot: Warning, skipping %d sensor messages\n",controllerPipe->UnreadCount()-1); fprintf(stderr," TODO: debug the controller pipe?\n"); } string msg = controllerPipe->Newest(); AnyCollection c; if(!c.read(msg.c_str())) { fprintf(stderr,"SerialControlledRobot: Unable to read parse data from robot client\n"); return; } if(sensors.sensors.empty()) { //no sensors defined by the user -- initialize default sensors based on //what's in the sensor message if(c.find("q") != NULL) { JointPositionSensor* jp = new JointPositionSensor; jp->name = "q"; jp->q.resize(klamptRobotModel->q.n,Zero); sensors.sensors.push_back(jp); } if(c.find("dq") != NULL) { JointVelocitySensor* jv = new JointVelocitySensor; jv->name = "dq"; jv->dq.resize(klamptRobotModel->q.n,Zero); sensors.sensors.push_back(jv); } if(c.find("torque") != NULL) { DriverTorqueSensor* ts = new DriverTorqueSensor; ts->name = "torque"; ts->t.resize(klamptRobotModel->drivers.size()); sensors.sensors.push_back(ts); } } //read off timing information vector<AnyKeyable> keys; c.enumerate_keys(keys); for(size_t i=0;i<keys.size();i++) { string key; if(LexicalCast(keys[i].value,key)) { if(key == "dt") timeStep = c["dt"]; else if(key == "t") robotTime = c["t"]; else if(key == "qcmd" || key=="dqcmd" || key=="torquecmd") //echo continue; else { SmartPointer<SensorBase> s = sensors.GetNamedSensor(key); if(!s) { fprintf(stderr,"SerialControlledRobot::ReadSensorData: warning, sensor %s not given in model\n",key.c_str()); } else { vector<double> values; bool converted = c[keys[i]].asvector<double>(values); if(!converted) fprintf(stderr,"SerialControlledRobot::ReadSensorData: key %s does not yield a vector\n",key.c_str()); else s->SetMeasurements(values); } } } else { FatalError("SerialControlledRobot::ReadSensorData: Invalid key, element %d...\n",i); } } } } void SerialControlledRobot::WriteCommandData(const RobotMotorCommand& command) { if(controllerPipe && controllerPipe->transport->WriteReady()) { AnyCollection c; AnyCollection qcmd,dqcmd,torquecmd; qcmd.resize(klamptRobotModel->links.size()); dqcmd.resize(klamptRobotModel->links.size()); torquecmd.resize(command.actuators.size()); bool anyNonzeroV=false,anyNonzeroTorque = false; int mode = ActuatorCommand::OFF; for(size_t i=0;i<command.actuators.size();i++) { if(mode == ActuatorCommand::OFF) mode = command.actuators[i].mode; else { if(mode != command.actuators[i].mode) { fprintf(stderr,"SerialControlledRobot: do not support mixed torque / velocity / PID mode\n"); Abort(); } } klamptRobotModel->SetDriverValue(i,command.actuators[i].qdes); klamptRobotModel->SetDriverVelocity(i,command.actuators[i].dqdes); torquecmd[(int)i] = command.actuators[i].torque; if(command.actuators[i].dqdes!=0) anyNonzeroV=true; if(command.actuators[i].torque!=0) anyNonzeroTorque=true; if(mode == ActuatorCommand::LOCKED_VELOCITY) klamptRobotModel->SetDriverVelocity(i,command.actuators[i].desiredVelocity); } if(mode == ActuatorCommand::PID) { for(size_t i=0;i<klamptRobotModel->links.size();i++) qcmd[(int)i] = klamptRobotModel->q[i]; } if(anyNonzeroV || mode == ActuatorCommand::LOCKED_VELOCITY) { for(size_t i=0;i<klamptRobotModel->links.size();i++) dqcmd[(int)i] = klamptRobotModel->dq[i]; } if(mode == ActuatorCommand::OFF) { //nothing to send return; } else if(mode == ActuatorCommand::LOCKED_VELOCITY) { //cout<<"Sending locked velocity command"<<endl; c["dqcmd"] = dqcmd; c["tcmd"] = timeStep; } else if(mode == ActuatorCommand::PID) { //cout<<"Sending PID command"<<endl; c["qcmd"] = qcmd; if(anyNonzeroV) c["dqcmd"] = dqcmd; if(anyNonzeroTorque) c["torquecmd"] = torquecmd; } else if(mode == ActuatorCommand::TORQUE) { //cout<<"Sending torque command"<<endl; c["torquecmd"] = torquecmd; } else { cout<<"SerialControlledRobot: Invalid mode?? "<<mode<<endl; } //write JSON message to socket file stringstream ss; c.write(ss); cout<<"Writing message: "<<ss.str()<<endl; controllerPipe->Send(ss.str()); } }
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/globals-array.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/member-lval.h" #include "hphp/runtime/base/mixed-array-defs.h" #include "hphp/runtime/base/runtime-error.h" namespace HPHP { ////////////////////////////////////////////////////////////////////// static __thread GlobalsArray* g_variables; GlobalsArray* get_global_variables() { assertx(g_variables != nullptr); return g_variables; } GlobalsArray::GlobalsArray(NameValueTable* tab) : ArrayData(kGlobalsKind) , m_tab(tab) { Variant arr(staticEmptyArray()); #define X(s,v) tab->set(makeStaticString(#s), v.asTypedValue()); X(argc, init_null_variant); X(argv, init_null_variant); X(_SERVER, arr); X(_GET, arr); X(_POST, arr); X(_COOKIE, arr); X(_FILES, arr); X(_ENV, arr); X(_REQUEST, arr); X(_SESSION, arr); X(HTTP_RAW_POST_DATA, init_null_variant); #undef X g_variables = this; assert(hasExactlyOneRef()); } inline GlobalsArray* GlobalsArray::asGlobals(ArrayData* ad) { assert(ad->kind() == kGlobalsKind); return static_cast<GlobalsArray*>(ad); } inline const GlobalsArray* GlobalsArray::asGlobals(const ArrayData* ad) { assert(ad->kind() == kGlobalsKind); return static_cast<const GlobalsArray*>(ad); } size_t GlobalsArray::Vsize(const ArrayData* ad) { // We need to iterate to find out the actual size, since kNamedLocalDataType // elements in the array may have been set to KindOfUninit. auto a = asGlobals(ad); if (a->m_tab->leaked()) return 0; size_t count = 0; auto iter_limit = IterEnd(a); for (auto iter = IterBegin(a); iter != iter_limit; iter = IterAdvance(a, iter)) { ++count; } return count; } Cell GlobalsArray::NvGetKey(const ArrayData* ad, ssize_t pos) { auto a = asGlobals(ad); NameValueTable::Iterator iter(a->m_tab, pos); if (iter.valid()) { auto k = iter.curKey(); if (k->isRefCounted()) { k->incRefCount(); return make_tv<KindOfString>(const_cast<StringData*>(k)); } return make_tv<KindOfPersistentString>(k); } return make_tv<KindOfUninit>(); } const Variant& GlobalsArray::GetValueRef(const ArrayData* ad, ssize_t pos) { auto a = asGlobals(ad); NameValueTable::Iterator iter(a->m_tab, pos); return iter.valid() ? tvAsCVarRef(iter.curVal()) : uninit_variant; } bool GlobalsArray::ExistsInt(const ArrayData* ad, int64_t k) { return ExistsStr(ad, String(k).get()); } bool GlobalsArray::ExistsStr(const ArrayData* ad, const StringData* k) { return asGlobals(ad)->m_tab->lookup(k) != nullptr; } const TypedValue* GlobalsArray::NvGetStr(const ArrayData* ad, const StringData* k) { return asGlobals(ad)->m_tab->lookup(k); } const TypedValue* GlobalsArray::NvGetInt(const ArrayData* ad, int64_t k) { return asGlobals(ad)->m_tab->lookup(String(k).get()); } member_lval GlobalsArray::LvalInt(ArrayData* ad, int64_t k, bool copy) { return LvalStr(ad, String(k).get(), copy); } member_lval GlobalsArray::LvalStr(ArrayData* ad, StringData* k, bool copy) { auto a = asGlobals(ad); TypedValue* tv = a->m_tab->lookup(k); if (!tv) { TypedValue nulVal; tvWriteNull(&nulVal); tv = a->m_tab->set(k, &nulVal); } return member_lval { a, tv }; } member_lval GlobalsArray::LvalNew(ArrayData* ad, bool copy) { return member_lval { ad, lvalBlackHole().asTypedValue() }; } ArrayData* GlobalsArray::SetInt(ArrayData* ad, int64_t k, Cell v, bool copy) { return SetStr(ad, String(k).get(), v, copy); } ArrayData* GlobalsArray::SetStr(ArrayData* ad, StringData* k, Cell v, bool copy) { auto a = asGlobals(ad); cellSet(v, *tvToCell(a->m_tab->lookupAdd(k))); return a; } ArrayData* GlobalsArray::SetRefInt(ArrayData* ad, int64_t k, Variant& v, bool copy) { return asGlobals(ad)->setRef(String(k).get(), v, copy); } ArrayData* GlobalsArray::SetRefStr(ArrayData* ad, StringData* k, Variant& v, bool copy) { auto a = asGlobals(ad); tvAsVariant(a->m_tab->lookupAdd(k)).assignRef(v); return a; } ArrayData* GlobalsArray::RemoveInt(ArrayData* ad, int64_t k, bool copy) { return RemoveStr(ad, String(k).get(), copy); } ArrayData* GlobalsArray::RemoveStr(ArrayData* ad, const StringData* k, bool copy) { auto a = asGlobals(ad); a->m_tab->unset(k); return a; } /* * The messages in the user-visible exceptions below claim we are * $GLOBALS, because the only user-visible GlobalsArray array * is currently $GLOBALS. */ ArrayData* GlobalsArray::Append(ArrayData*, Cell v, bool copy) { throw_not_implemented("append on $GLOBALS"); } ArrayData* GlobalsArray::AppendRef(ArrayData*, Variant&, bool) { throw_not_implemented("appendRef on $GLOBALS"); } ArrayData* GlobalsArray::AppendWithRef(ArrayData*, TypedValue, bool) { throw_not_implemented("appendWithRef on $GLOBALS"); } ArrayData* GlobalsArray::PlusEq(ArrayData*, const ArrayData*) { throw_not_implemented("plus on $GLOBALS"); } ArrayData* GlobalsArray::Merge(ArrayData*, const ArrayData*) { throw_not_implemented("merge on $GLOBALS"); } ArrayData* GlobalsArray::Prepend(ArrayData*, Cell, bool) { throw_not_implemented("prepend on $GLOBALS"); } ssize_t GlobalsArray::IterBegin(const ArrayData* ad) { auto a = asGlobals(ad); NameValueTable::Iterator iter(a->m_tab); return iter.toInteger(); } ssize_t GlobalsArray::IterLast(const ArrayData* ad) { auto a = asGlobals(ad); return NameValueTable::Iterator::getLast(a->m_tab).toInteger(); } ssize_t GlobalsArray::IterEnd(const ArrayData* ad) { auto a = asGlobals(ad); return NameValueTable::Iterator::getEnd(a->m_tab).toInteger(); } ssize_t GlobalsArray::IterAdvance(const ArrayData* ad, ssize_t prev) { auto a = asGlobals(ad); NameValueTable::Iterator iter(a->m_tab, prev); iter.next(); return iter.toInteger(); } ssize_t GlobalsArray::IterRewind(const ArrayData* ad, ssize_t prev) { auto a = asGlobals(ad); NameValueTable::Iterator iter(a->m_tab, prev); iter.prev(); return iter.toInteger(); } bool GlobalsArray::ValidMArrayIter(const ArrayData* ad, const MArrayIter & fp) { assert(fp.getContainer() == ad); auto a = asGlobals(ad); if (fp.getResetFlag()) return false; if (fp.m_pos == IterEnd(a)) return false; NameValueTable::Iterator iter(a->m_tab, fp.m_pos); return iter.valid(); } bool GlobalsArray::AdvanceMArrayIter(ArrayData* ad, MArrayIter& fp) { auto a = asGlobals(ad); bool reset = fp.getResetFlag(); NameValueTable::Iterator iter = reset ? NameValueTable::Iterator(a->m_tab) : NameValueTable::Iterator(a->m_tab, fp.m_pos); if (reset) { fp.setResetFlag(false); } else { if (!iter.valid()) { return false; } iter.next(); } fp.m_pos = iter.toInteger(); if (!iter.valid()) return false; // To conform to PHP behavior, we need to set the internal // cursor to point to the next element. iter.next(); a->m_pos = iter.toInteger(); return true; } ArrayData* GlobalsArray::EscalateForSort(ArrayData* ad, SortFunction sf) { raise_warning("Sorting the $GLOBALS array is not supported"); return ad; } void GlobalsArray::Ksort(ArrayData*, int sort_flags, bool ascending) {} void GlobalsArray::Sort(ArrayData*, int sort_flags, bool ascending) {} void GlobalsArray::Asort(ArrayData*, int sort_flags, bool ascending) {} bool GlobalsArray::Uksort(ArrayData*, const Variant& cmp_function) { return false; } bool GlobalsArray::Usort(ArrayData*, const Variant& cmp_function) { return false; } bool GlobalsArray::Uasort(ArrayData*, const Variant& cmp_function) { return false; } bool GlobalsArray::IsVectorData(const ArrayData*) { return false; } ArrayData* GlobalsArray::CopyWithStrongIterators(const ArrayData* ad) { raise_fatal_error( "Unimplemented ArrayData::copyWithStrongIterators"); } ArrayData* GlobalsArray::CopyStatic(const ArrayData*) { raise_fatal_error("GlobalsArray::copyStatic " "not implemented."); } void GlobalsArray::Renumber(ArrayData*) {} void GlobalsArray::OnSetEvalScalar(ArrayData*) { not_reached(); } ////////////////////////////////////////////////////////////////////// }
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/container for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP #define BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif #include <boost/container/detail/config_begin.hpp> #include <boost/container/detail/workaround.hpp> #include <boost/move/detail/type_traits.hpp> #include <boost/intrusive/detail/mpl.hpp> #include <cstddef> namespace boost { namespace container { namespace dtl { using boost::move_detail::integral_constant; using boost::move_detail::true_type; using boost::move_detail::false_type; using boost::move_detail::enable_if_c; using boost::move_detail::enable_if; using boost::move_detail::enable_if_convertible; using boost::move_detail::disable_if_c; using boost::move_detail::disable_if; using boost::move_detail::disable_if_convertible; using boost::move_detail::is_convertible; using boost::move_detail::if_c; using boost::move_detail::if_; using boost::move_detail::identity; using boost::move_detail::bool_; using boost::move_detail::true_; using boost::move_detail::false_; using boost::move_detail::yes_type; using boost::move_detail::no_type; using boost::move_detail::bool_; using boost::move_detail::true_; using boost::move_detail::false_; using boost::move_detail::unvoid_ref; using boost::move_detail::and_; using boost::move_detail::or_; using boost::move_detail::not_; using boost::move_detail::enable_if_and; using boost::move_detail::disable_if_and; using boost::move_detail::enable_if_or; using boost::move_detail::disable_if_or; using boost::move_detail::remove_const; template <class FirstType> struct select1st { typedef FirstType type; template<class T> BOOST_CONTAINER_FORCEINLINE const type& operator()(const T& x) const { return x.first; } template<class T> BOOST_CONTAINER_FORCEINLINE type& operator()(T& x) { return const_cast<type&>(x.first); } }; template<typename T> struct void_t { typedef void type; }; template <class T, class=void> struct is_transparent_base { static const bool value = false; }; template <class T> struct is_transparent_base<T, typename void_t<typename T::is_transparent>::type> { static const bool value = true; }; template <class T> struct is_transparent : is_transparent_base<T> {}; template <typename C, class /*Dummy*/, typename R> struct enable_if_transparent : boost::move_detail::enable_if_c<dtl::is_transparent<C>::value, R> {}; #ifndef BOOST_CONTAINER_NO_CXX17_CTAD // void_t (void_t for C++11) template<typename...> using variadic_void_t = void; // Trait to detect Allocator-like types. template<typename Allocator, typename = void> struct is_allocator { static const bool value = false; }; template <typename T> T&& ctad_declval(); template<typename Allocator> struct is_allocator < Allocator, variadic_void_t< typename Allocator::value_type , decltype(ctad_declval<Allocator&>().allocate(size_t{})) >> { static const bool value = true; }; template<class T> using require_allocator_t = typename enable_if_c<is_allocator<T>::value, T>::type; template<class T> using require_nonallocator_t = typename enable_if_c<!is_allocator<T>::value, T>::type; #endif } //namespace dtl { } //namespace container { } //namespace boost { #include <boost/container/detail/config_end.hpp> #endif //#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP
;program to turn an led on and off(with some delay) which is interfaced to pin P0.2 org 0000h ;pins are configured as output by default clr p0.2 ;led lights up: 8051 is better at sinking the current than sourcing it acall delay ;call delay routine setting:setb p0.2 ;led turned off sjmp finish delay:mov r0,#0ffh somewhere:mov r1,#0ffh there:mov r2,#0ffh here:djnz r2,here djnz r1,there djnz r0,somewhere sjmp setting finish: end
; ////////////////////////////////////////////////////////////////////////// ; > crc32.asm 2.0 12:53 PM 8/15/2001 CRC-32 Library < ; \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ; ; Source code to the CRC-32 library. ; ; Copyright (c) 1997, 1999 G. Adam Stanislav ; All Rights Reserved. ; ; ////////////////////////////////////////////////////////////////////////// .386 .model flat, stdcall option casemap :none ; case sensitive ; \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ; ////////////////////////////////////////////////////////////////////////// ; CODE SECTION ; \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ .code start: ; ; Sorry, not including the source code here because I did not write it. ; ; You'll have to visit G. Adam Stanislav's website and download the ; CRC-32 2.0 library yourself. Comes pre-compiled as a DLL with an ; example in C and assembly. ; ; Whiz Kid Technomagic ; http://www.geocities.com/SiliconValley/Heights/7394/ ; end start ; ////////////////////////////////////////////////////////////////////////// ; > 43 lines for MASM 6.15.8803 End of CRC-32 Library < ; \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
; A003878: n^4+(9/2)*n^3+n^2-(9/2)*n+1. ; Submitted by Jon Maiga ; 1,3,48,199,543,1191,2278,3963,6429,9883,14556,20703,28603,38559,50898,65971,84153,105843,131464,161463,196311,236503,282558,335019,394453,461451,536628,620623,714099,817743 mov $1,1 sub $1,$0 sub $1,$0 add $0,3 add $1,1 bin $1,2 add $1,1 mul $1,$0 add $1,6 mul $0,$1 div $0,2 sub $0,17
; ; ANSI Video handling for the Jupiter ACE ; ; Stefano Bodrato - Feb. 2001 ; ; Handles colors referring to current PAPER/INK/etc. settings ; ; Scrollup ; ; ; $Id: f_ansi_scrollup.asm,v 1.4 2015/01/19 01:33:18 pauloscustodio Exp $ ; PUBLIC ansi_SCROLLUP .ansi_SCROLLUP ld hl,$2420 ld de,$2400 ld bc,736 ldir ld hl,$2400+736 ld (hl),32 ;' ' ld d,h ld e,l inc de ld bc,31 ldir ret
; A044801: Numbers n such that string 8,8 occurs in the base 10 representation of n but not of n+1. ; 88,188,288,388,488,588,688,788,889,988,1088,1188,1288,1388,1488,1588,1688,1788,1889,1988,2088,2188,2288,2388,2488,2588,2688,2788,2889,2988,3088,3188,3288,3388,3488,3588,3688,3788,3889 mov $2,$0 add $0,2 lpb $0 trn $0,9 mov $1,$0 trn $0,1 lpe lpb $2 add $1,100 sub $2,1 lpe add $1,88 mov $0,$1
SECTION .text GLOBAL square_p434 square_p434: sub rsp, 0x620 ; last 0x30 (6) for Caller - save regs mov [ rsp + 0x5f0 ], rbx; saving to stack mov [ rsp + 0x5f8 ], rbp; saving to stack mov [ rsp + 0x600 ], r12; saving to stack mov [ rsp + 0x608 ], r13; saving to stack mov [ rsp + 0x610 ], r14; saving to stack mov [ rsp + 0x618 ], r15; saving to stack mov rax, [ rsi + 0x10 ]; load m64 x2 to register64 mov rdx, rax; x2 to rdx mulx rax, r10, [ rsi + 0x10 ]; x174, x173<- x2 * arg1[2] mulx r11, rbx, [ rsi + 0x18 ]; x172, x171<- x2 * arg1[3] mulx rbp, r12, [ rsi + 0x28 ]; x168, x167<- x2 * arg1[5] mulx r13, r14, [ rsi + 0x8 ]; x176, x175<- x2 * arg1[1] mulx r15, rcx, [ rsi + 0x0 ]; x178, x177<- x2 * arg1[0] mov r8, [ rsi + 0x28 ]; load m64 x5 to register64 xor r9, r9 adox r14, r15 adox r10, r13 mulx r13, r15, [ rsi + 0x20 ]; x170, x169<- x2 * arg1[4] adox rbx, rax mulx rdx, rax, [ rsi + 0x30 ]; x166, x165<- x2 * arg1[6] adox r15, r11 adox r12, r13 xchg rdx, r8; x5, swapping with x166, which is currently in rdx mulx r11, r13, [ rsi + 0x8 ]; x437, x436<- x5 * arg1[1] adox rax, rbp mulx rbp, r9, [ rsi + 0x28 ]; x429, x428<- x5 * arg1[5] mov [ rsp + 0x0 ], rdi; spilling out1 to mem mov [ rsp + 0x8 ], rax; spilling x189 to mem mulx rdi, rax, [ rsi + 0x0 ]; x439, x438<- x5 * arg1[0] mov [ rsp + 0x10 ], rax; spilling x438 to mem mov [ rsp + 0x18 ], r12; spilling x187 to mem mulx rax, r12, [ rsi + 0x10 ]; x435, x434<- x5 * arg1[2] mov [ rsp + 0x20 ], r15; spilling x185 to mem mov r15, [ rsi + 0x0 ]; load m64 x7 to register64 adcx r13, rdi mov [ rsp + 0x28 ], r13; spilling x440 to mem mulx rdi, r13, [ rsi + 0x30 ]; x427, x426<- x5 * arg1[6] adcx r12, r11 mov [ rsp + 0x30 ], r12; spilling x442 to mem mulx r11, r12, [ rsi + 0x18 ]; x433, x432<- x5 * arg1[3] mov [ rsp + 0x38 ], rbx; spilling x183 to mem mov rbx, rdx; preserving value of x5 into a new reg mov rdx, [ rsi + 0x0 ]; saving arg1[0] in rdx. mov [ rsp + 0x40 ], r10; spilling x181 to mem mov [ rsp + 0x48 ], r14; spilling x179 to mem mulx r10, r14, r15; x21, x20<- x7 * arg1[0] mov rdx, rbx; x5 to rdx mulx rdx, rbx, [ rsi + 0x20 ]; x431, x430<- x5 * arg1[4] adcx r12, rax adcx rbx, r11 mov rax, 0x0 ; moving imm to reg adox r8, rax mov r11, rdx; preserving value of x431 into a new reg mov rdx, [ rsi + 0x8 ]; saving arg1[1] in rdx. mov [ rsp + 0x50 ], rbx; spilling x446 to mem mulx rax, rbx, r15; x19, x18<- x7 * arg1[1] mov rdx, 0xffffffffffffffff ; moving imm to reg mov [ rsp + 0x58 ], r12; spilling x444 to mem mov [ rsp + 0x60 ], r8; spilling x191 to mem mulx r12, r8, r14; x48, x47<- x20 * 0xffffffffffffffff adcx r9, r11 mov r11, rdx; preserving value of 0xffffffffffffffff into a new reg mov rdx, [ rsi + 0x10 ]; saving arg1[2] in rdx. mov [ rsp + 0x68 ], r9; spilling x448 to mem mov [ rsp + 0x70 ], rcx; spilling x177 to mem mulx r9, rcx, r15; x17, x16<- x7 * arg1[2] adcx r13, rbp mov rdx, r11; 0xffffffffffffffff to rdx mulx r11, rbp, r14; x46, x45<- x20 * 0xffffffffffffffff mov rdx, -0x2 ; moving imm to reg inc rdx; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1) adox r8, r14 mov r8, [ rsi + 0x8 ]; load m64 x1 to register64 mov rdx, 0x0 ; moving imm to reg adcx rdi, rdx clc; adcx rbp, r12 mov r12, rdx; preserving value of 0x0 into a new reg mov rdx, [ rsi + 0x0 ]; saving arg1[0] in rdx. mov [ rsp + 0x78 ], rdi; spilling x452 to mem mov [ rsp + 0x80 ], r13; spilling x450 to mem mulx rdi, r13, r8; x91, x90<- x1 * arg1[0] setc dl; spill CF x50 to reg (rdx) clc; adcx rbx, r10 mov r10b, dl; preserving value of x50 into a new reg mov rdx, [ rsi + 0x8 ]; saving arg1[1] in rdx. mov [ rsp + 0x88 ], r9; spilling x17 to mem mulx r12, r9, r8; x89, x88<- x1 * arg1[1] adcx rcx, rax mov rdx, 0xffffffffffffffff ; moving imm to reg mov [ rsp + 0x90 ], r12; spilling x89 to mem mulx rax, r12, r14; x44, x43<- x20 * 0xffffffffffffffff adox rbp, rbx setc bl; spill CF x25 to reg (rbx) clc; adcx r13, rbp mov [ rsp + 0x98 ], rax; spilling x44 to mem mulx rbp, rax, r13; x132, x131<- x105 * 0xffffffffffffffff seto dl; spill OF x65 to reg (rdx) mov [ rsp + 0xa0 ], rbp; spilling x132 to mem mov rbp, 0x0 ; moving imm to reg dec rbp; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) movzx r10, r10b adox r10, rbp; loading flag adox r11, r12 mov r10, 0xffffffffffffffff ; moving imm to reg xchg rdx, r10; 0xffffffffffffffff, swapping with x65, which is currently in rdx mulx r12, rbp, r13; x134, x133<- x105 * 0xffffffffffffffff setc dl; spill CF x106 to reg (rdx) clc; adcx rax, r12 setc r12b; spill CF x136 to reg (r12) clc; adcx r9, rdi seto dil; spill OF x52 to reg (rdi) mov byte [ rsp + 0xa8 ], r12b; spilling byte x136 to mem mov r12, 0x0 ; moving imm to reg dec r12; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) movzx r10, r10b adox r10, r12; loading flag adox rcx, r11 setc r10b; spill CF x93 to reg (r10) clc; adcx rbp, r13 seto bpl; spill OF x67 to reg (rbp) inc r12; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r11, -0x1 ; moving imm to reg movzx rdx, dl adox rdx, r11; loading flag adox rcx, r9 mov rdx, [ rsi + 0x18 ]; arg1[3] to rdx mulx r9, r12, r15; x15, x14<- x7 * arg1[3] adcx rax, rcx mov rdx, r8; x1 to rdx mulx r8, rcx, [ rsi + 0x10 ]; x87, x86<- x1 * arg1[2] mov r11, 0xfdc1767ae2ffffff ; moving imm to reg xchg rdx, r11; 0xfdc1767ae2ffffff, swapping with x1, which is currently in rdx mov [ rsp + 0xb0 ], r8; spilling x87 to mem mov [ rsp + 0xb8 ], r9; spilling x15 to mem mulx r8, r9, r14; x42, x41<- x20 * 0xfdc1767ae2ffffff setc dl; spill CF x151 to reg (rdx) clc; mov [ rsp + 0xc0 ], r8; spilling x42 to mem mov r8, -0x1 ; moving imm to reg movzx rbx, bl adcx rbx, r8; loading flag adcx r12, [ rsp + 0x88 ] setc bl; spill CF x27 to reg (rbx) clc; movzx rdi, dil adcx rdi, r8; loading flag adcx r9, [ rsp + 0x98 ] mov rdi, 0xffffffffffffffff ; moving imm to reg xchg rdx, rdi; 0xffffffffffffffff, swapping with x151, which is currently in rdx mov byte [ rsp + 0xc8 ], bl; spilling byte x27 to mem mulx r8, rbx, r13; x130, x129<- x105 * 0xffffffffffffffff mov rdx, [ rsi + 0x18 ]; load m64 x3 to register64 mov [ rsp + 0xd0 ], r8; spilling x130 to mem setc r8b; spill CF x54 to reg (r8) clc; mov [ rsp + 0xd8 ], rdx; spilling x3 to mem mov rdx, -0x1 ; moving imm to reg movzx r10, r10b adcx r10, rdx; loading flag adcx rcx, [ rsp + 0x90 ] setc r10b; spill CF x95 to reg (r10) clc; adcx rax, [ rsp + 0x70 ] mov rdx, 0xffffffffffffffff ; moving imm to reg mov byte [ rsp + 0xe0 ], r10b; spilling byte x95 to mem mov byte [ rsp + 0xe8 ], r8b; spilling byte x54 to mem mulx r10, r8, rax; x221, x220<- x192 * 0xffffffffffffffff setc dl; spill CF x193 to reg (rdx) clc; mov [ rsp + 0xf0 ], r10; spilling x221 to mem mov r10, -0x1 ; moving imm to reg movzx rbp, bpl adcx rbp, r10; loading flag adcx r12, r9 setc bpl; spill CF x69 to reg (rbp) movzx r9, byte [ rsp + 0xa8 ]; load byte memx136 to register64 clc; adcx r9, r10; loading flag adcx rbx, [ rsp + 0xa0 ] adox rcx, r12 seto r9b; spill OF x110 to reg (r9) inc r10; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r12, -0x1 ; moving imm to reg movzx rdi, dil adox rdi, r12; loading flag adox rcx, rbx mov dil, dl; preserving value of x193 into a new reg mov rdx, [ rsi + 0x20 ]; saving arg1[4] in rdx. mulx rbx, r10, r15; x13, x12<- x7 * arg1[4] seto dl; spill OF x153 to reg (rdx) inc r12; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) adox r8, rax mov r8b, dl; preserving value of x153 into a new reg mov rdx, [ rsi + 0x0 ]; saving arg1[0] in rdx. mov [ rsp + 0xf8 ], rbx; spilling x13 to mem mulx r12, rbx, [ rsp + 0xd8 ]; x265, x264<- x3 * arg1[0] setc dl; spill CF x138 to reg (rdx) clc; mov [ rsp + 0x100 ], r12; spilling x265 to mem mov r12, -0x1 ; moving imm to reg movzx rdi, dil adcx rdi, r12; loading flag adcx rcx, [ rsp + 0x48 ] mov rdi, 0x7bc65c783158aea3 ; moving imm to reg xchg rdx, rdi; 0x7bc65c783158aea3, swapping with x138, which is currently in rdx mov byte [ rsp + 0x108 ], r8b; spilling byte x153 to mem mulx r12, r8, r14; x40, x39<- x20 * 0x7bc65c783158aea3 setc dl; spill CF x195 to reg (rdx) mov [ rsp + 0x110 ], r12; spilling x40 to mem movzx r12, byte [ rsp + 0xc8 ]; load byte memx27 to register64 clc; mov byte [ rsp + 0x118 ], dil; spilling byte x138 to mem mov rdi, -0x1 ; moving imm to reg adcx r12, rdi; loading flag adcx r10, [ rsp + 0xb8 ] mov r12, 0xffffffffffffffff ; moving imm to reg xchg rdx, rax; x192, swapping with x195, which is currently in rdx mov byte [ rsp + 0x120 ], al; spilling byte x195 to mem mulx rdi, rax, r12; x219, x218<- x192 * 0xffffffffffffffff setc r12b; spill CF x29 to reg (r12) clc; adcx rax, [ rsp + 0xf0 ] mov byte [ rsp + 0x128 ], r12b; spilling byte x29 to mem setc r12b; spill CF x223 to reg (r12) mov [ rsp + 0x130 ], rdi; spilling x219 to mem movzx rdi, byte [ rsp + 0xe8 ]; load byte memx54 to register64 clc; mov byte [ rsp + 0x138 ], r9b; spilling byte x110 to mem mov r9, -0x1 ; moving imm to reg adcx rdi, r9; loading flag adcx r8, [ rsp + 0xc0 ] mov rdi, rdx; preserving value of x192 into a new reg mov rdx, [ rsi + 0x18 ]; saving arg1[3] in rdx. mov byte [ rsp + 0x140 ], r12b; spilling byte x223 to mem mulx r9, r12, r11; x85, x84<- x1 * arg1[3] adox rax, rcx seto dl; spill OF x238 to reg (rdx) mov rcx, -0x2 ; moving imm to reg inc rcx; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1) adox rbx, rax mov rax, 0xffffffffffffffff ; moving imm to reg xchg rdx, rbx; x279, swapping with x238, which is currently in rdx mov byte [ rsp + 0x148 ], bl; spilling byte x238 to mem mulx rcx, rbx, rax; x308, x307<- x279 * 0xffffffffffffffff mov [ rsp + 0x150 ], rcx; spilling x308 to mem mov [ rsp + 0x158 ], r9; spilling x85 to mem mulx rcx, r9, rax; x306, x305<- x279 * 0xffffffffffffffff setc al; spill CF x56 to reg (rax) mov [ rsp + 0x160 ], rcx; spilling x306 to mem movzx rcx, byte [ rsp + 0xe0 ]; load byte memx95 to register64 clc; mov [ rsp + 0x168 ], r9; spilling x305 to mem mov r9, -0x1 ; moving imm to reg adcx rcx, r9; loading flag adcx r12, [ rsp + 0xb0 ] mov rcx, 0xffffffffffffffff ; moving imm to reg xchg rdx, rcx; 0xffffffffffffffff, swapping with x279, which is currently in rdx mov byte [ rsp + 0x170 ], al; spilling byte x56 to mem mulx r9, rax, rdi; x217, x216<- x192 * 0xffffffffffffffff mov rdx, [ rsi + 0x20 ]; load m64 x4 to register64 mov [ rsp + 0x178 ], r9; spilling x217 to mem setc r9b; spill CF x97 to reg (r9) clc; mov [ rsp + 0x180 ], rdx; spilling x4 to mem mov rdx, -0x1 ; moving imm to reg movzx rbp, bpl adcx rbp, rdx; loading flag adcx r10, r8 mov rbp, 0xfdc1767ae2ffffff ; moving imm to reg mov rdx, r13; x105 to rdx mulx r13, r8, rbp; x128, x127<- x105 * 0xfdc1767ae2ffffff setc bpl; spill CF x71 to reg (rbp) clc; adcx rbx, rcx setc bl; spill CF x323 to reg (rbx) mov [ rsp + 0x188 ], r13; spilling x128 to mem movzx r13, byte [ rsp + 0x138 ]; load byte memx110 to register64 clc; mov byte [ rsp + 0x190 ], bpl; spilling byte x71 to mem mov rbp, -0x1 ; moving imm to reg adcx r13, rbp; loading flag adcx r10, r12 setc r13b; spill CF x112 to reg (r13) movzx r12, byte [ rsp + 0x118 ]; load byte memx138 to register64 clc; adcx r12, rbp; loading flag adcx r8, [ rsp + 0xd0 ] setc r12b; spill CF x140 to reg (r12) movzx rbp, byte [ rsp + 0x140 ]; load byte memx223 to register64 clc; mov byte [ rsp + 0x198 ], r13b; spilling byte x112 to mem mov r13, -0x1 ; moving imm to reg adcx rbp, r13; loading flag adcx rax, [ rsp + 0x130 ] mov rbp, rdx; preserving value of x105 into a new reg mov rdx, [ rsi + 0x20 ]; saving arg1[4] in rdx. mov byte [ rsp + 0x1a0 ], r12b; spilling byte x140 to mem mulx r13, r12, r11; x83, x82<- x1 * arg1[4] setc dl; spill CF x225 to reg (rdx) clc; mov [ rsp + 0x1a8 ], r13; spilling x83 to mem mov r13, -0x1 ; moving imm to reg movzx r9, r9b adcx r9, r13; loading flag adcx r12, [ rsp + 0x158 ] seto r9b; spill OF x280 to reg (r9) movzx r13, byte [ rsp + 0x108 ]; load byte memx153 to register64 mov byte [ rsp + 0x1b0 ], dl; spilling byte x225 to mem mov rdx, 0x0 ; moving imm to reg dec rdx; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox r13, rdx; loading flag adox r10, r8 mov r13, [ rsp + 0x150 ]; load m64 x308 to register64 setc r8b; spill CF x99 to reg (r8) clc; adcx r13, [ rsp + 0x168 ] mov rdx, [ rsi + 0x0 ]; arg1[0] to rdx mov byte [ rsp + 0x1b8 ], r8b; spilling byte x99 to mem mov [ rsp + 0x1c0 ], r12; spilling x98 to mem mulx r8, r12, [ rsp + 0x180 ]; x352, x351<- x4 * arg1[0] setc dl; spill CF x310 to reg (rdx) mov [ rsp + 0x1c8 ], r8; spilling x352 to mem movzx r8, byte [ rsp + 0x120 ]; load byte memx195 to register64 clc; mov [ rsp + 0x1d0 ], r12; spilling x351 to mem mov r12, -0x1 ; moving imm to reg adcx r8, r12; loading flag adcx r10, [ rsp + 0x40 ] mov r8b, dl; preserving value of x310 into a new reg mov rdx, [ rsi + 0x28 ]; saving arg1[5] in rdx. mov [ rsp + 0x1d8 ], r13; spilling x309 to mem mulx r12, r13, r15; x11, x10<- x7 * arg1[5] seto dl; spill OF x155 to reg (rdx) mov byte [ rsp + 0x1e0 ], r8b; spilling byte x310 to mem movzx r8, byte [ rsp + 0x148 ]; load byte memx238 to register64 mov [ rsp + 0x1e8 ], r12; spilling x11 to mem mov r12, -0x1 ; moving imm to reg inc r12; OF<-0x0, preserve CF (debug: state 5 (thanks Paul)) mov r12, -0x1 ; moving imm to reg adox r8, r12; loading flag adox r10, rax mov r8b, dl; preserving value of x155 into a new reg mov rdx, [ rsi + 0x8 ]; saving arg1[1] in rdx. mulx rax, r12, [ rsp + 0xd8 ]; x263, x262<- x3 * arg1[1] setc dl; spill CF x197 to reg (rdx) clc; adcx r12, [ rsp + 0x100 ] mov [ rsp + 0x1f0 ], rax; spilling x263 to mem mov rax, 0x6cfc5fd681c52056 ; moving imm to reg xchg rdx, r14; x20, swapping with x197, which is currently in rdx mov byte [ rsp + 0x1f8 ], r14b; spilling byte x197 to mem mov byte [ rsp + 0x200 ], r8b; spilling byte x155 to mem mulx r14, r8, rax; x38, x37<- x20 * 0x6cfc5fd681c52056 setc al; spill CF x267 to reg (rax) clc; mov [ rsp + 0x208 ], r14; spilling x38 to mem mov r14, -0x1 ; moving imm to reg movzx r9, r9b adcx r9, r14; loading flag adcx r10, r12 setc r9b; spill CF x282 to reg (r9) clc; movzx rbx, bl adcx rbx, r14; loading flag adcx r10, [ rsp + 0x1d8 ] seto bl; spill OF x240 to reg (rbx) movzx r12, byte [ rsp + 0x170 ]; load byte memx56 to register64 inc r14; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r14, -0x1 ; moving imm to reg adox r12, r14; loading flag adox r8, [ rsp + 0x110 ] setc r12b; spill CF x325 to reg (r12) clc; adcx r10, [ rsp + 0x1d0 ] mov r14, 0x7bc65c783158aea3 ; moving imm to reg xchg rdx, rbp; x105, swapping with x20, which is currently in rdx mov byte [ rsp + 0x210 ], r12b; spilling byte x325 to mem mov byte [ rsp + 0x218 ], r9b; spilling byte x282 to mem mulx r12, r9, r14; x126, x125<- x105 * 0x7bc65c783158aea3 setc r14b; spill CF x367 to reg (r14) mov [ rsp + 0x220 ], r12; spilling x126 to mem movzx r12, byte [ rsp + 0x128 ]; load byte memx29 to register64 clc; mov byte [ rsp + 0x228 ], al; spilling byte x267 to mem mov rax, -0x1 ; moving imm to reg adcx r12, rax; loading flag adcx r13, [ rsp + 0xf8 ] mov r12, 0xffffffffffffffff ; moving imm to reg xchg rdx, r12; 0xffffffffffffffff, swapping with x105, which is currently in rdx mov byte [ rsp + 0x230 ], r14b; spilling byte x367 to mem mulx rax, r14, r10; x395, x394<- x366 * 0xffffffffffffffff setc dl; spill CF x31 to reg (rdx) mov [ rsp + 0x238 ], rax; spilling x395 to mem movzx rax, byte [ rsp + 0x190 ]; load byte memx71 to register64 clc; mov byte [ rsp + 0x240 ], bl; spilling byte x240 to mem mov rbx, -0x1 ; moving imm to reg adcx rax, rbx; loading flag adcx r13, r8 mov rax, 0xfdc1767ae2ffffff ; moving imm to reg xchg rdx, rdi; x192, swapping with x31, which is currently in rdx mulx r8, rbx, rax; x215, x214<- x192 * 0xfdc1767ae2ffffff setc al; spill CF x73 to reg (rax) clc; adcx r14, r10 setc r14b; spill CF x410 to reg (r14) mov [ rsp + 0x248 ], r8; spilling x215 to mem movzx r8, byte [ rsp + 0x198 ]; load byte memx112 to register64 clc; mov byte [ rsp + 0x250 ], al; spilling byte x73 to mem mov rax, -0x1 ; moving imm to reg adcx r8, rax; loading flag adcx r13, [ rsp + 0x1c0 ] mov r8, rdx; preserving value of x192 into a new reg mov rdx, [ rsi + 0x10 ]; saving arg1[2] in rdx. mov byte [ rsp + 0x258 ], r14b; spilling byte x410 to mem mulx rax, r14, [ rsp + 0xd8 ]; x261, x260<- x3 * arg1[2] setc dl; spill CF x114 to reg (rdx) mov [ rsp + 0x260 ], rax; spilling x261 to mem movzx rax, byte [ rsp + 0x1a0 ]; load byte memx140 to register64 clc; mov [ rsp + 0x268 ], r14; spilling x260 to mem mov r14, -0x1 ; moving imm to reg adcx rax, r14; loading flag adcx r9, [ rsp + 0x188 ] seto al; spill OF x58 to reg (rax) movzx r14, byte [ rsp + 0x1b0 ]; load byte memx225 to register64 mov byte [ rsp + 0x270 ], dl; spilling byte x114 to mem mov rdx, 0x0 ; moving imm to reg dec rdx; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox r14, rdx; loading flag adox rbx, [ rsp + 0x178 ] mov r14, 0x2341f27177344 ; moving imm to reg mov rdx, rbp; x20 to rdx mulx rdx, rbp, r14; x36, x35<- x20 * 0x2341f27177344 mov r14, rdx; preserving value of x36 into a new reg mov rdx, [ rsi + 0x8 ]; saving arg1[1] in rdx. mov [ rsp + 0x278 ], rbp; spilling x35 to mem mov byte [ rsp + 0x280 ], al; spilling byte x58 to mem mulx rbp, rax, [ rsp + 0x180 ]; x350, x349<- x4 * arg1[1] setc dl; spill CF x142 to reg (rdx) mov [ rsp + 0x288 ], r14; spilling x36 to mem movzx r14, byte [ rsp + 0x200 ]; load byte memx155 to register64 clc; mov [ rsp + 0x290 ], rbp; spilling x350 to mem mov rbp, -0x1 ; moving imm to reg adcx r14, rbp; loading flag adcx r13, r9 xchg rdx, r15; x7, swapping with x142, which is currently in rdx mulx rdx, r14, [ rsi + 0x30 ]; x9, x8<- x7 * arg1[6] seto r9b; spill OF x227 to reg (r9) movzx rbp, byte [ rsp + 0x1f8 ]; load byte memx197 to register64 mov [ rsp + 0x298 ], rdx; spilling x9 to mem mov rdx, 0x0 ; moving imm to reg dec rdx; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox rbp, rdx; loading flag adox r13, [ rsp + 0x38 ] mov rbp, 0xffffffffffffffff ; moving imm to reg mov rdx, rbp; 0xffffffffffffffff to rdx mov byte [ rsp + 0x2a0 ], r9b; spilling byte x227 to mem mulx rbp, r9, rcx; x304, x303<- x279 * 0xffffffffffffffff setc dl; spill CF x157 to reg (rdx) mov byte [ rsp + 0x2a8 ], r15b; spilling byte x142 to mem movzx r15, byte [ rsp + 0x240 ]; load byte memx240 to register64 clc; mov [ rsp + 0x2b0 ], rbp; spilling x304 to mem mov rbp, -0x1 ; moving imm to reg adcx r15, rbp; loading flag adcx r13, rbx setc r15b; spill CF x242 to reg (r15) clc; movzx rdi, dil adcx rdi, rbp; loading flag adcx r14, [ rsp + 0x1e8 ] mov rdi, [ rsp + 0x268 ]; load m64 x260 to register64 setc bl; spill CF x33 to reg (rbx) movzx rbp, byte [ rsp + 0x228 ]; load byte memx267 to register64 clc; mov byte [ rsp + 0x2b8 ], r15b; spilling byte x242 to mem mov r15, -0x1 ; moving imm to reg adcx rbp, r15; loading flag adcx rdi, [ rsp + 0x1f0 ] setc bpl; spill CF x269 to reg (rbp) clc; adcx rax, [ rsp + 0x1c8 ] setc r15b; spill CF x354 to reg (r15) mov byte [ rsp + 0x2c0 ], bpl; spilling byte x269 to mem movzx rbp, byte [ rsp + 0x218 ]; load byte memx282 to register64 clc; mov byte [ rsp + 0x2c8 ], bl; spilling byte x33 to mem mov rbx, -0x1 ; moving imm to reg adcx rbp, rbx; loading flag adcx r13, rdi mov rbp, [ rsp + 0x208 ]; load m64 x38 to register64 setc dil; spill CF x284 to reg (rdi) movzx rbx, byte [ rsp + 0x280 ]; load byte memx58 to register64 clc; mov byte [ rsp + 0x2d0 ], dl; spilling byte x157 to mem mov rdx, -0x1 ; moving imm to reg adcx rbx, rdx; loading flag adcx rbp, [ rsp + 0x278 ] setc bl; spill CF x60 to reg (rbx) movzx rdx, byte [ rsp + 0x1e0 ]; load byte memx310 to register64 clc; mov byte [ rsp + 0x2d8 ], dil; spilling byte x284 to mem mov rdi, -0x1 ; moving imm to reg adcx rdx, rdi; loading flag adcx r9, [ rsp + 0x160 ] setc dl; spill CF x312 to reg (rdx) movzx rdi, byte [ rsp + 0x210 ]; load byte memx325 to register64 clc; mov byte [ rsp + 0x2e0 ], bl; spilling byte x60 to mem mov rbx, -0x1 ; moving imm to reg adcx rdi, rbx; loading flag adcx r13, r9 mov dil, dl; preserving value of x312 into a new reg mov rdx, [ rsi + 0x28 ]; saving arg1[5] in rdx. mulx r9, rbx, r11; x81, x80<- x1 * arg1[5] setc dl; spill CF x327 to reg (rdx) mov [ rsp + 0x2e8 ], r9; spilling x81 to mem movzx r9, byte [ rsp + 0x250 ]; load byte memx73 to register64 clc; mov byte [ rsp + 0x2f0 ], r15b; spilling byte x354 to mem mov r15, -0x1 ; moving imm to reg adcx r9, r15; loading flag adcx r14, rbp mov r9, 0xffffffffffffffff ; moving imm to reg xchg rdx, r10; x366, swapping with x327, which is currently in rdx mulx rbp, r15, r9; x393, x392<- x366 * 0xffffffffffffffff seto r9b; spill OF x199 to reg (r9) mov [ rsp + 0x2f8 ], rbp; spilling x393 to mem mov rbp, -0x2 ; moving imm to reg inc rbp; OF<-0x0, preserve CF (debug: 6; load -2, increase it, save as -1) adox r15, [ rsp + 0x238 ] setc bpl; spill CF x75 to reg (rbp) mov byte [ rsp + 0x300 ], r10b; spilling byte x327 to mem movzx r10, byte [ rsp + 0x230 ]; load byte memx367 to register64 clc; mov byte [ rsp + 0x308 ], r9b; spilling byte x199 to mem mov r9, -0x1 ; moving imm to reg adcx r10, r9; loading flag adcx r13, rax setc r10b; spill CF x369 to reg (r10) movzx rax, byte [ rsp + 0x258 ]; load byte memx410 to register64 clc; adcx rax, r9; loading flag adcx r13, r15 mov rax, 0xfdc1767ae2ffffff ; moving imm to reg xchg rdx, rax; 0xfdc1767ae2ffffff, swapping with x366, which is currently in rdx mulx r15, r9, rcx; x302, x301<- x279 * 0xfdc1767ae2ffffff setc dl; spill CF x412 to reg (rdx) clc; mov [ rsp + 0x310 ], r13; spilling x411 to mem mov r13, -0x1 ; moving imm to reg movzx rdi, dil adcx rdi, r13; loading flag adcx r9, [ rsp + 0x2b0 ] seto dil; spill OF x397 to reg (rdi) movzx r13, byte [ rsp + 0x1b8 ]; load byte memx99 to register64 mov [ rsp + 0x318 ], r15; spilling x302 to mem mov r15, 0x0 ; moving imm to reg dec r15; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox r13, r15; loading flag adox rbx, [ rsp + 0x1a8 ] mov r13, 0x7bc65c783158aea3 ; moving imm to reg xchg rdx, r13; 0x7bc65c783158aea3, swapping with x412, which is currently in rdx mov byte [ rsp + 0x320 ], bpl; spilling byte x75 to mem mulx r15, rbp, r8; x213, x212<- x192 * 0x7bc65c783158aea3 seto dl; spill OF x101 to reg (rdx) mov [ rsp + 0x328 ], r15; spilling x213 to mem movzx r15, byte [ rsp + 0x270 ]; load byte memx114 to register64 mov byte [ rsp + 0x330 ], r13b; spilling byte x412 to mem mov r13, -0x1 ; moving imm to reg inc r13; OF<-0x0, preserve CF (debug: state 5 (thanks Paul)) mov r13, -0x1 ; moving imm to reg adox r15, r13; loading flag adox r14, rbx mov r15, 0x6cfc5fd681c52056 ; moving imm to reg xchg rdx, r15; 0x6cfc5fd681c52056, swapping with x101, which is currently in rdx mulx rbx, r13, r12; x124, x123<- x105 * 0x6cfc5fd681c52056 setc dl; spill CF x314 to reg (rdx) mov [ rsp + 0x338 ], rbx; spilling x124 to mem movzx rbx, byte [ rsp + 0x2a8 ]; load byte memx142 to register64 clc; mov byte [ rsp + 0x340 ], r15b; spilling byte x101 to mem mov r15, -0x1 ; moving imm to reg adcx rbx, r15; loading flag adcx r13, [ rsp + 0x220 ] mov bl, dl; preserving value of x314 into a new reg mov rdx, [ rsi + 0x10 ]; saving arg1[2] in rdx. mov byte [ rsp + 0x348 ], dil; spilling byte x397 to mem mulx r15, rdi, [ rsp + 0x180 ]; x348, x347<- x4 * arg1[2] seto dl; spill OF x116 to reg (rdx) mov byte [ rsp + 0x350 ], bl; spilling byte x314 to mem movzx rbx, byte [ rsp + 0x2f0 ]; load byte memx354 to register64 mov [ rsp + 0x358 ], r15; spilling x348 to mem mov r15, 0x0 ; moving imm to reg dec r15; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox rbx, r15; loading flag adox rdi, [ rsp + 0x290 ] setc bl; spill CF x144 to reg (rbx) movzx r15, byte [ rsp + 0x2d0 ]; load byte memx157 to register64 clc; mov byte [ rsp + 0x360 ], dl; spilling byte x116 to mem mov rdx, -0x1 ; moving imm to reg adcx r15, rdx; loading flag adcx r14, r13 seto r15b; spill OF x356 to reg (r15) movzx r13, byte [ rsp + 0x308 ]; load byte memx199 to register64 inc rdx; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov rdx, -0x1 ; moving imm to reg adox r13, rdx; loading flag adox r14, [ rsp + 0x20 ] movzx r13, byte [ rsp + 0x2c8 ]; x34, copying x33 here, cause x33 is needed in a reg for other than x34, namely all: , x34, size: 1 mov rdx, [ rsp + 0x298 ]; load m64 x9 to register64 lea r13, [ r13 + rdx ]; r8/64 + m8 setc dl; spill CF x159 to reg (rdx) mov byte [ rsp + 0x368 ], r15b; spilling byte x356 to mem movzx r15, byte [ rsp + 0x2a0 ]; load byte memx227 to register64 clc; mov byte [ rsp + 0x370 ], bl; spilling byte x144 to mem mov rbx, -0x1 ; moving imm to reg adcx r15, rbx; loading flag adcx rbp, [ rsp + 0x248 ] mov r15b, dl; preserving value of x159 into a new reg mov rdx, [ rsi + 0x18 ]; saving arg1[3] in rdx. mov [ rsp + 0x378 ], r13; spilling x34 to mem mulx rbx, r13, [ rsp + 0xd8 ]; x259, x258<- x3 * arg1[3] seto dl; spill OF x201 to reg (rdx) mov byte [ rsp + 0x380 ], r15b; spilling byte x159 to mem movzx r15, byte [ rsp + 0x2c0 ]; load byte memx269 to register64 mov [ rsp + 0x388 ], rbx; spilling x259 to mem mov rbx, -0x1 ; moving imm to reg inc rbx; OF<-0x0, preserve CF (debug: state 5 (thanks Paul)) mov rbx, -0x1 ; moving imm to reg adox r15, rbx; loading flag adox r13, [ rsp + 0x260 ] mov r15b, dl; preserving value of x201 into a new reg mov rdx, [ rsi + 0x30 ]; saving arg1[6] in rdx. mulx r11, rbx, r11; x79, x78<- x1 * arg1[6] seto dl; spill OF x271 to reg (rdx) mov [ rsp + 0x390 ], r11; spilling x79 to mem movzx r11, byte [ rsp + 0x2b8 ]; load byte memx242 to register64 mov byte [ rsp + 0x398 ], r15b; spilling byte x201 to mem mov r15, 0x0 ; moving imm to reg dec r15; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox r11, r15; loading flag adox r14, rbp setc r11b; spill CF x229 to reg (r11) movzx rbp, byte [ rsp + 0x2d8 ]; load byte memx284 to register64 clc; adcx rbp, r15; loading flag adcx r14, r13 mov rbp, 0xffffffffffffffff ; moving imm to reg xchg rdx, rbp; 0xffffffffffffffff, swapping with x271, which is currently in rdx mulx r13, r15, rax; x391, x390<- x366 * 0xffffffffffffffff seto dl; spill OF x244 to reg (rdx) mov [ rsp + 0x3a0 ], r13; spilling x391 to mem movzx r13, byte [ rsp + 0x300 ]; load byte memx327 to register64 mov byte [ rsp + 0x3a8 ], r11b; spilling byte x229 to mem mov r11, -0x1 ; moving imm to reg inc r11; OF<-0x0, preserve CF (debug: state 5 (thanks Paul)) mov r11, -0x1 ; moving imm to reg adox r13, r11; loading flag adox r14, r9 mov r13, 0x6cfc5fd681c52056 ; moving imm to reg xchg rdx, r13; 0x6cfc5fd681c52056, swapping with x244, which is currently in rdx mulx r9, r11, r8; x211, x210<- x192 * 0x6cfc5fd681c52056 setc dl; spill CF x286 to reg (rdx) clc; mov [ rsp + 0x3b0 ], r9; spilling x211 to mem mov r9, -0x1 ; moving imm to reg movzx r10, r10b adcx r10, r9; loading flag adcx r14, rdi setc r10b; spill CF x371 to reg (r10) movzx rdi, byte [ rsp + 0x348 ]; load byte memx397 to register64 clc; adcx rdi, r9; loading flag adcx r15, [ rsp + 0x2f8 ] mov dil, dl; preserving value of x286 into a new reg mov rdx, [ rsi + 0x20 ]; saving arg1[4] in rdx. mov byte [ rsp + 0x3b8 ], r10b; spilling byte x371 to mem mulx r9, r10, [ rsp + 0xd8 ]; x257, x256<- x3 * arg1[4] setc dl; spill CF x399 to reg (rdx) mov [ rsp + 0x3c0 ], r9; spilling x257 to mem movzx r9, byte [ rsp + 0x330 ]; load byte memx412 to register64 clc; mov byte [ rsp + 0x3c8 ], dil; spilling byte x286 to mem mov rdi, -0x1 ; moving imm to reg adcx r9, rdi; loading flag adcx r14, r15 movzx r9, byte [ rsp + 0x2e0 ]; x61, copying x60 here, cause x60 is needed in a reg for other than x61, namely all: , x61, size: 1 mov r15, [ rsp + 0x288 ]; load m64 x36 to register64 lea r9, [ r9 + r15 ]; r8/64 + m8 setc r15b; spill CF x414 to reg (r15) clc; movzx rbp, bpl adcx rbp, rdi; loading flag adcx r10, [ rsp + 0x388 ] setc bpl; spill CF x273 to reg (rbp) movzx rdi, byte [ rsp + 0x320 ]; load byte memx75 to register64 clc; mov [ rsp + 0x3d0 ], r14; spilling x413 to mem mov r14, -0x1 ; moving imm to reg adcx rdi, r14; loading flag adcx r9, [ rsp + 0x378 ] mov dil, dl; preserving value of x399 into a new reg mov rdx, [ rsi + 0x18 ]; saving arg1[3] in rdx. mov byte [ rsp + 0x3d8 ], bpl; spilling byte x273 to mem mulx r14, rbp, [ rsp + 0x180 ]; x346, x345<- x4 * arg1[3] setc dl; spill CF x77 to reg (rdx) mov [ rsp + 0x3e0 ], r14; spilling x346 to mem movzx r14, byte [ rsp + 0x340 ]; load byte memx101 to register64 clc; mov byte [ rsp + 0x3e8 ], r15b; spilling byte x414 to mem mov r15, -0x1 ; moving imm to reg adcx r14, r15; loading flag adcx rbx, [ rsp + 0x2e8 ] mov r14, 0x2341f27177344 ; moving imm to reg xchg rdx, r12; x105, swapping with x77, which is currently in rdx mulx rdx, r15, r14; x122, x121<- x105 * 0x2341f27177344 setc r14b; spill CF x103 to reg (r14) mov byte [ rsp + 0x3f0 ], r12b; spilling byte x77 to mem movzx r12, byte [ rsp + 0x360 ]; load byte memx116 to register64 clc; mov byte [ rsp + 0x3f8 ], dil; spilling byte x399 to mem mov rdi, -0x1 ; moving imm to reg adcx r12, rdi; loading flag adcx r9, rbx setc r12b; spill CF x118 to reg (r12) movzx rbx, byte [ rsp + 0x370 ]; load byte memx144 to register64 clc; adcx rbx, rdi; loading flag adcx r15, [ rsp + 0x338 ] setc bl; spill CF x146 to reg (rbx) movzx rdi, byte [ rsp + 0x380 ]; load byte memx159 to register64 clc; mov byte [ rsp + 0x400 ], r12b; spilling byte x118 to mem mov r12, -0x1 ; moving imm to reg adcx rdi, r12; loading flag adcx r9, r15 setc dil; spill CF x161 to reg (rdi) movzx r15, byte [ rsp + 0x398 ]; load byte memx201 to register64 clc; adcx r15, r12; loading flag adcx r9, [ rsp + 0x18 ] setc r15b; spill CF x203 to reg (r15) movzx r12, byte [ rsp + 0x3a8 ]; load byte memx229 to register64 clc; mov byte [ rsp + 0x408 ], dil; spilling byte x161 to mem mov rdi, -0x1 ; moving imm to reg adcx r12, rdi; loading flag adcx r11, [ rsp + 0x328 ] seto r12b; spill OF x329 to reg (r12) inc rdi; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov rdi, -0x1 ; moving imm to reg movzx r13, r13b adox r13, rdi; loading flag adox r9, r11 mov r13, 0x7bc65c783158aea3 ; moving imm to reg xchg rdx, r13; 0x7bc65c783158aea3, swapping with x122, which is currently in rdx mulx r11, rdi, rcx; x300, x299<- x279 * 0x7bc65c783158aea3 seto dl; spill OF x246 to reg (rdx) mov [ rsp + 0x410 ], r11; spilling x300 to mem movzx r11, byte [ rsp + 0x368 ]; load byte memx356 to register64 mov byte [ rsp + 0x418 ], r15b; spilling byte x203 to mem mov r15, 0x0 ; moving imm to reg dec r15; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox r11, r15; loading flag adox rbp, [ rsp + 0x358 ] mov r11, 0xfdc1767ae2ffffff ; moving imm to reg xchg rdx, r11; 0xfdc1767ae2ffffff, swapping with x246, which is currently in rdx mov byte [ rsp + 0x420 ], r11b; spilling byte x246 to mem mulx r15, r11, rax; x389, x388<- x366 * 0xfdc1767ae2ffffff setc dl; spill CF x231 to reg (rdx) mov [ rsp + 0x428 ], r15; spilling x389 to mem movzx r15, byte [ rsp + 0x3c8 ]; load byte memx286 to register64 clc; mov byte [ rsp + 0x430 ], r14b; spilling byte x103 to mem mov r14, -0x1 ; moving imm to reg adcx r15, r14; loading flag adcx r9, r10 seto r15b; spill OF x358 to reg (r15) movzx r10, byte [ rsp + 0x350 ]; load byte memx314 to register64 inc r14; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r14, -0x1 ; moving imm to reg adox r10, r14; loading flag adox rdi, [ rsp + 0x318 ] seto r10b; spill OF x316 to reg (r10) inc r14; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r14, -0x1 ; moving imm to reg movzx r12, r12b adox r12, r14; loading flag adox r9, rdi movzx r12, bl; x147, copying x146 here, cause x146 is needed in a reg for other than x147, namely all: , x147, size: 1 lea r12, [ r12 + r13 ] setc r13b; spill CF x288 to reg (r13) movzx rbx, byte [ rsp + 0x3b8 ]; load byte memx371 to register64 clc; adcx rbx, r14; loading flag adcx r9, rbp mov rbx, 0x2341f27177344 ; moving imm to reg xchg rdx, r8; x192, swapping with x231, which is currently in rdx mulx rdx, rbp, rbx; x209, x208<- x192 * 0x2341f27177344 setc dil; spill CF x373 to reg (rdi) movzx r14, byte [ rsp + 0x3f8 ]; load byte memx399 to register64 clc; mov rbx, -0x1 ; moving imm to reg adcx r14, rbx; loading flag adcx r11, [ rsp + 0x3a0 ] movzx r14, byte [ rsp + 0x430 ]; x104, copying x103 here, cause x103 is needed in a reg for other than x104, namely all: , x104, size: 1 mov rbx, [ rsp + 0x390 ]; load m64 x79 to register64 lea r14, [ r14 + rbx ]; r8/64 + m8 seto bl; spill OF x331 to reg (rbx) mov [ rsp + 0x438 ], rdx; spilling x209 to mem movzx rdx, byte [ rsp + 0x400 ]; load byte memx118 to register64 mov byte [ rsp + 0x440 ], dil; spilling byte x373 to mem mov rdi, 0x0 ; moving imm to reg dec rdi; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) mov byte [ rsp + 0x448 ], r15b; spilling byte x358 to mem movzx r15, byte [ rsp + 0x3f0 ]; load byte memx77 to register64 adox rdx, rdi; loading flag adox r14, r15 setc r15b; spill CF x401 to reg (r15) movzx rdx, byte [ rsp + 0x408 ]; load byte memx161 to register64 clc; adcx rdx, rdi; loading flag adcx r14, r12 mov rdx, 0x6cfc5fd681c52056 ; moving imm to reg mulx r12, rdi, rcx; x298, x297<- x279 * 0x6cfc5fd681c52056 setc dl; spill CF x163 to reg (rdx) clc; mov [ rsp + 0x450 ], r12; spilling x298 to mem mov r12, -0x1 ; moving imm to reg movzx r8, r8b adcx r8, r12; loading flag adcx rbp, [ rsp + 0x3b0 ] setc r8b; spill CF x233 to reg (r8) movzx r12, byte [ rsp + 0x3e8 ]; load byte memx414 to register64 clc; mov byte [ rsp + 0x458 ], r15b; spilling byte x401 to mem mov r15, -0x1 ; moving imm to reg adcx r12, r15; loading flag adcx r9, r11 setc r12b; spill CF x416 to reg (r12) movzx r11, byte [ rsp + 0x418 ]; load byte memx203 to register64 clc; adcx r11, r15; loading flag adcx r14, [ rsp + 0x8 ] seto r11b; spill OF x120 to reg (r11) movzx r15, byte [ rsp + 0x420 ]; load byte memx246 to register64 mov [ rsp + 0x460 ], r9; spilling x415 to mem mov r9, 0x0 ; moving imm to reg dec r9; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox r15, r9; loading flag adox r14, rbp mov r15b, dl; preserving value of x163 into a new reg mov rdx, [ rsi + 0x28 ]; saving arg1[5] in rdx. mulx rbp, r9, [ rsp + 0xd8 ]; x255, x254<- x3 * arg1[5] mov rdx, [ rsi + 0x20 ]; arg1[4] to rdx mov byte [ rsp + 0x468 ], r12b; spilling byte x416 to mem mov [ rsp + 0x470 ], rbp; spilling x255 to mem mulx r12, rbp, [ rsp + 0x180 ]; x344, x343<- x4 * arg1[4] movzx rdx, r15b; x164, copying x163 here, cause x163 is needed in a reg for other than x164, namely all: , x164, size: 1 movzx r11, r11b lea rdx, [ rdx + r11 ] seto r11b; spill OF x248 to reg (r11) movzx r15, byte [ rsp + 0x3d8 ]; load byte memx273 to register64 mov [ rsp + 0x478 ], r12; spilling x344 to mem mov r12, 0x0 ; moving imm to reg dec r12; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox r15, r12; loading flag adox r9, [ rsp + 0x3c0 ] seto r15b; spill OF x275 to reg (r15) inc r12; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r12, -0x1 ; moving imm to reg movzx r13, r13b adox r13, r12; loading flag adox r14, r9 mov r13, [ rsp + 0x60 ]; x206, copying x191 here, cause x191 is needed in a reg for other than x206, namely all: , x206--x207, size: 1 adcx r13, rdx setc dl; spill CF x207 to reg (rdx) clc; movzx r10, r10b adcx r10, r12; loading flag adcx rdi, [ rsp + 0x410 ] seto r10b; spill OF x290 to reg (r10) movzx r9, byte [ rsp + 0x448 ]; load byte memx358 to register64 inc r12; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r12, -0x1 ; moving imm to reg adox r9, r12; loading flag adox rbp, [ rsp + 0x3e0 ] seto r9b; spill OF x360 to reg (r9) inc r12; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r12, -0x1 ; moving imm to reg movzx rbx, bl adox rbx, r12; loading flag adox r14, rdi setc bl; spill CF x318 to reg (rbx) movzx rdi, byte [ rsp + 0x440 ]; load byte memx373 to register64 clc; adcx rdi, r12; loading flag adcx r14, rbp mov rdi, 0x2341f27177344 ; moving imm to reg xchg rdx, rdi; 0x2341f27177344, swapping with x207, which is currently in rdx mulx rbp, r12, rax; x383, x382<- x366 * 0x2341f27177344 mov rdx, 0x6cfc5fd681c52056 ; moving imm to reg mov byte [ rsp + 0x480 ], dil; spilling byte x207 to mem mov byte [ rsp + 0x488 ], r9b; spilling byte x360 to mem mulx rdi, r9, rax; x385, x384<- x366 * 0x6cfc5fd681c52056 movzx rdx, r8b; x234, copying x233 here, cause x233 is needed in a reg for other than x234, namely all: , x234, size: 1 mov [ rsp + 0x490 ], rbp; spilling x383 to mem mov rbp, [ rsp + 0x438 ]; load m64 x209 to register64 lea rdx, [ rdx + rbp ]; r8/64 + m8 mov rbp, 0x2341f27177344 ; moving imm to reg xchg rdx, rbp; 0x2341f27177344, swapping with x234, which is currently in rdx mulx rcx, r8, rcx; x296, x295<- x279 * 0x2341f27177344 mov [ rsp + 0x498 ], rcx; spilling x296 to mem mov rcx, rdx; preserving value of 0x2341f27177344 into a new reg mov rdx, [ rsi + 0x28 ]; saving arg1[5] in rdx. mov [ rsp + 0x4a0 ], r12; spilling x382 to mem mov [ rsp + 0x4a8 ], rdi; spilling x385 to mem mulx r12, rdi, [ rsp + 0x180 ]; x342, x341<- x4 * arg1[5] setc dl; spill CF x375 to reg (rdx) clc; mov rcx, -0x1 ; moving imm to reg movzx r11, r11b adcx r11, rcx; loading flag adcx r13, rbp mov r11b, dl; preserving value of x375 into a new reg mov rdx, [ rsi + 0x30 ]; saving arg1[6] in rdx. mulx rbp, rcx, [ rsp + 0xd8 ]; x253, x252<- x3 * arg1[6] setc dl; spill CF x250 to reg (rdx) clc; mov byte [ rsp + 0x4b0 ], r11b; spilling byte x375 to mem mov r11, -0x1 ; moving imm to reg movzx r15, r15b adcx r15, r11; loading flag adcx rcx, [ rsp + 0x470 ] mov r15, 0x7bc65c783158aea3 ; moving imm to reg xchg rdx, r15; 0x7bc65c783158aea3, swapping with x250, which is currently in rdx mulx rax, r11, rax; x387, x386<- x366 * 0x7bc65c783158aea3 seto dl; spill OF x333 to reg (rdx) mov [ rsp + 0x4b8 ], r12; spilling x342 to mem mov r12, -0x1 ; moving imm to reg inc r12; OF<-0x0, preserve CF (debug: state 5 (thanks Paul)) mov r12, -0x1 ; moving imm to reg movzx r10, r10b adox r10, r12; loading flag adox r13, rcx setc r10b; spill CF x277 to reg (r10) movzx rcx, byte [ rsp + 0x458 ]; load byte memx401 to register64 clc; adcx rcx, r12; loading flag adcx r11, [ rsp + 0x428 ] seto cl; spill OF x292 to reg (rcx) inc r12; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r12, -0x1 ; moving imm to reg movzx rbx, bl adox rbx, r12; loading flag adox r8, [ rsp + 0x450 ] movzx rbx, r10b; x278, copying x277 here, cause x277 is needed in a reg for other than x278, namely all: , x278, size: 1 lea rbx, [ rbx + rbp ] mov rbp, [ rsi + 0x30 ]; load m64 x6 to register64 seto r10b; spill OF x320 to reg (r10) movzx r12, byte [ rsp + 0x468 ]; load byte memx416 to register64 mov [ rsp + 0x4c0 ], rbp; spilling x6 to mem mov rbp, 0x0 ; moving imm to reg dec rbp; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox r12, rbp; loading flag adox r14, r11 adcx r9, rax mov r12, [ rsp + 0x4a8 ]; load m64 x385 to register64 mov rax, [ rsp + 0x4a0 ]; x406, copying x382 here, cause x382 is needed in a reg for other than x406, namely all: , x406--x407, size: 1 adcx rax, r12 setc r12b; spill CF x407 to reg (r12) clc; movzx rdx, dl adcx rdx, rbp; loading flag adcx r13, r8 movzx rdx, r10b; x321, copying x320 here, cause x320 is needed in a reg for other than x321, namely all: , x321, size: 1 mov r11, [ rsp + 0x498 ]; load m64 x296 to register64 lea rdx, [ rdx + r11 ]; r8/64 + m8 movzx r11, r12b; x408, copying x407 here, cause x407 is needed in a reg for other than x408, namely all: , x408, size: 1 mov r8, [ rsp + 0x490 ]; load m64 x383 to register64 lea r11, [ r11 + r8 ]; r8/64 + m8 movzx r8, r15b; x251, copying x250 here, cause x250 is needed in a reg for other than x251, namely all: , x251, size: 1 movzx r10, byte [ rsp + 0x480 ]; load byte memx207 to register64 lea r8, [ r8 + r10 ]; r64+m8 setc r10b; spill CF x335 to reg (r10) movzx r15, byte [ rsp + 0x488 ]; load byte memx360 to register64 clc; adcx r15, rbp; loading flag adcx rdi, [ rsp + 0x478 ] mov r15, rdx; preserving value of x321 into a new reg mov rdx, [ rsp + 0x180 ]; saving x4 in rdx. mulx rdx, r12, [ rsi + 0x30 ]; x340, x339<- x4 * arg1[6] setc bpl; spill CF x362 to reg (rbp) clc; mov [ rsp + 0x4c8 ], r14; spilling x417 to mem mov r14, -0x1 ; moving imm to reg movzx rcx, cl adcx rcx, r14; loading flag adcx r8, rbx setc cl; spill CF x294 to reg (rcx) clc; movzx r10, r10b adcx r10, r14; loading flag adcx r8, r15 movzx rbx, cl; x338, copying x294 here, cause x294 is needed in a reg for other than x338, namely all: , x338, size: 1 mov r10, 0x0 ; moving imm to reg adcx rbx, r10 clc; movzx rbp, bpl adcx rbp, r14; loading flag adcx r12, [ rsp + 0x4b8 ] setc r15b; spill CF x364 to reg (r15) movzx rbp, byte [ rsp + 0x4b0 ]; load byte memx375 to register64 clc; adcx rbp, r14; loading flag adcx r13, rdi adcx r12, r8 movzx rbp, r15b; x365, copying x364 here, cause x364 is needed in a reg for other than x365, namely all: , x365, size: 1 lea rbp, [ rbp + rdx ] adox r9, r13 mov rdx, [ rsp + 0x4c0 ]; x6 to rdx mulx rdi, rcx, [ rsi + 0x8 ]; x524, x523<- x6 * arg1[1] adox rax, r12 adcx rbp, rbx mov r8, [ rsp + 0x10 ]; load m64 x438 to register64 setc bl; spill CF x381 to reg (rbx) clc; adcx r8, [ rsp + 0x310 ] mov r15, 0xffffffffffffffff ; moving imm to reg xchg rdx, r8; x453, swapping with x6, which is currently in rdx mulx r13, r12, r15; x482, x481<- x453 * 0xffffffffffffffff mov r10, [ rsp + 0x28 ]; load m64 x440 to register64 mov r14, [ rsp + 0x3d0 ]; x455, copying x413 here, cause x413 is needed in a reg for other than x455, namely all: , x455--x456, size: 1 adcx r14, r10 mov [ rsp + 0x4d0 ], rax; spilling x421 to mem mulx r10, rax, r15; x478, x477<- x453 * 0xffffffffffffffff adox r11, rbp mov [ rsp + 0x4d8 ], r11; spilling x423 to mem mulx rbp, r11, r15; x480, x479<- x453 * 0xffffffffffffffff setc r15b; spill CF x456 to reg (r15) clc; adcx r11, r13 adcx rax, rbp mov r13, rdx; preserving value of x453 into a new reg mov rdx, [ rsi + 0x0 ]; saving arg1[0] in rdx. mov [ rsp + 0x4e0 ], rdi; spilling x524 to mem mulx rbp, rdi, r8; x526, x525<- x6 * arg1[0] mov rdx, [ rsp + 0x30 ]; load m64 x442 to register64 mov [ rsp + 0x4e8 ], r9; spilling x419 to mem seto r9b; spill OF x424 to reg (r9) mov [ rsp + 0x4f0 ], r10; spilling x478 to mem mov r10, 0x0 ; moving imm to reg dec r10; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) movzx r15, r15b adox r15, r10; loading flag adox rdx, [ rsp + 0x460 ] setc r15b; spill CF x486 to reg (r15) clc; adcx r12, r13 movzx r12, r9b; x425, copying x424 here, cause x424 is needed in a reg for other than x425, namely all: , x425, size: 1 movzx rbx, bl lea r12, [ r12 + rbx ] adcx r11, r14 seto bl; spill OF x458 to reg (rbx) inc r10; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) adox rdi, r11 mov r14, 0xffffffffffffffff ; moving imm to reg xchg rdx, r14; 0xffffffffffffffff, swapping with x457, which is currently in rdx mulx r9, r11, rdi; x567, x566<- x540 * 0xffffffffffffffff adcx rax, r14 setc r14b; spill CF x501 to reg (r14) clc; adcx rcx, rbp adox rcx, rax mulx rbp, rax, rdi; x569, x568<- x540 * 0xffffffffffffffff setc dl; spill CF x528 to reg (rdx) clc; adcx r11, rbp setc bpl; spill CF x571 to reg (rbp) clc; adcx rax, rdi adcx r11, rcx mov rax, 0xfdc1767ae2ffffff ; moving imm to reg xchg rdx, r13; x453, swapping with x528, which is currently in rdx mulx rcx, r10, rax; x476, x475<- x453 * 0xfdc1767ae2ffffff mov rax, rdx; preserving value of x453 into a new reg mov rdx, [ rsi + 0x10 ]; saving arg1[2] in rdx. mov [ rsp + 0x4f8 ], r12; spilling x425 to mem mov [ rsp + 0x500 ], rcx; spilling x476 to mem mulx r12, rcx, r8; x522, x521<- x6 * arg1[2] mov rdx, 0xffffffffffffffff ; moving imm to reg mov [ rsp + 0x508 ], r9; spilling x567 to mem mov byte [ rsp + 0x510 ], bpl; spilling byte x571 to mem mulx r9, rbp, rdi; x565, x564<- x540 * 0xffffffffffffffff mov rdx, [ rsp + 0x58 ]; load m64 x444 to register64 mov [ rsp + 0x518 ], r9; spilling x565 to mem setc r9b; spill CF x586 to reg (r9) clc; mov [ rsp + 0x520 ], rbp; spilling x564 to mem mov rbp, -0x1 ; moving imm to reg movzx rbx, bl adcx rbx, rbp; loading flag adcx rdx, [ rsp + 0x4c8 ] setc bl; spill CF x460 to reg (rbx) seto bpl; spill OF x543 to reg (rbp) mov byte [ rsp + 0x528 ], r9b; spilling byte x586 to mem mov r9, r11; x600, copying x585 here, cause x585 is needed in a reg for other than x600, namely all: , x616, x600--x601, size: 2 mov [ rsp + 0x530 ], rdx; spilling x459 to mem mov rdx, 0xffffffffffffffff ; moving imm to reg sub r9, rdx mov rdx, -0x1 ; moving imm to reg inc rdx; OF<-0x0, preserve CF (debug: state 5 (thanks Paul)) mov rdx, -0x1 ; moving imm to reg movzx r15, r15b adox r15, rdx; loading flag adox r10, [ rsp + 0x4f0 ] mov r15, [ rsp + 0x50 ]; load m64 x446 to register64 setc dl; spill CF x601 to reg (rdx) clc; mov [ rsp + 0x538 ], r9; spilling x600 to mem mov r9, -0x1 ; moving imm to reg movzx rbx, bl adcx rbx, r9; loading flag adcx r15, [ rsp + 0x4e8 ] xchg rdx, r8; x6, swapping with x601, which is currently in rdx mulx rbx, r9, [ rsi + 0x18 ]; x520, x519<- x6 * arg1[3] mov [ rsp + 0x540 ], rbx; spilling x520 to mem setc bl; spill CF x462 to reg (rbx) clc; mov [ rsp + 0x548 ], r15; spilling x461 to mem mov r15, -0x1 ; moving imm to reg movzx r13, r13b adcx r13, r15; loading flag adcx rcx, [ rsp + 0x4e0 ] adcx r9, r12 seto r13b; spill OF x488 to reg (r13) inc r15; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r12, -0x1 ; moving imm to reg movzx r14, r14b adox r14, r12; loading flag adox r10, [ rsp + 0x530 ] mov r14, [ rsp + 0x520 ]; load m64 x564 to register64 setc r15b; spill CF x532 to reg (r15) movzx r12, byte [ rsp + 0x510 ]; load byte memx571 to register64 clc; mov byte [ rsp + 0x550 ], bl; spilling byte x462 to mem mov rbx, -0x1 ; moving imm to reg adcx r12, rbx; loading flag adcx r14, [ rsp + 0x508 ] seto r12b; spill OF x503 to reg (r12) inc rbx; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov rbx, -0x1 ; moving imm to reg movzx rbp, bpl adox rbp, rbx; loading flag adox r10, rcx mov rbp, 0x6cfc5fd681c52056 ; moving imm to reg xchg rdx, rbp; 0x6cfc5fd681c52056, swapping with x6, which is currently in rdx mulx rcx, rbx, rax; x472, x471<- x453 * 0x6cfc5fd681c52056 setc dl; spill CF x573 to reg (rdx) mov [ rsp + 0x558 ], rcx; spilling x472 to mem movzx rcx, byte [ rsp + 0x528 ]; load byte memx586 to register64 clc; mov byte [ rsp + 0x560 ], r15b; spilling byte x532 to mem mov r15, -0x1 ; moving imm to reg adcx rcx, r15; loading flag adcx r10, r14 setc cl; spill CF x588 to reg (rcx) seto r14b; spill OF x545 to reg (r14) movzx r15, r8b; x601, copying x601 here, cause x601 is needed in a reg for other than x601, namely all: , x602--x603, size: 1 add r15, -0x1 mov r15, r10; x602, copying x587 here, cause x587 is needed in a reg for other than x602, namely all: , x617, x602--x603, size: 2 mov r8, 0xffffffffffffffff ; moving imm to reg sbb r15, r8 mov r8, 0xfdc1767ae2ffffff ; moving imm to reg xchg rdx, rdi; x540, swapping with x573, which is currently in rdx mov [ rsp + 0x568 ], r15; spilling x602 to mem mov byte [ rsp + 0x570 ], cl; spilling byte x588 to mem mulx r15, rcx, r8; x563, x562<- x540 * 0xfdc1767ae2ffffff mov r8, -0x1 ; moving imm to reg inc r8; OF<-0x0, preserve CF (debug: state 5 (thanks Paul)) mov r8, -0x1 ; moving imm to reg movzx rdi, dil adox rdi, r8; loading flag adox rcx, [ rsp + 0x518 ] mov rdi, 0x7bc65c783158aea3 ; moving imm to reg xchg rdx, rdi; 0x7bc65c783158aea3, swapping with x540, which is currently in rdx mov [ rsp + 0x578 ], rcx; spilling x574 to mem mulx r8, rcx, rax; x474, x473<- x453 * 0x7bc65c783158aea3 mov [ rsp + 0x580 ], r9; spilling x531 to mem mov byte [ rsp + 0x588 ], r14b; spilling byte x545 to mem mulx r9, r14, rdi; x561, x560<- x540 * 0x7bc65c783158aea3 adox r14, r15 xchg rdx, rbp; x6, swapping with 0x7bc65c783158aea3, which is currently in rdx mulx r15, rbp, [ rsi + 0x20 ]; x518, x517<- x6 * arg1[4] mov [ rsp + 0x590 ], r9; spilling x561 to mem setc r9b; spill CF x603 to reg (r9) clc; mov [ rsp + 0x598 ], r15; spilling x518 to mem mov r15, -0x1 ; moving imm to reg movzx r13, r13b adcx r13, r15; loading flag adcx rcx, [ rsp + 0x500 ] adcx rbx, r8 setc r13b; spill CF x492 to reg (r13) clc; movzx r12, r12b adcx r12, r15; loading flag adcx rcx, [ rsp + 0x548 ] seto r12b; spill OF x577 to reg (r12) movzx r8, byte [ rsp + 0x588 ]; load byte memx545 to register64 inc r15; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r15, -0x1 ; moving imm to reg adox r8, r15; loading flag adox rcx, [ rsp + 0x580 ] setc r8b; spill CF x505 to reg (r8) movzx r15, byte [ rsp + 0x570 ]; load byte memx588 to register64 clc; mov byte [ rsp + 0x5a0 ], r12b; spilling byte x577 to mem mov r12, -0x1 ; moving imm to reg adcx r15, r12; loading flag adcx rcx, [ rsp + 0x578 ] mov r15, [ rsp + 0x68 ]; load m64 x448 to register64 seto r12b; spill OF x547 to reg (r12) mov [ rsp + 0x5a8 ], rcx; spilling x589 to mem movzx rcx, byte [ rsp + 0x550 ]; load byte memx462 to register64 mov byte [ rsp + 0x5b0 ], r9b; spilling byte x603 to mem mov r9, 0x0 ; moving imm to reg dec r9; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) adox rcx, r9; loading flag adox r15, [ rsp + 0x4d0 ] mov rcx, 0x2341f27177344 ; moving imm to reg xchg rdx, rcx; 0x2341f27177344, swapping with x6, which is currently in rdx mulx rax, r9, rax; x470, x469<- x453 * 0x2341f27177344 mov rdx, [ rsp + 0x4d8 ]; load m64 x423 to register64 mov [ rsp + 0x5b8 ], r14; spilling x576 to mem mov r14, [ rsp + 0x80 ]; x465, copying x450 here, cause x450 is needed in a reg for other than x465, namely all: , x465--x466, size: 1 adox r14, rdx setc dl; spill CF x590 to reg (rdx) clc; mov [ rsp + 0x5c0 ], r14; spilling x465 to mem mov r14, -0x1 ; moving imm to reg movzx r8, r8b adcx r8, r14; loading flag adcx r15, rbx setc bl; spill CF x507 to reg (rbx) movzx r8, byte [ rsp + 0x560 ]; load byte memx532 to register64 clc; adcx r8, r14; loading flag adcx rbp, [ rsp + 0x540 ] setc r8b; spill CF x534 to reg (r8) clc; movzx r13, r13b adcx r13, r14; loading flag adcx r9, [ rsp + 0x558 ] seto r13b; spill OF x466 to reg (r13) inc r14; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r14, -0x1 ; moving imm to reg movzx r12, r12b adox r12, r14; loading flag adox r15, rbp mov r12, 0x0 ; moving imm to reg adcx rax, r12 mov rbp, [ rsp + 0x78 ]; load m64 x452 to register64 clc; movzx r13, r13b adcx r13, r14; loading flag adcx rbp, [ rsp + 0x4f8 ] setc r13b; spill CF x468 to reg (r13) clc; movzx rdx, dl adcx rdx, r14; loading flag adcx r15, [ rsp + 0x5b8 ] setc dl; spill CF x592 to reg (rdx) seto r12b; spill OF x549 to reg (r12) movzx r14, byte [ rsp + 0x5b0 ]; x603, copying x603 here, cause x603 is needed in a reg for other than x603, namely all: , x604--x605, size: 1 add r14, -0x1 mov r14, [ rsp + 0x5a8 ]; x604, copying x589 here, cause x589 is needed in a reg for other than x604, namely all: , x618, x604--x605, size: 2 mov byte [ rsp + 0x5c8 ], r13b; spilling byte x468 to mem mov r13, 0xffffffffffffffff ; moving imm to reg sbb r14, r13 mov r13, r15; x606, copying x591 here, cause x591 is needed in a reg for other than x606, namely all: , x606--x607, x619, size: 2 mov [ rsp + 0x5d0 ], r14; spilling x604 to mem mov r14, 0xfdc1767ae2ffffff ; moving imm to reg sbb r13, r14 mov r14, 0x0 ; moving imm to reg dec r14; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) movzx rbx, bl adox rbx, r14; loading flag adox r9, [ rsp + 0x5c0 ] mov bl, dl; preserving value of x592 into a new reg mov rdx, [ rsi + 0x28 ]; saving arg1[5] in rdx. mov [ rsp + 0x5d8 ], r13; spilling x606 to mem mulx r14, r13, rcx; x516, x515<- x6 * arg1[5] seto dl; spill OF x509 to reg (rdx) mov byte [ rsp + 0x5e0 ], bl; spilling byte x592 to mem mov rbx, -0x1 ; moving imm to reg inc rbx; OF<-0x0, preserve CF (debug: state 5 (thanks Paul)) mov rbx, -0x1 ; moving imm to reg movzx r8, r8b adox r8, rbx; loading flag adox r13, [ rsp + 0x598 ] setc r8b; spill CF x607 to reg (r8) clc; movzx r12, r12b adcx r12, rbx; loading flag adcx r9, r13 xchg rdx, rcx; x6, swapping with x509, which is currently in rdx mulx rdx, r12, [ rsi + 0x30 ]; x514, x513<- x6 * arg1[6] adox r12, r14 setc r14b; spill CF x551 to reg (r14) clc; movzx rcx, cl adcx rcx, rbx; loading flag adcx rbp, rax mov rax, 0x6cfc5fd681c52056 ; moving imm to reg xchg rdx, rdi; x540, swapping with x514, which is currently in rdx mulx rcx, r13, rax; x559, x558<- x540 * 0x6cfc5fd681c52056 setc bl; spill CF x511 to reg (rbx) movzx rax, byte [ rsp + 0x5a0 ]; load byte memx577 to register64 clc; mov byte [ rsp + 0x5e8 ], r8b; spilling byte x607 to mem mov r8, -0x1 ; moving imm to reg adcx rax, r8; loading flag adcx r13, [ rsp + 0x590 ] mov rax, 0x0 ; moving imm to reg adox rdi, rax mov rax, 0x2341f27177344 ; moving imm to reg mulx rdx, r8, rax; x557, x556<- x540 * 0x2341f27177344 adcx r8, rcx mov rcx, 0x0 ; moving imm to reg dec rcx; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) movzx r14, r14b adox r14, rcx; loading flag adox rbp, r12 movzx r14, bl; x512, copying x511 here, cause x511 is needed in a reg for other than x512, namely all: , x512, size: 1 movzx r12, byte [ rsp + 0x5c8 ]; load byte memx468 to register64 lea r14, [ r14 + r12 ]; r64+m8 adox rdi, r14 seto r12b; spill OF x555 to reg (r12) movzx rbx, byte [ rsp + 0x5e0 ]; load byte memx592 to register64 inc rcx; OF<-0x0, preserve CF (debug: state 2 (y: -1, n: 0)) mov r14, -0x1 ; moving imm to reg adox rbx, r14; loading flag adox r9, r13 adox r8, rbp setc bl; spill CF x581 to reg (rbx) seto r13b; spill OF x596 to reg (r13) movzx rbp, byte [ rsp + 0x5e8 ]; x607, copying x607 here, cause x607 is needed in a reg for other than x607, namely all: , x608--x609, size: 1 add rbp, -0x1 mov rbp, r9; x608, copying x593 here, cause x593 is needed in a reg for other than x608, namely all: , x608--x609, x620, size: 2 mov rcx, 0x7bc65c783158aea3 ; moving imm to reg sbb rbp, rcx movzx r14, bl; x582, copying x581 here, cause x581 is needed in a reg for other than x582, namely all: , x582, size: 1 lea r14, [ r14 + rdx ] mov rdx, 0x0 ; moving imm to reg dec rdx; OF<-0x0, preserve CF (debug: state 4 (thanks Paul)) movzx r13, r13b adox r13, rdx; loading flag adox rdi, r14 movzx rbx, r12b; x599, copying x555 here, cause x555 is needed in a reg for other than x599, namely all: , x599, size: 1 mov r13, 0x0 ; moving imm to reg adox rbx, r13 mov r12, r8; x610, copying x595 here, cause x595 is needed in a reg for other than x610, namely all: , x610--x611, x621, size: 2 mov r14, 0x6cfc5fd681c52056 ; moving imm to reg sbb r12, r14 mov r13, rdi; x612, copying x597 here, cause x597 is needed in a reg for other than x612, namely all: , x612--x613, x622, size: 2 sbb r13, rax sbb rbx, 0x00000000 cmovc rbp, r9; if CF, x620<- x593 (nzVar) mov rbx, [ rsp + 0x0 ]; load m64 out1 to register64 mov [ rbx + 0x20 ], rbp; out1[4] = x620 cmovc r13, rdi; if CF, x622<- x597 (nzVar) mov r9, [ rsp + 0x5d0 ]; x618, copying x604 here, cause x604 is needed in a reg for other than x618, namely all: , x618, size: 1 cmovc r9, [ rsp + 0x5a8 ]; if CF, x618<- x589 (nzVar) cmovc r12, r8; if CF, x621<- x595 (nzVar) mov [ rbx + 0x30 ], r13; out1[6] = x622 mov r8, [ rsp + 0x5d8 ]; x619, copying x606 here, cause x606 is needed in a reg for other than x619, namely all: , x619, size: 1 cmovc r8, r15; if CF, x619<- x591 (nzVar) mov r15, [ rsp + 0x538 ]; x616, copying x600 here, cause x600 is needed in a reg for other than x616, namely all: , x616, size: 1 cmovc r15, r11; if CF, x616<- x585 (nzVar) mov [ rbx + 0x0 ], r15; out1[0] = x616 mov [ rbx + 0x18 ], r8; out1[3] = x619 mov r11, [ rsp + 0x568 ]; x617, copying x602 here, cause x602 is needed in a reg for other than x617, namely all: , x617, size: 1 cmovc r11, r10; if CF, x617<- x587 (nzVar) mov [ rbx + 0x8 ], r11; out1[1] = x617 mov [ rbx + 0x10 ], r9; out1[2] = x618 mov [ rbx + 0x28 ], r12; out1[5] = x621 mov rbx, [ rsp + 0x5f0 ]; restoring from stack mov rbp, [ rsp + 0x5f8 ]; restoring from stack mov r12, [ rsp + 0x600 ]; restoring from stack mov r13, [ rsp + 0x608 ]; restoring from stack mov r14, [ rsp + 0x610 ]; restoring from stack mov r15, [ rsp + 0x618 ]; restoring from stack add rsp, 0x620 ret ; cpu Intel(R) Core(TM) i7-6770HQ CPU @ 2.60GHz ; clocked at 2600 MHz ; first cyclecount 464.405, best 416.48148148148147, lastGood 421.037037037037 ; seed 3759678552496106 ; CC / CFLAGS clang / -march=native -mtune=native -O3 ; time needed: 9769871 ms / 60000 runs=> 162.83118333333334ms/run ; Time spent for assembling and measureing (initial batch_size=27, initial num_batches=101): 185267 ms ; Ratio (time for assembling + measure)/(total runtime for 60000runs): 0.018963095827979715 ; number reverted permutation/ tried permutation: 19410 / 29921 =64.871% ; number reverted decision/ tried decision: 18019 / 30080 =59.904%
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r14 push %r15 push %r8 push %rcx push %rdx // Store lea addresses_WT+0x13280, %r13 add %r8, %r8 mov $0x5152535455565758, %r10 movq %r10, (%r13) add %r15, %r15 // Store lea addresses_A+0x1533, %rdx nop nop nop add %r14, %r14 movl $0x51525354, (%rdx) nop nop nop and $7656, %r8 // Store lea addresses_RW+0x6533, %rcx clflush (%rcx) nop nop sub $19017, %r15 movl $0x51525354, (%rcx) nop nop nop and $36687, %r15 // Store lea addresses_WT+0x74f3, %r13 xor $43964, %r10 mov $0x5152535455565758, %rcx movq %rcx, %xmm7 movups %xmm7, (%r13) nop nop nop and %r14, %r14 // Faulty Load lea addresses_A+0x17d33, %r10 and %r15, %r15 mov (%r10), %cx lea oracles, %r10 and $0xff, %rcx shlq $12, %rcx mov (%r10,%rcx,1), %rcx pop %rdx pop %rcx pop %r8 pop %r15 pop %r14 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': True, 'type': 'addresses_A'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WT'}} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A'}} {'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_RW'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WT'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'00': 2} 00 00 */
; A111567: Binomial transform of A048654: generalized Pellian with second term equal to 4. ; 1,5,18,62,212,724,2472,8440,28816,98384,335904,1146848,3915584,13368640,45643392,155836288,532058368,1816560896,6202126848,21175385600,72297288704,246838383616,842758957056,2877359060992,9823918329856,33540955197440,114515984130048,390982026125312,1334896136241152,4557620492713984,15560689698373632,53127517808066560,181388691835518976,619299731725942784,2114421543232733184,7219086709479047168,24647503751450722304,84151841586844794880,287312358844477734912,980945752204221349888 mov $1,1 lpb $0 sub $0,1 add $2,$1 add $1,1 mul $1,2 add $1,$2 lpe mov $0,$1
;***************************************************************************** ;* MMX/SSE2/AVX-optimized 10-bit H.264 iDCT code ;***************************************************************************** ;* Copyright (C) 2005-2011 x264 project ;* ;* Authors: Daniel Kang <daniel.d.kang@gmail.com> ;* ;* This file is part of Libav. ;* ;* Libav is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* Libav 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 Libav; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "libavutil/x86/x86util.asm" SECTION_RODATA pw_pixel_max: times 8 dw ((1 << 10)-1) pd_32: times 4 dd 32 SECTION .text ;----------------------------------------------------------------------------- ; void ff_h264_idct_add_10(pixel *dst, int16_t *block, int stride) ;----------------------------------------------------------------------------- %macro STORE_DIFFx2 6 psrad %1, 6 psrad %2, 6 packssdw %1, %2 movq %3, [%5] movhps %3, [%5+%6] paddsw %1, %3 CLIPW %1, %4, [pw_pixel_max] movq [%5], %1 movhps [%5+%6], %1 %endmacro %macro STORE_DIFF16 5 psrad %1, 6 psrad %2, 6 packssdw %1, %2 paddsw %1, [%5] CLIPW %1, %3, %4 mova [%5], %1 %endmacro ;dst, in, stride %macro IDCT4_ADD_10 3 mova m0, [%2+ 0] mova m1, [%2+16] mova m2, [%2+32] mova m3, [%2+48] IDCT4_1D d,0,1,2,3,4,5 TRANSPOSE4x4D 0,1,2,3,4 paddd m0, [pd_32] IDCT4_1D d,0,1,2,3,4,5 pxor m5, m5 mova [%2+ 0], m5 mova [%2+16], m5 mova [%2+32], m5 mova [%2+48], m5 STORE_DIFFx2 m0, m1, m4, m5, %1, %3 lea %1, [%1+%3*2] STORE_DIFFx2 m2, m3, m4, m5, %1, %3 %endmacro %macro IDCT_ADD_10 0 cglobal h264_idct_add_10, 3,3 IDCT4_ADD_10 r0, r1, r2 RET %endmacro INIT_XMM sse2 IDCT_ADD_10 INIT_XMM avx IDCT_ADD_10 ;----------------------------------------------------------------------------- ; void ff_h264_idct_add16_10(pixel *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6*8]) ;----------------------------------------------------------------------------- ;;;;;;; NO FATE SAMPLES TRIGGER THIS %macro ADD4x4IDCT 0 add4x4_idct %+ SUFFIX: add r5, r0 mova m0, [r2+ 0] mova m1, [r2+16] mova m2, [r2+32] mova m3, [r2+48] IDCT4_1D d,0,1,2,3,4,5 TRANSPOSE4x4D 0,1,2,3,4 paddd m0, [pd_32] IDCT4_1D d,0,1,2,3,4,5 pxor m5, m5 mova [r2+ 0], m5 mova [r2+16], m5 mova [r2+32], m5 mova [r2+48], m5 STORE_DIFFx2 m0, m1, m4, m5, r5, r3 lea r5, [r5+r3*2] STORE_DIFFx2 m2, m3, m4, m5, r5, r3 ret %endmacro INIT_XMM sse2 ALIGN 16 ADD4x4IDCT INIT_XMM avx ALIGN 16 ADD4x4IDCT %macro ADD16_OP 2 cmp byte [r4+%2], 0 jz .skipblock%1 mov r5d, [r1+%1*4] call add4x4_idct %+ SUFFIX .skipblock%1: %if %1<15 add r2, 64 %endif %endmacro %macro IDCT_ADD16_10 0 cglobal h264_idct_add16_10, 5,6 ADD16_OP 0, 4+1*8 ADD16_OP 1, 5+1*8 ADD16_OP 2, 4+2*8 ADD16_OP 3, 5+2*8 ADD16_OP 4, 6+1*8 ADD16_OP 5, 7+1*8 ADD16_OP 6, 6+2*8 ADD16_OP 7, 7+2*8 ADD16_OP 8, 4+3*8 ADD16_OP 9, 5+3*8 ADD16_OP 10, 4+4*8 ADD16_OP 11, 5+4*8 ADD16_OP 12, 6+3*8 ADD16_OP 13, 7+3*8 ADD16_OP 14, 6+4*8 ADD16_OP 15, 7+4*8 REP_RET %endmacro INIT_XMM sse2 IDCT_ADD16_10 INIT_XMM avx IDCT_ADD16_10 ;----------------------------------------------------------------------------- ; void ff_h264_idct_dc_add_10(pixel *dst, int16_t *block, int stride) ;----------------------------------------------------------------------------- %macro IDCT_DC_ADD_OP_10 3 pxor m5, m5 %if avx_enabled paddw m1, m0, [%1+0 ] paddw m2, m0, [%1+%2 ] paddw m3, m0, [%1+%2*2] paddw m4, m0, [%1+%3 ] %else mova m1, [%1+0 ] mova m2, [%1+%2 ] mova m3, [%1+%2*2] mova m4, [%1+%3 ] paddw m1, m0 paddw m2, m0 paddw m3, m0 paddw m4, m0 %endif CLIPW m1, m5, m6 CLIPW m2, m5, m6 CLIPW m3, m5, m6 CLIPW m4, m5, m6 mova [%1+0 ], m1 mova [%1+%2 ], m2 mova [%1+%2*2], m3 mova [%1+%3 ], m4 %endmacro INIT_MMX mmxext cglobal h264_idct_dc_add_10,3,3 movd m0, [r1] mov dword [r1], 0 paddd m0, [pd_32] psrad m0, 6 lea r1, [r2*3] pshufw m0, m0, 0 mova m6, [pw_pixel_max] IDCT_DC_ADD_OP_10 r0, r2, r1 RET ;----------------------------------------------------------------------------- ; void ff_h264_idct8_dc_add_10(pixel *dst, int16_t *block, int stride) ;----------------------------------------------------------------------------- %macro IDCT8_DC_ADD 0 cglobal h264_idct8_dc_add_10,3,4,7 movd m0, [r1] mov dword[r1], 0 paddd m0, [pd_32] psrad m0, 6 lea r1, [r2*3] SPLATW m0, m0, 0 mova m6, [pw_pixel_max] IDCT_DC_ADD_OP_10 r0, r2, r1 lea r0, [r0+r2*4] IDCT_DC_ADD_OP_10 r0, r2, r1 RET %endmacro INIT_XMM sse2 IDCT8_DC_ADD INIT_XMM avx IDCT8_DC_ADD ;----------------------------------------------------------------------------- ; void ff_h264_idct_add16intra_10(pixel *dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6*8]) ;----------------------------------------------------------------------------- %macro AC 1 .ac%1: mov r5d, [r1+(%1+0)*4] call add4x4_idct %+ SUFFIX mov r5d, [r1+(%1+1)*4] add r2, 64 call add4x4_idct %+ SUFFIX add r2, 64 jmp .skipadd%1 %endmacro %assign last_block 16 %macro ADD16_OP_INTRA 2 cmp word [r4+%2], 0 jnz .ac%1 mov r5d, [r2+ 0] or r5d, [r2+64] jz .skipblock%1 mov r5d, [r1+(%1+0)*4] call idct_dc_add %+ SUFFIX .skipblock%1: %if %1<last_block-2 add r2, 128 %endif .skipadd%1: %endmacro %macro IDCT_ADD16INTRA_10 0 idct_dc_add %+ SUFFIX: add r5, r0 movq m0, [r2+ 0] movhps m0, [r2+64] mov dword [r2+ 0], 0 mov dword [r2+64], 0 paddd m0, [pd_32] psrad m0, 6 pshufhw m0, m0, 0 pshuflw m0, m0, 0 lea r6, [r3*3] mova m6, [pw_pixel_max] IDCT_DC_ADD_OP_10 r5, r3, r6 ret cglobal h264_idct_add16intra_10,5,7,8 ADD16_OP_INTRA 0, 4+1*8 ADD16_OP_INTRA 2, 4+2*8 ADD16_OP_INTRA 4, 6+1*8 ADD16_OP_INTRA 6, 6+2*8 ADD16_OP_INTRA 8, 4+3*8 ADD16_OP_INTRA 10, 4+4*8 ADD16_OP_INTRA 12, 6+3*8 ADD16_OP_INTRA 14, 6+4*8 REP_RET AC 8 AC 10 AC 12 AC 14 AC 0 AC 2 AC 4 AC 6 %endmacro INIT_XMM sse2 IDCT_ADD16INTRA_10 INIT_XMM avx IDCT_ADD16INTRA_10 %assign last_block 36 ;----------------------------------------------------------------------------- ; void ff_h264_idct_add8_10(pixel **dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6*8]) ;----------------------------------------------------------------------------- %macro IDCT_ADD8 0 cglobal h264_idct_add8_10,5,8,7 %if ARCH_X86_64 mov r7, r0 %endif add r2, 1024 mov r0, [r0] ADD16_OP_INTRA 16, 4+ 6*8 ADD16_OP_INTRA 18, 4+ 7*8 add r2, 1024-128*2 %if ARCH_X86_64 mov r0, [r7+gprsize] %else mov r0, r0m mov r0, [r0+gprsize] %endif ADD16_OP_INTRA 32, 4+11*8 ADD16_OP_INTRA 34, 4+12*8 REP_RET AC 16 AC 18 AC 32 AC 34 %endmacro ; IDCT_ADD8 INIT_XMM sse2 IDCT_ADD8 INIT_XMM avx IDCT_ADD8 ;----------------------------------------------------------------------------- ; void ff_h264_idct8_add_10(pixel *dst, int16_t *block, int stride) ;----------------------------------------------------------------------------- %macro IDCT8_1D 2 SWAP 0, 1 psrad m4, m5, 1 psrad m1, m0, 1 paddd m4, m5 paddd m1, m0 paddd m4, m7 paddd m1, m5 psubd m4, m0 paddd m1, m3 psubd m0, m3 psubd m5, m3 paddd m0, m7 psubd m5, m7 psrad m3, 1 psrad m7, 1 psubd m0, m3 psubd m5, m7 SWAP 1, 7 psrad m1, m7, 2 psrad m3, m4, 2 paddd m3, m0 psrad m0, 2 paddd m1, m5 psrad m5, 2 psubd m0, m4 psubd m7, m5 SWAP 5, 6 psrad m4, m2, 1 psrad m6, m5, 1 psubd m4, m5 paddd m6, m2 mova m2, %1 mova m5, %2 SUMSUB_BA d, 5, 2 SUMSUB_BA d, 6, 5 SUMSUB_BA d, 4, 2 SUMSUB_BA d, 7, 6 SUMSUB_BA d, 0, 4 SUMSUB_BA d, 3, 2 SUMSUB_BA d, 1, 5 SWAP 7, 6, 4, 5, 2, 3, 1, 0 ; 70315246 -> 01234567 %endmacro %macro IDCT8_1D_FULL 1 mova m7, [%1+112*2] mova m6, [%1+ 96*2] mova m5, [%1+ 80*2] mova m3, [%1+ 48*2] mova m2, [%1+ 32*2] mova m1, [%1+ 16*2] IDCT8_1D [%1], [%1+ 64*2] %endmacro ; %1=int16_t *block, %2=int16_t *dstblock %macro IDCT8_ADD_SSE_START 2 IDCT8_1D_FULL %1 %if ARCH_X86_64 TRANSPOSE4x4D 0,1,2,3,8 mova [%2 ], m0 TRANSPOSE4x4D 4,5,6,7,8 mova [%2+8*2], m4 %else mova [%1], m7 TRANSPOSE4x4D 0,1,2,3,7 mova m7, [%1] mova [%2 ], m0 mova [%2+16*2], m1 mova [%2+32*2], m2 mova [%2+48*2], m3 TRANSPOSE4x4D 4,5,6,7,3 mova [%2+ 8*2], m4 mova [%2+24*2], m5 mova [%2+40*2], m6 mova [%2+56*2], m7 %endif %endmacro ; %1=uint8_t *dst, %2=int16_t *block, %3=int stride %macro IDCT8_ADD_SSE_END 3 IDCT8_1D_FULL %2 mova [%2 ], m6 mova [%2+16*2], m7 pxor m7, m7 STORE_DIFFx2 m0, m1, m6, m7, %1, %3 lea %1, [%1+%3*2] STORE_DIFFx2 m2, m3, m6, m7, %1, %3 mova m0, [%2 ] mova m1, [%2+16*2] lea %1, [%1+%3*2] STORE_DIFFx2 m4, m5, m6, m7, %1, %3 lea %1, [%1+%3*2] STORE_DIFFx2 m0, m1, m6, m7, %1, %3 %endmacro %macro IDCT8_ADD 0 cglobal h264_idct8_add_10, 3,4,16 %if UNIX64 == 0 %assign pad 16-gprsize-(stack_offset&15) sub rsp, pad call h264_idct8_add1_10 %+ SUFFIX add rsp, pad RET %endif ALIGN 16 ; TODO: does not need to use stack h264_idct8_add1_10 %+ SUFFIX: %assign pad 256+16-gprsize sub rsp, pad add dword [r1], 32 %if ARCH_X86_64 IDCT8_ADD_SSE_START r1, rsp SWAP 1, 9 SWAP 2, 10 SWAP 3, 11 SWAP 5, 13 SWAP 6, 14 SWAP 7, 15 IDCT8_ADD_SSE_START r1+16, rsp+128 PERMUTE 1,9, 2,10, 3,11, 5,1, 6,2, 7,3, 9,13, 10,14, 11,15, 13,5, 14,6, 15,7 IDCT8_1D [rsp], [rsp+128] SWAP 0, 8 SWAP 1, 9 SWAP 2, 10 SWAP 3, 11 SWAP 4, 12 SWAP 5, 13 SWAP 6, 14 SWAP 7, 15 IDCT8_1D [rsp+16], [rsp+144] psrad m8, 6 psrad m0, 6 packssdw m8, m0 paddsw m8, [r0] pxor m0, m0 mova [r1+ 0], m0 mova [r1+ 16], m0 mova [r1+ 32], m0 mova [r1+ 48], m0 mova [r1+ 64], m0 mova [r1+ 80], m0 mova [r1+ 96], m0 mova [r1+112], m0 mova [r1+128], m0 mova [r1+144], m0 mova [r1+160], m0 mova [r1+176], m0 mova [r1+192], m0 mova [r1+208], m0 mova [r1+224], m0 mova [r1+240], m0 CLIPW m8, m0, [pw_pixel_max] mova [r0], m8 mova m8, [pw_pixel_max] STORE_DIFF16 m9, m1, m0, m8, r0+r2 lea r0, [r0+r2*2] STORE_DIFF16 m10, m2, m0, m8, r0 STORE_DIFF16 m11, m3, m0, m8, r0+r2 lea r0, [r0+r2*2] STORE_DIFF16 m12, m4, m0, m8, r0 STORE_DIFF16 m13, m5, m0, m8, r0+r2 lea r0, [r0+r2*2] STORE_DIFF16 m14, m6, m0, m8, r0 STORE_DIFF16 m15, m7, m0, m8, r0+r2 %else IDCT8_ADD_SSE_START r1, rsp IDCT8_ADD_SSE_START r1+16, rsp+128 lea r3, [r0+8] IDCT8_ADD_SSE_END r0, rsp, r2 IDCT8_ADD_SSE_END r3, rsp+16, r2 mova [r1+ 0], m7 mova [r1+ 16], m7 mova [r1+ 32], m7 mova [r1+ 48], m7 mova [r1+ 64], m7 mova [r1+ 80], m7 mova [r1+ 96], m7 mova [r1+112], m7 mova [r1+128], m7 mova [r1+144], m7 mova [r1+160], m7 mova [r1+176], m7 mova [r1+192], m7 mova [r1+208], m7 mova [r1+224], m7 mova [r1+240], m7 %endif ; ARCH_X86_64 add rsp, pad ret %endmacro INIT_XMM sse2 IDCT8_ADD INIT_XMM avx IDCT8_ADD ;----------------------------------------------------------------------------- ; void ff_h264_idct8_add4_10(pixel **dst, const int *block_offset, ; int16_t *block, int stride, ; const uint8_t nnzc[6*8]) ;----------------------------------------------------------------------------- ;;;;;;; NO FATE SAMPLES TRIGGER THIS %macro IDCT8_ADD4_OP 2 cmp byte [r4+%2], 0 jz .skipblock%1 mov r0d, [r6+%1*4] add r0, r5 call h264_idct8_add1_10 %+ SUFFIX .skipblock%1: %if %1<12 add r1, 256 %endif %endmacro %macro IDCT8_ADD4 0 cglobal h264_idct8_add4_10, 0,7,16 %assign pad 16-gprsize-(stack_offset&15) SUB rsp, pad mov r5, r0mp mov r6, r1mp mov r1, r2mp mov r2d, r3m movifnidn r4, r4mp IDCT8_ADD4_OP 0, 4+1*8 IDCT8_ADD4_OP 4, 6+1*8 IDCT8_ADD4_OP 8, 4+3*8 IDCT8_ADD4_OP 12, 6+3*8 ADD rsp, pad RET %endmacro ; IDCT8_ADD4 INIT_XMM sse2 IDCT8_ADD4 INIT_XMM avx IDCT8_ADD4
; A093485: a(n) = (27*n^2 + 9*n + 2)/2. ; 1,19,64,136,235,361,514,694,901,1135,1396,1684,1999,2341,2710,3106,3529,3979,4456,4960,5491,6049,6634,7246,7885,8551,9244,9964,10711,11485,12286,13114,13969,14851,15760,16696,17659,18649,19666,20710,21781,22879,24004,25156,26335,27541,28774,30034,31321,32635,33976,35344,36739,38161,39610,41086,42589,44119,45676,47260,48871,50509,52174,53866,55585,57331,59104,60904,62731,64585,66466,68374,70309,72271,74260,76276,78319,80389,82486,84610,86761,88939,91144,93376,95635,97921,100234,102574,104941,107335,109756,112204,114679,117181,119710,122266,124849,127459,130096,132760,135451,138169,140914,143686,146485,149311,152164,155044,157951,160885,163846,166834,169849,172891,175960,179056,182179,185329,188506,191710,194941,198199,201484,204796,208135,211501,214894,218314,221761,225235,228736,232264,235819,239401,243010,246646,250309,253999,257716,261460,265231,269029,272854,276706,280585,284491,288424,292384,296371,300385,304426,308494,312589,316711,320860,325036,329239,333469,337726,342010,346321,350659,355024,359416,363835,368281,372754,377254,381781,386335,390916,395524,400159,404821,409510,414226,418969,423739,428536,433360,438211,443089,447994,452926,457885,462871,467884,472924,477991,483085,488206,493354,498529,503731,508960,514216,519499,524809,530146,535510,540901,546319,551764,557236,562735,568261,573814,579394,585001,590635,596296,601984,607699,613441,619210,625006,630829,636679,642556,648460,654391,660349,666334,672346,678385,684451,690544,696664,702811,708985,715186,721414,727669,733951,740260,746596,752959,759349,765766,772210,778681,785179,791704,798256,804835,811441,818074,824734,831421,838135 mul $0,-3 bin $0,2 mov $1,$0 mul $1,3 add $1,1
LDA 00A1H CPI 00H JZ FAILURE ;Divide by zero MOV B,A LDA 00A0H MVI C,00H LOOP: CMP B JC SUCCESS SUB B INR C JMP LOOP SUCCESS: STA 00B1H MOV A,C STA 00B0H FAILURE: HLT
; A156635: 144*n^2 - n. ; 143,574,1293,2300,3595,5178,7049,9208,11655,14390,17413,20724,24323,28210,32385,36848,41599,46638,51965,57580,63483,69674,76153,82920,89975,97318,104949,112868,121075,129570,138353,147424,156783,166430,176365,186588,197099,207898,218985,230360,242023,253974,266213,278740,291555,304658,318049,331728,345695,359950,374493,389324,404443,419850,435545,451528,467799,484358,501205,518340,535763,553474,571473,589760,608335,627198,646349,665788,685515,705530,725833,746424,767303,788470,809925,831668,853699,876018,898625,921520,944703,968174,991933,1015980,1040315,1064938,1089849,1115048,1140535,1166310,1192373,1218724,1245363,1272290,1299505,1327008,1354799,1382878,1411245,1439900,1468843,1498074,1527593,1557400,1587495,1617878,1648549,1679508,1710755,1742290,1774113,1806224,1838623,1871310,1904285,1937548,1971099,2004938,2039065,2073480,2108183,2143174,2178453,2214020,2249875,2286018,2322449,2359168,2396175,2433470,2471053,2508924,2547083,2585530,2624265,2663288,2702599,2742198,2782085,2822260,2862723,2903474,2944513,2985840,3027455,3069358,3111549,3154028,3196795,3239850,3283193,3326824,3370743,3414950,3459445,3504228,3549299,3594658,3640305,3686240,3732463,3778974,3825773,3872860,3920235,3967898,4015849,4064088,4112615,4161430,4210533,4259924,4309603,4359570,4409825,4460368,4511199,4562318,4613725,4665420,4717403,4769674,4822233,4875080,4928215,4981638,5035349,5089348,5143635,5198210,5253073,5308224,5363663,5419390,5475405,5531708,5588299,5645178,5702345,5759800,5817543,5875574,5933893,5992500,6051395,6110578,6170049,6229808,6289855,6350190,6410813,6471724,6532923,6594410,6656185,6718248,6780599,6843238,6906165,6969380,7032883,7096674,7160753,7225120,7289775,7354718,7419949,7485468,7551275,7617370,7683753,7750424,7817383,7884630,7952165,8019988,8088099,8156498,8225185,8294160,8363423,8432974,8502813,8572940,8643355,8714058,8785049,8856328,8927895,8999750 add $0,1 mul $0,144 bin $0,2 mov $1,$0 div $1,72
Function17c000: call DisableLCD ld hl, vTiles2 ld bc, $31 tiles xor a call ByteFill call LoadStandardFont call LoadFontsExtra ld hl, HaveWantMap decoord 0, 0 bccoord 0, 0, wAttrMap ld a, SCREEN_HEIGHT .y push af ld a, SCREEN_WIDTH push hl .x push af ld a, [hli] ld [de], a inc de ld a, [hli] ld [bc], a inc bc pop af dec a jr nz, .x pop hl push bc ld bc, BG_MAP_WIDTH * 2 add hl, bc pop bc pop af dec a jr nz, .y ldh a, [rSVBK] push af ld a, BANK(wBGPals1) ldh [rSVBK], a ld hl, HaveWantPals ld de, wBGPals1 ld bc, 16 palettes call CopyBytes pop af ldh [rSVBK], a ld hl, MobileSelectGFX ld de, vTiles0 tile $30 ld bc, $20 tiles call CopyBytes ld a, 1 ldh [rVBK], a ld hl, HaveWantGFX ld de, vTiles2 ld bc, $80 tiles call CopyBytes ld hl, HaveWantGFX + $800 ld de, vTiles1 ld bc, $10 tiles call CopyBytes xor a ldh [rVBK], a call EnableLCD farcall ReloadMapPart ret HaveWantGFX: INCBIN "gfx/mobile/havewant.2bpp" MobileSelectGFX: INCBIN "gfx/mobile/select.2bpp" HaveWantMap: ; Interleaved tile/palette map. INCBIN "gfx/mobile/havewant_map.bin" HaveWantPals: ; BG and OBJ palettes. RGB 0, 0, 0 RGB 21, 21, 21 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 4, 17, 29 RGB 6, 19, 31 RGB 31, 31, 31 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 2, 13, 18 RGB 6, 19, 31 RGB 31, 31, 31 RGB 0, 0, 0 RGB 31, 5, 5 RGB 29, 21, 21 RGB 31, 31, 31 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 4, 17, 29 RGB 6, 19, 31 RGB 2, 15, 27 RGB 0, 0, 0 RGB 28, 19, 18 RGB 25, 9, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 31, 27, 27 RGB 31, 10, 4 RGB 29, 0, 0 RGB 0, 0, 0 RGB 31, 31, 31 RGB 26, 8, 23 RGB 22, 0, 16 RGB 0, 0, 0 RGB 31, 31, 31 RGB 20, 8, 31 RGB 15, 1, 26 RGB 0, 0, 0 RGB 31, 31, 31 RGB 17, 12, 31 RGB 12, 6, 31 RGB 0, 16, 0 RGB 11, 11, 14 RGB 5, 5, 7 RGB 31, 31, 31 RGB 0, 31, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 16, 31, 0 RGB 0, 0, 0 RGB 0, 0, 0 RGB 0, 0, 0 CheckStringForErrors: ; Valid character ranges: ; $0, $5 - $13, $19 - $1c, $26 - $34, $3a - $3e, $40 - $48, $60 - $ff .loop ld a, [de] inc de and a ; "<NULL>" jr z, .NextChar cp FIRST_REGULAR_TEXT_CHAR jr nc, .NextChar cp "<NEXT>" jr z, .NextChar cp "@" jr z, .Done cp "ガ" jr c, .Fail cp "<PLAY_G>" jr c, .NextChar cp "<JP_18>" + 1 jr c, .Fail cp "<NI>" jr c, .NextChar cp "<NO>" + 1 jr c, .Fail cp "<ROUTE>" jr c, .NextChar cp "<GREEN>" + 1 jr c, .Fail cp "<ENEMY>" jr c, .NextChar cp "<ENEMY>" + 1 jr c, .Fail cp "<MOM>" jr c, .NextChar .Fail: scf ret .NextChar: dec c jr nz, .loop .Done: and a ret CheckStringForErrors_IgnoreTerminator: ; Find control chars .loop ld a, [de] inc de and a jr z, .next cp "<DEXEND>" + 1 jr nc, .next cp "<NEXT>" jr z, .next cp "@" jr z, .next cp "ガ" jr c, .end cp "<PLAY_G>" jr c, .next cp "<JP_18>" + 1 jr c, .end cp "<NI>" jr c, .next cp "<NO>" + 1 jr c, .end cp "<ROUTE>" jr c, .next cp "<GREEN>" + 1 jr c, .end cp "<ENEMY>" jr c, .next cp "<ENEMY>" + 1 jr c, .end cp "<MOM>" jr c, .next .end scf ret .next dec c jr nz, .loop and a ret Function17d0f3: ld a, [wc608 + 5] ld [wOTTrademonSpecies], a ld [wCurPartySpecies], a ld a, [wcd81] ld [wc74e], a ld hl, wc608 + 53 ld de, wOTTrademonOTName ld bc, 5 call CopyBytes ld a, "@" ld [de], a ld a, [wc608 + 11] ld [wOTTrademonID], a ld a, [wc608 + 12] ld [wOTTrademonID + 1], a ld hl, wc608 + 26 ld a, [hli] ld [wOTTrademonDVs], a ld a, [hl] ld [wOTTrademonDVs + 1], a ld bc, wc608 + 5 farcall GetCaughtGender ld a, c ld [wOTTrademonCaughtData], a call SpeechTextbox call FadeToMenu farcall Function10804d farcall Function17d1f1 ld a, $1 ld [wForceEvolution], a ld a, $2 ld [wLinkMode], a farcall EvolvePokemon xor a ld [wLinkMode], a farcall SaveAfterLinkTrade ld a, $5 call GetSRAMBank ld a, $5 ld [$a800], a call CloseSRAM ld a, [wMapGroup] ld b, a ld a, [wMapNumber] ld c, a call GetMapSceneID ld a, d or e jr z, .asm_17d180 ld a, $1 ld [de], a .asm_17d180 call CloseSubmenu call RestartMapMusic ret Mobile_CopyDefaultOTName: ld hl, Mobile5F_PlayersName ld de, wc63d ld bc, 5 call CopyBytes ret Mobile5F_PlayersName: db "クりス@@" Mobile_CopyDefaultNickname: ld hl, .DefaultNickname ld de, wc642 ld bc, 5 call CopyBytes ret .DefaultNickname: db "?????" Mobile_CopyDefaultMail: ld a, "@" ld hl, wc647 ld bc, MAIL_MSG_LENGTH + 1 call ByteFill ld hl, .DefaultMessage ld de, wc647 ld bc, 6 call CopyBytes ret .DefaultMessage: db "こんにちは@" Mobile_CopyDefaultMailAuthor: ld a, "@" ld de, wc668 ld bc, 5 call ByteFill ld hl, Mobile5F_PlayersName ld de, wc668 ld bc, 5 call CopyBytes ret CheckStringContainsLessThanBNextCharacters: .loop ld a, [de] inc de cp "<NEXT>" jr nz, .next_char dec b jr z, .done .next_char dec c jr nz, .loop and a ret .done scf ret Function17d1f1: ld a, [wCurPartySpecies] call SetSeenAndCaughtMon ld a, [wCurPartySpecies] call GetPokemonIndexFromID sub LOW(UNOWN) if HIGH(UNOWN) == 0 or h else ret nz if HIGH(UNOWN) == 1 dec h else ld a, h cp HIGH(UNOWN) endc endc ret nz ld hl, wPartyMon1DVs ld a, [wPartyCount] dec a ld bc, PARTYMON_STRUCT_LENGTH call AddNTimes predef GetUnownLetter callfar UpdateUnownDex ld a, [wFirstUnownSeen] and a ret nz ld a, [wUnownLetter] ld [wFirstUnownSeen], a ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Parameter: [wScriptVar] = 0..1 ; ; if [wScriptVar] == FALSE ; Show japanese menu options ; - News - News - ??? - Cancel ; if [wScriptVar] == TRUE ; Show BattleTower-Menu with 3 options in english language ; - Challenge - Explanation - Cancel Menu_ChallengeExplanationCancel: ld a, [wScriptVar] and a jr nz, .English ld a, $4 ld [wScriptVar], a ld hl, MenuHeader_17d26a ; Japanese Menu, where you can choose 'News' as an option jr .Load_Interpret .English: ld a, $4 ld [wScriptVar], a ld hl, MenuHeader_ChallengeExplanationCancel ; English Menu .Load_Interpret: call LoadMenuHeader call Function17d246 call CloseWindow ret Function17d246: call VerticalMenu jr c, .Exit ld a, [wScriptVar] cp $5 jr nz, .UsewMenuCursorY ld a, [wMenuCursorY] cp $3 ret z jr c, .UsewMenuCursorY dec a jr .LoadToScriptVar .UsewMenuCursorY: ld a, [wMenuCursorY] .LoadToScriptVar: ld [wScriptVar], a ret .Exit: ld a, $4 ld [wScriptVar], a ret MenuHeader_17d26a: db MENU_BACKUP_TILES ; flags menu_coords 0, 0, 14, 9 dw MenuData_17d272 db 1 ; default option MenuData_17d272: db STATICMENU_CURSOR | STATICMENU_WRAP ; flags db 4 db "ニュース¯よみこむ@" db "ニュース¯みる@" db "せつめい@" db "やめる@" MenuHeader_ChallengeExplanationCancel: db MENU_BACKUP_TILES ; flags menu_coords 0, 0, 14, 7 dw MenuData_ChallengeExplanationCancel db 1 ; default option MenuData_ChallengeExplanationCancel: db STATICMENU_CURSOR | STATICMENU_WRAP ; flags db 3 db "Challenge@" db "Explanation@" db "Cancel@" Function17d2b6: call Function17d2c0 farcall Function1181da ret Function17d2c0: xor a ld [wJumptableIndex], a ld [wcf64], a ld [wcf65], a ld [wcf66], a ret Function17d2ce: ld a, $5 call GetSRAMBank ld a, [$aa72] call CloseSRAM and a jr nz, .asm_17d2e2 ld a, $1 ld [wScriptVar], a ret .asm_17d2e2 call Function17d314 ret c call SpeechTextbox call FadeToMenu ldh a, [rSVBK] push af ld a, $4 ldh [rSVBK], a call Function17d370 call Function17d45a pop af ldh [rSVBK], a ld de, MUSIC_MOBILE_CENTER ld a, e ld [wMapMusic], a ld [wMusicFadeID], a ld a, d ld [wMusicFadeID + 1], a call PlayMusic call ReturnToMapFromSubmenu call CloseSubmenu ret Function17d314: ld a, $5 call GetSRAMBank ld a, [$b1b1] call CloseSRAM cp $21 jr nc, .asm_17d354 ld a, $6 call GetSRAMBank ld l, $0 ld h, l ld de, $a006 ld a, [$a004] ld c, a ld a, [$a005] ld b, a .asm_17d336 push bc ld a, [de] inc de ld c, a ld b, $0 add hl, bc pop bc dec bc ld a, b or c jr nz, .asm_17d336 ld a, [$a002] cp l jr nz, .asm_17d354 ld a, [$a003] cp h jr nz, .asm_17d354 call CloseSRAM and a ret .asm_17d354 call CloseSRAM ld a, $5 call GetSRAMBank xor a ld hl, $aa73 ld bc, $c call ByteFill call CloseSRAM ld a, $2 ld [wScriptVar], a scf ret Function17d370: xor a ld [wcd77], a ld [wMobileCrashCheckPointer], a ld [wMobileCrashCheckPointer + 1], a dec a ld [wcd6c], a call ClearBGPalettes call ClearSprites call ClearScreen farcall ReloadMapPart call DisableLCD ld hl, vTiles0 tile $ee ld de, wc608 ld bc, 1 tiles call CopyBytes ld a, $1 ldh [rVBK], a ld hl, PokemonNewsGFX ld de, vTiles1 ld bc, $48 tiles call CopyBytes xor a ld hl, vTiles2 tile $7f ld bc, 1 tiles call ByteFill ld hl, wc608 ld de, vTiles0 tile $ee ld bc, 1 tiles call CopyBytes xor a ldh [rVBK], a ld hl, GFX_17eb7e ld de, vTiles2 tile $60 ld bc, 1 tiles call CopyBytes call EnableLCD call Function17d60b ld a, $0 ld [wBGMapBuffer], a ld a, $d0 ld [wcd21], a ld a, $6 call GetSRAMBank ld hl, $a006 ld de, wBGPals1 ld bc, $1000 call CopyBytes call CloseSRAM ret Function17d3f6: call ClearBGPalettes call ClearSprites call ClearScreen farcall ReloadMapPart Function17d405: call DisableLCD ld hl, vTiles0 tile $ee ld de, wc608 ld bc, 1 tiles call CopyBytes ld a, $1 ldh [rVBK], a ld hl, PokemonNewsGFX ld de, vTiles1 ld bc, $48 tiles call CopyBytes xor a ld hl, vTiles2 tile $7f ld bc, 1 tiles call ByteFill ld hl, wc608 ld de, vTiles0 tile $ee ld bc, 1 tiles call CopyBytes xor a ldh [rVBK], a call EnableLCD ldh a, [rSVBK] push af ld a, $5 ldh [rSVBK], a ld hl, Palette_17eff6 ld de, wBGPals1 ld bc, 8 palettes call CopyBytes call SetPalettes pop af ldh [rSVBK], a ret Function17d45a: .asm_17d45a call JoyTextDelay ld a, [wcd77] bit 7, a jr nz, .asm_17d46f call Function17d474 farcall ReloadMapPart jr .asm_17d45a .asm_17d46f xor a ld [wScriptVar], a ret Function17d474: jumptable Jumptable_17d483, wcd77 Jumptable_17d483: dw Function17d48d dw Function17d5be dw Function17d5c4 dw Function17d6fd dw Function17e427 Function17d48d: ld hl, Palette_17eff6 ld de, wc608 ld bc, $40 call CopyBytes ld hl, TileAttrmap_17eb8e decoord 0, 0 bccoord 0, 0, wAttrMap ld a, $12 .asm_17d4a4 push af ld a, $14 push hl .asm_17d4a8 push af ld a, [hli] cp $7f jr z, .asm_17d4b0 add $80 .asm_17d4b0 ld [de], a inc de ld a, [hli] ld [bc], a inc bc pop af dec a jr nz, .asm_17d4a8 pop hl push bc ld bc, $40 add hl, bc pop bc pop af dec a jr nz, .asm_17d4a4 ld a, [wBGMapBuffer] ld l, a ld a, [wcd21] ld h, a ld a, [hli] ld e, a ld a, [wcd6c] cp e jr z, .asm_17d4e0 ld a, e ld [wcd6c], a ld [wMapMusic], a ld d, $0 call PlayMusic2 .asm_17d4e0 ld a, [hli] ld de, wc608 ld c, $8 .asm_17d4e6 srl a jr nc, .asm_17d4f6 ld b, $8 push af .asm_17d4ed ld a, [hli] ld [de], a inc de dec b jr nz, .asm_17d4ed pop af jr .asm_17d4fc .asm_17d4f6 push af ld a, e add $8 ld e, a pop af .asm_17d4fc dec c jr nz, .asm_17d4e6 push hl call Function17d5f6 pop hl ld a, [hli] and a jr z, .asm_17d539 .asm_17d508 push af ld a, [hli] ld [wcd4f], a ld a, [hli] ld [wcd50], a ld a, [hli] ld [wcd51], a ld a, [hli] ld [wcd52], a ld a, [hli] sla a sla a sla a add $98 ld [wcd53], a ld de, wcd4f call Function17e613 ld a, [hli] ld [wcd53], a ld de, wcd4f call Function17e691 pop af dec a jr nz, .asm_17d508 .asm_17d539 ld a, [hli] .asm_17d53a push af ld a, [hli] ld c, a ld a, [hli] ld b, a push hl pop de hlcoord 0, 0 add hl, bc call PlaceString push de pop hl inc hl pop af dec a jr nz, .asm_17d53a ld de, wCreditsTimer ld bc, $c call CopyBytes xor a ld [wcd2e], a ld [wcd2f], a inc a ld [wcd30], a ld [wcd31], a ld de, wcd32 ld bc, $10 call CopyBytes ld a, [hli] ld [wcd42], a ld a, [hli] ld [wcd43], a ld a, [hli] ld [wMobileInactivityTimerMinutes], a ld a, [hli] ld [wMobileInactivityTimerSeconds], a ld a, [hli] ld [wMobileInactivityTimerFrames], a ld a, [hli] and a jr z, .asm_17d58a call Function17d6a1 .asm_17d58a ld a, l ld [wcd49], a ld a, h ld [wcd4a], a ld a, [wcd42] ld c, a ld b, $0 add hl, bc add hl, bc ld a, l ld [wcd4b], a ld a, h ld [wcd4c], a add hl, bc add hl, bc ld a, l ld [wcd4d], a ld a, h ld [wcd4e], a call Function17e451 call Function17e55b call Function17e5af farcall ReloadMapPart jp Function17e438 Function17d5be: call SetPalettes call Function17e438 Function17d5c4: ldh a, [hJoyPressed] and a ret z ld c, 0 ld b, c ld hl, wcd32 .loop srl a jr c, .got_button inc c inc c jr .loop .got_button add hl, bc ld a, [hli] ld c, a ld a, [hli] ld b, a and c cp $ff ret z ld a, [wcd20] ld l, a ld a, [wcd21] ld h, a add hl, bc ld a, l ld [wMobileCrashCheckPointer], a ld a, h ld [wMobileCrashCheckPointer + 1], a ld a, $3 ld [wcd77], a ret Function17d5f6: ld a, $5 ldh [rSVBK], a ld hl, wc608 ld de, wBGPals1 ld bc, 8 palettes call CopyBytes ld a, $4 ldh [rSVBK], a ret Function17d60b: ld a, $5 call GetSRAMBank ld hl, $b1d3 ld de, wc608 ld bc, $20 call CopyBytes ld a, [$b1b1] ld c, a ld a, [$b1b2] ld b, a ld a, [$b1b3] ld l, a ld a, [$b1b4] ld h, a call CloseSRAM ld a, $6 call GetSRAMBank ld de, wc708 ld a, c and a jr z, .asm_17d684 .asm_17d63b push bc ld a, l ld [de], a inc de ld a, h ld [de], a inc de ld bc, $a add hl, bc pop bc ld a, [hli] ld [wcd4a], a ld a, [hli] ld [wcd49], a push hl push de ld hl, wc608 ld e, b ld d, $0 add hl, de ld a, [hli] ld [wcd4b], a ld a, [hl] ld [wcd4c], a pop de pop hl inc b inc b dec c dec c jr z, .asm_17d684 push bc push de ld a, [wcd49] ld c, a ld a, [wcd4a] ld b, a ld a, [wcd4b] ld e, a ld a, [wcd4c] ld d, a .asm_17d67a add hl, de dec bc ld a, c or b jr nz, .asm_17d67a pop de pop bc jr .asm_17d63b .asm_17d684 call CloseSRAM ld a, $5 call GetSRAMBank ld hl, wc708 ld de, $b1b3 ld a, [$b1b1] ld c, a ld a, [$b1b2] ld b, a call CopyBytes call CloseSRAM ret Function17d6a1: push hl ld a, [wcd6e] ld c, a ld b, $0 ld a, $5 call GetSRAMBank ld hl, $b1d3 add hl, bc add hl, bc ld a, [hli] ld [wcd47], a ld a, [hl] ld [wBGMapPalBuffer], a ld hl, $b1b3 add hl, bc add hl, bc ld a, [hli] ld c, a ld a, [hl] ld h, a ld l, c call CloseSRAM ld a, $6 call GetSRAMBank ld a, l ld [wcd5e], a ld a, h ld [wcd5f], a ld de, wcd60 ld bc, $4 call CopyBytes inc hl inc hl ld de, wcd64 ld bc, $4 call CopyBytes ld a, [hli] ld [wcd69], a ld a, [hli] ld [wcd68], a ld a, l ld [wcd6a], a ld a, h ld [wcd6b], a call CloseSRAM pop hl ret Function17d6fd: ld a, [wcd77] bit 7, a jr nz, asm_17d721 ld a, [wMobileCrashCheckPointer] ld l, a ld a, [wMobileCrashCheckPointer + 1] ld h, a ld a, [hl] cp $ff jr z, asm_17d721 Function17d711: .crash_loop cp $31 jr nc, .crash_loop ld e, a ld d, 0 ld hl, Jumptable17d72a add hl, de add hl, de ld a, [hli] ld h, [hl] ld l, a jp hl asm_17d721: call Function17e5af ld a, $2 ld [wcd77], a ret Jumptable17d72a: dw Function17d78c dw Function17d78d dw Function17d7b4 dw Function17d7c2 dw Function17d7d3 dw Function17d7e5 dw Function17d818 dw Function17d833 dw Function17d85d dw Function17d902 dw Function17d93a dw Function17d98b dw Function17d9e3 dw Function17da31 dw Function17da9c dw Function17dadc dw Function17db2d dw Function17db56 dw Function17db77 dw Function17dbe9 dw Function17dc1f dw Function17dc9f dw Function17dca9 dw Function17dccf dw Function17dd13 dw Function17dd30 dw Function17dd49 dw Function17ddcd dw Function17de32 dw Function17de91 dw Function17ded9 dw Function17e0fd dw Function17e133 dw Function17e165 dw Function17e1a1 dw Function17e254 dw Function17e261 dw Function17e270 dw Function17e27f dw Function17e293 dw Function17e2a7 dw IncCrashCheckPointer_SaveGameData dw IncCrashCheckPointer_SaveAfterLinkTrade dw IncCrashCheckPointer_SaveBox dw IncCrashCheckPointer_SaveChecksum dw IncCrashCheckPointer_SaveTrainerRankingsChecksum dw Function17e3e0 dw Function17e3f0 dw Function17e409 Function17d78c: ret Function17d78d: call IncCrashCheckPointer ld a, [hli] ld c, a ld a, [hli] ld b, a call HlToCrashCheckPointer ld a, $6 call GetSRAMBank ld hl, $a006 add hl, bc ld de, wBGPals1 ld bc, $1000 call CopyBytes call CloseSRAM xor a ld [wcd77], a call ClearBGPalettes ret Function17d7b4: call IncCrashCheckPointer ld a, [hli] ld e, a ld d, $0 call PlayMusic2 call HlToCrashCheckPointer ret Function17d7c2: call IncCrashCheckPointer ld a, [hli] ld e, a ld d, $0 call PlaySFX call WaitSFX call HlToCrashCheckPointer ret Function17d7d3: call IncCrashCheckPointer ld a, [hli] push bc call GetCryIndex ld d, b ld e, c pop bc call nc, PlayCry call WaitSFX call HlToCrashCheckPointer ret Function17d7e5: call IncCrashCheckPointer ld a, [hli] ld [wcd4f], a ld a, [hli] ld [wcd50], a ld a, [hli] ld [wcd51], a ld a, [hli] ld [wcd52], a ld a, [hli] sla a sla a sla a add $98 ld [wcd53], a ld de, wcd4f call Function17e613 ld a, [hli] ld [wcd53], a ld de, wcd4f call Function17e691 call HlToCrashCheckPointer ret Function17d818: call IncCrashCheckPointer ld a, [hli] ld c, a ld a, [hli] ld b, a ld a, [hli] ld e, a ld a, [hli] ld d, a call HlToCrashCheckPointer call Function17e447 ld e, l ld d, h hlcoord 0, 0 add hl, bc call PlaceString ret Function17d833: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld c, a ld a, [hli] ld b, a call HlToCrashCheckPointer push de push bc call Function17e32b pop bc pop de call Function17e43d ld c, l ld b, h hlcoord 0, 0 add hl, de ld e, l ld d, h farcall Function11c08f call Function17e349 ret Function17d85d: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a push hl ld hl, wBGPals1 add hl, de ld de, wcc60 .asm_17d86c ld a, [hli] ld [de], a inc de and a jr nz, .asm_17d86c pop hl ld de, wc608 ld c, $0 .asm_17d878 ld a, [hli] cp $ff jr z, .asm_17d8c7 ld [wcd4f], a ld a, [hli] ld [wcd50], a ld a, [hli] ld [wcd51], a ld a, [hli] ld [wcd52], a ld a, [wcd51] push af cp $c0 jr c, .asm_17d89b ld a, [wcd4f] ldh [rSVBK], a jr .asm_17d8a1 .asm_17d89b ld a, [wcd4f] call GetSRAMBank .asm_17d8a1 push hl ld a, [wcd50] ld l, a ld a, [wcd51] ld h, a ld a, [wcd52] .asm_17d8ad push af ld a, [hli] ld [de], a inc de inc c pop af dec a jr nz, .asm_17d8ad pop hl pop af cp $c0 jr c, .asm_17d8c2 ld a, $4 ldh [rSVBK], a jr .asm_17d878 .asm_17d8c2 call CloseSRAM jr .asm_17d878 .asm_17d8c7 call HlToCrashCheckPointer push bc ld a, $3 ldh [rSVBK], a ld hl, wc608 ld de, wBGPals1 ld b, $0 call CopyBytes ld a, $4 ldh [rSVBK], a call Function17e32b pop bc ld a, c ld [wcd3b], a xor a ld [wcf66], a farcall Function118329 ld a, [wc300] and a jr z, .asm_17d8fe cp $a jr z, .asm_17d8fe call Function17e309 ret .asm_17d8fe call Function17e349 ret Function17d902: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a push de call HlToCrashCheckPointer call Function17e32b pop de ld hl, wBGPals1 add hl, de ld de, wcc60 .asm_17d918 ld a, [hli] ld [de], a inc de and a jr nz, .asm_17d918 xor a ld [wcf66], a farcall Function11837a ld a, [wc300] and a jr z, .asm_17d936 cp $a jr z, .asm_17d936 call Function17e309 ret .asm_17d936 call Function17e349 ret Function17d93a: call IncCrashCheckPointer ld de, wc708 ld bc, $5 call CopyBytes call HlToCrashCheckPointer call Function17e32b ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a ld a, [wc70c] call Function17e6de ld a, [wc70a] ld [wCurPartySpecies], a ld a, [wc70c] ld e, a farcall LoadMonPaletteAsNthBGPal call SetPalettes ld a, [wc708] ld l, a ld a, [wc709] ld h, a ld a, [wc70b] ld c, a decoord 0, 0 add hl, de ld e, l ld d, h farcall HOF_PlayCry pop af ldh [rSVBK], a call Function17e349 ret Function17d98b: call IncCrashCheckPointer ld de, wc708 ld bc, $4 call CopyBytes call HlToCrashCheckPointer call Function17e32b ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a ld a, [wc70b] call Function17e6de ld a, [wc70a] ld [wTrainerClass], a ld a, [wc70b] ld e, a farcall LoadTrainerClassPaletteAsNthBGPal call SetPalettes ld a, [wc708] ld e, a ld a, [wc709] ld d, a push de ld de, vTiles2 farcall GetTrainerPic pop hl decoord 0, 0 add hl, de ld bc, $707 predef PlaceGraphic pop af ldh [rSVBK], a call Function17e349 ret Function17d9e3: call IncCrashCheckPointer ld de, wc708 ld bc, $7 call CopyBytes call HlToCrashCheckPointer ld a, [wc70b] push af cp $c0 jr c, .asm_17da01 ld a, [wc70c] ldh [rSVBK], a jr .asm_17da07 .asm_17da01 ld a, [wc70c] call GetSRAMBank .asm_17da07 ld a, [wc708] ld l, a ld a, [wc709] ld h, a ld a, [wc70a] ld e, a ld a, [wc70b] ld d, a ld a, [wc70d] ld c, a ld a, [wc70e] ld b, a call CopyBytes pop af cp $c0 jr c, .asm_17da2d ld a, $4 ldh [rSVBK], a jr .asm_17da30 .asm_17da2d call CloseSRAM .asm_17da30 ret Function17da31: call IncCrashCheckPointer ld de, wc708 ld bc, $4 call CopyBytes call HlToCrashCheckPointer ld a, [wc709] push af cp $c0 jr c, .asm_17da4f ld a, [wc70a] ldh [rSVBK], a jr .asm_17da55 .asm_17da4f ld a, [wc70a] call GetSRAMBank .asm_17da55 ld a, [wc708] ld e, a ld a, [wc709] ld d, a ld a, [wc70b] ld c, a bit 7, c jr nz, .asm_17da70 ld hl, Unknown_17da8c ld b, $0 add hl, bc ld a, [de] or [hl] ld [de], a jr .asm_17da7d .asm_17da70 ld hl, Unknown_17da94 ld a, c and $7f ld c, a ld b, $0 add hl, bc ld a, [de] and [hl] ld [de], a .asm_17da7d pop af cp $c0 jr c, .asm_17da88 ld a, $4 ldh [rSVBK], a jr .asm_17da8b .asm_17da88 call CloseSRAM .asm_17da8b ret Unknown_17da8c: x = 0 rept 8 db 1 << x x = x + 1 endr Unknown_17da94: x = 0 rept 8 db $ff ^ (1 << x) x = x + 1 endr Function17da9c: ld a, [wcd31] dec a jr z, .asm_17dabd push af call Function17e566 pop af ld [wcd31], a ld hl, wcd24 ld a, [wcd2e] sub [hl] ld [wcd2e], a call Function17e55b call Function17e5af .asm_17daba jp IncCrashCheckPointer .asm_17dabd ld a, [wcd2f] and a jr z, .asm_17daba ld hl, wcd24 sub [hl] ld [wcd2f], a ld a, [wcd2e] sub [hl] ld [wcd2e], a call Function17e451 call Function17e55b call Function17e5af jr .asm_17daba Function17dadc: ld a, [wcd2e] ld hl, wcd24 add [hl] ld hl, wcd42 cp [hl] jr z, .asm_17db0e jr nc, .asm_17db0e ld hl, wcd31 ld a, [wcd2b] cp [hl] jr z, .asm_17db11 call Function17e566 ld a, [wcd31] inc a ld [wcd31], a ld hl, wcd24 ld a, [wcd2e] add [hl] ld [wcd2e], a call Function17e55b call Function17e5af .asm_17db0e jp IncCrashCheckPointer .asm_17db11 ld hl, wcd24 ld a, [wcd2f] add [hl] ld [wcd2f], a ld a, [wcd2e] add [hl] ld [wcd2e], a call Function17e451 call Function17e55b call Function17e5af jr .asm_17db0e Function17db2d: ld a, [wcd30] ld hl, wcd24 cp [hl] jr z, .asm_17db53 ld hl, wcd42 ld a, [wcd2e] inc a cp [hl] jr z, .asm_17db53 ld [wcd2e], a call Function17e566 ld a, [wcd30] inc a ld [wcd30], a call Function17e55b call Function17e5af .asm_17db53 jp IncCrashCheckPointer Function17db56: ld a, [wcd30] cp $1 jr z, .asm_17db74 call Function17e566 ld a, [wcd30] dec a ld [wcd30], a ld a, [wcd2e] dec a ld [wcd2e], a call Function17e55b call Function17e5af .asm_17db74 jp IncCrashCheckPointer Function17db77: ld hl, wcd2d ld a, [wcd2f] add [hl] ld hl, wcd42 cp [hl] jr z, .asm_17dbae jr nc, .asm_17dbae call Function17e566 ld hl, wcd2d ld a, [wcd2f] add [hl] ld [wcd2f], a ld a, [wcd2e] add [hl] ld hl, wcd42 cp [hl] jr c, .asm_17db9f ld a, [hl] dec a .asm_17db9f ld [wcd2e], a call Function17dbb1 call Function17e451 call Function17e55b call Function17e5af .asm_17dbae jp IncCrashCheckPointer Function17dbb1: ld hl, wcd2f ld a, [wcd42] sub [hl] ld hl, wcd2d cp [hl] ret nc ld a, $1 ld [wcd30], a ld [wcd31], a ld a, [wcd24] ld c, a ld a, [wcd24] ld b, a ld a, [wcd2e] ld hl, wcd2f sub [hl] .asm_17dbd4 and a ret z push af ld hl, wcd30 ld a, b cp [hl] jr nz, .asm_17dbe4 ld a, $1 ld [hl], a ld hl, wcd31 .asm_17dbe4 inc [hl] pop af dec a jr .asm_17dbd4 Function17dbe9: ld hl, wcd2d ld a, [wcd2f] sub [hl] bit 7, a jr z, .asm_17dbf5 xor a .asm_17dbf5 ld [wcd2f], a ld a, [wcd30] dec a ld c, a ld a, [wcd31] ld b, a xor a ld hl, wcd24 .asm_17dc05 dec b jr z, .asm_17dc0b add [hl] jr .asm_17dc05 .asm_17dc0b add c ld hl, wcd2f add [hl] ld [wcd2e], a call Function17e451 call Function17e55b call Function17e5af jp IncCrashCheckPointer Function17dc1f: call IncCrashCheckPointer ld de, wc688 ld bc, $6 call CopyBytes call Function17e32b ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a ld hl, wc688 ld a, $40 ld [wc708], a ld a, [hli] ld [wc70a], a add $5 ld [wc70c], a ld a, [hli] ld [wc709], a add $4 ld [wc70b], a ld a, $96 ld [wc70d], a ld a, $5c ld [wc70e], a ld a, $1 ld [wc70f], a ld hl, wc708 call LoadMenuHeader call VerticalMenu jr nc, .asm_17dc6e ld a, $2 ld [wMenuCursorY], a .asm_17dc6e call CloseWindow pop af ldh [rSVBK], a ld a, [wMenuCursorY] cp $1 jr nz, .asm_17dc85 ld a, [wc68a] ld l, a ld a, [wc68a + 1] ld h, a jr .asm_17dc8d .asm_17dc85 ld a, [wc68a + 2] ld l, a ld a, [wc68a + 3] ld h, a .asm_17dc8d push hl call Function17e349 pop hl call Function17e40f ret MenuData_17dc96: db STATICMENU_CURSOR | STATICMENU_NO_TOP_SPACING | STATICMENU_WRAP ; flags db 2 db "はい@" db "いいえ@" Function17dc9f: call IncCrashCheckPointer call HlToCrashCheckPointer call RotateFourPalettesLeft ret Function17dca9: call IncCrashCheckPointer call HlToCrashCheckPointer Function17dcaf: ld a, $5 ldh [rSVBK], a ld hl, wBGPals1 ld de, 1 palettes ld c, 8 .asm_17dcbb push hl ld a, $ff ld [hli], a ld a, $7f ld [hl], a pop hl add hl, de dec c jr nz, .asm_17dcbb call RotateThreePalettesRight ld a, $4 ldh [rSVBK], a ret Function17dccf: call IncCrashCheckPointer push hl ld a, [wcd4b] ld l, a ld a, [wcd4c] ld h, a ld a, [wcd2e] ld c, a ld b, $0 add hl, bc add hl, bc ld a, [hli] ld c, a ld a, [hl] ld b, a call Function17e43d call HlToCrashCheckPointer .asm_17dced ld a, [wMobileCrashCheckPointer] ld l, a ld a, [wMobileCrashCheckPointer + 1] ld h, a ld a, [hl] cp $ff jr z, .asm_17dd0d .crash_loop cp $31 jr nc, .crash_loop call Function17d711 ld a, [wcd77] bit 7, a jr nz, .asm_17dd0d and a jr z, .asm_17dd11 jr .asm_17dced .asm_17dd0d pop hl jp HlToCrashCheckPointer .asm_17dd11 pop hl ret Function17dd13: call IncCrashCheckPointer ld a, [hli] ld c, a ld a, [hli] ld b, a ld a, [hli] ld e, a ld a, [hli] ld d, a call HlToCrashCheckPointer call Function17e447 push hl hlcoord 0, 0 add hl, bc push hl pop bc pop hl call PlaceHLTextAtBC ret Function17dd30: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld c, a ld b, $0 ld a, [hli] push af call HlToCrashCheckPointer pop af hlcoord 0, 0 add hl, de call Function17e600 ret Function17dd49: call IncCrashCheckPointer ld de, wc708 ld bc, $a call CopyBytes ld a, [wc711] ld c, a ld b, $0 call CopyBytes ld a, [wc70a] cp $c0 jr c, .sram ld a, [wc708] ldh [rSVBK], a jr .got_bank .sram ld a, [wc708] call GetSRAMBank .got_bank ld a, [wc709] ld l, a ld a, [wc70a] ld h, a ld de, wc688 ld a, [wc711] ld c, a ld b, $0 call CopyBytes ld a, [wc70a] cp $c0 jr c, .close_sram ld a, $4 ldh [rSVBK], a jr .exited_bank .close_sram call CloseSRAM .exited_bank ld a, [wc711] ld c, a ld hl, wc712 ld de, wc688 .loop ld a, [de] inc de cp [hl] inc hl jr z, .next jr c, .load jr .load2 .next dec c jr nz, .loop ld a, [wc70d] ld l, a ld a, [wc70e] ld h, a jr .done .load2 ld a, [wc70f] ld l, a ld a, [wc710] ld h, a jr .done .load ld a, [wc70b] ld l, a ld a, [wc70c] ld h, a .done call Function17e40f ret Function17ddcd: call IncCrashCheckPointer ld de, wc708 ld bc, $8 call CopyBytes ld a, [wc70a] cp $c0 jr c, .asm_17dde7 ld a, [wc708] ldh [rSVBK], a jr .asm_17dded .asm_17dde7 ld a, [wc708] call GetSRAMBank .asm_17dded ld a, [wc709] ld e, a ld a, [wc70a] ld d, a ld a, [de] ld [wc710], a ld a, [wc70b] ld c, a ld b, $0 ld a, [wc70a] cp $c0 jr c, .asm_17de0c ld a, $4 ldh [rSVBK], a jr .asm_17de0f .asm_17de0c call CloseSRAM .asm_17de0f push hl ld hl, Unknown_17da8c add hl, bc ld a, [hl] ld hl, wc710 and [hl] pop hl jr nz, .asm_17de26 ld a, [wc70e] ld l, a ld a, [wc70f] ld h, a jr .asm_17de2e .asm_17de26 ld a, [wc70c] ld l, a ld a, [wc70d] ld h, a .asm_17de2e call Function17e40f ret Function17de32: call IncCrashCheckPointer ld de, wc708 ld bc, $9 call CopyBytes ld a, [wc710] ld c, a ld b, $0 call CopyBytes ld a, $6 call GetSRAMBank call Function17f4f6 ld a, [wc708] ld e, a ld a, [wc709] ld d, a add hl, de ld e, l ld d, h ld a, [wc710] ld c, a ld hl, wc711 .asm_17de61 ld a, [de] inc de cp [hl] inc hl jr z, .asm_17de6b jr c, .asm_17de82 jr .asm_17de78 .asm_17de6b dec c jr nz, .asm_17de61 ld a, [wc70c] ld l, a ld a, [wc70d] ld h, a jr .asm_17de8a .asm_17de78 ld a, [wc70e] ld l, a ld a, [wc70f] ld h, a jr .asm_17de8a .asm_17de82 ld a, [wc70a] ld l, a ld a, [wc70b] ld h, a .asm_17de8a call CloseSRAM call Function17e40f ret Function17de91: call IncCrashCheckPointer ld de, wc708 ld bc, $7 call CopyBytes ld a, $6 call GetSRAMBank call Function17f4f6 ld a, [wc708] ld e, a ld a, [wc709] ld d, a add hl, de ld e, l ld d, h ld a, [wc70a] ld c, a ld b, $0 ld hl, Unknown_17da8c add hl, bc ld a, [hl] ld l, e ld h, d and [hl] jr nz, .asm_17deca ld a, [wc70d] ld l, a ld a, [wc70e] ld h, a jr .asm_17ded2 .asm_17deca ld a, [wc70b] ld l, a ld a, [wc70c] ld h, a .asm_17ded2 call CloseSRAM call Function17e40f ret Function17ded9: call IncCrashCheckPointer ld de, wc708 ld bc, $1f call CopyBytes call Function17e32b ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a ld hl, wc708 ld a, [hli] ld [wCurPartySpecies], a ld [wTempEnemyMonSpecies], a ld a, [hli] ld [wCurPartyLevel], a ld a, [hli] ld b, a ld a, [wPartyCount] cp $6 jp nc, Function17e026 xor a ld [wMonType], a push hl push bc predef TryAddMonToParty farcall SetCaughtData pop bc pop hl bit 1, b jr z, .asm_17df33 push bc push hl ld a, [wPartyCount] dec a ld hl, wPartyMonNicknames call SkipNames ld d, h ld e, l pop hl call CopyBytes pop bc jr .asm_17df37 .asm_17df33 ld de, $6 add hl, de .asm_17df37 bit 2, b jr z, .asm_17df5a push bc push hl ld a, [wPartyCount] dec a ld hl, wPartyMonOT call SkipNames ld d, h ld e, l pop hl call CopyBytes ld a, [hli] ld b, a push hl farcall SetGiftPartyMonCaughtData pop hl pop bc jr .asm_17df5e .asm_17df5a ld de, $7 add hl, de .asm_17df5e bit 3, b jr z, .asm_17df79 push bc push hl ld a, [wPartyCount] dec a ld hl, wPartyMon1ID call GetPartyLocation ld d, h ld e, l pop hl ld a, [hli] ld [de], a inc de ld a, [hli] ld [de], a pop bc jr .asm_17df7b .asm_17df79 inc hl inc hl .asm_17df7b bit 4, b jr z, .asm_17dfd0 push bc push hl ld a, [wPartyCount] dec a ld hl, wPartyMon1DVs call GetPartyLocation ld d, h ld e, l pop hl ld a, [hli] ld [de], a inc de ld a, [hli] ld [de], a push hl ld a, [wPartyCount] dec a ld hl, wPartyMon1Species call GetPartyLocation ld a, [hl] ld [wCurSpecies], a call GetBaseData ld a, [wPartyCount] dec a ld hl, wPartyMon1MaxHP call GetPartyLocation ld d, h ld e, l push hl ld b, FALSE farcall CalcMonStats ld a, [wPartyCount] dec a ld hl, wPartyMon1HP call GetPartyLocation ld d, h ld e, l pop hl ld a, [hli] ld [de], a inc de ld a, [hl] ld [de], a pop hl pop bc jr .asm_17dfd2 .asm_17dfd0 inc hl inc hl .asm_17dfd2 bit 5, b jr z, .asm_17dfea push bc push hl ld a, [wPartyCount] dec a ld hl, wPartyMon1Item call GetPartyLocation ld d, h ld e, l pop hl ld a, [hli] ld [de], a pop bc jr .asm_17dfeb .asm_17dfea inc hl .asm_17dfeb bit 6, b jr z, .asm_17e01f push bc push hl ld a, [wPartyCount] dec a ld hl, wPartyMon1Moves call GetPartyLocation ld d, h ld e, l pop hl push de ld bc, $4 call CopyBytes pop de push hl push de ld a, [wPartyCount] dec a ld hl, wPartyMon1PP call GetPartyLocation ld d, h ld e, l pop hl predef FillPP pop hl pop bc jp asm_17e0ee .asm_17e01f ld de, $4 add hl, de jp asm_17e0ee Function17e026: ld a, BANK(sBoxCount) call GetSRAMBank ld a, [sBoxCount] call CloseSRAM cp $14 jp nc, .asm_17e0ea bit 0, b jp z, .asm_17e0ea push bc push hl farcall LoadEnemyMon farcall SendMonIntoBox farcall SetBoxMonCaughtData pop hl pop bc ld a, BANK(sBoxMonNicknames) call GetSRAMBank bit 1, b jr z, .asm_17e067 push bc ld bc, $b ld de, sBoxMonNicknames call CopyBytes pop bc jr .asm_17e06b .asm_17e067 ld de, $6 add hl, de .asm_17e06b bit 2, b jr z, .asm_17e08e push bc ld bc, $6 ld de, sBoxMonOT call CopyBytes ld a, [hli] ld b, a push hl call CloseSRAM farcall SetGiftBoxMonCaughtData ld a, $1 call GetSRAMBank pop hl pop bc jr .asm_17e092 .asm_17e08e ld de, $7 add hl, de .asm_17e092 bit 3, b jr z, .asm_17e0a2 push bc ld de, sBoxMon1ID ld a, [hli] ld [de], a inc de ld a, [hli] ld [de], a pop bc jr .asm_17e0a4 .asm_17e0a2 inc hl inc hl .asm_17e0a4 bit 4, b jr z, .asm_17e0b4 push bc ld de, sBoxMon1DVs ld a, [hli] ld [de], a inc de ld a, [hli] ld [de], a pop bc jr .asm_17e0b6 .asm_17e0b4 inc hl inc hl .asm_17e0b6 bit 5, b ld a, [hli] jr z, .asm_17e0be ld [sBoxMon1Item], a .asm_17e0be bit 6, b jr z, .asm_17e0e1 push bc ld de, sBoxMon1Moves ld bc, $4 call CopyBytes push hl ld hl, sBoxMon1Moves ld de, sBoxMon1PP predef FillPP call CloseSRAM pop hl pop bc inc hl inc hl jr asm_17e0ee .asm_17e0e1 call CloseSRAM ld de, $6 add hl, de jr asm_17e0ee .asm_17e0ea ld bc, $1a add hl, bc asm_17e0ee: ld a, [hli] ld h, [hl] ld l, a pop af ldh [rSVBK], a push hl call Function17e349 pop hl call Function17e40f ret Function17e0fd: call IncCrashCheckPointer ld de, wc708 ld bc, $6 call CopyBytes ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a ld hl, wc708 ld a, [hli] ld [wCurItem], a ld a, [hli] ld [wItemQuantityChangeBuffer], a push hl ld hl, wNumItems call ReceiveItem pop hl jr c, .asm_17e127 inc hl inc hl .asm_17e127 ld a, [hli] ld b, a ld a, [hl] ld h, a ld l, b pop af ldh [rSVBK], a call Function17e40f ret Function17e133: call IncCrashCheckPointer ld de, wc708 ld bc, $5 call CopyBytes ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a ld hl, wc708 ld a, [hli] ld [wScriptVar], a push hl farcall MobileCheckOwnMonAnywhere pop hl jr c, .asm_17e159 inc hl inc hl .asm_17e159 ld a, [hli] ld b, a ld a, [hl] ld h, a ld l, b pop af ldh [rSVBK], a call Function17e40f ret Function17e165: call IncCrashCheckPointer ld de, wc708 ld bc, $5 call CopyBytes ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a ld hl, wc708 ld a, [hli] ld [wCurItem], a push hl ld hl, wNumItems call CheckItem pop hl jr c, .asm_17e195 push hl ld hl, wNumPCItems call CheckItem pop hl jr c, .asm_17e195 inc hl inc hl .asm_17e195 ld a, [hli] ld b, a ld a, [hl] ld h, a ld l, b pop af ldh [rSVBK], a call Function17e40f ret Function17e1a1: call IncCrashCheckPointer ld de, wc708 ld bc, $d call CopyBytes ld a, [wc70a] cp $c0 jr c, .asm_17e1bb ld a, [wc708] ldh [rSVBK], a jr .asm_17e1c1 .asm_17e1bb ld a, [wc708] call GetSRAMBank .asm_17e1c1 ld a, [wc709] ld l, a ld a, [wc70a] ld h, a ld de, wc608 ld a, [wc70b] ld c, a ld b, $0 call CopyBytes ld a, [wc70a] cp $c0 jr c, .asm_17e1e2 ld a, $4 ldh [rSVBK], a jr .asm_17e1e5 .asm_17e1e2 call CloseSRAM .asm_17e1e5 ld a, [wc70e] cp $c0 jr c, .asm_17e1f3 ld a, [wc70c] ldh [rSVBK], a jr .asm_17e1f9 .asm_17e1f3 ld a, [wc70c] call GetSRAMBank .asm_17e1f9 ld a, [wc70d] ld l, a ld a, [wc70e] ld h, a ld de, wc688 ld a, [wc70b] ld c, a ld b, $0 call CopyBytes ld a, [wc70e] cp $c0 jr c, .asm_17e21a ld a, $4 ldh [rSVBK], a jr .asm_17e21d .asm_17e21a call CloseSRAM .asm_17e21d ld a, [wc70b] ld c, a ld hl, wc688 ld de, wc608 .asm_17e227 ld a, [de] inc de cp [hl] inc hl jr z, .asm_17e231 jr c, .asm_17e23e jr .asm_17e248 .asm_17e231 dec c jr nz, .asm_17e227 ld a, [wc711] ld l, a ld a, [wc712] ld h, a jr .asm_17e250 .asm_17e23e ld a, [wc70f] ld l, a ld a, [wc710] ld h, a jr .asm_17e250 .asm_17e248 ld a, [wc712 + 1] ld l, a ld a, [wc712 + 2] ld h, a .asm_17e250 call Function17e40f ret Function17e254: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld [de], a call HlToCrashCheckPointer ret Function17e261: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [de] add [hl] ld [de], a inc hl call HlToCrashCheckPointer ret Function17e270: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [de] sub [hl] ld [de], a inc hl call HlToCrashCheckPointer ret Function17e27f: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld c, a ld a, [hli] ld b, a call HlToCrashCheckPointer ld l, c ld h, b ld a, [de] add [hl] ld [de], a ret Function17e293: call IncCrashCheckPointer ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld c, a ld a, [hli] ld b, a call HlToCrashCheckPointer ld l, c ld h, b ld a, [de] sub [hl] ld [de], a ret Function17e2a7: call IncCrashCheckPointer call HlToCrashCheckPointer call Function17e32b xor a ld [wcf66], a farcall Function118233 ld de, GFX_17eb7e ld hl, vTiles2 tile $60 lb bc, BANK(GFX_17eb7e), 1 call Get2bpp ld a, [wc300] and a jr z, .asm_17e2d8 cp $a jr z, .asm_17e2f7 cp $b jr z, .asm_17e300 call Function17e309 ret .asm_17e2d8 call Function17d60b call Function17e349 xor a ld [wcd7a], a ld a, $5 call GetSRAMBank ld hl, $aa73 ld de, $aa7f ld bc, $c call CopyBytes call CloseSRAM ret .asm_17e2f7 call Function17e349 ld a, $1 ld [wcd7a], a ret .asm_17e300 call Function17e349 ld a, $2 ld [wcd7a], a ret Function17e309: ld a, $2 ld [wc303], a call Function17dcaf call ClearScreen call Function17e349 call Function17d5f6 farcall DisplayMobileError call Function17e349 call Function17dcaf xor a ld [wcd77], a ret Function17e32b: ld a, $5 call GetSRAMBank ld hl, wc608 ld de, $b0b1 ld bc, $40 call CopyBytes ld hl, wBGMapBuffer ld bc, $5b call CopyBytes call CloseSRAM ret Function17e349: ld a, $5 call GetSRAMBank ld hl, $b0b1 ld de, wc608 ld bc, $40 call CopyBytes ld de, wBGMapBuffer ld bc, $5b call CopyBytes call CloseSRAM ret inc_crash_check_pointer_farcall: MACRO call IncCrashCheckPointer call HlToCrashCheckPointer ; redundant ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a rept _NARG farcall \1 shift endr pop af ldh [rSVBK], a ret ENDM IncCrashCheckPointer_SaveGameData: inc_crash_check_pointer_farcall SaveGameData IncCrashCheckPointer_SaveAfterLinkTrade: inc_crash_check_pointer_farcall SaveAfterLinkTrade IncCrashCheckPointer_SaveBox: inc_crash_check_pointer_farcall SaveBox IncCrashCheckPointer_SaveChecksum: inc_crash_check_pointer_farcall SaveChecksum IncCrashCheckPointer_SaveTrainerRankingsChecksum: inc_crash_check_pointer_farcall UpdateTrainerRankingsChecksum2, BackupMobileEventIndex Function17e3e0: call IncCrashCheckPointer ld a, [hli] ld c, a call HlToCrashCheckPointer ld a, $1 ldh [hBGMapMode], a call DelayFrames ret Function17e3f0: call IncCrashCheckPointer call HlToCrashCheckPointer .asm_17e3f6 call JoyTextDelay ld hl, hJoyPressed ld a, [hl] and $1 ret nz ld a, [hl] and $2 ret nz call WaitBGMap jr .asm_17e3f6 Function17e409: ld hl, wcd77 set 7, [hl] ret Function17e40f: ld de, wBGPals1 add hl, de jr HlToCrashCheckPointer IncCrashCheckPointer: ld a, [wMobileCrashCheckPointer] ld l, a ld a, [wMobileCrashCheckPointer + 1] ld h, a inc hl HlToCrashCheckPointer: ld a, l ld [wMobileCrashCheckPointer], a ld a, h ld [wMobileCrashCheckPointer + 1], a ret Function17e427: ld hl, hJoyPressed ld a, [hl] and $1 jr nz, .asm_17e432 and $2 ret z .asm_17e432 ld a, $3 ld [wcd77], a ret Function17e438: ld hl, wcd77 inc [hl] ret Function17e43d: ld a, [wBGMapBuffer] ld l, a ld a, [wcd21] ld h, a add hl, bc ret Function17e447: ld a, [wBGMapBuffer] ld l, a ld a, [wcd21] ld h, a add hl, de ret Function17e451: ld a, [wcd42] and a ret z call Function17e51b call Function17e4dd ld a, [wcd2e] push af ld a, [wcd49] ld l, a ld a, [wcd4a] ld h, a ld a, [wcd2f] ld [wcd2e], a ld c, a ld b, $0 add hl, bc add hl, bc push hl hlcoord 0, 0 ld bc, $14 ld a, [wcd23] call AddNTimes ld a, [wCreditsTimer] ld c, a ld b, $0 add hl, bc pop bc ld a, [wMobileCommsJumptableIndex] .asm_17e48b push af push hl ld a, [wcd24] .asm_17e490 push af push hl ld a, [bc] inc bc ld e, a ld a, [bc] inc bc ld d, a push bc push hl ld a, [wBGMapBuffer] ld l, a ld a, [wcd21] ld h, a add hl, de push hl pop de pop hl call PlaceString pop bc pop hl ld a, [wcd26] ld e, a ld d, $0 add hl, de ld a, [wcd2e] inc a ld [wcd2e], a ld e, a ld a, [wcd42] cp e jr z, .asm_17e4d5 pop af dec a jr nz, .asm_17e490 pop hl ld a, [wcd27] ld de, $14 .asm_17e4cb add hl, de dec a jr nz, .asm_17e4cb pop af dec a jr nz, .asm_17e48b jr .asm_17e4d8 .asm_17e4d5 pop af pop hl pop af .asm_17e4d8 pop af ld [wcd2e], a ret Function17e4dd: ld a, [wcd2c] and $1 ret z ld a, [wcd29] hlcoord 0, 0 ld bc, $14 call AddNTimes ld a, [wcd28] ld c, a ld b, $0 add hl, bc ld a, [wcd2f] and a jr z, .asm_17e4ff ld a, $61 ld [hl], a .asm_17e4ff ld a, [wcd2a] ld bc, $14 call AddNTimes ld a, [wcd42] ld c, a ld a, [wcd2e] ld b, a ld a, [wcd24] add b cp c ret z ret nc ld a, $ee ld [hl], a ret Function17e51b: ld a, [wcd28] ld hl, wCreditsTimer sub [hl] inc a ld [wcd4f], a hlcoord 0, 0 ld bc, $14 ld a, [wcd23] dec a call AddNTimes ld a, [wCreditsTimer] ld c, a ld b, $0 add hl, bc ld a, [wMobileCommsJumptableIndex] ld c, a ld a, [wcd27] call SimpleMultiply .asm_17e544 push af push hl ld a, [wcd4f] ld c, a ld b, $0 ld a, $7f call ByteFill pop hl ld bc, $14 add hl, bc pop af dec a jr nz, .asm_17e544 ret Function17e55b: ld a, [wcd42] and a ret z ld a, $ed call Function17e571 ret Function17e566: ld a, [wcd42] and a ret z ld a, $7f call Function17e571 ret Function17e571: push af hlcoord 0, 0 ld bc, $14 ld a, [wcd23] call AddNTimes ld a, [wCreditsTimer] ld c, a ld b, $0 add hl, bc dec hl push hl ld a, [wcd31] dec a ld c, a ld a, [wcd27] call SimpleMultiply ld l, $0 ld h, l ld bc, $14 call AddNTimes ld a, [wcd30] dec a ld c, a ld a, [wcd26] call SimpleMultiply ld c, a ld b, $0 add hl, bc pop bc add hl, bc pop af ld [hl], a ret Function17e5af: ld a, [wcd2c] and $2 ret z ld a, [wcd43] ld l, a ld a, [wMobileInactivityTimerMinutes] ld h, a bccoord 0, 0 add hl, bc ld bc, $ffec add hl, bc ld a, [wMobileInactivityTimerSeconds] ld c, a ld b, $0 ld a, [wMobileInactivityTimerFrames] call Function17e600 ld a, [wcd2e] ld c, a ld b, $0 ld a, [wcd4d] ld l, a ld a, [wcd4e] ld h, a add hl, bc add hl, bc ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [wBGMapBuffer] ld l, a ld a, [wcd21] ld h, a add hl, de push hl pop de ld a, [wcd43] ld l, a ld a, [wMobileInactivityTimerMinutes] ld h, a bccoord 0, 0 add hl, bc call PlaceString ret Function17e600: .asm_17e600 push af push hl push bc ld a, $7f call ByteFill pop bc pop hl ld de, $14 add hl, de pop af dec a jr nz, .asm_17e600 ret Function17e613: push hl hlcoord 0, 0 ld bc, $14 ld a, [de] inc de push af ld a, [de] inc de and a .asm_17e620 jr z, .asm_17e626 add hl, bc dec a jr .asm_17e620 .asm_17e626 pop af ld c, a ld b, $0 add hl, bc push hl ld a, [wcd53] ld [hli], a ld a, [de] inc de dec a dec a jr z, .asm_17e63f ld c, a ld a, [wcd53] inc a .asm_17e63b ld [hli], a dec c jr nz, .asm_17e63b .asm_17e63f ld a, [wcd53] add $2 ld [hl], a pop hl ld bc, $14 add hl, bc ld a, [de] dec de dec a dec a jr z, .asm_17e674 ld b, a .asm_17e651 push hl ld a, [wcd53] add $3 ld [hli], a ld a, [de] dec a dec a jr z, .asm_17e664 ld c, a ld a, $7f .asm_17e660 ld [hli], a dec c jr nz, .asm_17e660 .asm_17e664 ld a, [wcd53] add $4 ld [hl], a pop hl push bc ld bc, $14 add hl, bc pop bc dec b jr nz, .asm_17e651 .asm_17e674 ld a, [wcd53] add $5 ld [hli], a ld a, [de] dec a dec a jr z, .asm_17e689 ld c, a ld a, [wcd53] add $6 .asm_17e685 ld [hli], a dec c jr nz, .asm_17e685 .asm_17e689 ld a, [wcd53] add $7 ld [hl], a pop hl ret Function17e691: push hl ld hl, NULL ld bc, $14 ld a, [de] inc de push af ld a, [de] inc de inc de and a .asm_17e69f jr z, .asm_17e6a5 add hl, bc dec a jr .asm_17e69f .asm_17e6a5 pop af ld c, a ld b, $0 add hl, bc ld a, [de] dec de .asm_17e6ac push af push hl ld a, [de] .asm_17e6af push af push hl push hl bccoord 0, 0 add hl, bc ld a, [hl] cp $7f jr z, .asm_17e6c2 ld a, [wcd53] add $8 jr .asm_17e6c7 .asm_17e6c2 ld a, [wcd53] jr .asm_17e6c7 .asm_17e6c7 pop hl bccoord 0, 0, wAttrMap add hl, bc ld [hl], a pop hl inc hl pop af dec a jr nz, .asm_17e6af pop hl ld bc, $14 add hl, bc pop af dec a jr nz, .asm_17e6ac pop hl ret Function17e6de: push af ld a, [wc708] ld l, a ld a, [wc709] ld h, a decoord 0, 0, wAttrMap add hl, de pop af ld b, $7 .asm_17e6ee push hl ld c, $7 .asm_17e6f1 ld [hli], a dec c jr nz, .asm_17e6f1 pop hl ld de, $14 add hl, de dec b jr nz, .asm_17e6ee ret PokemonNewsGFX: INCBIN "gfx/mobile/pokemon_news.2bpp" GFX_17eb7e: INCBIN "gfx/unknown/17eb7e.2bpp" TileAttrmap_17eb8e: INCBIN "gfx/unknown/17eb8e.attrmap" Palette_17eff6: RGB 24, 9, 8 RGB 4, 9, 18 RGB 18, 18, 12 RGB 0, 0, 0 RGB 24, 24, 18 RGB 18, 18, 12 RGB 4, 9, 18 RGB 0, 0, 0 RGB 31, 31, 31 RGB 23, 11, 10 RGB 13, 6, 5 RGB 0, 0, 0 RGB 31, 31, 31 RGB 15, 25, 5 RGB 10, 20, 0 RGB 0, 0, 0 RGB 31, 31, 31 RGB 20, 28, 20 RGB 10, 18, 15 RGB 0, 0, 0 RGB 31, 31, 31 RGB 22, 22, 12 RGB 17, 12, 5 RGB 0, 0, 0 RGB 5, 5, 16 RGB 8, 19, 28 RGB 0, 0, 0 RGB 31, 31, 31 RGB 31, 31, 31 RGB 27, 24, 0 RGB 24, 16, 3 RGB 0, 0, 0 RunMobileScript:: ld a, $6 call GetSRAMBank inc de .loop call _RunMobileScript jr c, .finished jr .loop .finished call CloseSRAM ret _RunMobileScript: ld a, [de] inc de cp "@" jr z, .finished cp $10 ; jumptable size jr nc, .finished dec a push de ld e, a ld d, 0 ld hl, .Jumptable add hl, de add hl, de ld a, [hli] ld h, [hl] ld l, a jp hl .finished scf ret .Jumptable: dw Function17f081 ; 0 dw Function17f0f8 ; 1 dw Function17f154 ; 2 dw Function17f181 ; 3 dw Function17f1d0 ; 4 dw Function17f220 ; 5 dw Function17f27b ; 6 dw Function17f2cb ; 7 dw Function17f2ff ; 8 dw Function17f334 ; 9 dw Function17f382 ; a dw Function17f3c9 ; b dw Function17f3f0 ; c dw Function17f41d ; d dw Function17f44f ; e dw Function17f44f ; f Function17f081: pop hl call Function17f524 jr c, .asm_17f09f ld de, 4 add hl, de ld a, [hli] inc hl inc hl ld e, l ld d, h ld l, c ld h, b ld c, a ld b, $0 add hl, bc ld a, [de] cp "@" jr z, .asm_17f09d and a ret .asm_17f09d scf ret .asm_17f09f push bc ld de, wcd54 ld bc, 7 call CopyBytes pop bc push hl push bc call Function17f4f6 pop bc ld a, [wcd54] ld e, a ld a, [wcd55] ld d, a add hl, de ld e, l ld d, h ld l, c ld h, b push hl ld a, [wcd56] ld b, a ld a, [wcd57] ld c, a call MobilePrintNum ld a, l ld [wcd52], a ld a, h ld [wcd53], a ld a, [wcd59] and a jr z, .asm_17f0ee ld c, a ld a, [wcd57] inc a ld b, a ld e, l ld d, h dec de .asm_17f0e0 ld a, c cp b jr z, .asm_17f0ea ld a, [de] dec de ld [hld], a dec b jr .asm_17f0e0 .asm_17f0ea ld a, [wcd5a] ld [hl], a .asm_17f0ee pop hl ld a, [wcd58] call Function17f50f pop de and a ret Function17f0f8: pop hl call Function17f524 jr c, .asm_17f114 ld de, $3 add hl, de ld a, [hli] ld e, l ld d, h ld l, c ld h, b ld c, a ld b, $0 add hl, bc ld a, [de] cp "@" jr z, .asm_17f112 and a ret .asm_17f112 scf ret .asm_17f114 push bc ld de, wcd54 ld bc, $4 call CopyBytes pop bc push hl push bc call Function17f4f6 ld a, [wcd54] ld e, a ld a, [wcd55] ld d, a add hl, de ld de, wc608 ld a, [wcd56] ld c, a ld b, $0 call CopyBytes ld a, "@" ld [de], a pop hl ld de, wc608 call PlaceString ld a, c ld [wcd52], a ld a, b ld [wcd53], a ld a, [wcd57] call Function17f50f pop de and a ret Function17f154: pop hl call Function17f524 jr c, .asm_17f167 inc hl inc hl ld e, l ld d, h ld a, [de] cp "@" jr z, .asm_17f165 and a ret .asm_17f165 scf ret .asm_17f167 push bc ld a, [hli] ld e, a ld a, [hli] ld d, a pop bc push hl push bc call Function17f4f6 add hl, de ld c, l ld b, h pop de farcall Function11c08f ld c, l ld b, h pop de and a ret Function17f181: pop hl call Function17f524 jr c, .asm_17f19d ld de, $2 add hl, de ld a, [hli] ld e, l ld d, h ld l, c ld h, b ld c, a ld b, $0 add hl, bc ld a, [de] cp "@" jr z, .asm_17f19b and a ret .asm_17f19b scf ret .asm_17f19d push bc ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld [wcd54], a pop bc push hl push bc call Function17f4f6 add hl, de ld a, [hl] ld c, a ld de, wc608 farcall Function48c63 pop hl ld de, wc608 call PlaceString ld a, c ld [wcd52], a ld a, b ld [wcd53], a ld a, [wcd54] call Function17f50f pop de and a ret Function17f1d0: pop hl call Function17f524 jr c, .asm_17f1ec ld de, $2 add hl, de ld a, [hli] ld e, l ld d, h ld l, c ld h, b ld c, a ld b, $0 add hl, bc ld a, [de] cp "@" jr z, .asm_17f1ea and a ret .asm_17f1ea scf ret .asm_17f1ec push bc ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld [wcd54], a pop bc push hl push bc call Function17f4f6 add hl, de ld a, [hl] ld a, $1 ldh [rSVBK], a ld [wNamedObjectIndexBuffer], a call GetPokemonName pop hl call PlaceString ld a, c ld [wcd52], a ld a, b ld [wcd53], a ld a, $4 ldh [rSVBK], a ld a, [wcd54] call Function17f50f pop de and a ret Function17f220: pop hl call Function17f524 jr c, .asm_17f23c ld de, $2 add hl, de ld a, [hli] ld e, l ld d, h ld l, c ld h, b ld c, a ld b, $0 add hl, bc ld a, [de] cp "@" jr z, .asm_17f23a and a ret .asm_17f23a scf ret .asm_17f23c push bc ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld [wcd54], a pop bc push hl push bc call Function17f4f6 add hl, de ld a, [hl] ld e, a ld d, 0 ld hl, .Genders add hl, de add hl, de ld a, [hli] ld e, a ld a, [hl] ld d, a pop hl call PlaceString ld a, c ld [wcd52], a ld a, b ld [wcd53], a ld a, [wcd54] call Function17f50f pop de and a ret .Genders: dw .Boy, .Girl .Boy: db "Boy@" .Girl: db "Girl@" Function17f27b: pop hl call Function17f524 jr c, .asm_17f297 ld de, $2 add hl, de ld a, [hli] ld e, l ld d, h ld l, c ld h, b ld c, a ld b, $0 add hl, bc ld a, [de] cp "@" jr z, .asm_17f295 and a ret .asm_17f295 scf ret .asm_17f297 push bc ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [hli] ld [wcd54], a pop bc push hl push bc call Function17f4f6 add hl, de ld a, [hl] ld a, $1 ldh [rSVBK], a ld [wNamedObjectIndexBuffer], a call GetItemName pop hl call PlaceString ld a, c ld [wcd52], a ld a, b ld [wcd53], a ld a, $4 ldh [rSVBK], a ld a, [wcd54] call Function17f50f pop de and a ret Function17f2cb: pop hl push bc ld a, [hli] ld [wcd54], a ld a, [hli] ld [wcd55], a ld a, [wcd2e] inc a ld [wcd56], a pop bc push hl ld l, c ld h, b push hl ld de, wcd56 ld b, $1 ld a, [wcd54] ld c, a call MobilePrintNum ld a, l ld [wcd52], a ld a, h ld [wcd53], a pop hl ld a, [wcd55] call Function17f50f pop de and a ret Function17f2ff: pop hl push bc ld a, [hli] ld [wcd54], a pop bc push hl push bc ld a, $1 ldh [rSVBK], a ld hl, wPlayerName ld de, wc608 ld bc, $6 call CopyBytes ld a, $4 ldh [rSVBK], a pop hl ld de, wc608 call PlaceString ld a, c ld [wcd52], a ld a, b ld [wcd53], a ld a, [wcd54] call Function17f50f pop de and a ret Function17f334: pop hl push bc ld a, [hli] ld [wcd55], a and $f ld [wcd54], a pop bc push hl ld l, c ld h, b push hl ld a, [wcd55] bit 7, a jr nz, .asm_17f355 ld a, BANK(sCrystalData) call GetSRAMBank ld a, [sCrystalData + 2] jr .asm_17f35d .asm_17f355 ld a, $5 call GetSRAMBank ld a, [$b2f3] .asm_17f35d ld c, a call CloseSRAM ld de, wc608 farcall Function48c63 pop hl ld de, wc608 call PlaceString ld a, c ld [wcd52], a ld a, b ld [wcd53], a ld a, [wcd54] call Function17f50f pop de and a ret Function17f382: pop hl push bc ld a, [hli] ld [wcd55], a and $f ld [wcd54], a pop bc push hl push bc ld l, c ld h, b ld a, [wcd55] bit 7, a jr nz, .asm_17f3a3 ld a, BANK(sCrystalData) call GetSRAMBank ld de, sCrystalData + 3 jr .asm_17f3ab .asm_17f3a3 ld a, $5 call GetSRAMBank ld de, $b2f4 .asm_17f3ab ld a, PRINTNUM_LEADINGZEROS | 2 ld b, a ld a, 3 ld c, a call PrintNum call CloseSRAM ld a, l ld [wcd52], a ld a, h ld [wcd53], a pop hl ld a, [wcd54] call Function17f50f pop de and a ret Function17f3c9: push bc ld hl, wcd36 ld de, wc708 ld bc, 12 call CopyBytes pop de ld c, $0 farcall Function11c075 push hl ld hl, wc708 ld de, wcd36 ld bc, $c call CopyBytes pop bc pop de and a ret Function17f3f0: pop hl push hl ld a, [hli] push af push bc ld a, [hli] ld e, a ld a, [hli] ld d, a ld a, [de] ld c, a ld b, $0 add hl, bc add hl, bc ld a, [hli] ld e, a ld a, [hli] ld d, a ld hl, wBGPals1 add hl, de ld e, l ld d, h pop hl call PlaceString pop af ld e, a ld d, $0 pop hl add hl, de add hl, de inc hl inc hl inc hl ld e, l ld d, h ld l, c ld h, b scf ret Function17f41d: pop hl ld a, [hli] push hl push af ld l, c ld h, b ld bc, -wTileMap + $10000 add hl, bc ld de, -SCREEN_WIDTH ld c, $1 .asm_17f42c ld a, h and a jr nz, .asm_17f435 ld a, l cp SCREEN_WIDTH jr c, .asm_17f439 .asm_17f435 add hl, de inc c jr .asm_17f42c .asm_17f439 hlcoord 0, 0 ld de, SCREEN_WIDTH ld a, c .asm_17f440 and a jr z, .asm_17f447 add hl, de dec a jr .asm_17f440 .asm_17f447 pop af ld e, a ld d, 0 add hl, de pop de and a ret Function17f44f: pop hl call Function17f524 jr c, .asm_17f46d ld de, $5 add hl, de ld a, [hli] inc hl inc hl ld e, l ld d, h ld l, c ld h, b ld c, a ld b, 0 add hl, bc ld a, [de] cp "@" jr z, .asm_17f46b and a ret .asm_17f46b scf ret .asm_17f46d push bc ld de, wcd54 ld bc, $8 call CopyBytes pop bc push hl push bc ld a, [wcd56] cp $c0 jr c, .asm_17f488 ld a, [wcd54] ldh [rSVBK], a jr .asm_17f48e .asm_17f488 ld a, [wcd54] call GetSRAMBank .asm_17f48e ld a, [wcd55] ld l, a ld a, [wcd56] ld h, a ld de, wc608 ld a, [wcd57] ld c, a ld b, $0 call CopyBytes ld a, [wcd56] cp $c0 jr c, .asm_17f4af ld a, $4 ldh [rSVBK], a jr .asm_17f4b7 .asm_17f4af call CloseSRAM ld a, $6 call GetSRAMBank .asm_17f4b7 ld de, wc608 pop hl push hl ld a, [wcd57] ld b, a ld a, [wcd58] ld c, a call MobilePrintNum ld a, l ld [wcd52], a ld a, h ld [wcd53], a ld a, [wcd5a] and a jr z, .asm_17f4ec ld c, a ld a, [wcd58] inc a ld b, a ld e, l ld d, h dec de .asm_17f4de ld a, c cp b jr z, .asm_17f4e8 ld a, [de] dec de ld [hld], a dec b jr .asm_17f4de .asm_17f4e8 ld a, [wcd5b] ld [hl], a .asm_17f4ec pop hl ld a, [wcd59] call Function17f50f pop de and a ret Function17f4f6: ld a, [wcd6a] ld l, a ld a, [wcd6b] ld h, a ld a, [wcd47] ld c, a ld a, [wBGMapPalBuffer] ld b, a ld a, [wcd2e] .asm_17f509 and a ret z dec a add hl, bc jr .asm_17f509 Function17f50f: and a jr z, .asm_17f519 ld c, a ld b, $0 add hl, bc ld c, l ld b, h ret .asm_17f519 ld a, [wcd52] ld c, a ld l, a ld a, [wcd53] ld b, a ld h, a ret Function17f524: push hl push bc push de ld a, [wcd42] dec a ld b, a ld a, [wcd2e] cp b jr z, .asm_17f53a ld hl, wcd68 cp [hl] .asm_17f536 pop de pop bc pop hl ret .asm_17f53a scf jr .asm_17f536 BattleTowerMobileError: call FadeToMenu xor a ld [wc303], a ldh a, [rSVBK] push af ld a, $1 ldh [rSVBK], a call DisplayMobileError pop af ldh [rSVBK], a call ExitAllMenus ret DisplayMobileError: .loop call JoyTextDelay call .RunJumptable ld a, [wc303] bit 7, a jr nz, .quit farcall HDMATransferAttrMapAndTileMapToWRAMBank3 jr .loop .quit call .deinit ret .deinit ld a, [wc300] cp $22 jr z, .asm_17f597 cp $31 jr z, .asm_17f58a cp $33 ret nz ld a, [wc301] cp $1 ret nz ld a, [wc302] cp $2 ret nz jr .asm_17f5a1 .asm_17f58a ld a, [wc301] cp $3 ret nz ld a, [wc302] and a ret nz jr .asm_17f5a1 .asm_17f597 ld a, [wc301] and a ret nz ld a, [wc302] and a ret nz .asm_17f5a1 ld a, BANK(sMobileLoginPassword) call GetSRAMBank xor a ld [sMobileLoginPassword], a call CloseSRAM ret .RunJumptable: jumptable .Jumptable, wc303 .Jumptable: dw Function17f5c3 dw Function17ff23 dw Function17f5d2 Function17f5c3: call Function17f5e4 farcall FinishExitMenu ld a, $1 ld [wc303], a ret Function17f5d2: call Function17f5e4 farcall HDMATransferAttrMapAndTileMapToWRAMBank3 call SetPalettes ld a, $1 ld [wc303], a ret Function17f5e4: ld a, $8 ld [wMusicFade], a ld de, MUSIC_NONE ld a, e ld [wMusicFadeID], a ld a, d ld [wMusicFadeID + 1], a ld a, " " hlcoord 0, 0 ld bc, SCREEN_WIDTH * SCREEN_HEIGHT call ByteFill ld a, $6 hlcoord 0, 0, wAttrMap ld bc, SCREEN_WIDTH * SCREEN_HEIGHT call ByteFill hlcoord 2, 1 ld b, $1 ld c, $e call Function3eea hlcoord 1, 4 ld b, $c ld c, $10 call Function3eea hlcoord 3, 2 ld de, String_17f6dc call PlaceString call Function17ff3c jr nc, .asm_17f632 hlcoord 11, 2 call Function17f6b7 .asm_17f632 ld a, [wc300] cp $d0 jr nc, .asm_17f684 cp $10 jr c, .asm_17f679 sub $10 cp $24 jr nc, .asm_17f679 ld e, a ld d, $0 ld hl, Table_17f706 add hl, de add hl, de ld a, [wc301] ld e, a ld a, [wc302] ld d, a ld a, [hli] ld c, a ld a, [hl] ld h, a ld l, c ld a, [hli] and a jr z, .asm_17f679 ld c, a .asm_17f65d ld a, [hli] ld b, a ld a, [hli] cp $ff jr nz, .asm_17f667 cp b jr z, .asm_17f66e .asm_17f667 xor d jr nz, .asm_17f674 ld a, b xor e jr nz, .asm_17f674 .asm_17f66e ld a, [hli] ld e, a ld a, [hl] ld d, a jr .asm_17f67d .asm_17f674 inc hl inc hl dec c jr nz, .asm_17f65d .asm_17f679 ld a, $d9 jr .asm_17f684 .asm_17f67d hlcoord 2, 6 call PlaceString ret .asm_17f684 sub $d0 ld e, a ld d, 0 ld hl, Table_17f699 add hl, de add hl, de ld a, [hli] ld e, a ld a, [hl] ld d, a hlcoord 2, 6 call PlaceString ret Table_17f699: dw String_17fedf dw String_17fdd9 dw String_17fdd9 dw String_17fe03 dw String_17fd84 dw String_17fe63 dw String_17fdb2 dw String_17fe4b dw String_17fe03 dw String_17fe03 dw String_17fe03 Palette_17f6af: RGB 5, 5, 16 RGB 8, 19, 28 RGB 0, 0, 0 RGB 31, 31, 31 Function17f6b7: ld a, [wc300] call .bcd_two_digits inc hl ld a, [wc302] and $f call .bcd_digit ld a, [wc301] call .bcd_two_digits ret .bcd_two_digits ld c, a and $f0 swap a call .bcd_digit ld a, c and $f .bcd_digit add "0" ld [hli], a ret String_17f6dc: db "つうしんエラー   ー@" String_17f6e8: db "みていぎ<NO>エラーです" next "プログラム<WO>" next "かくにん してください" db "@" Table_17f706: dw Unknown_17f74e dw Unknown_17f753 dw Unknown_17f758 dw Unknown_17f75d dw Unknown_17f762 dw Unknown_17f767 dw Unknown_17f778 dw Unknown_17f77d dw Unknown_17f782 dw Unknown_17f782 dw Unknown_17f782 dw Unknown_17f782 dw Unknown_17f782 dw Unknown_17f782 dw Unknown_17f782 dw Unknown_17f782 dw Unknown_17f782 dw Unknown_17f787 dw Unknown_17f78c dw Unknown_17f791 dw Unknown_17f796 dw Unknown_17f79b dw Unknown_17f7a0 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7a5 dw Unknown_17f7ea dw Unknown_17f7ff dw Unknown_17f844 Unknown_17f74e: db 1 dbbw $0, $0, String_17f891 Unknown_17f753: db 1 dbbw $0, $0, String_17f8d1 Unknown_17f758: db 1 dbbw $0, $0, String_17f913 Unknown_17f75d: db 1 dbbw $0, $0, String_17f8d1 Unknown_17f762: db 1 dbbw $0, $0, String_17fa71 Unknown_17f767: db 4 dbbw $0, $0, String_17f946 dbbw $1, $0, String_17f946 dbbw $2, $0, String_17f946 dbbw $3, $0, String_17f946 Unknown_17f778: db 1 dbbw $0, $0, String_17f98e Unknown_17f77d: db 1 dbbw $0, $0, String_17f98e Unknown_17f782: db 1 dbbw $0, $0, String_17f98e Unknown_17f787: db 1 dbbw $0, $0, String_17f98e Unknown_17f78c: db 1 dbbw $0, $0, String_17f9d0 Unknown_17f791: db 1 dbbw $0, $0, String_17fa14 Unknown_17f796: db 1 dbbw $0, $0, String_17fcbf Unknown_17f79b: db 1 dbbw $0, $0, String_17fa71 Unknown_17f7a0: db 1 dbbw $0, $0, String_17fbfe Unknown_17f7a5: db 17 dbbw $0, $0, String_17f98e dbbw $21, $2, String_17fcbf dbbw $21, $4, String_17fcbf dbbw $50, $4, String_17faf9 dbbw $51, $4, String_17fcbf dbbw $52, $4, String_17fcbf dbbw $0, $5, String_17f98e dbbw $1, $5, String_17f98e dbbw $2, $5, String_17f98e dbbw $3, $5, String_17f98e dbbw $4, $5, String_17f98e dbbw $50, $5, String_17faf9 dbbw $51, $5, String_17faf9 dbbw $52, $5, String_17fcbf dbbw $53, $5, String_17faf9 dbbw $54, $5, String_17fcbf dbbw $ff, $ff, String_17fcbf Unknown_17f7ea: db 5 dbbw $0, $0, String_17f98e dbbw $2, $0, String_17fb2a dbbw $3, $0, String_17fb6e dbbw $4, $0, String_17f98e dbbw $ff, $ff, String_17fcbf Unknown_17f7ff: db 17 dbbw $0, $0, String_17f98e dbbw $1, $3, String_17f98e dbbw $2, $3, String_17f98e dbbw $0, $4, String_17f98e dbbw $1, $4, String_17f98e dbbw $3, $4, String_17fbb6 dbbw $4, $4, String_17fbb6 dbbw $5, $4, String_17f98e dbbw $6, $4, String_17f98e dbbw $7, $4, String_17f98e dbbw $8, $4, String_17fbfe dbbw $0, $5, String_17fa49 dbbw $1, $5, String_17f98e dbbw $2, $5, String_17fa49 dbbw $3, $5, String_17fab0 dbbw $4, $5, String_17fa49 dbbw $ff, $ff, String_17fa49 Unknown_17f844: db 19 dbbw $1, $1, String_17fc3e dbbw $2, $1, String_17fc88 dbbw $3, $1, String_17fcff dbbw $4, $1, String_17fd84 dbbw $5, $1, String_17fd84 dbbw $6, $1, String_17fd47 dbbw $1, $2, String_17fb6e dbbw $2, $2, String_17f98e dbbw $3, $2, String_17fd84 dbbw $4, $2, String_17f98e dbbw $5, $2, String_17fa49 dbbw $6, $2, String_17fd84 dbbw $99, $2, String_17fc88 dbbw $1, $3, String_17fa49 dbbw $1, $4, String_17fa49 dbbw $2, $4, String_17fa49 dbbw $3, $4, String_17fa49 dbbw $4, $4, String_17fa49 dbbw $ff, $ff, String_17fa49 String_17f891: db "モバイルアダプタが ただしく" next "さしこまれていません" next "とりあつかいせつめいしょを" next "ごらんのうえ しっかりと" next "さしこんで ください" db "@" String_17f8d1: db "でんわが うまく かけられないか" next "でんわかいせんが こんでいるので" next "つうしん できません" next "しばらく まって" next "かけなおして ください" db "@" String_17f913: db "でんわかいせんが こんでいるため" next "でんわが かけられません" next "しばらく まって" next "かけなおして ください" db "@" String_17f946: db "モバイルアダプタの エラーです" next "しばらく まって" next "かけなおして ください" next "なおらない ときは" next "モバイルサポートセンターへ" next "おといあわせください" db "@" String_17f98e: db "つうしんエラーです" next "しばらく まって" next "かけなおして ください" next "なおらない ときは" next "モバイルサポートセンターへ" next "おといあわせください" db "@" String_17f9d0: db "ログインパスワードか" next "ログイン アイディーに" next "まちがいがあります" next "パスワードを かくにんして" next "しばらく まって" next "かけなおして ください" db "@" String_17fa14: db "でんわが きれました" next "とりあつかいせつめいしょを" next "ごらんのうえ" next "しばらく まって" next "かけなおして ください" db "@" String_17fa49: db "モバイルセンターの" next "つうしんエラーです" next "しばらくまって" next "かけなおして ください" db "@" String_17fa71: db "モバイルアダプタに" next "とうろくされた じょうほうが" next "ただしく ありません" next "モバイルトレーナーで" next "しょきとうろくを してください" db "@" String_17fab0: db "モバイルセンターが" next "こんでいて つながりません" next "しばらくまって" next "かけなおして ください" next "くわしくは とりあつかい" next "せつめいしょを ごらんください" db "@" String_17faf9: db "あてさき メールアドレスに" next "まちがいがあります" next "ただしい メールアドレスを" next "いれなおしてください" db "@" String_17fb2a: db "メールアドレスに" next "まちがいが あります" next "とりあつかいせつめいしょを" next "ごらんのうえ" next "モバイルトレーナーで" next "しょきとうろくを してください" db "@" String_17fb6e: db "ログインパスワードに" next "まちがいが あるか" next "モバイルセンターの エラーです" next "パスワードを かくにんして" next "しばらく まって" next "かけなおして ください" db "@" String_17fbb6: db "データの よみこみが できません" next "しばらくまって" next "かけなおして ください" next "なおらない ときは" next "モバイルサポートセンターへ" next "おといあわせください" db "@" String_17fbfe: db "じかんぎれです" next "でんわが きれました" next "でんわを かけなおしてください" next "くわしくは とりあつかい" next "せつめいしょを ごらんください" db "@" String_17fc3e: db "ごりよう りょうきんの " next "おしはらいが おくれたばあいには" next "ごりようが できなくなります" next "くわしくは とりあつかい" next "せつめいしょを ごらんください" db "@" String_17fc88: db "おきゃくさまの ごつごうにより" next "ごりようできません" next "くわしくは とりあつかい" next "せつめいしょを ごらんください" db "@" String_17fcbf: db "でんわかいせんが こんでいるか" next "モバイルセンターの エラーで" next "つうしんが できません" next "しばらく まって" next "かけなおして ください" db "@" String_17fcff: db "ごりよう りょうきんが" next "じょうげんを こえているため" next "こんげつは ごりようできません" next "くわしくは とりあつかい" next "せつめいしょを ごらんください" db "@" String_17fd47: db "げんざい モバイルセンターの" next "てんけんを しているので" next "つうしんが できません" next "しばらく まって" next "かけなおして ください" db "@" String_17fd84: db "データの よみこみが できません" next "くわしくは とりあつかい" next "せつめいしょを ごらんください" db "@" String_17fdb2: db "3ぷん いじょう なにも" next "にゅうりょく しなかったので" next "でんわが きれました" db "@" String_17fdd9: db "つうしんが うまく" next "できませんでした" next "もういちど はじめから" next "やりなおしてください" db "@" String_17fe03: db "データの よみこみが できません" next "しばらくまって" next "かけなおして ください" next "なおらない ときは" next "モバイルサポートセンターへ" next "おといあわせください" db "@" String_17fe4b: db "まちじかんが ながいので" next "でんわが きれました" db "@" String_17fe63: db "あいての モバイルアダプタと" next "タイプが ちがいます" next "くわしくは とりあつかい" next "せつめいしょを ごらんください" db "@" String_17fe9a: ; unused db "ポケモンニュースが" next "あたらしくなっているので" next "レポートを おくれません" next "あたらしい ポケモンニュースの" next "よみこみを さきに してください" db "@" String_17fedf: db "つうしんの じょうきょうが" next "よくないか かけるあいてが" next "まちがっています" next "もういちど かくにんをして" next "でんわを かけなおして ください" db "@" Function17ff23: ldh a, [hJoyPressed] and a ret z ld a, $8 ld [wMusicFade], a ld a, [wMapMusic] ld [wMusicFadeID], a xor a ld [wMusicFadeID + 1], a ld hl, wc303 set 7, [hl] ret Function17ff3c: nop ld a, [wc300] cp $d0 ret c hlcoord 10, 2 ld de, String_17ff68 call PlaceString ld a, [wc300] push af sub $d0 inc a ld [wc300], a hlcoord 14, 2 ld de, wc300 lb bc, PRINTNUM_LEADINGZEROS | 1, 3 call PrintNum pop af ld [wc300], a and a ret String_17ff68: db "101@"
; A047665: Expansion of (1/sqrt(1-6*x+x^2)-1/(1-x))/2. ; Submitted by Jamie Morken(w4) ; 0,1,6,31,160,841,4494,24319,132864,731281,4048726,22523359,125797984,704966809,3961924126,22321190911,126027618304,712917362209,4039658528934,22924714957471,130271906898720,741188107113961,4221707080583086,24070622500965631,137369104574280960,784622537295845041,4485116176611817974,25656788374503225439,146866855179446896864,841235936593080312121,4821320732559041841214,27647245676145556373503,158620890315068120547328,910495810600049263720513,5228681427947431000875334,30039434229277615491848479 seq $0,1850 ; Central Delannoy numbers: a(n) = Sum_{k=0..n} C(n,k)*C(n+k,k). div $0,2
dnl mpn_hamdist dnl Copyright 2010 The Code Cavern dnl This file is part of the MPIR Library. dnl The MPIR Library is free software; you can redistribute it and/or modify dnl it under the terms of the GNU Lesser General Public License as published dnl by the Free Software Foundation; either version 2.1 of the License, or (at dnl your option) any later version. dnl The MPIR Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public dnl License for more details. dnl You should have received a copy of the GNU Lesser General Public License dnl along with the MPIR Library; see the file COPYING.LIB. If not, write dnl to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, dnl Boston, MA 02110-1301, USA. include(`../config.m4') ASM_START() PROLOGUE(mpn_hamdist) mov $1,%rcx lea -8(%rsi,%rdx,8),%rsi lea -8(%rdi,%rdx,8),%rdi xor %eax,%eax sub %rdx,%rcx jnc L(skiplp) ALIGN(16) L(lp): mov (%rdi,%rcx,8),%r8 xor (%rsi,%rcx,8),%r8 popcnt %r8,%r8 mov 8(%rdi,%rcx,8),%r9 xor 8(%rsi,%rcx,8),%r9 popcnt %r9,%r9 add %r8,%rax add %r9,%rax add $2,%rcx jnc L(lp) L(skiplp): jne L(fin) mov (%rdi,%rcx,8),%r8 xor (%rsi,%rcx,8),%r8 popcnt %r8,%r8 add %r8,%rax L(fin): ret EPILOGUE()
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r8 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x159aa, %rsi lea addresses_normal_ht+0x93dc, %rdi nop nop nop cmp $14485, %rbp mov $55, %rcx rep movsw nop nop nop nop nop inc %rbx lea addresses_A_ht+0x1d26a, %r14 nop nop nop nop nop cmp $9087, %r8 mov (%r14), %bp sub $2686, %rbx lea addresses_normal_ht+0xb60c, %rsi lea addresses_WT_ht+0x1b8b2, %rdi nop nop nop sub $13095, %r8 mov $47, %rcx rep movsb nop nop cmp %rbp, %rbp lea addresses_A_ht+0x950c, %rsi lea addresses_A_ht+0x15880, %rdi nop nop and %r14, %r14 mov $67, %rcx rep movsq nop nop nop nop nop and %rbx, %rbx lea addresses_WT_ht+0x1ae1c, %rbx nop nop nop nop xor %rbp, %rbp movb $0x61, (%rbx) nop and $50523, %rbx lea addresses_WT_ht+0x1088c, %rsi lea addresses_A_ht+0x150c, %rdi cmp $14124, %r8 mov $8, %rcx rep movsq nop nop nop nop inc %rbp lea addresses_WT_ht+0x19a0a, %r14 nop nop nop nop nop cmp %rbx, %rbx movb (%r14), %r8b and %rdi, %rdi lea addresses_UC_ht+0x2cc, %rsi lea addresses_D_ht+0x120c, %rdi nop nop nop add %r8, %r8 mov $27, %rcx rep movsb nop nop nop nop inc %rsi lea addresses_WT_ht+0xd50c, %rbp nop nop cmp $25035, %rsi vmovups (%rbp), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $1, %xmm7, %rcx nop nop nop nop nop cmp $59641, %r14 lea addresses_normal_ht+0x6d0c, %r14 nop nop nop nop dec %rbx mov (%r14), %rsi mfence lea addresses_WC_ht+0x1662c, %rsi lea addresses_UC_ht+0xcfbc, %rdi clflush (%rdi) and %r14, %r14 mov $15, %rcx rep movsw nop nop nop nop inc %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r8 pop %r14 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r14 push %r15 push %rcx push %rdi push %rdx // Load lea addresses_UC+0x1672c, %r13 nop nop nop nop add %r14, %r14 vmovups (%r13), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $0, %xmm7, %rdx nop sub $54117, %r13 // Faulty Load lea addresses_D+0x1390c, %r10 nop nop and $25715, %rcx movups (%r10), %xmm7 vpextrq $1, %xmm7, %rdx lea oracles, %rdi and $0xff, %rdx shlq $12, %rdx mov (%rdi,%rdx,1), %rdx pop %rdx pop %rdi pop %rcx pop %r15 pop %r14 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 5}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_normal_ht'}} {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_normal_ht'}, 'dst': {'same': True, 'congruent': 1, 'type': 'addresses_WT_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_A_ht'}, 'dst': {'same': True, 'congruent': 2, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': True, 'AVXalign': False, 'size': 1, 'congruent': 3}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_WT_ht'}, 'dst': {'same': True, 'congruent': 8, 'type': 'addresses_A_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 5}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 9}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
GLOBAL _cli GLOBAL _sti GLOBAL _hlt GLOBAL _picMasterMask GLOBAL _picSlaveMask GLOBAL _haltCpu GLOBAL _irq00Handler GLOBAL _irq01Handler GLOBAL _exception0Handler GLOBAL _exception1Handler GLOBAL _systemCallHandler GLOBAL _changeProcess GLOBAL _contextSwitchProcess GLOBAL _contextSwitchInterrupt EXTERN switchProcess EXTERN systemCallDispatcher EXTERN irqDispatcher EXTERN exceptionDispatcher SECTION .text %macro pushState 0 push rax push rbx push rcx push rdx push rbp push rdi push rsi push r8 push r9 push r10 push r11 push r12 push r13 push r14 push r15 push fs push gs %endmacro %macro popState 0 pop gs pop fs pop r15 pop r14 pop r13 pop r12 pop r11 pop r10 pop r9 pop r8 pop rsi pop rdi pop rbp pop rdx pop rcx pop rbx pop rax %endmacro %macro pushStateNoRax 0 push rbx push rcx push rdx push rbp push rdi push rsi push r8 push r9 push r10 push r11 push r12 push r13 push r14 push r15 %endmacro %macro popStateNoRax 0 pop r15 pop r14 pop r13 pop r12 pop r11 pop r10 pop r9 pop r8 pop rsi pop rdi pop rbp pop rdx pop rcx pop rbx %endmacro %macro irqHandlerMaster 1 pushState mov rdi, %1 ; pasaje de parametro call irqDispatcher ; signal pic EOI (End of Interrupt) mov al, 20h out 20h, al ;context switcher mov rdi, rsp call switchProcess mov rsp, rax popState iretq %endmacro %macro exceptionHandler 1 pushState push rsp mov rdi, %1 ; pasaje de parametro nro de excepcion mov rsi, rsp ; pasaje de registros como estan pusheados call exceptionDispatcher pop rsp popState mov qword [rsp], 0x400000 ;After the exception go back to SampleCodeModule at 0x400000 iretq %endmacro _hlt: sti hlt ret _cli: cli ret _sti: sti ret _picMasterMask: push rbp mov rbp, rsp mov ax, di out 21h,al pop rbp retn _picSlaveMask: push rbp mov rbp, rsp mov ax, di ; ax = 16 bits mask out 0A1h,al pop rbp retn ;Timer (Timer Tick) _irq00Handler: irqHandlerMaster 0 ;Keyboard _irq01Handler: irqHandlerMaster 1 ;Zero Division Exception _exception0Handler: exceptionHandler 0 ;Invalid Code Exception _exception1Handler: exceptionHandler 6 ;System Calls _systemCallHandler: pushStateNoRax call systemCallDispatcher popStateNoRax iretq _haltCpu: cli hlt ret _changeProcess: mov rsp, rdi popState iretq _contextSwitchProcess: int 70h ret _contextSwitchInterrupt: pushState mov rdi, rsp call switchProcess mov rsp, rax popState iretq
############################################################################### # Copyright 2018 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .text .p2align 4, 0x90 .globl _n8_cpSub_BNU _n8_cpSub_BNU: movslq %ecx, %rcx xor %rax, %rax cmp $(2), %rcx jge .LSUB_GE2gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq %r8, (%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GE2gas_1: jg .LSUB_GT2gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq %r8, (%rdi) movq %r9, (8)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GT2gas_1: cmp $(4), %rcx jge .LSUB_GE4gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GE4gas_1: jg .LSUB_GT4gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GT4gas_1: cmp $(6), %rcx jge .LSUB_GE6gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq (32)(%rsi), %rcx sbbq (32)(%rdx), %rcx movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %rcx, (32)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GE6gas_1: jg .LSUB_GT6gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq (32)(%rsi), %rcx sbbq (32)(%rdx), %rcx movq (40)(%rsi), %rsi sbbq (40)(%rdx), %rsi movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %rcx, (32)(%rdi) movq %rsi, (40)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GT6gas_1: cmp $(8), %rcx jge .LSUB_GE8gas_1 .LSUB_EQ7gas_1: add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq (32)(%rsi), %rcx sbbq (32)(%rdx), %rcx movq %r8, (%rdi) movq (40)(%rsi), %r8 sbbq (40)(%rdx), %r8 movq (48)(%rsi), %rsi sbbq (48)(%rdx), %rsi movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %rcx, (32)(%rdi) movq %r8, (40)(%rdi) movq %rsi, (48)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GE8gas_1: jg .LSUB_GT8gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq (32)(%rsi), %rcx sbbq (32)(%rdx), %rcx movq %r8, (%rdi) movq (40)(%rsi), %r8 sbbq (40)(%rdx), %r8 movq %r9, (8)(%rdi) movq (48)(%rsi), %r9 sbbq (48)(%rdx), %r9 movq (56)(%rsi), %rsi sbbq (56)(%rdx), %rsi movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %rcx, (32)(%rdi) movq %r8, (40)(%rdi) movq %r9, (48)(%rdi) movq %rsi, (56)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GT8gas_1: mov %rax, %r8 mov %rcx, %rax and $(3), %rcx xor %rax, %rcx lea (%rsi,%rcx,8), %rsi lea (%rdx,%rcx,8), %rdx lea (%rdi,%rcx,8), %rdi neg %rcx add %r8, %r8 jmp .LSUB_GLOOPgas_1 .p2align 4, 0x90 .LSUB_GLOOPgas_1: movq (%rsi,%rcx,8), %r8 movq (8)(%rsi,%rcx,8), %r9 movq (16)(%rsi,%rcx,8), %r10 movq (24)(%rsi,%rcx,8), %r11 sbbq (%rdx,%rcx,8), %r8 sbbq (8)(%rdx,%rcx,8), %r9 sbbq (16)(%rdx,%rcx,8), %r10 sbbq (24)(%rdx,%rcx,8), %r11 movq %r8, (%rdi,%rcx,8) movq %r9, (8)(%rdi,%rcx,8) movq %r10, (16)(%rdi,%rcx,8) movq %r11, (24)(%rdi,%rcx,8) lea (4)(%rcx), %rcx jrcxz .LSUB_LLAST0gas_1 jmp .LSUB_GLOOPgas_1 .LSUB_LLAST0gas_1: sbb %rcx, %rcx and $(3), %rax jz .LFIN0gas_1 .LSUB_LLOOPgas_1: test $(2), %rax jz .LSUB_LLAST1gas_1 add %rcx, %rcx movq (%rsi), %r8 movq (8)(%rsi), %r9 sbbq (%rdx), %r8 sbbq (8)(%rdx), %r9 movq %r8, (%rdi) movq %r9, (8)(%rdi) sbb %rcx, %rcx test $(1), %rax jz .LFIN0gas_1 add $(16), %rsi add $(16), %rdx add $(16), %rdi .LSUB_LLAST1gas_1: add %rcx, %rcx movq (%rsi), %r8 sbbq (%rdx), %r8 movq %r8, (%rdi) sbb %rcx, %rcx .LFIN0gas_1: mov %rcx, %rax .LFINALgas_1: neg %rax ret
.MODEL SMALL .DATA PROMPT_1 DB 'Enter the First digit : $' NUM_1 DB ? NUM_2 DB ? NUM_3 DB ? V1 DB ? V2 DB ? NL DB ' ', 0DH,0AH,'$' VALUE_1 DB ? .CODE MAIN PROC MOV AX,@DATA MOV DX,AX MOV CX,6 MOV CH,0 MOV NUM_1,0 MOV NUM_2,1 MOV DL,NUM_1 OR DL,30H MOV AH,02H INT 21H MOV DL,NUM_2 OR DL,30H MOV AH,02H INT 21H L1: MOV AL,NUM_1 ADD AL,NUM_2 MOV AH,0 MOV BL,AL MOV DL,10 DIV DL ADD AX,3030H MOV V1,AL MOV V2,AH MOV DL,V1 MOV AH,02H INT 21H MOV DL,V2 MOV AH,02H INT 21H SHIFT: MOV AL,NUM_2 MOV NUM_1,AL MOV NUM_2,BL LOOP L1 MOV AX,4C00H INT 21H MAIN ENDP END MAIN
// Copyright (c) 2014-2015, Pacific Biosciences of California, Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted (subject to the limitations in the // disclaimer below) 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 Pacific Biosciences nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY PACIFIC // BIOSCIENCES AND ITS 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 PACIFIC BIOSCIENCES OR ITS // 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: Lance Hepler #include <string> #include <utility> #include <vector> #include <iostream> #include <ConsensusCore/Align/AlignConfig.hpp> #include <ConsensusCore/Poa/PoaConsensus.hpp> #include <ConsensusCore/Poa/PoaGraph.hpp> #include <ConsensusCore/Sequence.hpp> #include <pacbio/ccs/Logging.h> #include <pacbio/ccs/SparsePoa.h> #include <pacbio/ccs/SparseAlignment.h> using ConsensusCore::detail::SdpAnchorVector; using ConsensusCore::AlignConfig; using ConsensusCore::DefaultPoaConfig; using ConsensusCore::LOCAL; using ConsensusCore::PoaConsensus; using ConsensusCore::PoaGraph; using ConsensusCore::ReverseComplement; namespace PacBio { namespace CCS { typedef PoaGraph::Vertex Vertex; SdpAnchorVector SdpRangeFinder::FindAnchors(const std::string& consensusSequence, const std::string& readSequence) const { return SparseAlign<6>(consensusSequence, readSequence); } SparsePoa::SparsePoa() : graph_(new PoaGraph()), readPaths_(), reverseComplemented_(), rangeFinder_(new SdpRangeFinder()) {} SparsePoa::~SparsePoa() { delete graph_; delete rangeFinder_; } SparsePoa::ReadKey SparsePoa::AddRead (std::string readSequence, const PoaAlignmentOptions& alnOptions, float minScoreToAdd) { AlignConfig config = DefaultPoaConfig(LOCAL); Path outputPath; graph_->AddRead(readSequence, config, rangeFinder_, &outputPath); readPaths_.push_back(outputPath); return graph_->NumReads() - 1; } SparsePoa::ReadKey SparsePoa::OrientAndAddRead (std::string readSequence, const PoaAlignmentOptions& alnOptions, float minScoreToAdd) { AlignConfig config = DefaultPoaConfig(LOCAL); Path outputPath; ReadKey key; if (graph_->NumReads() == 0) { graph_->AddFirstRead(readSequence, &outputPath); readPaths_.push_back(outputPath); reverseComplemented_.push_back(false); key = graph_->NumReads() - 1; } else { auto c1 = graph_->TryAddRead(readSequence, config, rangeFinder_); auto c2 = graph_->TryAddRead(ReverseComplement(readSequence), config, rangeFinder_); if (c1->Score() >= c2->Score() && c1->Score() >= minScoreToAdd) { graph_->CommitAdd(c1, &outputPath); readPaths_.push_back(outputPath); reverseComplemented_.push_back(false); key = graph_->NumReads() - 1; } else if (c2->Score() >= c1->Score() && c2->Score() >= minScoreToAdd) { graph_->CommitAdd(c2, &outputPath); readPaths_.push_back(outputPath); reverseComplemented_.push_back(true); key = graph_->NumReads() - 1; } else { key = -1; } delete c1; delete c2; } return key; } std::shared_ptr<const PoaConsensus> SparsePoa::FindConsensus(int minCoverage, std::vector<PoaAlignmentSummary>* summaries) const { AlignConfig config = DefaultPoaConfig(LOCAL); std::shared_ptr<const PoaConsensus> pc(graph_->FindConsensus(config, minCoverage)); std::string css = pc->Sequence; if (summaries != NULL) { summaries->clear(); // digest the consensus path consensus into map(vtx, pos) // the fold over the readPaths std::map<Vertex, size_t> cssPosition; int i = 0; foreach (Vertex v, pc->Path) { cssPosition[v] = i; i++; } for (size_t readId=0; readId < graph_->NumReads(); readId++) { size_t readS = 0, readE = 0; size_t cssS = 0, cssE = 0; bool foundStart = false; const std::vector<Vertex>& readPath = readPaths_[readId]; for (size_t readPos = 0; readPos < readPath.size(); readPos++) { Vertex v = readPath[readPos]; if (cssPosition.find(v) != cssPosition.end()) { if (!foundStart) { cssS = cssPosition[v]; readS = readPos; foundStart = true; } cssE = cssPosition[v] + 1; readE = readPos + 1; } } Interval readExtent(readS, readE); Interval cssExtent(cssS, cssE); PoaAlignmentSummary summary; summary.ReverseComplementedRead = reverseComplemented_[readId]; summary.ExtentOnRead = readExtent; summary.ExtentOnConsensus = cssExtent; (*summaries).push_back(summary); } } return pc; } void SparsePoa::PruneGraph(float minCoverageFraction) {} void SparsePoa::repCheck() { assert(graph_->NumReads() == readPaths_.size()); assert(graph_->NumReads() == reverseComplemented_.size()); } } // namespace CCS } // namespace PacBio
%define nop8 db 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00 %macro cache_line 0 nop8 nop8 nop8 nop8 nop8 nop8 nop8 nop8 %endmacro GLOBAL foo ALIGN 256 foo: ; This number of nops was adjusted in a way to align hot loops in both cases at a 64 bytes boundary ; Hot loops should have the same alignment, otherwise comparison will not be equal. cache_line cache_line cache_line nop8 nop8 nop8 nop8 nop8 nop8 nop8 nop nop cmp rdi, 0 jnz .cold .hot: dec rsi jnz .hot .merge: ret ud2 .cold: call err_handler jmp .merge ud2 err_handler: cache_line cache_line cache_line cache_line ret
SFX_Press_AB_2_Ch4: duty 2 squarenote 0, 9, 1, 1984 squarenote 0, 8, 1, 2000 squarenote 0, 9, 1, 1984 squarenote 12, 10, 1, 2000 endchannel
; A017192: a(n) = (9*n + 2)^8. ; 256,214358881,25600000000,500246412961,4347792138496,23811286661761,96717311574016,318644812890625,899194740203776,2252292232139041,5132188731375616,10828567056280801,21435888100000000,40213853471634241,72057594037927936,124097929967680321,206453783524884736,333160561500390625,523300059815673856,802359178476091681,1203846470694789376,1771197285652216321,2560000000000000000,3640577568861717121,5100960362726891776,7050287992278341281,9622679558836781056,12981613503750390625,17324859965700833536,22890010290541014721,29960650073923649536,38873223852623509441,50024641296100000000,63880676485490517601,80985213602868822016,101970394089246452641,127567722065439006976,158620186545562890625,196095460708571938816,241100240228887100161,294895784402816164096,358914725543104304161,434779213849600000000,524320466699664691681,629599793037598310656,752931165277996622401,896905412873600106496,1064416113433837890625,1258687259015914045696,1483302776945927340001,1742237986263159341056,2039893072616309544481,2381128666176100000000,2771303608864315695361,3216314998934990749696,3722640602679094258561,4297383724759713423616,4948320630420375390625,5683950614544793010176,6513548814281963526241,7447221863686192988416,8495966490557262974401,9671731157401600000000,10987480850170951784641,12457265120170718331136,14096289486265729569121,15920990306246905102336,17949113227957875390625,20199795332516287488256,22693651083700162250881,25452862199305313714176,28501271562015485137921,31864481289062500000000,35569955081689370015521,39647124977164946046976,44127502627834341562081,49044795233425002086656,54435026254563937890625,60336661037197280935936,66790737479338970905921,73841001873311018926336,81534050058373441379041,89919474020377600000000,99050014076812328244001,108981716787347867689216,119774098731718282045441,131490316298518660120576,144197341630229062890625,157966144871512813609216,172871882869572373683361,188994094477081690832896,206416902609949549841761,225229223213904100000000,245524981295624377126081,267403334175880281849856,290968902123878119627201,316332006533744451748096,343608915805816650390625,372922099097144194564096,404400488107340387575201 mul $0,9 add $0,2 pow $0,8
; ; ZX Spectrum OPUS DISCOVERY specific routines ; ; Stefano Bodrato - Jun. 2006 ; ; void opus_lptwrite (unsigned char databyte); ; ; $Id: opus_lptwrite.asm,v 1.5 2016/06/27 19:16:34 dom Exp $ ; SECTION code_clib PUBLIC opus_lptwrite PUBLIC _opus_lptwrite EXTERN opus_rommap EXTERN P_DEVICE opus_lptwrite: _opus_lptwrite: push ix ; save callers ld ix,4 add ix,sp call opus_rommap ;call $1708 ; Page in the Discovery ROM ld h,(ix+0) ; drive ld b,2 ld a,$81 call P_DEVICE call $1748 ; Page out the Discovery ROM ; HL = number of blocks pop ix ;restore callers ret
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/client/lib/testing.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/execution_options_util.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/tests/test_utils.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/types.h" namespace xla { namespace { // Calculates the number of bytes required to store the data within the // specified shape. In case of a (nested) tuple shape this is the total byte // size of all sub-shapes within the tuple. int64 DataSizeOfShape(const Shape& shape) { if (ShapeUtil::IsArray(shape)) { return ShapeUtil::ByteSizeOf(shape); } int64 total_size = 0; for (const Shape& s : shape.tuple_shapes()) { total_size += DataSizeOfShape(s); } return total_size; } // Creates a XlaOp for an op what generates fake data with the given shape. XlaOp BuildFakeDataOpOnDevice(const Shape& shape, XlaBuilder* builder) { if (ShapeUtil::IsArray(shape)) { return Broadcast( ConstantLiteral(builder, LiteralUtil::One(shape.element_type())), AsInt64Slice(shape.dimensions())); } std::vector<XlaOp> parts; for (const Shape& s : shape.tuple_shapes()) { parts.push_back(BuildFakeDataOpOnDevice(s, builder)); } return Tuple(builder, parts); } std::unique_ptr<GlobalData> MakeFakeDataViaDeviceOrDie(const Shape& shape, Client* client) { XlaBuilder b( tensorflow::strings::StrCat("make_fake_", ShapeUtil::HumanString(shape))); BuildFakeDataOpOnDevice(shape, &b); XlaComputation computation = b.Build().ConsumeValueOrDie(); auto execution_options = CreateDefaultExecutionOptions(); *execution_options.mutable_shape_with_output_layout() = shape; return client->Execute(computation, /*arguments=*/{}, &execution_options) .ConsumeValueOrDie(); } } // namespace std::unique_ptr<GlobalData> MakeFakeDataOrDie(const Shape& shape, Client* client) { if (DataSizeOfShape(shape) < (1LL << 20)) { StatusOr<std::unique_ptr<Literal>> literal_status = MakeFakeLiteral(shape); if (!literal_status.ok()) { // If we got an Unimplemented error, fall back to making the fake data via // an on-device computation. CHECK_EQ(literal_status.status().code(), tensorflow::error::UNIMPLEMENTED); return MakeFakeDataViaDeviceOrDie(shape, client); } return client->TransferToServer(*literal_status.ValueOrDie()).ValueOrDie(); } // If the data is large, generate it on-device. return MakeFakeDataViaDeviceOrDie(shape, client); } std::vector<std::unique_ptr<GlobalData>> MakeFakeArgumentsOrDie( const XlaComputation& computation, Client* client) { CHECK(computation.proto().has_program_shape()) << "Computation should have progran shape."; auto program_shape = computation.proto().program_shape(); // Create and run a program which produces a tuple with one element per // parameter, then return the tuple's constituent buffers. std::vector<Shape> param_shapes(program_shape.parameters().begin(), program_shape.parameters().end()); auto fake_input_tuple = MakeFakeDataOrDie(ShapeUtil::MakeTupleShape(param_shapes), client); return client->DeconstructTuple(*fake_input_tuple).ValueOrDie(); } } // namespace xla
//===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // // And has the following additional copyright: // // (C) Copyright 2016-2020 Xilinx, Inc. // All Rights Reserved. // //===----------------------------------------------------------------------===// // // This file implements decl-related attribute processing. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTMutationListener.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/Mangle.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/DelayedDiagnostic.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaInternal.h" #include "clang/Basic/HLSDiagnostic.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/MathExtras.h" using namespace clang; using namespace sema; namespace AttributeLangSupport { enum LANG { C, Cpp, ObjC }; } // end namespace AttributeLangSupport //===----------------------------------------------------------------------===// // Helper functions //===----------------------------------------------------------------------===// /// createIntegerLiteral - create a integer AST node. static IntegerLiteral * createIntegerLiteral(int64_t i, Sema &S, SourceLocation Loc = SourceLocation()) { auto &Ctx = S.getASTContext(); auto IntTy = Ctx.IntTy; auto Width = Ctx.getIntWidth(IntTy); auto Int = llvm::APInt(Width, i); return IntegerLiteral::Create(Ctx, Int, IntTy, Loc); } /// isFunctionOrMethod - Return true if the given decl has function /// type (function or function-typed variable) or an Objective-C /// method. static bool isFunctionOrMethod(const Decl *D) { return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D); } /// \brief Return true if the given decl has function type (function or /// function-typed variable) or an Objective-C method or a block. static bool isFunctionOrMethodOrBlock(const Decl *D) { return isFunctionOrMethod(D) || isa<BlockDecl>(D); } /// Return true if the given decl has a declarator that should have /// been processed by Sema::GetTypeForDeclarator. static bool hasDeclarator(const Decl *D) { // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) || isa<ObjCPropertyDecl>(D); } /// hasFunctionProto - Return true if the given decl has a argument /// information. This decl should have already passed /// isFunctionOrMethod or isFunctionOrMethodOrBlock. static bool hasFunctionProto(const Decl *D) { if (const FunctionType *FnTy = D->getFunctionType()) return isa<FunctionProtoType>(FnTy); return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D); } /// getFunctionOrMethodNumParams - Return number of function or method /// parameters. It is an error to call this on a K&R function (use /// hasFunctionProto first). static unsigned getFunctionOrMethodNumParams(const Decl *D) { if (const FunctionType *FnTy = D->getFunctionType()) return cast<FunctionProtoType>(FnTy)->getNumParams(); if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) return BD->getNumParams(); return cast<ObjCMethodDecl>(D)->param_size(); } static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { if (const FunctionType *FnTy = D->getFunctionType()) return cast<FunctionProtoType>(FnTy)->getParamType(Idx); if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) return BD->getParamDecl(Idx)->getType(); return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType(); } static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { if (const auto *FD = dyn_cast<FunctionDecl>(D)) return FD->getParamDecl(Idx)->getSourceRange(); if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) return MD->parameters()[Idx]->getSourceRange(); if (const auto *BD = dyn_cast<BlockDecl>(D)) return BD->getParamDecl(Idx)->getSourceRange(); return SourceRange(); } static QualType getFunctionOrMethodResultType(const Decl *D) { if (const FunctionType *FnTy = D->getFunctionType()) return cast<FunctionType>(FnTy)->getReturnType(); return cast<ObjCMethodDecl>(D)->getReturnType(); } static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { if (const auto *FD = dyn_cast<FunctionDecl>(D)) return FD->getReturnTypeSourceRange(); if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) return MD->getReturnTypeSourceRange(); return SourceRange(); } static bool isFunctionOrMethodVariadic(const Decl *D) { if (const FunctionType *FnTy = D->getFunctionType()) { const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy); return proto->isVariadic(); } if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) return BD->isVariadic(); return cast<ObjCMethodDecl>(D)->isVariadic(); } static bool isInstanceMethod(const Decl *D) { if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) return MethodDecl->isInstance(); return false; } static inline bool isNSStringType(QualType T, ASTContext &Ctx) { const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); if (!PT) return false; ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); if (!Cls) return false; IdentifierInfo* ClsName = Cls->getIdentifier(); // FIXME: Should we walk the chain of classes? return ClsName == &Ctx.Idents.get("NSString") || ClsName == &Ctx.Idents.get("NSMutableString"); } static inline bool isCFStringType(QualType T, ASTContext &Ctx) { const PointerType *PT = T->getAs<PointerType>(); if (!PT) return false; const RecordType *RT = PT->getPointeeType()->getAs<RecordType>(); if (!RT) return false; const RecordDecl *RD = RT->getDecl(); if (RD->getTagKind() != TTK_Struct) return false; return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); } static unsigned getNumAttributeArgs(const AttributeList &Attr) { // FIXME: Include the type in the argument list. return Attr.getNumArgs() + Attr.hasParsedType(); } template <typename Compare> static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr, unsigned Num, unsigned Diag, Compare Comp) { if (Comp(getNumAttributeArgs(Attr), Num)) { S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num; return false; } return true; } /// \brief Check if the attribute has exactly as many args as Num. May /// output an error. static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr, unsigned Num) { return checkAttributeNumArgsImpl(S, Attr, Num, diag::err_attribute_wrong_number_arguments, std::not_equal_to<unsigned>()); } /// \brief Check if the attribute has at least as many args as Num. May /// output an error. static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr, unsigned Num) { return checkAttributeNumArgsImpl(S, Attr, Num, diag::err_attribute_too_few_arguments, std::less<unsigned>()); } /// \brief Check if the attribute has at most as many args as Num. May /// output an error. static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr, unsigned Num) { return checkAttributeNumArgsImpl(S, Attr, Num, diag::err_attribute_too_many_arguments, std::greater<unsigned>()); } /// \brief A helper function to provide Attribute Location for the Attr types /// AND the AttributeList. template <typename AttrInfo> static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value, SourceLocation>::type getAttrLoc(const AttrInfo &Attr) { return Attr.getLocation(); } static SourceLocation getAttrLoc(const clang::AttributeList &Attr) { return Attr.getLoc(); } /// \brief A helper function to provide Attribute Name for the Attr types /// AND the AttributeList. template <typename AttrInfo> static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value, const AttrInfo *>::type getAttrName(const AttrInfo &Attr) { return &Attr; } static const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) { return Attr.getName(); } template <typename AttrInfo> static void DiagnoseIntArgument(Sema &S, const AttrInfo &Attr, SourceRange Range, unsigned Idx, bool Warning = false) { if (Idx != UINT_MAX) { S.Diag(getAttrLoc(Attr), Warning ? diag::warn_attribute_argument_n_type : diag::err_attribute_argument_n_type) << getAttrName(Attr) << Idx << AANT_ArgumentIntegerConstant << Range; return; } S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_type) << getAttrName(Attr) << AANT_ArgumentIntegerConstant << Range; } /// \brief If Expr is a valid integer constant, get the value of the integer /// expression and return success or failure. May output an error. template<typename AttrInfo> static bool checkUInt32Argument(Sema &S, const AttrInfo& Attr, const Expr *Expr, uint32_t &Val, unsigned Idx = UINT_MAX) { llvm::APSInt I(32); if (Expr->isTypeDependent() || Expr->isValueDependent() || !Expr->isIntegerConstantExpr(I, S.Context)) { DiagnoseIntArgument(S, Attr, Expr->getSourceRange(), Idx); return false; } if (!I.isIntN(32)) { S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) << 32 << /* Unsigned */ 1; return false; } Val = (uint32_t)I.getZExtValue(); return true; } template<typename AttrInfo> static bool checkICEArgument(Sema &S, const AttrInfo& Attr, Expr *Expr, uint32_t &Val, unsigned Idx = UINT_MAX) { llvm::APSInt I(32); if (Expr->isTypeDependent() || Expr->isValueDependent()) { DiagnoseIntArgument(S, Attr, Expr->getSourceRange(), Idx, true); return false; } auto ICE = S.VerifyIntegerConstantExpression( Expr, &I, diag::err_align_value_attribute_argument_not_int); if (ICE.isInvalid()) { DiagnoseIntArgument(S, Attr, Expr->getSourceRange(), Idx); return false; } if (!I.isIntN(32)) { S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) << 32 << /* Unsigned */ 1; return false; } Val = (uint32_t)I.getZExtValue(); return true; } /// \brief Wrapper around checkUInt32Argument, with an extra check to be sure /// that the result will fit into a regular (signed) int. All args have the same /// purpose as they do in checkUInt32Argument. template<typename AttrInfo> static bool checkPositiveIntArgument(Sema &S, const AttrInfo& Attr, const Expr *Expr, int &Val, unsigned Idx = UINT_MAX) { uint32_t UVal; if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx)) return false; if (UVal > (uint32_t)std::numeric_limits<int>::max()) { llvm::APSInt I(32); // for toString I = UVal; S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) << 32 << /* Unsigned */ 0; return false; } Val = UVal; return true; } /// \brief Diagnose mutually exclusive attributes when present on a given /// declaration. Returns true if diagnosed. template <typename AttrTy> static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range, IdentifierInfo *Ident, bool Warning = false) { if (AttrTy *A = D->getAttr<AttrTy>()) { S.Diag(Range.getBegin(), Warning ? diag::warn_attributes_are_not_compatible : diag::err_attributes_are_not_compatible) << Ident << A; S.Diag(A->getLocation(), diag::note_conflicting_attribute); return true; } return false; } template <typename AttrTy> static bool checkAttrMutualExclusion(Sema &S, Decl *D, StringRef Mode, SourceRange Range, IdentifierInfo *Ident, bool Warning = false) { AttrTy *A = D->getAttr<AttrTy>(); if (A && A->getMode().contains_lower(Mode)) { S.Diag(Range.getBegin(), Warning ? diag::warn_attributes_are_not_compatible : diag::err_attributes_are_not_compatible) << Ident << A; S.Diag(A->getLocation(), diag::note_conflicting_attribute); return true; } return false; } /// \brief Check if IdxExpr is a valid parameter index for a function or /// instance method D. May output an error. /// /// \returns true if IdxExpr is a valid index. template <typename AttrInfo> static bool checkFunctionOrMethodParameterIndex( Sema &S, const Decl *D, const AttrInfo &Attr, unsigned AttrArgNum, const Expr *IdxExpr, uint64_t &Idx, bool AllowImplicitThis = false) { assert(isFunctionOrMethodOrBlock(D)); // In C++ the implicit 'this' function parameter also counts. // Parameters are counted from one. bool HP = hasFunctionProto(D); bool HasImplicitThisParam = isInstanceMethod(D); bool IV = HP && isFunctionOrMethodVariadic(D); unsigned NumParams = (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; llvm::APSInt IdxInt; if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() || !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) { S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type) << getAttrName(Attr) << AttrArgNum << AANT_ArgumentIntegerConstant << IdxExpr->getSourceRange(); return false; } Idx = IdxInt.getLimitedValue(); if (Idx < 1 || (!IV && Idx > NumParams)) { S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_out_of_bounds) << getAttrName(Attr) << AttrArgNum << IdxExpr->getSourceRange(); return false; } Idx--; // Convert to zero-based. if (HasImplicitThisParam && !AllowImplicitThis) { if (Idx == 0) { S.Diag(getAttrLoc(Attr), diag::err_attribute_invalid_implicit_this_argument) << getAttrName(Attr) << IdxExpr->getSourceRange(); return false; } --Idx; } return true; } /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal. /// If not emit an error and return false. If the argument is an identifier it /// will emit an error with a fixit hint and treat it as if it was a string /// literal. bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation) { // Look for identifiers. If we have one emit a hint to fix it to a literal. if (Attr.isArgIdent(ArgNum)) { IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum); Diag(Loc->Loc, diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentString << FixItHint::CreateInsertion(Loc->Loc, "\"") << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\""); Str = Loc->Ident->getName(); if (ArgLocation) *ArgLocation = Loc->Loc; return true; } // Now check for an actual string literal. Expr *ArgExpr = Attr.getArgAsExpr(ArgNum); StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts()); if (ArgLocation) *ArgLocation = ArgExpr->getLocStart(); if (!Literal || !Literal->isAscii()) { Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentString; return false; } Str = Literal->getString(); return true; } /// \brief Applies the given attribute to the Decl without performing any /// additional semantic checking. template <typename AttrType> static void handleSimpleAttribute(Sema &S, Decl *D, const AttributeList &Attr) { D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } template <typename AttrType> static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, const AttributeList &Attr) { handleSimpleAttribute<AttrType>(S, D, Attr); } /// \brief Applies the given attribute to the Decl so long as the Decl doesn't /// already have one of the given incompatible attributes. template <typename AttrType, typename IncompatibleAttrType, typename... IncompatibleAttrTypes> static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(), Attr.getName())) return; handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D, Attr); } template <typename AttrType> static void handleEnableAttribute(Sema &S, Decl *D, const AttributeList &Attr, bool Reverse = true) { if (D->isInvalidDecl()) return; if (Attr.getNumArgs() > 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 1; return; } uint32_t Off = Reverse ? 1 : 0; if (Attr.getNumArgs() == 1) { if (!checkICEArgument(S, Attr, Attr.getArgAsExpr(0), Off, 0)) { D->setInvalidDecl(); return; } } // reverse Off for Enabled uint32_t Enabled = Off; if (Reverse) Enabled = Off ? 0 : 1; D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context, Enabled, Attr.getAttributeSpellingListIndex())); } /// \brief Check if the passed-in expression is of type int or bool. static bool isIntOrBool(Expr *Exp) { QualType QT = Exp->getType(); return QT->isBooleanType() || QT->isIntegerType(); } // Check to see if the type is a smart pointer of some kind. We assume // it's a smart pointer if it defines both operator-> and operator*. static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { DeclContextLookupResult Res1 = RT->getDecl()->lookup( S.Context.DeclarationNames.getCXXOperatorName(OO_Star)); if (Res1.empty()) return false; DeclContextLookupResult Res2 = RT->getDecl()->lookup( S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow)); if (Res2.empty()) return false; return true; } /// \brief Check if passed in Decl is a pointer type. /// Note that this function may produce an error message. /// \return true if the Decl is a pointer type; false otherwise static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, const AttributeList &Attr) { const ValueDecl *vd = cast<ValueDecl>(D); QualType QT = vd->getType(); if (QT->isAnyPointerType()) return true; if (const RecordType *RT = QT->getAs<RecordType>()) { // If it's an incomplete type, it could be a smart pointer; skip it. // (We don't want to force template instantiation if we can avoid it, // since that would alter the order in which templates are instantiated.) if (RT->isIncompleteType()) return true; if (threadSafetyCheckIsSmartPointer(S, RT)) return true; } S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << Attr.getName() << QT; return false; } /// \brief Checks that the passed in QualType either is of RecordType or points /// to RecordType. Returns the relevant RecordType, null if it does not exit. static const RecordType *getRecordType(QualType QT) { if (const RecordType *RT = QT->getAs<RecordType>()) return RT; // Now check if we point to record type. if (const PointerType *PT = QT->getAs<PointerType>()) return PT->getPointeeType()->getAs<RecordType>(); return nullptr; } static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { const RecordType *RT = getRecordType(Ty); if (!RT) return false; // Don't check for the capability if the class hasn't been defined yet. if (RT->isIncompleteType()) return true; // Allow smart pointers to be used as capability objects. // FIXME -- Check the type that the smart pointer points to. if (threadSafetyCheckIsSmartPointer(S, RT)) return true; // Check if the record itself has a capability. RecordDecl *RD = RT->getDecl(); if (RD->hasAttr<CapabilityAttr>()) return true; // Else check if any base classes have a capability. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { CXXBasePaths BPaths(false, false); if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) { const auto *Type = BS->getType()->getAs<RecordType>(); return Type->getDecl()->hasAttr<CapabilityAttr>(); }, BPaths)) return true; } return false; } static bool checkTypedefTypeForCapability(QualType Ty) { const auto *TD = Ty->getAs<TypedefType>(); if (!TD) return false; TypedefNameDecl *TN = TD->getDecl(); if (!TN) return false; return TN->hasAttr<CapabilityAttr>(); } static bool typeHasCapability(Sema &S, QualType Ty) { if (checkTypedefTypeForCapability(Ty)) return true; if (checkRecordTypeForCapability(S, Ty)) return true; return false; } static bool isCapabilityExpr(Sema &S, const Expr *Ex) { // Capability expressions are simple expressions involving the boolean logic // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once // a DeclRefExpr is found, its type should be checked to determine whether it // is a capability or not. if (const auto *E = dyn_cast<CastExpr>(Ex)) return isCapabilityExpr(S, E->getSubExpr()); else if (const auto *E = dyn_cast<ParenExpr>(Ex)) return isCapabilityExpr(S, E->getSubExpr()); else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) { if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf || E->getOpcode() == UO_Deref) return isCapabilityExpr(S, E->getSubExpr()); return false; } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) { if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) return isCapabilityExpr(S, E->getLHS()) && isCapabilityExpr(S, E->getRHS()); return false; } return typeHasCapability(S, Ex->getType()); } /// \brief Checks that all attribute arguments, starting from Sidx, resolve to /// a capability object. /// \param Sidx The attribute argument index to start checking with. /// \param ParamIdxOk Whether an argument can be indexing into a function /// parameter list. static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, const AttributeList &Attr, SmallVectorImpl<Expr *> &Args, int Sidx = 0, bool ParamIdxOk = false) { for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) { Expr *ArgExp = Attr.getArgAsExpr(Idx); if (ArgExp->isTypeDependent()) { // FIXME -- need to check this again on template instantiation Args.push_back(ArgExp); continue; } if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) { if (StrLit->getLength() == 0 || (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { // Pass empty strings to the analyzer without warnings. // Treat "*" as the universal lock. Args.push_back(ArgExp); continue; } // We allow constant strings to be used as a placeholder for expressions // that are not valid C++ syntax, but warn that they are ignored. S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) << Attr.getName(); Args.push_back(ArgExp); continue; } QualType ArgTy = ArgExp->getType(); // A pointer to member expression of the form &MyClass::mu is treated // specially -- we need to look at the type of the member. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp)) if (UOp->getOpcode() == UO_AddrOf) if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr())) if (DRE->getDecl()->isCXXInstanceMember()) ArgTy = DRE->getDecl()->getType(); // First see if we can just cast to record type, or pointer to record type. const RecordType *RT = getRecordType(ArgTy); // Now check if we index into a record type function param. if(!RT && ParamIdxOk) { FunctionDecl *FD = dyn_cast<FunctionDecl>(D); IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp); if(FD && IL) { unsigned int NumParams = FD->getNumParams(); llvm::APInt ArgValue = IL->getValue(); uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range) << Attr.getName() << Idx + 1 << NumParams; continue; } ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); } } // If the type does not have a capability, see if the components of the // expression have capabilities. This allows for writing C code where the // capability may be on the type, and the expression is a capability // boolean logic expression. Eg) requires_capability(A || B && !C) if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable) << Attr.getName() << ArgTy; Args.push_back(ArgExp); } } //===----------------------------------------------------------------------===// // Attribute Implementations //===----------------------------------------------------------------------===// static void handlePtGuardedVarAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!threadSafetyCheckIsPointer(S, D, Attr)) return; D->addAttr(::new (S.Context) PtGuardedVarAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const AttributeList &Attr, Expr* &Arg) { SmallVector<Expr*, 1> Args; // check that all arguments are lockable objects checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); unsigned Size = Args.size(); if (Size != 1) return false; Arg = Args[0]; return true; } static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) { Expr *Arg = nullptr; if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) return; D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg, Attr.getAttributeSpellingListIndex())); } static void handlePtGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) { Expr *Arg = nullptr; if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) return; if (!threadSafetyCheckIsPointer(S, D, Attr)) return; D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(), S.Context, Arg, Attr.getAttributeSpellingListIndex())); } static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const AttributeList &Attr, SmallVectorImpl<Expr *> &Args) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return false; // Check that this attribute only applies to lockable types. QualType QT = cast<ValueDecl>(D)->getType(); if (!QT->isDependentType() && !typeHasCapability(S, QT)) { S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << Attr.getName(); return false; } // Check that all arguments are lockable objects. checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); if (Args.empty()) return false; return true; } static void handleAcquiredAfterAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 1> Args; if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) return; Expr **StartArg = &Args[0]; D->addAttr(::new (S.Context) AcquiredAfterAttr(Attr.getRange(), S.Context, StartArg, Args.size(), Attr.getAttributeSpellingListIndex())); } static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 1> Args; if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) return; Expr **StartArg = &Args[0]; D->addAttr(::new (S.Context) AcquiredBeforeAttr(Attr.getRange(), S.Context, StartArg, Args.size(), Attr.getAttributeSpellingListIndex())); } static bool checkLockFunAttrCommon(Sema &S, Decl *D, const AttributeList &Attr, SmallVectorImpl<Expr *> &Args) { // zero or more arguments ok // check that all arguments are lockable objects checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true); return true; } static void handleAssertSharedLockAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 1> Args; if (!checkLockFunAttrCommon(S, D, Attr, Args)) return; unsigned Size = Args.size(); Expr **StartArg = Size == 0 ? nullptr : &Args[0]; D->addAttr(::new (S.Context) AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size, Attr.getAttributeSpellingListIndex())); } static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 1> Args; if (!checkLockFunAttrCommon(S, D, Attr, Args)) return; unsigned Size = Args.size(); Expr **StartArg = Size == 0 ? nullptr : &Args[0]; D->addAttr(::new (S.Context) AssertExclusiveLockAttr(Attr.getRange(), S.Context, StartArg, Size, Attr.getAttributeSpellingListIndex())); } /// \brief Checks to be sure that the given parameter number is in bounds, and is /// an integral type. Will emit appropriate diagnostics if this returns /// false. /// /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used /// to actually retrieve the argument, so it's base-0. template <typename AttrInfo> static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD, const AttrInfo &Attr, Expr *AttrArg, unsigned FuncParamNo, unsigned AttrArgNo, bool AllowDependentType = false) { uint64_t Idx; if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, AttrArg, Idx)) return false; const ParmVarDecl *Param = FD->getParamDecl(Idx); if (AllowDependentType && Param->getType()->isDependentType()) return true; if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) { SourceLocation SrcLoc = AttrArg->getLocStart(); S.Diag(SrcLoc, diag::err_attribute_integers_only) << getAttrName(Attr) << Param->getSourceRange(); return false; } return true; } /// \brief Checks to be sure that the given parameter number is in bounds, and is /// an integral type. Will emit appropriate diagnostics if this returns false. /// /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used /// to actually retrieve the argument, so it's base-0. static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD, const AttributeList &Attr, unsigned FuncParamNo, unsigned AttrArgNo, bool AllowDependentType = false) { assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument"); return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo), FuncParamNo, AttrArgNo, AllowDependentType); } static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1) || !checkAttributeAtMostNumArgs(S, Attr, 2)) return; const auto *FD = cast<FunctionDecl>(D); if (!FD->getReturnType()->isPointerType()) { S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) << Attr.getName(); return; } const Expr *SizeExpr = Attr.getArgAsExpr(0); int SizeArgNo; // Parameter indices are 1-indexed, hence Index=1 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1)) return; if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0)) return; // Args are 1-indexed, so 0 implies that the arg was not present int NumberArgNo = 0; if (Attr.getNumArgs() == 2) { const Expr *NumberExpr = Attr.getArgAsExpr(1); // Parameter indices are 1-based, hence Index=2 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo, /*Index=*/2)) return; if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1)) return; } D->addAttr(::new (S.Context) AllocSizeAttr( Attr.getRange(), S.Context, SizeArgNo, NumberArgNo, Attr.getAttributeSpellingListIndex())); } static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const AttributeList &Attr, SmallVectorImpl<Expr *> &Args) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return false; if (!isIntOrBool(Attr.getArgAsExpr(0))) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << 1 << AANT_ArgumentIntOrBool; return false; } // check that all arguments are lockable objects checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1); return true; } static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 2> Args; if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) return; D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(), Args.size(), Attr.getAttributeSpellingListIndex())); } static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 2> Args; if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) return; D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(), Args.size(), Attr.getAttributeSpellingListIndex())); } static void handleLockReturnedAttr(Sema &S, Decl *D, const AttributeList &Attr) { // check that the argument is lockable object SmallVector<Expr*, 1> Args; checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); unsigned Size = Args.size(); if (Size == 0) return; D->addAttr(::new (S.Context) LockReturnedAttr(Attr.getRange(), S.Context, Args[0], Attr.getAttributeSpellingListIndex())); } static void handleLocksExcludedAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return; // check that all arguments are lockable objects SmallVector<Expr*, 1> Args; checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); unsigned Size = Args.size(); if (Size == 0) return; Expr **StartArg = &Args[0]; D->addAttr(::new (S.Context) LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size, Attr.getAttributeSpellingListIndex())); } static bool checkFunctionConditionAttr(Sema &S, Decl *D, const AttributeList &Attr, Expr *&Cond, StringRef &Msg) { Cond = Attr.getArgAsExpr(0); if (!Cond->isTypeDependent()) { ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); if (Converted.isInvalid()) return false; Cond = Converted.get(); } if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg)) return false; if (Msg.empty()) Msg = "<no message provided>"; SmallVector<PartialDiagnosticAt, 8> Diags; if (isa<FunctionDecl>(D) && !Cond->isValueDependent() && !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D), Diags)) { S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr) << Attr.getName(); for (const PartialDiagnosticAt &PDiag : Diags) S.Diag(PDiag.first, PDiag.second); return false; } return true; } static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) { S.Diag(Attr.getLoc(), diag::ext_clang_enable_if); Expr *Cond; StringRef Msg; if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg)) D->addAttr(::new (S.Context) EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg, Attr.getAttributeSpellingListIndex())); } namespace { /// Determines if a given Expr references any of the given function's /// ParmVarDecls, or the function's implicit `this` parameter (if applicable). class ArgumentDependenceChecker : public RecursiveASTVisitor<ArgumentDependenceChecker> { #ifndef NDEBUG const CXXRecordDecl *ClassType; #endif llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms; bool Result; public: ArgumentDependenceChecker(const FunctionDecl *FD) { #ifndef NDEBUG if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) ClassType = MD->getParent(); else ClassType = nullptr; #endif Parms.insert(FD->param_begin(), FD->param_end()); } bool referencesArgs(Expr *E) { Result = false; TraverseStmt(E); return Result; } bool VisitCXXThisExpr(CXXThisExpr *E) { assert(E->getType()->getPointeeCXXRecordDecl() == ClassType && "`this` doesn't refer to the enclosing class?"); Result = true; return false; } bool VisitDeclRefExpr(DeclRefExpr *DRE) { if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) if (Parms.count(PVD)) { Result = true; return false; } return true; } }; } static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) { S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if); Expr *Cond; StringRef Msg; if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg)) return; StringRef DiagTypeStr; if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr)) return; DiagnoseIfAttr::DiagnosticType DiagType; if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) { S.Diag(Attr.getArgAsExpr(2)->getLocStart(), diag::err_diagnose_if_invalid_diagnostic_type); return; } bool ArgDependent = false; if (const auto *FD = dyn_cast<FunctionDecl>(D)) ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond); D->addAttr(::new (S.Context) DiagnoseIfAttr( Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D), Attr.getAttributeSpellingListIndex())); } static void handlePassObjectSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->hasAttr<PassObjectSizeAttr>()) { S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter) << Attr.getName(); return; } Expr *E = Attr.getArgAsExpr(0); uint32_t Type; if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1)) return; // pass_object_size's argument is passed in as the second argument of // __builtin_object_size. So, it has the same constraints as that second // argument; namely, it must be in the range [0, 3]. if (Type > 3) { S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range) << Attr.getName() << 0 << 3 << E->getSourceRange(); return; } // pass_object_size is only supported on constant pointer parameters; as a // kindness to users, we allow the parameter to be non-const for declarations. // At this point, we have no clue if `D` belongs to a function declaration or // definition, so we defer the constness check until later. if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) { S.Diag(D->getLocStart(), diag::err_attribute_pointers_only) << Attr.getName() << 1; return; } D->addAttr(::new (S.Context) PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type, Attr.getAttributeSpellingListIndex())); } static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) { ConsumableAttr::ConsumedState DefaultState; if (Attr.isArgIdent(0)) { IdentifierLoc *IL = Attr.getArgAsIdent(0); if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), DefaultState)) { S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << IL->Ident; return; } } else { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentIdentifier; return; } D->addAttr(::new (S.Context) ConsumableAttr(Attr.getRange(), S.Context, DefaultState, Attr.getAttributeSpellingListIndex())); } static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, const AttributeList &Attr) { ASTContext &CurrContext = S.getASTContext(); QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { if (!RD->hasAttr<ConsumableAttr>()) { S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) << RD->getNameAsString(); return false; } } return true; } static void handleCallableWhenAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return; if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) return; SmallVector<CallableWhenAttr::ConsumedState, 3> States; for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) { CallableWhenAttr::ConsumedState CallableState; StringRef StateString; SourceLocation Loc; if (Attr.isArgIdent(ArgIndex)) { IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex); StateString = Ident->Ident->getName(); Loc = Ident->Loc; } else { if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc)) return; } if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, CallableState)) { S.Diag(Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << StateString; return; } States.push_back(CallableState); } D->addAttr(::new (S.Context) CallableWhenAttr(Attr.getRange(), S.Context, States.data(), States.size(), Attr.getAttributeSpellingListIndex())); } static void handleParamTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { ParamTypestateAttr::ConsumedState ParamState; if (Attr.isArgIdent(0)) { IdentifierLoc *Ident = Attr.getArgAsIdent(0); StringRef StateString = Ident->Ident->getName(); if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, ParamState)) { S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << StateString; return; } } else { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentIdentifier; return; } // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. //QualType ReturnType = cast<ParmVarDecl>(D)->getType(); //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); // //if (!RD || !RD->hasAttr<ConsumableAttr>()) { // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << // ReturnType.getAsString(); // return; //} D->addAttr(::new (S.Context) ParamTypestateAttr(Attr.getRange(), S.Context, ParamState, Attr.getAttributeSpellingListIndex())); } static void handleReturnTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { ReturnTypestateAttr::ConsumedState ReturnState; if (Attr.isArgIdent(0)) { IdentifierLoc *IL = Attr.getArgAsIdent(0); if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), ReturnState)) { S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << IL->Ident; return; } } else { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentIdentifier; return; } // FIXME: This check is currently being done in the analysis. It can be // enabled here only after the parser propagates attributes at // template specialization definition, not declaration. //QualType ReturnType; // //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) { // ReturnType = Param->getType(); // //} else if (const CXXConstructorDecl *Constructor = // dyn_cast<CXXConstructorDecl>(D)) { // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); // //} else { // // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); //} // //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); // //if (!RD || !RD->hasAttr<ConsumableAttr>()) { // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << // ReturnType.getAsString(); // return; //} D->addAttr(::new (S.Context) ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState, Attr.getAttributeSpellingListIndex())); } static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) return; SetTypestateAttr::ConsumedState NewState; if (Attr.isArgIdent(0)) { IdentifierLoc *Ident = Attr.getArgAsIdent(0); StringRef Param = Ident->Ident->getName(); if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << Param; return; } } else { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentIdentifier; return; } D->addAttr(::new (S.Context) SetTypestateAttr(Attr.getRange(), S.Context, NewState, Attr.getAttributeSpellingListIndex())); } static void handleTestTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) return; TestTypestateAttr::ConsumedState TestState; if (Attr.isArgIdent(0)) { IdentifierLoc *Ident = Attr.getArgAsIdent(0); StringRef Param = Ident->Ident->getName(); if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << Param; return; } } else { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentIdentifier; return; } D->addAttr(::new (S.Context) TestTypestateAttr(Attr.getRange(), S.Context, TestState, Attr.getAttributeSpellingListIndex())); } static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D, const AttributeList &Attr) { // Remember this typedef decl, we will need it later for diagnostics. S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D)); } static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (TagDecl *TD = dyn_cast<TagDecl>(D)) TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { bool BitfieldByteAligned = (!FD->getType()->isDependentType() && !FD->getType()->isIncompleteType() && FD->isBitField() && S.Context.getTypeAlign(FD->getType()) <= 8); if (S.getASTContext().getTargetInfo().getTriple().isPS4()) { if (BitfieldByteAligned) // The PS4 target needs to maintain ABI backwards compatibility. S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type) << Attr.getName() << FD->getType(); else FD->addAttr(::new (S.Context) PackedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } else { // Report warning about changed offset in the newer compiler versions. if (BitfieldByteAligned) S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield); FD->addAttr(::new (S.Context) PackedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } } else S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); } static void handleUnpackedAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (TagDecl *TD = dyn_cast<TagDecl>(D)) TD->addAttr(::new (S.Context) UnpackedAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); else S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); } static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) { // The IBOutlet/IBOutletCollection attributes only apply to instance // variables or properties of Objective-C classes. The outlet must also // have an object reference type. if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) { if (!VD->getType()->getAs<ObjCObjectPointerType>()) { S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) << Attr.getName() << VD->getType() << 0; return false; } } else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { if (!PD->getType()->getAs<ObjCObjectPointerType>()) { S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) << Attr.getName() << PD->getType() << 1; return false; } } else { S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName(); return false; } return true; } static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkIBOutletCommon(S, D, Attr)) return; D->addAttr(::new (S.Context) IBOutletAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleIBOutletCollection(Sema &S, Decl *D, const AttributeList &Attr) { // The iboutletcollection attribute can have zero or one arguments. if (Attr.getNumArgs() > 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 1; return; } if (!checkIBOutletCommon(S, D, Attr)) return; ParsedType PT; if (Attr.hasParsedType()) PT = Attr.getTypeArg(); else { PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(), S.getScopeForContext(D->getDeclContext()->getParent())); if (!PT) { S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; return; } } TypeSourceInfo *QTLoc = nullptr; QualType QT = S.GetTypeFromParser(PT, &QTLoc); if (!QTLoc) QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc()); // Diagnose use of non-object type in iboutletcollection attribute. // FIXME. Gnu attribute extension ignores use of builtin types in // attributes. So, __attribute__((iboutletcollection(char))) will be // treated as __attribute__((iboutletcollection())). if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { S.Diag(Attr.getLoc(), QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype : diag::err_iboutletcollection_type) << QT; return; } D->addAttr(::new (S.Context) IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc, Attr.getAttributeSpellingListIndex())); } bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { if (RefOkay) { if (T->isReferenceType()) return true; } else { T = T.getNonReferenceType(); } // The nonnull attribute, and other similar attributes, can be applied to a // transparent union that contains a pointer type. if (const RecordType *UT = T->getAsUnionType()) { if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { RecordDecl *UD = UT->getDecl(); for (const auto *I : UD->fields()) { QualType QT = I->getType(); if (QT->isAnyPointerType() || QT->isBlockPointerType()) return true; } } } return T->isAnyPointerType() || T->isBlockPointerType(); } static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr, SourceRange AttrParmRange, SourceRange TypeRange, bool isReturnValue = false) { if (!S.isValidPointerAttrType(T)) { if (isReturnValue) S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) << Attr.getName() << AttrParmRange << TypeRange; else S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only) << Attr.getName() << AttrParmRange << TypeRange << 0; return false; } return true; } static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<unsigned, 8> NonNullArgs; for (unsigned I = 0; I < Attr.getNumArgs(); ++I) { Expr *Ex = Attr.getArgAsExpr(I); uint64_t Idx; if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx)) return; // Is the function argument a pointer type? if (Idx < getFunctionOrMethodNumParams(D) && !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr, Ex->getSourceRange(), getFunctionOrMethodParamRange(D, Idx))) continue; NonNullArgs.push_back(Idx); } // If no arguments were specified to __attribute__((nonnull)) then all pointer // arguments have a nonnull attribute; warn if there aren't any. Skip this // check if the attribute came from a macro expansion or a template // instantiation. if (NonNullArgs.empty() && Attr.getLoc().isFileID() && !S.inTemplateInstantiation()) { bool AnyPointers = isFunctionOrMethodVariadic(D); for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E && !AnyPointers; ++I) { QualType T = getFunctionOrMethodParamType(D, I); if (T->isDependentType() || S.isValidPointerAttrType(T)) AnyPointers = true; } if (!AnyPointers) S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers); } unsigned *Start = NonNullArgs.data(); unsigned Size = NonNullArgs.size(); llvm::array_pod_sort(Start, Start + Size); D->addAttr(::new (S.Context) NonNullAttr(Attr.getRange(), S.Context, Start, Size, Attr.getAttributeSpellingListIndex())); } static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, const AttributeList &Attr) { if (Attr.getNumArgs() > 0) { if (D->getFunctionType()) { handleNonNullAttr(S, D, Attr); } else { S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args) << D->getSourceRange(); } return; } // Is the argument a pointer type? if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(), D->getSourceRange())) return; D->addAttr(::new (S.Context) NonNullAttr(Attr.getRange(), S.Context, nullptr, 0, Attr.getAttributeSpellingListIndex())); } static void handleReturnsNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) { QualType ResultType = getFunctionOrMethodResultType(D); SourceRange SR = getFunctionOrMethodResultSourceRange(D); if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR, /* isReturnValue */ true)) return; D->addAttr(::new (S.Context) ReturnsNonNullAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleNoEscapeAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; // noescape only applies to pointer types. QualType T = cast<ParmVarDecl>(D)->getType(); if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) { S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only) << Attr.getName() << Attr.getRange() << 0; return; } D->addAttr(::new (S.Context) NoEscapeAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleAssumeAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) { Expr *E = Attr.getArgAsExpr(0), *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr; S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE, Attr.getAttributeSpellingListIndex()); } static void handleAllocAlignAttr(Sema &S, Decl *D, const AttributeList &Attr) { S.AddAllocAlignAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), Attr.getAttributeSpellingListIndex()); } void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, unsigned SpellingListIndex) { QualType ResultType = getFunctionOrMethodResultType(D); SourceRange SR = getFunctionOrMethodResultSourceRange(D); AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex); SourceLocation AttrLoc = AttrRange.getBegin(); if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) << &TmpAttr << AttrRange << SR; return; } if (!E->isValueDependent()) { llvm::APSInt I(64); if (!E->isIntegerConstantExpr(I, Context)) { if (OE) Diag(AttrLoc, diag::err_attribute_argument_n_type) << &TmpAttr << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange(); else Diag(AttrLoc, diag::err_attribute_argument_type) << &TmpAttr << AANT_ArgumentIntegerConstant << E->getSourceRange(); return; } if (!I.isPowerOf2()) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) << E->getSourceRange(); return; } } if (OE) { if (!OE->isValueDependent()) { llvm::APSInt I(64); if (!OE->isIntegerConstantExpr(I, Context)) { Diag(AttrLoc, diag::err_attribute_argument_n_type) << &TmpAttr << 2 << AANT_ArgumentIntegerConstant << OE->getSourceRange(); return; } } } D->addAttr(::new (Context) AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); } void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, unsigned SpellingListIndex) { QualType ResultType = getFunctionOrMethodResultType(D); AllocAlignAttr TmpAttr(AttrRange, Context, 0, SpellingListIndex); SourceLocation AttrLoc = AttrRange.getBegin(); if (!ResultType->isDependentType() && !isValidPointerAttrType(ResultType, /* RefOkay */ true)) { Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D); return; } uint64_t IndexVal; const auto *FuncDecl = cast<FunctionDecl>(D); if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr, /*AttrArgNo=*/1, ParamExpr, IndexVal)) return; QualType Ty = getFunctionOrMethodParamType(D, IndexVal); if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) { Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only) << &TmpAttr << FuncDecl->getParamDecl(IndexVal)->getSourceRange(); return; } // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex // because that has corrected for the implicit this parameter, and is zero- // based. The attribute expects what the user wrote explicitly. llvm::APSInt Val; ParamExpr->EvaluateAsInt(Val, Context); D->addAttr(::new (Context) AllocAlignAttr( AttrRange, Context, Val.getZExtValue(), SpellingListIndex)); } /// Normalize the attribute, __foo__ becomes foo. /// Returns true if normalization was applied. static bool normalizeName(StringRef &AttrName) { if (AttrName.size() > 4 && AttrName.startswith("__") && AttrName.endswith("__")) { AttrName = AttrName.drop_front(2).drop_back(2); return true; } return false; } static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) { // This attribute must be applied to a function declaration. The first // argument to the attribute must be an identifier, the name of the resource, // for example: malloc. The following arguments must be argument indexes, the // arguments must be of integer type for Returns, otherwise of pointer type. // The difference between Holds and Takes is that a pointer may still be used // after being held. free() should be __attribute((ownership_takes)), whereas // a list append function may well be __attribute((ownership_holds)). if (!AL.isArgIdent(0)) { S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) << AL.getName() << 1 << AANT_ArgumentIdentifier; return; } // Figure out our Kind. OwnershipAttr::OwnershipKind K = OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, AL.getAttributeSpellingListIndex()).getOwnKind(); // Check arguments. switch (K) { case OwnershipAttr::Takes: case OwnershipAttr::Holds: if (AL.getNumArgs() < 2) { S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL.getName() << 2; return; } break; case OwnershipAttr::Returns: if (AL.getNumArgs() > 2) { S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL.getName() << 1; return; } break; } IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; StringRef ModuleName = Module->getName(); if (normalizeName(ModuleName)) { Module = &S.PP.getIdentifierTable().get(ModuleName); } SmallVector<unsigned, 8> OwnershipArgs; for (unsigned i = 1; i < AL.getNumArgs(); ++i) { Expr *Ex = AL.getArgAsExpr(i); uint64_t Idx; if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) return; // Is the function argument a pointer type? QualType T = getFunctionOrMethodParamType(D, Idx); int Err = -1; // No error switch (K) { case OwnershipAttr::Takes: case OwnershipAttr::Holds: if (!T->isAnyPointerType() && !T->isBlockPointerType()) Err = 0; break; case OwnershipAttr::Returns: if (!T->isIntegerType()) Err = 1; break; } if (-1 != Err) { S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err << Ex->getSourceRange(); return; } // Check we don't have a conflict with another ownership attribute. for (const auto *I : D->specific_attrs<OwnershipAttr>()) { // Cannot have two ownership attributes of different kinds for the same // index. if (I->getOwnKind() != K && I->args_end() != std::find(I->args_begin(), I->args_end(), Idx)) { S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL.getName() << I; return; } else if (K == OwnershipAttr::Returns && I->getOwnKind() == OwnershipAttr::Returns) { // A returns attribute conflicts with any other returns attribute using // a different index. Note, diagnostic reporting is 1-based, but stored // argument indexes are 0-based. if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) << *(I->args_begin()) + 1; if (I->args_size()) S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) << (unsigned)Idx + 1 << Ex->getSourceRange(); return; } } } OwnershipArgs.push_back(Idx); } unsigned* start = OwnershipArgs.data(); unsigned size = OwnershipArgs.size(); llvm::array_pod_sort(start, start + size); D->addAttr(::new (S.Context) OwnershipAttr(AL.getLoc(), S.Context, Module, start, size, AL.getAttributeSpellingListIndex())); } static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Check the attribute arguments. if (Attr.getNumArgs() > 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 1; return; } NamedDecl *nd = cast<NamedDecl>(D); // gcc rejects // class c { // static int a __attribute__((weakref ("v2"))); // static int b() __attribute__((weakref ("f3"))); // }; // and ignores the attributes of // void f(void) { // static int a __attribute__((weakref ("v2"))); // } // we reject them const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); if (!Ctx->isFileContext()) { S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) << nd; return; } // The GCC manual says // // At present, a declaration to which `weakref' is attached can only // be `static'. // // It also says // // Without a TARGET, // given as an argument to `weakref' or to `alias', `weakref' is // equivalent to `weak'. // // gcc 4.4.1 will accept // int a7 __attribute__((weakref)); // as // int a7 __attribute__((weak)); // This looks like a bug in gcc. We reject that for now. We should revisit // it if this behaviour is actually used. // GCC rejects // static ((alias ("y"), weakref)). // Should we? How to check that weakref is before or after alias? // FIXME: it would be good for us to keep the WeakRefAttr as-written instead // of transforming it into an AliasAttr. The WeakRefAttr never uses the // StringRef parameter it was given anyway. StringRef Str; if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str)) // GCC will accept anything as the argument of weakref. Should we // check for an existing decl? D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, Attr.getAttributeSpellingListIndex())); D->addAttr(::new (S.Context) WeakRefAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) { StringRef Str; if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) return; // Aliases should be on declarations, not definitions. const auto *FD = cast<FunctionDecl>(D); if (FD->isThisDeclarationADefinition()) { S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1; return; } D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str, Attr.getAttributeSpellingListIndex())); } static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) { StringRef Str; if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) return; if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin); return; } if (S.Context.getTargetInfo().getTriple().isNVPTX()) { S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx); } // Aliases should be on declarations, not definitions. if (const auto *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isThisDeclarationADefinition()) { S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0; return; } } else { const auto *VD = cast<VarDecl>(D); if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) { S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0; return; } } // FIXME: check if target symbol exists in current file D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, Attr.getAttributeSpellingListIndex())); } static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName())) return; D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName())) return; D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleTLSModelAttr(Sema &S, Decl *D, const AttributeList &Attr) { StringRef Model; SourceLocation LiteralLoc; // Check that it is a string. if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc)) return; // Check that the value. if (Model != "global-dynamic" && Model != "local-dynamic" && Model != "initial-exec" && Model != "local-exec") { S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); return; } D->addAttr(::new (S.Context) TLSModelAttr(Attr.getRange(), S.Context, Model, Attr.getAttributeSpellingListIndex())); } static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) { QualType ResultType = getFunctionOrMethodResultType(D); if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) { D->addAttr(::new (S.Context) RestrictAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; } S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) << Attr.getName() << getFunctionOrMethodResultSourceRange(D); } static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (S.LangOpts.CPlusPlus) { S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) << Attr.getName() << AttributeLangSupport::Cpp; return; } if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(), Attr.getAttributeSpellingListIndex())) D->addAttr(CA); } static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(), Attr.getName())) return; if (Attr.isDeclspecAttribute()) { const auto &Triple = S.getASTContext().getTargetInfo().getTriple(); const auto &Arch = Triple.getArch(); if (Arch != llvm::Triple::x86 && (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) { S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_on_arch) << Attr.getName() << Triple.getArchName(); return; } } D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &Attrs) { if (hasDeclarator(D)) return; if (S.CheckNoReturnAttr(Attrs)) return; if (!isa<ObjCMethodDecl>(D)) { S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type) << Attrs.getName() << ExpectedFunctionOrMethod; return; } D->addAttr(::new (S.Context) NoReturnAttr( Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); } static void handleNoCallerSavedRegsAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (S.CheckNoCallerSavedRegsAttr(Attr)) return; D->addAttr(::new (S.Context) AnyX86NoCallerSavedRegistersAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } bool Sema::CheckNoReturnAttr(const AttributeList &Attrs) { if (!checkAttributeNumArgs(*this, Attrs, 0)) { Attrs.setInvalid(); return true; } return false; } bool Sema::CheckNoCallerSavedRegsAttr(const AttributeList &Attr) { // Check whether the attribute is valid on the current target. if (!Attr.existsInTarget(Context.getTargetInfo())) { Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored) << Attr.getName(); Attr.setInvalid(); return true; } if (!checkAttributeNumArgs(*this, Attr, 0)) { Attr.setInvalid(); return true; } return false; } static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) { // The checking path for 'noreturn' and 'analyzer_noreturn' are different // because 'analyzer_noreturn' does not impact the type. if (!isFunctionOrMethodOrBlock(D)) { ValueDecl *VD = dyn_cast<ValueDecl>(D); if (!VD || (!VD->getType()->isBlockPointerType() && !VD->getType()->isFunctionPointerType())) { S.Diag(Attr.getLoc(), Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type : diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunctionMethodOrBlock; return; } } D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } // PS3 PPU-specific. static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) { /* Returning a Vector Class in Registers According to the PPU ABI specifications, a class with a single member of vector type is returned in memory when used as the return value of a function. This results in inefficient code when implementing vector classes. To return the value in a single vector register, add the vecreturn attribute to the class definition. This attribute is also applicable to struct types. Example: struct Vector { __vector float xyzw; } __attribute__((vecreturn)); Vector Add(Vector lhs, Vector rhs) { Vector result; result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); return result; // This will be returned in a register } */ if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A; return; } RecordDecl *record = cast<RecordDecl>(D); int count = 0; if (!isa<CXXRecordDecl>(record)) { S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); return; } if (!cast<CXXRecordDecl>(record)->isPOD()) { S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record); return; } for (const auto *I : record->fields()) { if ((count == 1) || !I->getType()->isVectorType()) { S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); return; } count++; } D->addAttr(::new (S.Context) VecReturnAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, const AttributeList &Attr) { if (isa<ParmVarDecl>(D)) { // [[carries_dependency]] can only be applied to a parameter if it is a // parameter of a function declaration or lambda. if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { S.Diag(Attr.getLoc(), diag::err_carries_dependency_param_not_function_decl); return; } } D->addAttr(::new (S.Context) CarriesDependencyAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleNotTailCalledAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(), Attr.getName())) return; D->addAttr(::new (S.Context) NotTailCalledAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleDisableTailCallsAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(), Attr.getName())) return; D->addAttr(::new (S.Context) DisableTailCallsAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { if (VD->hasLocalStorage()) { S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); return; } } else if (!isFunctionOrMethod(D)) { S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedVariableOrFunction; return; } D->addAttr(::new (S.Context) UsedAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) { bool IsCXX17Attr = Attr.isCXX11Attribute() && !Attr.getScopeName(); if (IsCXX17Attr && isa<VarDecl>(D)) { // The C++17 spelling of this attribute cannot be applied to a static data // member per [dcl.attr.unused]p2. if (cast<VarDecl>(D)->isStaticDataMember()) { S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedForMaybeUnused; return; } } // If this is spelled as the standard C++17 attribute, but not in C++17, warn // about using it as an extension. if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr) S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName(); D->addAttr(::new (S.Context) UnusedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t priority = ConstructorAttr::DefaultPriority; if (Attr.getNumArgs() && !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) return; D->addAttr(::new (S.Context) ConstructorAttr(Attr.getRange(), S.Context, priority, Attr.getAttributeSpellingListIndex())); } static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t priority = DestructorAttr::DefaultPriority; if (Attr.getNumArgs() && !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) return; D->addAttr(::new (S.Context) DestructorAttr(Attr.getRange(), S.Context, priority, Attr.getAttributeSpellingListIndex())); } template <typename AttrTy> static void handleAttrWithMessage(Sema &S, Decl *D, const AttributeList &Attr) { // Handle the case where the attribute has a text message. StringRef Str; if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) return; D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str, Attr.getAttributeSpellingListIndex())); } static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition) << Attr.getName() << Attr.getRange(); return; } D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static bool checkAvailabilityAttr(Sema &S, SourceRange Range, IdentifierInfo *Platform, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted) { StringRef PlatformName = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); if (PlatformName.empty()) PlatformName = Platform->getName(); // Ensure that Introduced <= Deprecated <= Obsoleted (although not all // of these steps are needed). if (!Introduced.empty() && !Deprecated.empty() && !(Introduced <= Deprecated)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) << 1 << PlatformName << Deprecated.getAsString() << 0 << Introduced.getAsString(); return true; } if (!Introduced.empty() && !Obsoleted.empty() && !(Introduced <= Obsoleted)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) << 2 << PlatformName << Obsoleted.getAsString() << 0 << Introduced.getAsString(); return true; } if (!Deprecated.empty() && !Obsoleted.empty() && !(Deprecated <= Obsoleted)) { S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) << 2 << PlatformName << Obsoleted.getAsString() << 1 << Deprecated.getAsString(); return true; } return false; } /// \brief Check whether the two versions match. /// /// If either version tuple is empty, then they are assumed to match. If /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, bool BeforeIsOkay) { if (X.empty() || Y.empty()) return true; if (X == Y) return true; if (BeforeIsOkay && X < Y) return true; return false; } AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, unsigned AttrSpellingListIndex) { VersionTuple MergedIntroduced = Introduced; VersionTuple MergedDeprecated = Deprecated; VersionTuple MergedObsoleted = Obsoleted; bool FoundAny = false; bool OverrideOrImpl = false; switch (AMK) { case AMK_None: case AMK_Redeclaration: OverrideOrImpl = false; break; case AMK_Override: case AMK_ProtocolImplementation: OverrideOrImpl = true; break; } if (D->hasAttrs()) { AttrVec &Attrs = D->getAttrs(); for (unsigned i = 0, e = Attrs.size(); i != e;) { const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); if (!OldAA) { ++i; continue; } IdentifierInfo *OldPlatform = OldAA->getPlatform(); if (OldPlatform != Platform) { ++i; continue; } // If there is an existing availability attribute for this platform that // is explicit and the new one is implicit use the explicit one and // discard the new implicit attribute. if (!OldAA->isImplicit() && Implicit) { return nullptr; } // If there is an existing attribute for this platform that is implicit // and the new attribute is explicit then erase the old one and // continue processing the attributes. if (!Implicit && OldAA->isImplicit()) { Attrs.erase(Attrs.begin() + i); --e; continue; } FoundAny = true; VersionTuple OldIntroduced = OldAA->getIntroduced(); VersionTuple OldDeprecated = OldAA->getDeprecated(); VersionTuple OldObsoleted = OldAA->getObsoleted(); bool OldIsUnavailable = OldAA->getUnavailable(); if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) || !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) || !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) || !(OldIsUnavailable == IsUnavailable || (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) { if (OverrideOrImpl) { int Which = -1; VersionTuple FirstVersion; VersionTuple SecondVersion; if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) { Which = 0; FirstVersion = OldIntroduced; SecondVersion = Introduced; } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { Which = 1; FirstVersion = Deprecated; SecondVersion = OldDeprecated; } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) { Which = 2; FirstVersion = Obsoleted; SecondVersion = OldObsoleted; } if (Which == -1) { Diag(OldAA->getLocation(), diag::warn_mismatched_availability_override_unavail) << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) << (AMK == AMK_Override); } else { Diag(OldAA->getLocation(), diag::warn_mismatched_availability_override) << Which << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) << FirstVersion.getAsString() << SecondVersion.getAsString() << (AMK == AMK_Override); } if (AMK == AMK_Override) Diag(Range.getBegin(), diag::note_overridden_method); else Diag(Range.getBegin(), diag::note_protocol_method); } else { Diag(OldAA->getLocation(), diag::warn_mismatched_availability); Diag(Range.getBegin(), diag::note_previous_attribute); } Attrs.erase(Attrs.begin() + i); --e; continue; } VersionTuple MergedIntroduced2 = MergedIntroduced; VersionTuple MergedDeprecated2 = MergedDeprecated; VersionTuple MergedObsoleted2 = MergedObsoleted; if (MergedIntroduced2.empty()) MergedIntroduced2 = OldIntroduced; if (MergedDeprecated2.empty()) MergedDeprecated2 = OldDeprecated; if (MergedObsoleted2.empty()) MergedObsoleted2 = OldObsoleted; if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, MergedIntroduced2, MergedDeprecated2, MergedObsoleted2)) { Attrs.erase(Attrs.begin() + i); --e; continue; } MergedIntroduced = MergedIntroduced2; MergedDeprecated = MergedDeprecated2; MergedObsoleted = MergedObsoleted2; ++i; } } if (FoundAny && MergedIntroduced == Introduced && MergedDeprecated == Deprecated && MergedObsoleted == Obsoleted) return nullptr; // Only create a new attribute if !OverrideOrImpl, but we want to do // the checking. if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced, MergedDeprecated, MergedObsoleted) && !OverrideOrImpl) { auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable, Message, IsStrict, Replacement, AttrSpellingListIndex); Avail->setImplicit(Implicit); return Avail; } return nullptr; } static void handleAvailabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeNumArgs(S, Attr, 1)) return; IdentifierLoc *Platform = Attr.getArgAsIdent(0); unsigned Index = Attr.getAttributeSpellingListIndex(); IdentifierInfo *II = Platform->Ident; if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) << Platform->Ident; NamedDecl *ND = dyn_cast<NamedDecl>(D); if (!ND) // We warned about this already, so just return. return; AvailabilityChange Introduced = Attr.getAvailabilityIntroduced(); AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated(); AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted(); bool IsUnavailable = Attr.getUnavailableLoc().isValid(); bool IsStrict = Attr.getStrictLoc().isValid(); StringRef Str; if (const StringLiteral *SE = dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr())) Str = SE->getString(); StringRef Replacement; if (const StringLiteral *SE = dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr())) Replacement = SE->getString(); AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II, false/*Implicit*/, Introduced.Version, Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement, Sema::AMK_None, Index); if (NewAttr) D->addAttr(NewAttr); // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning // matches before the start of the watchOS platform. if (S.Context.getTargetInfo().getTriple().isWatchOS()) { IdentifierInfo *NewII = nullptr; if (II->getName() == "ios") NewII = &S.Context.Idents.get("watchos"); else if (II->getName() == "ios_app_extension") NewII = &S.Context.Idents.get("watchos_app_extension"); if (NewII) { auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { if (Version.empty()) return Version; auto Major = Version.getMajor(); auto NewMajor = Major >= 9 ? Major - 7 : 0; if (NewMajor >= 2) { if (Version.getMinor().hasValue()) { if (Version.getSubminor().hasValue()) return VersionTuple(NewMajor, Version.getMinor().getValue(), Version.getSubminor().getValue()); else return VersionTuple(NewMajor, Version.getMinor().getValue()); } } return VersionTuple(2, 0); }; auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), NewII, true/*Implicit*/, NewIntroduced, NewDeprecated, NewObsoleted, IsUnavailable, Str, IsStrict, Replacement, Sema::AMK_None, Index); if (NewAttr) D->addAttr(NewAttr); } } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning // matches before the start of the tvOS platform. IdentifierInfo *NewII = nullptr; if (II->getName() == "ios") NewII = &S.Context.Idents.get("tvos"); else if (II->getName() == "ios_app_extension") NewII = &S.Context.Idents.get("tvos_app_extension"); if (NewII) { AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), NewII, true/*Implicit*/, Introduced.Version, Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement, Sema::AMK_None, Index); if (NewAttr) D->addAttr(NewAttr); } } } static void handleExternalSourceSymbolAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return; assert(checkAttributeAtMostNumArgs(S, Attr, 3) && "Invalid number of arguments in an external_source_symbol attribute"); StringRef Language; if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0))) Language = SE->getString(); StringRef DefinedIn; if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1))) DefinedIn = SE->getString(); bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr; D->addAttr(::new (S.Context) ExternalSourceSymbolAttr( Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration, Attr.getAttributeSpellingListIndex())); } template <class T> static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range, typename T::VisibilityType value, unsigned attrSpellingListIndex) { T *existingAttr = D->getAttr<T>(); if (existingAttr) { typename T::VisibilityType existingValue = existingAttr->getVisibility(); if (existingValue == value) return nullptr; S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); S.Diag(range.getBegin(), diag::note_previous_attribute); D->dropAttr<T>(); } return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex); } VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range, VisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex) { return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis, AttrSpellingListIndex); } TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, TypeVisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex) { return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis, AttrSpellingListIndex); } static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr, bool isTypeVisibility) { // Visibility attributes don't mean anything on a typedef. if (isa<TypedefNameDecl>(D)) { S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored) << Attr.getName(); return; } // 'type_visibility' can only go on a type or namespace. if (isTypeVisibility && !(isa<TagDecl>(D) || isa<ObjCInterfaceDecl>(D) || isa<NamespaceDecl>(D))) { S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type) << Attr.getName() << ExpectedTypeOrNamespace; return; } // Check that the argument is a string literal. StringRef TypeStr; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc)) return; VisibilityAttr::VisibilityType type; if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << Attr.getName() << TypeStr; return; } // Complain about attempts to use protected visibility on targets // (like Darwin) that don't support it. if (type == VisibilityAttr::Protected && !S.Context.getTargetInfo().hasProtectedVisibility()) { S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility); type = VisibilityAttr::Default; } unsigned Index = Attr.getAttributeSpellingListIndex(); clang::Attr *newAttr; if (isTypeVisibility) { newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(), (TypeVisibilityAttr::VisibilityType) type, Index); } else { newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index); } if (newAttr) D->addAttr(newAttr); } static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl, const AttributeList &Attr) { ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl); if (!Attr.isArgIdent(0)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << 1 << AANT_ArgumentIdentifier; return; } IdentifierLoc *IL = Attr.getArgAsIdent(0); ObjCMethodFamilyAttr::FamilyKind F; if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << IL->Ident; return; } if (F == ObjCMethodFamilyAttr::OMF_init && !method->getReturnType()->isObjCObjectPointerType()) { S.Diag(method->getLocation(), diag::err_init_method_bad_return_type) << method->getReturnType(); // Ignore the attribute. return; } method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(), S.Context, F, Attr.getAttributeSpellingListIndex())); } static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) { if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { QualType T = TD->getUnderlyingType(); if (!T->isCARCBridgableType()) { S.Diag(TD->getLocation(), diag::err_nsobject_attribute); return; } } else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { QualType T = PD->getType(); if (!T->isCARCBridgableType()) { S.Diag(PD->getLocation(), diag::err_nsobject_attribute); return; } } else { // It is okay to include this attribute on properties, e.g.: // // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); // // In this case it follows tradition and suppresses an error in the above // case. S.Diag(D->getLocation(), diag::warn_nsobject_attribute); } D->addAttr(::new (S.Context) ObjCNSObjectAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) { if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { QualType T = TD->getUnderlyingType(); if (!T->isObjCObjectPointerType()) { S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); return; } } else { S.Diag(D->getLocation(), diag::warn_independentclass_attribute); return; } D->addAttr(::new (S.Context) ObjCIndependentClassAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!Attr.isArgIdent(0)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << 1 << AANT_ArgumentIdentifier; return; } IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; BlocksAttr::BlockType type; if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) << Attr.getName() << II; return; } D->addAttr(::new (S.Context) BlocksAttr(Attr.getRange(), S.Context, type, Attr.getAttributeSpellingListIndex())); } static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) { unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; if (Attr.getNumArgs() > 0) { Expr *E = Attr.getArgAsExpr(0); llvm::APSInt Idx(32); if (E->isTypeDependent() || E->isValueDependent() || !E->isIntegerConstantExpr(Idx, S.Context)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange(); return; } if (Idx.isSigned() && Idx.isNegative()) { S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero) << E->getSourceRange(); return; } sentinel = Idx.getZExtValue(); } unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; if (Attr.getNumArgs() > 1) { Expr *E = Attr.getArgAsExpr(1); llvm::APSInt Idx(32); if (E->isTypeDependent() || E->isValueDependent() || !E->isIntegerConstantExpr(Idx, S.Context)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange(); return; } nullPos = Idx.getZExtValue(); if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) { // FIXME: This error message could be improved, it would be nice // to say what the bounds actually are. S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) << E->getSourceRange(); return; } } if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { const FunctionType *FT = FD->getType()->castAs<FunctionType>(); if (isa<FunctionNoProtoType>(FT)) { S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments); return; } if (!cast<FunctionProtoType>(FT)->isVariadic()) { S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; return; } } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { if (!MD->isVariadic()) { S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; return; } } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) { if (!BD->isVariadic()) { S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; return; } } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { QualType Ty = V->getType(); if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { const FunctionType *FT = Ty->isFunctionPointerType() ? D->getFunctionType() : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); if (!cast<FunctionProtoType>(FT)->isVariadic()) { int m = Ty->isFunctionPointerType() ? 0 : 1; S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; return; } } else { S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunctionMethodOrBlock; return; } } else { S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunctionMethodOrBlock; return; } D->addAttr(::new (S.Context) SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos, Attr.getAttributeSpellingListIndex())); } static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) { if (D->getFunctionType() && D->getFunctionType()->getReturnType()->isVoidType()) { S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) << Attr.getName() << 0; return; } if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) if (MD->getReturnType()->isVoidType()) { S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) << Attr.getName() << 1; return; } // If this is spelled as the standard C++17 attribute, but not in C++17, warn // about using it as an extension. if (!S.getLangOpts().CPlusPlus17 && Attr.isCXX11Attribute() && !Attr.getScopeName()) S.Diag(Attr.getLoc(), diag::ext_cxx17_attr) << Attr.getName(); D->addAttr(::new (S.Context) WarnUnusedResultAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) { // weak_import only applies to variable & function declarations. bool isDef = false; if (!D->canBeWeakImported(isDef)) { if (isDef) S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition) << "weak_import"; else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || (S.Context.getTargetInfo().getTriple().isOSDarwin() && (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { // Nothing to warn about here. } else S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedVariableOrFunction; return; } D->addAttr(::new (S.Context) WeakImportAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } // Handles reqd_work_group_size and work_group_size_hint. template <typename WorkGroupAttr> static void handleWorkGroupSize(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t WGSize[3]; for (unsigned i = 0; i < 3; ++i) { const Expr *E = Attr.getArgAsExpr(i); if (!checkUInt32Argument(S, Attr, E, WGSize[i], i)) return; if (WGSize[i] == 0) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero) << Attr.getName() << E->getSourceRange(); return; } } WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); if (Existing && !(Existing->getXDim() == WGSize[0] && Existing->getYDim() == WGSize[1] && Existing->getZDim() == WGSize[2])) S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context, WGSize[0], WGSize[1], WGSize[2], Attr.getAttributeSpellingListIndex())); } // Handles intel_reqd_sub_group_size. static void handleSubGroupSize(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t SGSize; const Expr *E = Attr.getArgAsExpr(0); if (!checkUInt32Argument(S, Attr, E, SGSize)) return; if (SGSize == 0) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero) << Attr.getName() << E->getSourceRange(); return; } OpenCLIntelReqdSubGroupSizeAttr *Existing = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>(); if (Existing && Existing->getSubGroupSize() != SGSize) S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr( Attr.getRange(), S.Context, SGSize, Attr.getAttributeSpellingListIndex())); } static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) { if (!Attr.hasParsedType()) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 1; return; } TypeSourceInfo *ParmTSI = nullptr; QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI); assert(ParmTSI && "no type source info for attribute argument"); if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && (ParmType->isBooleanType() || !ParmType->isIntegralType(S.getASTContext()))) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint) << ParmType; return; } if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); return; } } D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context, ParmTSI, Attr.getAttributeSpellingListIndex())); } SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex) { if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { if (ExistingAttr->getName() == Name) return nullptr; Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section); Diag(Range.getBegin(), diag::note_previous_attribute); return nullptr; } return ::new (Context) SectionAttr(Range, Context, Name, AttrSpellingListIndex); } bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); if (!Error.empty()) { Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; return false; } return true; } static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Make sure that there is a string literal as the sections's single // argument. StringRef Str; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) return; if (!S.checkSectionName(LiteralLoc, Str)) return; // If the target wants to validate the section specifier, make it happen. std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); if (!Error.empty()) { S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; return; } unsigned Index = Attr.getAttributeSpellingListIndex(); SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index); if (NewAttr) D->addAttr(NewAttr); } // Check for things we'd like to warn about. Multiversioning issues are // handled later in the process, once we know how many exist. bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { enum FirstParam { Unsupported, Duplicate }; enum SecondParam { None, Architecture }; for (auto Str : {"tune=", "fpmath="}) if (AttrStr.find(Str) != StringRef::npos) return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Unsupported << None << Str; TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr); if (!ParsedAttrs.Architecture.empty() && !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture)) return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Unsupported << Architecture << ParsedAttrs.Architecture; if (ParsedAttrs.DuplicateArchitecture) return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Duplicate << None << "arch="; for (const auto &Feature : ParsedAttrs.Features) { auto CurFeature = StringRef(Feature).drop_front(); // remove + or -. if (!Context.getTargetInfo().isValidFeatureName(CurFeature)) return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Unsupported << None << CurFeature; } return true; } static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) { StringRef Str; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc) || !S.checkTargetAttr(LiteralLoc, Str)) return; unsigned Index = Attr.getAttributeSpellingListIndex(); TargetAttr *NewAttr = ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index); D->addAttr(NewAttr); } static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) { Expr *E = Attr.getArgAsExpr(0); SourceLocation Loc = E->getExprLoc(); FunctionDecl *FD = nullptr; DeclarationNameInfo NI; // gcc only allows for simple identifiers. Since we support more than gcc, we // will warn the user. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { if (DRE->hasQualifier()) S.Diag(Loc, diag::warn_cleanup_ext); FD = dyn_cast<FunctionDecl>(DRE->getDecl()); NI = DRE->getNameInfo(); if (!FD) { S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 << NI.getName(); return; } } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { if (ULE->hasExplicitTemplateArgs()) S.Diag(Loc, diag::warn_cleanup_ext); FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); NI = ULE->getNameInfo(); if (!FD) { S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 << NI.getName(); if (ULE->getType() == S.Context.OverloadTy) S.NoteAllOverloadCandidates(ULE); return; } } else { S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; return; } if (FD->getNumParams() != 1) { S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) << NI.getName(); return; } // We're currently more strict than GCC about what function types we accept. // If this ever proves to be a problem it should be easy to fix. QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType()); QualType ParamTy = FD->getParamDecl(0)->getType(); if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), ParamTy, Ty) != Sema::Compatible) { S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) << NI.getName() << ParamTy << Ty; return; } D->addAttr(::new (S.Context) CleanupAttr(Attr.getRange(), S.Context, FD, Attr.getAttributeSpellingListIndex())); } static void handleEnumExtensibilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!Attr.isArgIdent(0)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << 0 << AANT_ArgumentIdentifier; return; } EnumExtensibilityAttr::Kind ExtensibilityKind; IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(), ExtensibilityKind)) { S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) << Attr.getName() << II; return; } D->addAttr(::new (S.Context) EnumExtensibilityAttr( Attr.getRange(), S.Context, ExtensibilityKind, Attr.getAttributeSpellingListIndex())); } /// Handle __attribute__((format_arg((idx)))) attribute based on /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) { Expr *IdxExpr = Attr.getArgAsExpr(0); uint64_t Idx; if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx)) return; // Make sure the format string is really a string. QualType Ty = getFunctionOrMethodParamType(D, Idx); bool NotNSStringTy = !isNSStringType(Ty, S.Context); if (NotNSStringTy && !isCFStringType(Ty, S.Context) && (!Ty->isPointerType() || !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { S.Diag(Attr.getLoc(), diag::err_format_attribute_not) << "a string type" << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); return; } Ty = getFunctionOrMethodResultType(D); if (!isNSStringType(Ty, S.Context) && !isCFStringType(Ty, S.Context) && (!Ty->isPointerType() || !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not) << (NotNSStringTy ? "string type" : "NSString") << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); return; } // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex // because that has corrected for the implicit this parameter, and is zero- // based. The attribute expects what the user wrote explicitly. llvm::APSInt Val; IdxExpr->EvaluateAsInt(Val, S.Context); D->addAttr(::new (S.Context) FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(), Attr.getAttributeSpellingListIndex())); } enum FormatAttrKind { CFStringFormat, NSStringFormat, StrftimeFormat, SupportedFormat, IgnoredFormat, InvalidFormat }; /// getFormatAttrKind - Map from format attribute names to supported format /// types. static FormatAttrKind getFormatAttrKind(StringRef Format) { return llvm::StringSwitch<FormatAttrKind>(Format) // Check for formats that get handled specially. .Case("NSString", NSStringFormat) .Case("CFString", CFStringFormat) .Case("strftime", StrftimeFormat) // Otherwise, check for supported formats. .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) .Case("kprintf", SupportedFormat) // OpenBSD. .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. .Case("os_trace", SupportedFormat) .Case("os_log", SupportedFormat) .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) .Default(InvalidFormat); } /// Handle __attribute__((init_priority(priority))) attributes based on /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html static void handleInitPriorityAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!S.getLangOpts().CPlusPlus) { S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); return; } if (S.getCurFunctionOrMethodDecl()) { S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); Attr.setInvalid(); return; } QualType T = cast<VarDecl>(D)->getType(); if (S.Context.getAsArrayType(T)) T = S.Context.getBaseElementType(T); if (!T->getAs<RecordType>()) { S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); Attr.setInvalid(); return; } Expr *E = Attr.getArgAsExpr(0); uint32_t prioritynum; if (!checkUInt32Argument(S, Attr, E, prioritynum)) { Attr.setInvalid(); return; } if (prioritynum < 101 || prioritynum > 65535) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range) << E->getSourceRange() << Attr.getName() << 101 << 65535; Attr.setInvalid(); return; } D->addAttr(::new (S.Context) InitPriorityAttr(Attr.getRange(), S.Context, prioritynum, Attr.getAttributeSpellingListIndex())); } FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, IdentifierInfo *Format, int FormatIdx, int FirstArg, unsigned AttrSpellingListIndex) { // Check whether we already have an equivalent format attribute. for (auto *F : D->specific_attrs<FormatAttr>()) { if (F->getType() == Format && F->getFormatIdx() == FormatIdx && F->getFirstArg() == FirstArg) { // If we don't have a valid location for this attribute, adopt the // location. if (F->getLocation().isInvalid()) F->setRange(Range); return nullptr; } } return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, FirstArg, AttrSpellingListIndex); } /// Handle __attribute__((format(type,idx,firstarg))) attributes based on /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!Attr.isArgIdent(0)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << 1 << AANT_ArgumentIdentifier; return; } // In C++ the implicit 'this' function parameter also counts, and they are // counted from one. bool HasImplicitThisParam = isInstanceMethod(D); unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; StringRef Format = II->getName(); if (normalizeName(Format)) { // If we've modified the string name, we need a new identifier for it. II = &S.Context.Idents.get(Format); } // Check for supported formats. FormatAttrKind Kind = getFormatAttrKind(Format); if (Kind == IgnoredFormat) return; if (Kind == InvalidFormat) { S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) << Attr.getName() << II->getName(); return; } // checks for the 2nd argument Expr *IdxExpr = Attr.getArgAsExpr(1); uint32_t Idx; if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2)) return; if (Idx < 1 || Idx > NumArgs) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) << Attr.getName() << 2 << IdxExpr->getSourceRange(); return; } // FIXME: Do we need to bounds check? unsigned ArgIdx = Idx - 1; if (HasImplicitThisParam) { if (ArgIdx == 0) { S.Diag(Attr.getLoc(), diag::err_format_attribute_implicit_this_format_string) << IdxExpr->getSourceRange(); return; } ArgIdx--; } // make sure the format string is really a string QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); if (Kind == CFStringFormat) { if (!isCFStringType(Ty, S.Context)) { S.Diag(Attr.getLoc(), diag::err_format_attribute_not) << "a CFString" << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx); return; } } else if (Kind == NSStringFormat) { // FIXME: do we need to check if the type is NSString*? What are the // semantics? if (!isNSStringType(Ty, S.Context)) { S.Diag(Attr.getLoc(), diag::err_format_attribute_not) << "an NSString" << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx); return; } } else if (!Ty->isPointerType() || !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) { S.Diag(Attr.getLoc(), diag::err_format_attribute_not) << "a string type" << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx); return; } // check the 3rd argument Expr *FirstArgExpr = Attr.getArgAsExpr(2); uint32_t FirstArg; if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3)) return; // check if the function is variadic if the 3rd argument non-zero if (FirstArg != 0) { if (isFunctionOrMethodVariadic(D)) { ++NumArgs; // +1 for ... } else { S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); return; } } // strftime requires FirstArg to be 0 because it doesn't read from any // variable the input is just the current time + the format string. if (Kind == StrftimeFormat) { if (FirstArg != 0) { S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter) << FirstArgExpr->getSourceRange(); return; } // if 0 it disables parameter checking (to use with e.g. va_list) } else if (FirstArg != 0 && FirstArg != NumArgs) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) << Attr.getName() << 3 << FirstArgExpr->getSourceRange(); return; } FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II, Idx, FirstArg, Attr.getAttributeSpellingListIndex()); if (NewAttr) D->addAttr(NewAttr); } static void handleTransparentUnionAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Try to find the underlying union declaration. RecordDecl *RD = nullptr; TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); if (TD && TD->getUnderlyingType()->isUnionType()) RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); else RD = dyn_cast<RecordDecl>(D); if (!RD || !RD->isUnion()) { S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedUnion; return; } if (!RD->isCompleteDefinition()) { if (!RD->isBeingDefined()) S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_not_definition); return; } RecordDecl::field_iterator Field = RD->field_begin(), FieldEnd = RD->field_end(); if (Field == FieldEnd) { S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields); return; } FieldDecl *FirstField = *Field; QualType FirstType = FirstField->getType(); if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { S.Diag(FirstField->getLocation(), diag::warn_transparent_union_attribute_floating) << FirstType->isVectorType() << FirstType; return; } if (FirstType->isIncompleteType()) return; uint64_t FirstSize = S.Context.getTypeSize(FirstType); uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); for (; Field != FieldEnd; ++Field) { QualType FieldType = Field->getType(); if (FieldType->isIncompleteType()) return; // FIXME: this isn't fully correct; we also need to test whether the // members of the union would all have the same calling convention as the // first member of the union. Checking just the size and alignment isn't // sufficient (consider structs passed on the stack instead of in registers // as an example). if (S.Context.getTypeSize(FieldType) != FirstSize || S.Context.getTypeAlign(FieldType) > FirstAlign) { // Warn if we drop the attribute. bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) : S.Context.getTypeAlign(FieldType); S.Diag(Field->getLocation(), diag::warn_transparent_union_attribute_field_size_align) << isSize << Field->getDeclName() << FieldBits; unsigned FirstBits = isSize? FirstSize : FirstAlign; S.Diag(FirstField->getLocation(), diag::note_transparent_union_first_field_size_align) << isSize << FirstBits; return; } } RD->addAttr(::new (S.Context) TransparentUnionAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Make sure that there is a string literal as the annotation's single // argument. StringRef Str; if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) return; // Don't duplicate annotations that are already set. for (const auto *I : D->specific_attrs<AnnotateAttr>()) { if (I->getAnnotation() == Str) return; } D->addAttr(::new (S.Context) AnnotateAttr(Attr.getRange(), S.Context, Str, Attr.getAttributeSpellingListIndex())); } static void handleAlignValueAttr(Sema &S, Decl *D, const AttributeList &Attr) { S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), Attr.getAttributeSpellingListIndex()); } void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex) { AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex); SourceLocation AttrLoc = AttrRange.getBegin(); QualType T; if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) T = TD->getUnderlyingType(); else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) T = VD->getType(); else llvm_unreachable("Unknown decl type for align_value"); if (!T->isDependentType() && !T->isAnyPointerType() && !T->isReferenceType() && !T->isMemberPointerType()) { Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); return; } if (!E->isValueDependent()) { llvm::APSInt Alignment; ExprResult ICE = VerifyIntegerConstantExpression(E, &Alignment, diag::err_align_value_attribute_argument_not_int, /*AllowFold*/ false); if (ICE.isInvalid()) return; if (!Alignment.isPowerOf2()) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) << E->getSourceRange(); return; } D->addAttr(::new (Context) AlignValueAttr(AttrRange, Context, ICE.get(), SpellingListIndex)); return; } // Save dependent expressions in the AST to be instantiated. D->addAttr(::new (Context) AlignValueAttr(TmpAttr)); } static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) { // check the attribute arguments. if (Attr.getNumArgs() > 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 1; return; } if (Attr.getNumArgs() == 0) { D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context, true, nullptr, Attr.getAttributeSpellingListIndex())); return; } Expr *E = Attr.getArgAsExpr(0); if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) { S.Diag(Attr.getEllipsisLoc(), diag::err_pack_expansion_without_parameter_packs); return; } if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) return; if (E->isValueDependent()) { if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { if (!TND->getUnderlyingType()->isDependentType()) { S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name) << E->getSourceRange(); return; } } } S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(), Attr.isPackExpansion()); } void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex, bool IsPackExpansion) { AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex); SourceLocation AttrLoc = AttrRange.getBegin(); // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. if (TmpAttr.isAlignas()) { // C++11 [dcl.align]p1: // An alignment-specifier may be applied to a variable or to a class // data member, but it shall not be applied to a bit-field, a function // parameter, the formal parameter of a catch clause, or a variable // declared with the register storage class specifier. An // alignment-specifier may also be applied to the declaration of a class // or enumeration type. // C11 6.7.5/2: // An alignment attribute shall not be specified in a declaration of // a typedef, or a bit-field, or a function, or a parameter, or an // object declared with the register storage-class specifier. int DiagKind = -1; if (isa<ParmVarDecl>(D)) { DiagKind = 0; } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { if (VD->getStorageClass() == SC_Register) DiagKind = 1; if (VD->isExceptionVariable()) DiagKind = 2; } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { if (FD->isBitField()) DiagKind = 3; } else if (!isa<TagDecl>(D)) { Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr << (TmpAttr.isC11() ? ExpectedVariableOrField : ExpectedVariableFieldOrTag); return; } if (DiagKind != -1) { Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) << &TmpAttr << DiagKind; return; } } if (E->isTypeDependent() || E->isValueDependent()) { // Save dependent expressions in the AST to be instantiated. AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr); AA->setPackExpansion(IsPackExpansion); D->addAttr(AA); return; } // FIXME: Cache the number on the Attr object? llvm::APSInt Alignment; ExprResult ICE = VerifyIntegerConstantExpression(E, &Alignment, diag::err_aligned_attribute_argument_not_int, /*AllowFold*/ false); if (ICE.isInvalid()) return; uint64_t AlignVal = Alignment.getZExtValue(); // C++11 [dcl.align]p2: // -- if the constant expression evaluates to zero, the alignment // specifier shall have no effect // C11 6.7.5p6: // An alignment specification of zero has no effect. if (!(TmpAttr.isAlignas() && !Alignment)) { if (!llvm::isPowerOf2_64(AlignVal)) { Diag(AttrLoc, diag::err_alignment_not_power_of_two) << E->getSourceRange(); return; } } // Alignment calculations can wrap around if it's greater than 2**28. unsigned MaxValidAlignment = Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192 : 268435456; if (AlignVal > MaxValidAlignment) { Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment << E->getSourceRange(); return; } if (Context.getTargetInfo().isTLSSupported()) { unsigned MaxTLSAlign = Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) .getQuantity(); auto *VD = dyn_cast<VarDecl>(D); if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD && VD->getTLSKind() != VarDecl::TLS_None) { Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) << (unsigned)AlignVal << VD << MaxTLSAlign; return; } } AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, ICE.get(), SpellingListIndex); AA->setPackExpansion(IsPackExpansion); D->addAttr(AA); } void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS, unsigned SpellingListIndex, bool IsPackExpansion) { // FIXME: Cache the number on the Attr object if non-dependent? // FIXME: Perform checking of type validity AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, SpellingListIndex); AA->setPackExpansion(IsPackExpansion); D->addAttr(AA); } void Sema::CheckAlignasUnderalignment(Decl *D) { assert(D->hasAttrs() && "no attributes on decl"); QualType UnderlyingTy, DiagTy; if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { UnderlyingTy = DiagTy = VD->getType(); } else { UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) UnderlyingTy = ED->getIntegerType(); } if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) return; // C++11 [dcl.align]p5, C11 6.7.5/4: // The combined effect of all alignment attributes in a declaration shall // not specify an alignment that is less strict than the alignment that // would otherwise be required for the entity being declared. AlignedAttr *AlignasAttr = nullptr; unsigned Align = 0; for (auto *I : D->specific_attrs<AlignedAttr>()) { if (I->isAlignmentDependent()) return; if (I->isAlignas()) AlignasAttr = I; Align = std::max(Align, I->getAlignment(Context)); } if (AlignasAttr && Align) { CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); if (NaturalAlign > RequestedAlign) Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) << DiagTy << (unsigned)NaturalAlign.getQuantity(); } } bool Sema::checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling) { assert(RD->hasDefinition() && "RD has no definition!"); // We may not have seen base specifiers or any virtual methods yet. We will // have to wait until the record is defined to catch any mismatches. if (!RD->getDefinition()->isCompleteDefinition()) return false; // The unspecified model never matches what a definition could need. if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance) return false; if (BestCase) { if (RD->calculateInheritanceModel() == SemanticSpelling) return false; } else { if (RD->calculateInheritanceModel() <= SemanticSpelling) return false; } Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) << 0 /*definition*/; Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD->getNameAsString(); return true; } /// parseModeAttrArg - Parses attribute mode string and returns parsed type /// attribute. static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, bool &IntegerMode, bool &ComplexMode) { IntegerMode = true; ComplexMode = false; switch (Str.size()) { case 2: switch (Str[0]) { case 'Q': DestWidth = 8; break; case 'H': DestWidth = 16; break; case 'S': DestWidth = 32; break; case 'D': DestWidth = 64; break; case 'X': DestWidth = 96; break; case 'T': DestWidth = 128; break; } if (Str[1] == 'F') { IntegerMode = false; } else if (Str[1] == 'C') { IntegerMode = false; ComplexMode = true; } else if (Str[1] != 'I') { DestWidth = 0; } break; case 4: // FIXME: glibc uses 'word' to define register_t; this is narrower than a // pointer on PIC16 and other embedded platforms. if (Str == "word") DestWidth = S.Context.getTargetInfo().getRegisterWidth(); else if (Str == "byte") DestWidth = S.Context.getTargetInfo().getCharWidth(); break; case 7: if (Str == "pointer") DestWidth = S.Context.getTargetInfo().getPointerWidth(0); break; case 11: if (Str == "unwind_word") DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); break; } } /// handleModeAttr - This attribute modifies the width of a decl with primitive /// type. /// /// Despite what would be logical, the mode attribute is a decl attribute, not a /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be /// HImode, not an intermediate pointer. static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) { // This attribute isn't documented, but glibc uses it. It changes // the width of an int or unsigned int to the specified size. if (!Attr.isArgIdent(0)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentIdentifier; return; } IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident; S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex()); } void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, unsigned SpellingListIndex, bool InInstantiation) { StringRef Str = Name->getName(); normalizeName(Str); SourceLocation AttrLoc = AttrRange.getBegin(); unsigned DestWidth = 0; bool IntegerMode = true; bool ComplexMode = false; llvm::APInt VectorSize(64, 0); if (Str.size() >= 4 && Str[0] == 'V') { // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). size_t StrSize = Str.size(); size_t VectorStringLength = 0; while ((VectorStringLength + 1) < StrSize && isdigit(Str[VectorStringLength + 1])) ++VectorStringLength; if (VectorStringLength && !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && VectorSize.isPowerOf2()) { parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, IntegerMode, ComplexMode); // Avoid duplicate warning from template instantiation. if (!InInstantiation) Diag(AttrLoc, diag::warn_vector_mode_deprecated); } else { VectorSize = 0; } } if (!VectorSize) parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode); // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t // and friends, at least with glibc. // FIXME: Make sure floating-point mappings are accurate // FIXME: Support XF and TF types if (!DestWidth) { Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; return; } QualType OldTy; if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) OldTy = TD->getUnderlyingType(); else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. // Try to get type from enum declaration, default to int. OldTy = ED->getIntegerType(); if (OldTy.isNull()) OldTy = Context.IntTy; } else OldTy = cast<ValueDecl>(D)->getType(); if (OldTy->isDependentType()) { D->addAttr(::new (Context) ModeAttr(AttrRange, Context, Name, SpellingListIndex)); return; } // Base type can also be a vector type (see PR17453). // Distinguish between base type and base element type. QualType OldElemTy = OldTy; if (const VectorType *VT = OldTy->getAs<VectorType>()) OldElemTy = VT->getElementType(); // GCC allows 'mode' attribute on enumeration types (even incomplete), except // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) && VectorSize.getBoolValue()) { Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange; return; } bool IntegralOrAnyEnumType = OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>(); if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() && !IntegralOrAnyEnumType) Diag(AttrLoc, diag::err_mode_not_primitive); else if (IntegerMode) { if (!IntegralOrAnyEnumType) Diag(AttrLoc, diag::err_mode_wrong_type); } else if (ComplexMode) { if (!OldElemTy->isComplexType()) Diag(AttrLoc, diag::err_mode_wrong_type); } else { if (!OldElemTy->isFloatingType()) Diag(AttrLoc, diag::err_mode_wrong_type); } QualType NewElemTy; if (IntegerMode) NewElemTy = Context.getIntTypeForBitwidth(DestWidth, OldElemTy->isSignedIntegerType()); else NewElemTy = Context.getRealTypeForBitwidth(DestWidth); if (NewElemTy.isNull()) { Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; return; } if (ComplexMode) { NewElemTy = Context.getComplexType(NewElemTy); } QualType NewTy = NewElemTy; if (VectorSize.getBoolValue()) { NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), VectorType::GenericVector); } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) { // Complex machine mode does not support base vector types. if (ComplexMode) { Diag(AttrLoc, diag::err_complex_mode_vector_type); return; } unsigned NumElements = Context.getTypeSize(OldElemTy) * OldVT->getNumElements() / Context.getTypeSize(NewElemTy); NewTy = Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); } if (NewTy.isNull()) { Diag(AttrLoc, diag::err_mode_wrong_type); return; } // Install the new type. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) ED->setIntegerType(NewTy); else cast<ValueDecl>(D)->setType(NewTy); D->addAttr(::new (Context) ModeAttr(AttrRange, Context, Name, SpellingListIndex)); } static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) { D->addAttr(::new (S.Context) NoDebugAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex) { if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident; Diag(Optnone->getLocation(), diag::note_conflicting_attribute); return nullptr; } if (D->hasAttr<AlwaysInlineAttr>()) return nullptr; return ::new (Context) AlwaysInlineAttr(Range, Context, AttrSpellingListIndex); } CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex) { if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident)) return nullptr; return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex); } InternalLinkageAttr * Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex) { if (auto VD = dyn_cast<VarDecl>(D)) { // Attribute applies to Var but not any subclass of it (like ParmVar, // ImplicitParm or VarTemplateSpecialization). if (VD->getKind() != Decl::Var) { Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type) << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : ExpectedVariableOrFunction); return nullptr; } // Attribute does not apply to non-static local variables. if (VD->hasLocalStorage()) { Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); return nullptr; } } if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident)) return nullptr; return ::new (Context) InternalLinkageAttr(Range, Context, AttrSpellingListIndex); } MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex) { if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'"; Diag(Optnone->getLocation(), diag::note_conflicting_attribute); return nullptr; } if (D->hasAttr<MinSizeAttr>()) return nullptr; return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex); } OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex) { if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; Diag(Range.getBegin(), diag::note_conflicting_attribute); D->dropAttr<AlwaysInlineAttr>(); } if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; Diag(Range.getBegin(), diag::note_conflicting_attribute); D->dropAttr<MinSizeAttr>(); } if (D->hasAttr<OptimizeNoneAttr>()) return nullptr; return ::new (Context) OptimizeNoneAttr(Range, Context, AttrSpellingListIndex); } static void handleAlwaysInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(), Attr.getName())) return; if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr( D, Attr.getRange(), Attr.getName(), Attr.getAttributeSpellingListIndex())) D->addAttr(Inline); } static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (MinSizeAttr *MinSize = S.mergeMinSizeAttr( D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) D->addAttr(MinSize); } static void handleOptimizeNoneAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr( D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) D->addAttr(Optnone); } static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(), Attr.getName())) return; auto *VD = cast<VarDecl>(D); if (!VD->hasGlobalStorage()) { S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant); return; } D->addAttr(::new (S.Context) CUDAConstantAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(), Attr.getName())) return; auto *VD = cast<VarDecl>(D); // extern __shared__ is only allowed on arrays with no length (e.g. // "int x[]"). if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) { S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD; return; } if (S.getLangOpts().CUDA && VD->hasLocalStorage() && S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared) << S.CurrentCUDATarget()) return; D->addAttr(::new (S.Context) CUDASharedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(), Attr.getName()) || checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(), Attr.getName())) { return; } FunctionDecl *FD = cast<FunctionDecl>(D); if (!FD->getReturnType()->isVoidType()) { SourceRange RTRange = FD->getReturnTypeSourceRange(); S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) << FD->getType() << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") : FixItHint()); return; } if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) { if (Method->isInstance()) { S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method) << Method; return; } S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method; } // Only warn for "inline" when compiling for host, to cut down on noise. if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD; D->addAttr(::new (S.Context) CUDAGlobalAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) { FunctionDecl *Fn = cast<FunctionDecl>(D); if (!Fn->isInlineSpecified()) { S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); return; } D->addAttr(::new (S.Context) GNUInlineAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (hasDeclarator(D)) return; // Diagnostic is emitted elsewhere: here we store the (valid) Attr // in the Decl node for syntactic reasoning, e.g., pretty-printing. CallingConv CC; if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr)) return; if (!isa<ObjCMethodDecl>(D)) { S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunctionOrMethod; return; } switch (Attr.getKind()) { case AttributeList::AT_FastCall: D->addAttr(::new (S.Context) FastCallAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_StdCall: D->addAttr(::new (S.Context) StdCallAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_ThisCall: D->addAttr(::new (S.Context) ThisCallAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_CDecl: D->addAttr(::new (S.Context) CDeclAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_Pascal: D->addAttr(::new (S.Context) PascalAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_SwiftCall: D->addAttr(::new (S.Context) SwiftCallAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_VectorCall: D->addAttr(::new (S.Context) VectorCallAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_MSABI: D->addAttr(::new (S.Context) MSABIAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_SysVABI: D->addAttr(::new (S.Context) SysVABIAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_RegCall: D->addAttr(::new (S.Context) RegCallAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_Pcs: { PcsAttr::PCSType PCS; switch (CC) { case CC_AAPCS: PCS = PcsAttr::AAPCS; break; case CC_AAPCS_VFP: PCS = PcsAttr::AAPCS_VFP; break; default: llvm_unreachable("unexpected calling convention in pcs attribute"); } D->addAttr(::new (S.Context) PcsAttr(Attr.getRange(), S.Context, PCS, Attr.getAttributeSpellingListIndex())); return; } case AttributeList::AT_IntelOclBicc: D->addAttr(::new (S.Context) IntelOclBiccAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_PreserveMost: D->addAttr(::new (S.Context) PreserveMostAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_PreserveAll: D->addAttr(::new (S.Context) PreserveAllAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; default: llvm_unreachable("unexpected attribute kind"); } } static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return; std::vector<StringRef> DiagnosticIdentifiers; for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { StringRef RuleName; if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr)) return; // FIXME: Warn if the rule name is unknown. This is tricky because only // clang-tidy knows about available rules. DiagnosticIdentifiers.push_back(RuleName); } D->addAttr(::new (S.Context) SuppressAttr( Attr.getRange(), S.Context, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex())); } bool Sema::CheckCallingConvAttr(const AttributeList &Attrs, CallingConv &CC, const FunctionDecl *FD) { if (Attrs.isInvalid()) return true; if (Attrs.hasProcessingCache()) { CC = (CallingConv) Attrs.getProcessingCache(); return false; } unsigned ReqArgs = Attrs.getKind() == AttributeList::AT_Pcs ? 1 : 0; if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) { Attrs.setInvalid(); return true; } // TODO: diagnose uses of these conventions on the wrong target. switch (Attrs.getKind()) { case AttributeList::AT_CDecl: CC = CC_C; break; case AttributeList::AT_FastCall: CC = CC_X86FastCall; break; case AttributeList::AT_StdCall: CC = CC_X86StdCall; break; case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break; case AttributeList::AT_Pascal: CC = CC_X86Pascal; break; case AttributeList::AT_SwiftCall: CC = CC_Swift; break; case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break; case AttributeList::AT_RegCall: CC = CC_X86RegCall; break; case AttributeList::AT_MSABI: CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : CC_Win64; break; case AttributeList::AT_SysVABI: CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : CC_C; break; case AttributeList::AT_Pcs: { StringRef StrRef; if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) { Attrs.setInvalid(); return true; } if (StrRef == "aapcs") { CC = CC_AAPCS; break; } else if (StrRef == "aapcs-vfp") { CC = CC_AAPCS_VFP; break; } Attrs.setInvalid(); Diag(Attrs.getLoc(), diag::err_invalid_pcs); return true; } case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break; case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break; case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break; default: llvm_unreachable("unexpected attribute kind"); } const TargetInfo &TI = Context.getTargetInfo(); TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC); if (A != TargetInfo::CCCR_OK) { if (A == TargetInfo::CCCR_Warning) Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs.getName(); // This convention is not valid for the target. Use the default function or // method calling convention. bool IsCXXMethod = false, IsVariadic = false; if (FD) { IsCXXMethod = FD->isCXXInstanceMember(); IsVariadic = FD->isVariadic(); } CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); } Attrs.setProcessingCache((unsigned) CC); return false; } /// Pointer-like types in the default address space. static bool isValidSwiftContextType(QualType type) { if (!type->hasPointerRepresentation()) return type->isDependentType(); return type->getPointeeType().getAddressSpace() == LangAS::Default; } /// Pointers and references in the default address space. static bool isValidSwiftIndirectResultType(QualType type) { if (auto ptrType = type->getAs<PointerType>()) { type = ptrType->getPointeeType(); } else if (auto refType = type->getAs<ReferenceType>()) { type = refType->getPointeeType(); } else { return type->isDependentType(); } return type.getAddressSpace() == LangAS::Default; } /// Pointers and references to pointers in the default address space. static bool isValidSwiftErrorResultType(QualType type) { if (auto ptrType = type->getAs<PointerType>()) { type = ptrType->getPointeeType(); } else if (auto refType = type->getAs<ReferenceType>()) { type = refType->getPointeeType(); } else { return type->isDependentType(); } if (!type.getQualifiers().empty()) return false; return isValidSwiftContextType(type); } static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &Attrs, ParameterABI Abi) { S.AddParameterABIAttr(Attrs.getRange(), D, Abi, Attrs.getAttributeSpellingListIndex()); } void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi, unsigned spellingIndex) { QualType type = cast<ParmVarDecl>(D)->getType(); if (auto existingAttr = D->getAttr<ParameterABIAttr>()) { if (existingAttr->getABI() != abi) { Diag(range.getBegin(), diag::err_attributes_are_not_compatible) << getParameterABISpelling(abi) << existingAttr; Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); return; } } switch (abi) { case ParameterABI::Ordinary: llvm_unreachable("explicit attribute for ordinary parameter ABI?"); case ParameterABI::SwiftContext: if (!isValidSwiftContextType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; } D->addAttr(::new (Context) SwiftContextAttr(range, Context, spellingIndex)); return; case ParameterABI::SwiftErrorResult: if (!isValidSwiftErrorResultType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type; } D->addAttr(::new (Context) SwiftErrorResultAttr(range, Context, spellingIndex)); return; case ParameterABI::SwiftIndirectResult: if (!isValidSwiftIndirectResultType(type)) { Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) << getParameterABISpelling(abi) << /*pointer*/ 0 << type; } D->addAttr(::new (Context) SwiftIndirectResultAttr(range, Context, spellingIndex)); return; } llvm_unreachable("bad parameter ABI attribute"); } /// Checks a regparm attribute, returning true if it is ill-formed and /// otherwise setting numParams to the appropriate value. bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) { if (Attr.isInvalid()) return true; if (!checkAttributeNumArgs(*this, Attr, 1)) { Attr.setInvalid(); return true; } uint32_t NP; Expr *NumParamsExpr = Attr.getArgAsExpr(0); if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) { Attr.setInvalid(); return true; } if (Context.getTargetInfo().getRegParmMax() == 0) { Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform) << NumParamsExpr->getSourceRange(); Attr.setInvalid(); return true; } numParams = NP; if (numParams > Context.getTargetInfo().getRegParmMax()) { Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number) << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); Attr.setInvalid(); return true; } return false; } // Checks whether an argument of launch_bounds attribute is // acceptable, performs implicit conversion to Rvalue, and returns // non-nullptr Expr result on success. Otherwise, it returns nullptr // and may output an error. static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, const CUDALaunchBoundsAttr &Attr, const unsigned Idx) { if (S.DiagnoseUnexpandedParameterPack(E)) return nullptr; // Accept template arguments for now as they depend on something else. // We'll get to check them when they eventually get instantiated. if (E->isValueDependent()) return E; llvm::APSInt I(64); if (!E->isIntegerConstantExpr(I, S.Context)) { S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); return nullptr; } // Make sure we can fit it in 32 bits. if (!I.isIntN(32)) { S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) << 32 << /* Unsigned */ 1; return nullptr; } if (I < 0) S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) << &Attr << Idx << E->getSourceRange(); // We may need to perform implicit conversion of the argument. InitializedEntity Entity = InitializedEntity::InitializeParameter( S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false); ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E); assert(!ValArg.isInvalid() && "Unexpected PerformCopyInitialization() failure."); return ValArg.getAs<Expr>(); } void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, Expr *MinBlocks, unsigned SpellingListIndex) { CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex); MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0); if (MaxThreads == nullptr) return; if (MinBlocks) { MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1); if (MinBlocks == nullptr) return; } D->addAttr(::new (Context) CUDALaunchBoundsAttr( AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex)); } static void handleLaunchBoundsAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1) || !checkAttributeAtMostNumArgs(S, Attr, 2)) return; S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr, Attr.getAttributeSpellingListIndex()); } static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!Attr.isArgIdent(0)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier; return; } if (!checkAttributeNumArgs(S, Attr, 3)) return; IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident; if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunctionOrMethod; return; } uint64_t ArgumentIdx; if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1), ArgumentIdx)) return; uint64_t TypeTagIdx; if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2), TypeTagIdx)) return; bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag"); if (IsPointer) { // Ensure that buffer has a pointer type. QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx); if (!BufferTy->isPointerType()) { S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) << Attr.getName() << 0; } } D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind, ArgumentIdx, TypeTagIdx, IsPointer, Attr.getAttributeSpellingListIndex())); } static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!Attr.isArgIdent(0)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) << Attr.getName() << 1 << AANT_ArgumentIdentifier; return; } if (!checkAttributeNumArgs(S, Attr, 1)) return; if (!isa<VarDecl>(D)) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) << Attr.getName() << ExpectedVariable; return; } IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident; TypeSourceInfo *MatchingCTypeLoc = nullptr; S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc); assert(MatchingCTypeLoc && "no type source info for attribute argument"); D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind, MatchingCTypeLoc, Attr.getLayoutCompatible(), Attr.getMustBeNull(), Attr.getAttributeSpellingListIndex())); } static void handleXRayLogArgsAttr(Sema &S, Decl *D, const AttributeList &Attr) { uint64_t ArgCount; if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0), ArgCount, true /* AllowImplicitThis*/)) return; // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1. D->addAttr(::new (S.Context) XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount, Attr.getAttributeSpellingListIndex())); } //===----------------------------------------------------------------------===// // Checker-specific attribute handlers. //===----------------------------------------------------------------------===// static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) { return type->isDependentType() || type->isObjCRetainableType(); } static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) { return type->isDependentType() || type->isObjCObjectPointerType() || S.Context.isObjCNSObjectType(type); } static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) { return type->isDependentType() || type->isPointerType() || isValidSubjectOfNSAttribute(S, type); } static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) { S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(), Attr.getKind() == AttributeList::AT_NSConsumed, /*template instantiation*/ false); } void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D, unsigned spellingIndex, bool isNSConsumed, bool isTemplateInstantiation) { ParmVarDecl *param = cast<ParmVarDecl>(D); bool typeOK; if (isNSConsumed) { typeOK = isValidSubjectOfNSAttribute(*this, param->getType()); } else { typeOK = isValidSubjectOfCFAttribute(*this, param->getType()); } if (!typeOK) { // These attributes are normally just advisory, but in ARC, ns_consumed // is significant. Allow non-dependent code to contain inappropriate // attributes even in ARC, but require template instantiations to be // set up correctly. Diag(D->getLocStart(), (isTemplateInstantiation && isNSConsumed && getLangOpts().ObjCAutoRefCount ? diag::err_ns_attribute_wrong_parameter_type : diag::warn_ns_attribute_wrong_parameter_type)) << attrRange << (isNSConsumed ? "ns_consumed" : "cf_consumed") << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1); return; } if (isNSConsumed) param->addAttr(::new (Context) NSConsumedAttr(attrRange, Context, spellingIndex)); else param->addAttr(::new (Context) CFConsumedAttr(attrRange, Context, spellingIndex)); } bool Sema::checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type) { if (isValidSubjectOfNSReturnsRetainedAttribute(type)) return false; Diag(loc, diag::warn_ns_attribute_wrong_return_type) << "'ns_returns_retained'" << 0 << 0; return true; } static void handleNSReturnsRetainedAttr(Sema &S, Decl *D, const AttributeList &Attr) { QualType returnType; if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) returnType = MD->getReturnType(); else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && (Attr.getKind() == AttributeList::AT_NSReturnsRetained)) return; // ignore: was handled as a type attribute else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) returnType = PD->getType(); else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) returnType = FD->getReturnType(); else if (auto *Param = dyn_cast<ParmVarDecl>(D)) { returnType = Param->getType()->getPointeeType(); if (returnType.isNull()) { S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) << Attr.getName() << /*pointer-to-CF*/2 << Attr.getRange(); return; } } else if (Attr.isUsedAsTypeAttr()) { return; } else { AttributeDeclKind ExpectedDeclKind; switch (Attr.getKind()) { default: llvm_unreachable("invalid ownership attribute"); case AttributeList::AT_NSReturnsRetained: case AttributeList::AT_NSReturnsAutoreleased: case AttributeList::AT_NSReturnsNotRetained: ExpectedDeclKind = ExpectedFunctionOrMethod; break; case AttributeList::AT_CFReturnsRetained: case AttributeList::AT_CFReturnsNotRetained: ExpectedDeclKind = ExpectedFunctionMethodOrParameter; break; } S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type) << Attr.getRange() << Attr.getName() << ExpectedDeclKind; return; } bool typeOK; bool cf; switch (Attr.getKind()) { default: llvm_unreachable("invalid ownership attribute"); case AttributeList::AT_NSReturnsRetained: typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType); cf = false; break; case AttributeList::AT_NSReturnsAutoreleased: case AttributeList::AT_NSReturnsNotRetained: typeOK = isValidSubjectOfNSAttribute(S, returnType); cf = false; break; case AttributeList::AT_CFReturnsRetained: case AttributeList::AT_CFReturnsNotRetained: typeOK = isValidSubjectOfCFAttribute(S, returnType); cf = true; break; } if (!typeOK) { if (Attr.isUsedAsTypeAttr()) return; if (isa<ParmVarDecl>(D)) { S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) << Attr.getName() << /*pointer-to-CF*/2 << Attr.getRange(); } else { // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. enum : unsigned { Function, Method, Property } SubjectKind = Function; if (isa<ObjCMethodDecl>(D)) SubjectKind = Method; else if (isa<ObjCPropertyDecl>(D)) SubjectKind = Property; S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) << Attr.getName() << SubjectKind << cf << Attr.getRange(); } return; } switch (Attr.getKind()) { default: llvm_unreachable("invalid ownership attribute"); case AttributeList::AT_NSReturnsAutoreleased: D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_CFReturnsNotRetained: D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_NSReturnsNotRetained: D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_CFReturnsRetained: D->addAttr(::new (S.Context) CFReturnsRetainedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; case AttributeList::AT_NSReturnsRetained: D->addAttr(::new (S.Context) NSReturnsRetainedAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); return; }; } static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, const AttributeList &Attrs) { const int EP_ObjCMethod = 1; const int EP_ObjCProperty = 2; SourceLocation loc = Attrs.getLoc(); QualType resultType; if (isa<ObjCMethodDecl>(D)) resultType = cast<ObjCMethodDecl>(D)->getReturnType(); else resultType = cast<ObjCPropertyDecl>(D)->getType(); if (!resultType->isReferenceType() && (!resultType->isPointerType() || resultType->isObjCRetainableType())) { S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) << SourceRange(loc) << Attrs.getName() << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) << /*non-retainable pointer*/ 2; // Drop the attribute. return; } D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr( Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); } static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, const AttributeList &Attrs) { ObjCMethodDecl *method = cast<ObjCMethodDecl>(D); DeclContext *DC = method->getDeclContext(); if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) << Attrs.getName() << 0; S.Diag(PDecl->getLocation(), diag::note_protocol_decl); return; } if (method->getMethodFamily() == OMF_dealloc) { S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) << Attrs.getName() << 1; return; } method->addAttr(::new (S.Context) ObjCRequiresSuperAttr(Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); } static void handleCFAuditedTransferAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(), Attr.getName())) return; D->addAttr(::new (S.Context) CFAuditedTransferAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleCFUnknownTransferAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(), Attr.getName())) return; D->addAttr(::new (S.Context) CFUnknownTransferAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D, const AttributeList &Attr) { IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; if (!Parm) { S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; return; } // Typedefs only allow objc_bridge(id) and have some additional checking. if (auto TD = dyn_cast<TypedefNameDecl>(D)) { if (!Parm->Ident->isStr("id")) { S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id) << Attr.getName(); return; } // Only allow 'cv void *'. QualType T = TD->getUnderlyingType(); if (!T->isVoidPointerType()) { S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); return; } } D->addAttr(::new (S.Context) ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident, Attr.getAttributeSpellingListIndex())); } static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D, const AttributeList &Attr) { IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; if (!Parm) { S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; return; } D->addAttr(::new (S.Context) ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident, Attr.getAttributeSpellingListIndex())); } static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D, const AttributeList &Attr) { IdentifierInfo *RelatedClass = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr; if (!RelatedClass) { S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; return; } IdentifierInfo *ClassMethod = Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr; IdentifierInfo *InstanceMethod = Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr; D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass, ClassMethod, InstanceMethod, Attr.getAttributeSpellingListIndex())); } static void handleObjCDesignatedInitializer(Sema &S, Decl *D, const AttributeList &Attr) { ObjCInterfaceDecl *IFace; if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D->getDeclContext())) IFace = CatDecl->getClassInterface(); else IFace = cast<ObjCInterfaceDecl>(D->getDeclContext()); if (!IFace) return; IFace->setHasDesignatedInitializers(); D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleObjCRuntimeName(Sema &S, Decl *D, const AttributeList &Attr) { StringRef MetaDataName; if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName)) return; D->addAttr(::new (S.Context) ObjCRuntimeNameAttr(Attr.getRange(), S.Context, MetaDataName, Attr.getAttributeSpellingListIndex())); } // When a user wants to use objc_boxable with a union or struct // but they don't have access to the declaration (legacy/third-party code) // then they can 'enable' this feature with a typedef: // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) { bool notify = false; RecordDecl *RD = dyn_cast<RecordDecl>(D); if (RD && RD->getDefinition()) { RD = RD->getDefinition(); notify = true; } if (RD) { ObjCBoxableAttr *BoxableAttr = ::new (S.Context) ObjCBoxableAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()); RD->addAttr(BoxableAttr); if (notify) { // we need to notify ASTReader/ASTWriter about // modification of existing declaration if (ASTMutationListener *L = S.getASTMutationListener()) L->AddedAttributeToRecord(BoxableAttr, RD); } } } static void handleObjCOwnershipAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (hasDeclarator(D)) return; S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type) << Attr.getRange() << Attr.getName() << ExpectedVariable; } static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, const AttributeList &Attr) { ValueDecl *vd = cast<ValueDecl>(D); QualType type = vd->getType(); if (!type->isDependentType() && !type->isObjCLifetimeType()) { S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type) << type; return; } Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); // If we have no lifetime yet, check the lifetime we're presumably // going to infer. if (lifetime == Qualifiers::OCL_None && !type->isDependentType()) lifetime = type->getObjCARCImplicitLifetime(); switch (lifetime) { case Qualifiers::OCL_None: assert(type->isDependentType() && "didn't infer lifetime for non-dependent type?"); break; case Qualifiers::OCL_Weak: // meaningful case Qualifiers::OCL_Strong: // meaningful break; case Qualifiers::OCL_ExplicitNone: case Qualifiers::OCL_Autoreleasing: S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless) << (lifetime == Qualifiers::OCL_Autoreleasing); break; } D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } //===----------------------------------------------------------------------===// // Microsoft specific attribute handlers. //===----------------------------------------------------------------------===// UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex, StringRef Uuid) { if (const auto *UA = D->getAttr<UuidAttr>()) { if (UA->getGuid().equals_lower(Uuid)) return nullptr; Diag(UA->getLocation(), diag::err_mismatched_uuid); Diag(Range.getBegin(), diag::note_previous_uuid); D->dropAttr<UuidAttr>(); } return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex); } static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!S.LangOpts.CPlusPlus) { S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) << Attr.getName() << AttributeLangSupport::C; return; } StringRef StrRef; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc)) return; // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') StrRef = StrRef.drop_front().drop_back(); // Validate GUID length. if (StrRef.size() != 36) { S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); return; } for (unsigned i = 0; i < 36; ++i) { if (i == 8 || i == 13 || i == 18 || i == 23) { if (StrRef[i] != '-') { S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); return; } } else if (!isHexDigit(StrRef[i])) { S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); return; } } // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's // the only thing in the [] list, the [] too), and add an insertion of // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas // separating attributes nor of the [ and the ] are in the AST. // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc" // on cfe-dev. if (Attr.isMicrosoftAttribute()) // Check for [uuid(...)] spelling. S.Diag(Attr.getLoc(), diag::warn_atl_uuid_deprecated); UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(), Attr.getAttributeSpellingListIndex(), StrRef); if (UA) D->addAttr(UA); } static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!S.LangOpts.CPlusPlus) { S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) << Attr.getName() << AttributeLangSupport::C; return; } MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( D, Attr.getRange(), /*BestCase=*/true, Attr.getAttributeSpellingListIndex(), (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling()); if (IA) { D->addAttr(IA); S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); } } static void handleDeclspecThreadAttr(Sema &S, Decl *D, const AttributeList &Attr) { VarDecl *VD = cast<VarDecl>(D); if (!S.Context.getTargetInfo().isTLSSupported()) { S.Diag(Attr.getLoc(), diag::err_thread_unsupported); return; } if (VD->getTSCSpec() != TSCS_unspecified) { S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable); return; } if (VD->hasLocalStorage()) { S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; return; } VD->addAttr(::new (S.Context) ThreadAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<StringRef, 4> Tags; for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { StringRef Tag; if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag)) return; Tags.push_back(Tag); } if (const auto *NS = dyn_cast<NamespaceDecl>(D)) { if (!NS->isInline()) { S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; return; } if (NS->isAnonymousNamespace()) { S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; return; } if (Attr.getNumArgs() == 0) Tags.push_back(NS->getName()); } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return; // Store tags sorted and without duplicates. std::sort(Tags.begin(), Tags.end()); Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); D->addAttr(::new (S.Context) AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(), Attr.getAttributeSpellingListIndex())); } static void handleARMInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Check the attribute arguments. if (Attr.getNumArgs() > 1) { S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << Attr.getName() << 1; return; } StringRef Str; SourceLocation ArgLoc; if (Attr.getNumArgs() == 0) Str = ""; else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) return; ARMInterruptAttr::InterruptType Kind; if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) << Attr.getName() << Str << ArgLoc; return; } unsigned Index = Attr.getAttributeSpellingListIndex(); D->addAttr(::new (S.Context) ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index)); } static void handleMSP430InterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeNumArgs(S, Attr, 1)) return; if (!Attr.isArgExpr(0)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentIntegerConstant; return; } // FIXME: Check for decl - it should be void ()(void). Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); llvm::APSInt NumParams(32); if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() << AANT_ArgumentIntegerConstant << NumParamsExpr->getSourceRange(); return; } unsigned Num = NumParams.getLimitedValue(255); if ((Num & 1) || Num > 30) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) << Attr.getName() << (int)NumParams.getSExtValue() << NumParamsExpr->getSourceRange(); return; } D->addAttr(::new (S.Context) MSP430InterruptAttr(Attr.getLoc(), S.Context, Num, Attr.getAttributeSpellingListIndex())); D->addAttr(UsedAttr::CreateImplicit(S.Context)); } static void handleMipsInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Only one optional argument permitted. if (Attr.getNumArgs() > 1) { S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << Attr.getName() << 1; return; } StringRef Str; SourceLocation ArgLoc; if (Attr.getNumArgs() == 0) Str = ""; else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) return; // Semantic checks for a function with the 'interrupt' attribute for MIPS: // a) Must be a function. // b) Must have no parameters. // c) Must have the 'void' return type. // d) Cannot have the 'mips16' attribute, as that instruction set // lacks the 'eret' instruction. // e) The attribute itself must either have no argument or one of the // valid interrupt types, see [MipsInterruptDocs]. if (!isFunctionOrMethod(D)) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'interrupt'" << ExpectedFunctionOrMethod; return; } if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) << 0; return; } if (!getFunctionOrMethodResultType(D)->isVoidType()) { S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) << 1; return; } if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(), Attr.getName())) return; MipsInterruptAttr::InterruptType Kind; if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) << Attr.getName() << "'" + std::string(Str) + "'"; return; } D->addAttr(::new (S.Context) MipsInterruptAttr( Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex())); } static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Semantic checks for a function with the 'interrupt' attribute. // a) Must be a function. // b) Must have the 'void' return type. // c) Must take 1 or 2 arguments. // d) The 1st argument must be a pointer. // e) The 2nd argument (if any) must be an unsigned integer. if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || CXXMethodDecl::isStaticOverloadedOperator( cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) { S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunctionWithProtoType; return; } // Interrupt handler must have void return type. if (!getFunctionOrMethodResultType(D)->isVoidType()) { S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), diag::err_anyx86_interrupt_attribute) << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 ? 0 : 1) << 0; return; } // Interrupt handler must have 1 or 2 parameters. unsigned NumParams = getFunctionOrMethodNumParams(D); if (NumParams < 1 || NumParams > 2) { S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute) << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 ? 0 : 1) << 1; return; } // The first argument must be a pointer. if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), diag::err_anyx86_interrupt_attribute) << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 ? 0 : 1) << 2; return; } // The second argument, if present, must be an unsigned integer. unsigned TypeSize = S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 ? 64 : 32; if (NumParams == 2 && (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), diag::err_anyx86_interrupt_attribute) << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 ? 0 : 1) << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); return; } D->addAttr(::new (S.Context) AnyX86InterruptAttr( Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex())); D->addAttr(UsedAttr::CreateImplicit(S.Context)); } static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!isFunctionOrMethod(D)) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'interrupt'" << ExpectedFunction; return; } if (!checkAttributeNumArgs(S, Attr, 0)) return; handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr); } static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!isFunctionOrMethod(D)) { S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) << "'signal'" << ExpectedFunction; return; } if (!checkAttributeNumArgs(S, Attr, 0)) return; handleSimpleAttribute<AVRSignalAttr>(S, D, Attr); } static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Dispatch the interrupt attribute based on the current target. switch (S.Context.getTargetInfo().getTriple().getArch()) { case llvm::Triple::msp430: handleMSP430InterruptAttr(S, D, Attr); break; case llvm::Triple::mipsel: case llvm::Triple::mips: handleMipsInterruptAttr(S, D, Attr); break; case llvm::Triple::x86: case llvm::Triple::x86_64: handleAnyX86InterruptAttr(S, D, Attr); break; case llvm::Triple::avr: handleAVRInterruptAttr(S, D, Attr); break; default: handleARMInterruptAttr(S, D, Attr); break; } } static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t Min = 0; Expr *MinExpr = Attr.getArgAsExpr(0); if (!checkUInt32Argument(S, Attr, MinExpr, Min)) return; uint32_t Max = 0; Expr *MaxExpr = Attr.getArgAsExpr(1); if (!checkUInt32Argument(S, Attr, MaxExpr, Max)) return; if (Min == 0 && Max != 0) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid) << Attr.getName() << 0; return; } if (Min > Max) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid) << Attr.getName() << 1; return; } D->addAttr(::new (S.Context) AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max, Attr.getAttributeSpellingListIndex())); } static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t Min = 0; Expr *MinExpr = Attr.getArgAsExpr(0); if (!checkUInt32Argument(S, Attr, MinExpr, Min)) return; uint32_t Max = 0; if (Attr.getNumArgs() == 2) { Expr *MaxExpr = Attr.getArgAsExpr(1); if (!checkUInt32Argument(S, Attr, MaxExpr, Max)) return; } if (Min == 0 && Max != 0) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid) << Attr.getName() << 0; return; } if (Max != 0 && Min > Max) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid) << Attr.getName() << 1; return; } D->addAttr(::new (S.Context) AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max, Attr.getAttributeSpellingListIndex())); } static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t NumSGPR = 0; Expr *NumSGPRExpr = Attr.getArgAsExpr(0); if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR)) return; D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR, Attr.getAttributeSpellingListIndex())); } static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t NumVGPR = 0; Expr *NumVGPRExpr = Attr.getArgAsExpr(0); if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR)) return; D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR, Attr.getAttributeSpellingListIndex())); } static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, const AttributeList& Attr) { // If we try to apply it to a function pointer, don't warn, but don't // do anything, either. It doesn't matter anyway, because there's nothing // special about calling a force_align_arg_pointer function. ValueDecl *VD = dyn_cast<ValueDecl>(D); if (VD && VD->getType()->isFunctionPointerType()) return; // Also don't warn on function pointer typedefs. TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || TD->getUnderlyingType()->isFunctionType())) return; // Attribute can only be applied to function types. if (!isa<FunctionDecl>(D)) { S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunction; return; } D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) { uint32_t Version; Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version)) return; // TODO: Investigate what happens with the next major version of MSVC. if (Version != LangOptions::MSVC2015) { S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) << Attr.getName() << Version << VersionExpr->getSourceRange(); return; } D->addAttr(::new (S.Context) LayoutVersionAttr(Attr.getRange(), S.Context, Version, Attr.getAttributeSpellingListIndex())); } DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex) { if (D->hasAttr<DLLExportAttr>()) { Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'"; return nullptr; } if (D->hasAttr<DLLImportAttr>()) return nullptr; return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex); } DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex) { if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; D->dropAttr<DLLImportAttr>(); } if (D->hasAttr<DLLExportAttr>()) return nullptr; return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex); } static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) { if (isa<ClassTemplatePartialSpecializationDecl>(D) && S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A.getName(); return; } if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport && !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { // MinGW doesn't allow dllimport on inline functions. S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) << A.getName(); return; } } if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && MD->getParent()->isLambda()) { S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName(); return; } } unsigned Index = A.getAttributeSpellingListIndex(); Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index) : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index); if (NewAttr) D->addAttr(NewAttr); } MSInheritanceAttr * Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, unsigned AttrSpellingListIndex, MSInheritanceAttr::Spelling SemanticSpelling) { if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { if (IA->getSemanticSpelling() == SemanticSpelling) return nullptr; Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) << 1 /*previous declaration*/; Diag(Range.getBegin(), diag::note_previous_ms_inheritance); D->dropAttr<MSInheritanceAttr>(); } CXXRecordDecl *RD = cast<CXXRecordDecl>(D); if (RD->hasDefinition()) { if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase, SemanticSpelling)) { return nullptr; } } else { if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) << 1 /*partial specialization*/; return nullptr; } if (RD->getDescribedClassTemplate()) { Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) << 0 /*primary template*/; return nullptr; } } return ::new (Context) MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex); } static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { // The capability attributes take a single string parameter for the name of // the capability they represent. The lockable attribute does not take any // parameters. However, semantically, both attributes represent the same // concept, and so they use the same semantic attribute. Eventually, the // lockable attribute will be removed. // // For backward compatibility, any capability which has no specified string // literal will be considered a "mutex." StringRef N("mutex"); SourceLocation LiteralLoc; if (Attr.getKind() == AttributeList::AT_Capability && !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc)) return; // Currently, there are only two names allowed for a capability: role and // mutex (case insensitive). Diagnose other capability names. if (!N.equals_lower("mutex") && !N.equals_lower("role")) S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N, Attr.getAttributeSpellingListIndex())); } static void handleAssertCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 1> Args; if (!checkLockFunAttrCommon(S, D, Attr, Args)) return; D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context, Args.data(), Args.size(), Attr.getAttributeSpellingListIndex())); } static void handleAcquireCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 1> Args; if (!checkLockFunAttrCommon(S, D, Attr, Args)) return; D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(), S.Context, Args.data(), Args.size(), Attr.getAttributeSpellingListIndex())); } static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { SmallVector<Expr*, 2> Args; if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) return; D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(), Args.size(), Attr.getAttributeSpellingListIndex())); } static void handleReleaseCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { // Check that all arguments are lockable objects. SmallVector<Expr *, 1> Args; checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true); D->addAttr(::new (S.Context) ReleaseCapabilityAttr( Attr.getRange(), S.Context, Args.data(), Args.size(), Attr.getAttributeSpellingListIndex())); } static void handleRequiresCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return; // check that all arguments are lockable objects SmallVector<Expr*, 1> Args; checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); if (Args.empty()) return; RequiresCapabilityAttr *RCA = ::new (S.Context) RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(), Args.size(), Attr.getAttributeSpellingListIndex()); D->addAttr(RCA); } static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (auto *NSD = dyn_cast<NamespaceDecl>(D)) { if (NSD->isAnonymousNamespace()) { S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace); // Do not want to attach the attribute to the namespace because that will // cause confusing diagnostic reports for uses of declarations within the // namespace. return; } } // Handle the cases where the attribute has a text message. StringRef Str, Replacement; if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) && !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) return; // Only support a single optional message for Declspec and CXX11. if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute()) checkAttributeAtMostNumArgs(S, Attr, 1); else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) && !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement)) return; if (!S.getLangOpts().CPlusPlus14) if (Attr.isCXX11Attribute() && !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu"))) S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName(); D->addAttr(::new (S.Context) DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement, Attr.getAttributeSpellingListIndex())); } static bool isGlobalVar(const Decl *D) { if (const auto *S = dyn_cast<VarDecl>(D)) return S->hasGlobalStorage(); return false; } static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return; std::vector<StringRef> Sanitizers; for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { StringRef SanitizerName; SourceLocation LiteralLoc; if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc)) return; if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0) S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; else if (isGlobalVar(D) && SanitizerName != "address") S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunctionOrMethod; Sanitizers.push_back(SanitizerName); } D->addAttr(::new (S.Context) NoSanitizeAttr( Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(), Attr.getAttributeSpellingListIndex())); } static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, const AttributeList &Attr) { StringRef AttrName = Attr.getName()->getName(); normalizeName(AttrName); StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName) .Case("no_address_safety_analysis", "address") .Case("no_sanitize_address", "address") .Case("no_sanitize_thread", "thread") .Case("no_sanitize_memory", "memory"); if (isGlobalVar(D) && SanitizerName != "address") S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << Attr.getName() << ExpectedFunction; D->addAttr(::new (S.Context) NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1, Attr.getAttributeSpellingListIndex())); } static void handleInternalLinkageAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(), Attr.getAttributeSpellingListIndex())) D->addAttr(Internal); } static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (S.LangOpts.OpenCLVersion != 200) S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version) << Attr.getName() << "2.0" << 0; else S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << Attr.getName() << "2.0"; } /// Handles semantic checking for features that are common to all attributes, /// such as checking whether a parameter was properly specified, or the correct /// number of arguments were passed, etc. static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D, const AttributeList &Attr) { // Several attributes carry different semantics than the parsing requires, so // those are opted out of the common argument checks. // // We also bail on unknown and ignored attributes because those are handled // as part of the target-specific handling logic. if (Attr.getKind() == AttributeList::UnknownAttribute) return false; // Check whether the attribute requires specific language extensions to be // enabled. if (!Attr.diagnoseLangOpts(S)) return true; // Check whether the attribute appertains to the given subject. if (!Attr.diagnoseAppertainsTo(S, D)) return true; if (Attr.hasCustomParsing()) return false; if (Attr.getMinArgs() == Attr.getMaxArgs()) { // If there are no optional arguments, then checking for the argument count // is trivial. if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs())) return true; } else { // There are optional arguments, so checking is slightly more involved. if (Attr.getMinArgs() && !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs())) return true; else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() && !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs())) return true; } return false; } static void handleOpenCLAccessAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; // Check if there is only one access qualifier. if (D->hasAttr<OpenCLAccessAttr>()) { S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers) << D->getSourceRange(); D->setInvalidDecl(true); return; } // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an // image object can be read and written. // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe // object. Using the read_write (or __read_write) qualifier with the pipe // qualifier is a compilation error. if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) { const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); if (Attr.getName()->getName().find("read_write") != StringRef::npos) { if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) { S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write) << Attr.getName() << PDecl->getType() << DeclTy->isImageType(); D->setInvalidDecl(true); return; } } } D->addAttr(::new (S.Context) OpenCLAccessAttr( Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); } static void handleFPGASignalNameAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGASignalNameAttr>(S, D, Attr.getRange(), Attr.getName(), true)) { return; } auto Name = Attr.getArgAsIdent(0)->Ident->getName(); D->addAttr(::new (S.Context) FPGASignalNameAttr( Attr.getRange(), S.Context, Name, Attr.getAttributeSpellingListIndex())); } static void handleFPGADataFootPrintHintAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGADataFootPrintHintAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } Expr *Depth = Attr.getArgAsExpr(0); if (S.CheckFPGADataFootPrintHintExprs(Depth, Attr.getLoc(), Attr.getName()->getName())) { D->setInvalidDecl(); return; } D->addAttr(::new (S.Context) FPGADataFootPrintHintAttr( Attr.getRange(), S.Context, Depth, Attr.getAttributeSpellingListIndex())); } static void handleFPGAMaxiMaxWidenBitwidthAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGAMaxiMaxWidenBitwidthAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } Expr *MaxWidenBitwidth = Attr.getArgAsExpr(0); if (S.CheckFPGAMaxiMaxWidenBitwidthExprs(MaxWidenBitwidth, Attr.getLoc(), Attr.getName()->getName())) { D->setInvalidDecl(); return; } D->addAttr(::new (S.Context) FPGAMaxiMaxWidenBitwidthAttr( Attr.getRange(), S.Context, MaxWidenBitwidth, Attr.getAttributeSpellingListIndex())); } static void handleFPGAMaxiLatencyAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGAMaxiLatencyAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } Expr *Latency = Attr.getArgAsExpr(0); if (S.CheckFPGAMaxiLatencyExprs(Latency, Attr.getLoc(), Attr.getName()->getName())) { D->setInvalidDecl(); return; } D->addAttr(::new (S.Context) FPGAMaxiLatencyAttr( Attr.getRange(), S.Context, Latency, Attr.getAttributeSpellingListIndex())); } static void handleFPGAMaxiNumRdOutstandAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGAMaxiNumRdOutstandAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } Expr *NumRdOutstand = Attr.getArgAsExpr(0); if (S.CheckFPGAMaxiNumRdOutstandExprs(NumRdOutstand, Attr.getLoc(), Attr.getName()->getName())) { D->setInvalidDecl(); return; } D->addAttr(::new (S.Context) FPGAMaxiNumRdOutstandAttr( Attr.getRange(), S.Context, NumRdOutstand, Attr.getAttributeSpellingListIndex())); } static void handleFPGAMaxiNumWtOutstandAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGAMaxiNumWtOutstandAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } Expr *NumWtOutstand = Attr.getArgAsExpr(0); if (S.CheckFPGAMaxiNumWtOutstandExprs(NumWtOutstand, Attr.getLoc(), Attr.getName()->getName())) { D->setInvalidDecl(); return; } D->addAttr(::new (S.Context) FPGAMaxiNumWtOutstandAttr( Attr.getRange(), S.Context, NumWtOutstand, Attr.getAttributeSpellingListIndex())); } static void handleFPGAMaxiRdBurstLenAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGAMaxiRdBurstLenAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } Expr *RdBurstLen = Attr.getArgAsExpr(0); if (S.CheckFPGAMaxiRdBurstLenExprs(RdBurstLen, Attr.getLoc(), Attr.getName()->getName())) { D->setInvalidDecl(); return; } D->addAttr(::new (S.Context) FPGAMaxiRdBurstLenAttr( Attr.getRange(), S.Context, RdBurstLen, Attr.getAttributeSpellingListIndex())); } static void handleFPGAMaxiWtBurstLenAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGAMaxiWtBurstLenAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } Expr *WtBurstLen = Attr.getArgAsExpr(0); if (S.CheckFPGAMaxiWtBurstLenExprs(WtBurstLen, Attr.getLoc(), Attr.getName()->getName())) { D->setInvalidDecl(); return; } D->addAttr(::new (S.Context) FPGAMaxiWtBurstLenAttr( Attr.getRange(), S.Context, WtBurstLen, Attr.getAttributeSpellingListIndex())); } template <typename T> static bool CheckRedundantAdaptor(Decl *D, StringRef Name) { return llvm::any_of(D->specific_attrs<T>(), [Name](T *A) { if (Name != A->getName()) return false; // TODO: Check them to have the same parameters return true; }); } static void handleMAXIAdaptorAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (Attr.getNumArgs() != 6) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 6; return; } auto Name = Attr.getArgAsIdent(0)->Ident->getName(); if (Name.empty()) { S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type) << getAttrName(Attr) << 0 << AANT_ArgumentIdentifier << Attr.getArgAsIdent(0)->Loc; return; } if (CheckRedundantAdaptor<MAXIAdaptorAttr>(D, Name)) return; Expr *ReadOutStanding = Attr.getArgAsExpr(1); Expr *WriteOutStanding = Attr.getArgAsExpr(2); Expr *ReadBurstLength = Attr.getArgAsExpr(3); Expr *WriteBurstLength = Attr.getArgAsExpr(4); Expr *Latency = Attr.getArgAsExpr(5); if (S.CheckMAXIAdaptorExprs(ReadOutStanding, WriteOutStanding, ReadBurstLength, WriteBurstLength, Latency, Attr.getLoc(), Attr.getName()->getName())) return; D->addAttr(::new (S.Context) MAXIAdaptorAttr( Attr.getRange(), S.Context, Name, ReadOutStanding, WriteOutStanding, ReadBurstLength, WriteBurstLength, Latency, Attr.getAttributeSpellingListIndex())); } static void handleAXISAdaptorAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (Attr.getNumArgs() != 3) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 3; return; } auto Name = Attr.getArgAsIdent(0)->Ident->getName(); if (Name.empty()) { S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type) << getAttrName(Attr) << 0 << AANT_ArgumentIdentifier << Attr.getArgAsIdent(0)->Loc; return; } if (CheckRedundantAdaptor<AXISAdaptorAttr>(D, Name)) return; auto ModeStr = Attr.getArgAsIdent(1)->Ident->getName(); auto DirectionStr = Attr.getArgAsIdent(2)->Ident->getName(); AXISAdaptorAttr::AXISRegisterModeType RegMode = AXISAdaptorAttr::Both; AXISAdaptorAttr::DirectionType Direction = AXISAdaptorAttr::Unknown; if (!AXISAdaptorAttr::ConvertStrToAXISRegisterModeType(ModeStr, RegMode)) { S.Diag(Attr.getArgAsIdent(1)->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << ModeStr; return; } if (!AXISAdaptorAttr::ConvertStrToDirectionType(DirectionStr, Direction)) { S.Diag(Attr.getArgAsIdent(2)->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << DirectionStr; return; } D->addAttr(::new (S.Context) AXISAdaptorAttr( Attr.getRange(), S.Context, Name, RegMode, Direction, Attr.getAttributeSpellingListIndex())); } static void handleBRAMAdaptorAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (Attr.getNumArgs() != 5) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 5; return; } auto Name = Attr.getArgAsIdent(0)->Ident->getName(); if (Name.empty()) { S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type) << getAttrName(Attr) << 0 << AANT_ArgumentIdentifier << Attr.getArgAsIdent(0)->Loc; return; } if (CheckRedundantAdaptor<BRAMAdaptorAttr>(D, Name)) return; auto ModeStr = Attr.getArgAsIdent(1)->Ident->getName().lower(); BRAMAdaptorAttr::ModeType Mode = BRAMAdaptorAttr::BRAM; if (!BRAMAdaptorAttr::ConvertStrToModeType(ModeStr, Mode)) { S.Diag(Attr.getArgAsIdent(1)->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << ModeStr; return; } auto op_enum = Attr.getArgAsExpr(2); auto impl_enum = Attr.getArgAsExpr(3); Expr *Latency = Attr.getArgAsExpr(4); if (S.CheckBRAMAdaptorExprs(Latency, Attr.getLoc(), Attr.getName()->getName())) return; D->addAttr(::new (S.Context) BRAMAdaptorAttr( Attr.getRange(), S.Context, Name, Mode, op_enum, impl_enum, Latency, Attr.getAttributeSpellingListIndex())); } static void handleXCLReqdPipeDepthAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<XCLReqdPipeDepthAttr>(S, D, Attr.getRange(), Attr.getName(), true)) { return; } auto DepthExpr = Attr.getArgAsExpr(0); if (S.CheckXCLReqdPipeDepthExprs(DepthExpr, Attr.getLoc(), Attr.getName()->getName())) { D->setInvalidDecl(); return; } int64_t offIntVal = 0; //for Opencl Attribute, user may only specify only one depth argument , and off argument is missed //we need support it if (Attr.getNumArgs() == 2 ) { auto OffExpr = Attr.getArgAsExpr(1); llvm::APSInt Int(32); S.VerifyIntegerConstantExpression(OffExpr, &Int); offIntVal = Int.getSExtValue(); } D->addAttr(::new (S.Context) XCLReqdPipeDepthAttr( Attr.getRange(), S.Context, DepthExpr, offIntVal, Attr.getAttributeSpellingListIndex())); } static void handleFPGAAddressInterfaceAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGAAddressInterfaceAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } // address interface isnot compatible with ap scalar interface if (checkAttrMutualExclusion<FPGAScalarInterfaceAttr>( S, D, "ap", Attr.getRange(), Attr.getName(), true)) { return; } auto Mode = Attr.getArgAsIdent(0)->Ident->getName(); auto Adaptor = Attr.getArgAsIdent(1)->Ident->getName(); FPGAAddressInterfaceAttr::OffsetModeType OffsetMode = FPGAAddressInterfaceAttr::Default; if (Attr.getNumArgs() > 2) { auto *OffsetModeIL = Attr.getArgAsIdent(2); auto OffsetModeStr = OffsetModeIL->Ident->getName(); if (!FPGAAddressInterfaceAttr::ConvertStrToOffsetModeType(OffsetModeStr, OffsetMode)) { S.Diag(OffsetModeIL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() << OffsetModeStr; return; } } D->addAttr(::new (S.Context) FPGAAddressInterfaceAttr( Attr.getRange(), S.Context, Mode, Adaptor, OffsetMode, Attr.getAttributeSpellingListIndex())); } static void handleFPGAScalarInterfaceAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; auto Mode = Attr.getArgAsIdent(0)->Ident->getName(); // FIXME: need better handler for s_axilite // s_axilit is compatible with ap_* if (Mode.equals_lower("s_axilite")) { if (checkAttrMutualExclusion<FPGAScalarInterfaceAttr>( S, D, Mode, Attr.getRange(), Attr.getName(), true)) { return; } } else { // ap scalar interface isnot compatible with address interface if (checkAttrMutualExclusion<FPGAAddressInterfaceAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } // ap scalar interface isnot compatible with other ap scalar interface if (checkAttrMutualExclusion<FPGAScalarInterfaceAttr>( S, D, "ap", Attr.getRange(), Attr.getName(), true)) { return; } } auto Adaptor = Attr.getArgAsIdent(1)->Ident->getName(); D->addAttr(::new (S.Context) FPGAScalarInterfaceAttr( Attr.getRange(), S.Context, Mode, Adaptor, Attr.getAttributeSpellingListIndex())); } static void handleFPGAScalarInterfaceWrapperAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; auto Mode = Attr.getArgAsIdent(0)->Ident->getName(); // Cannot apply the s_saxilite to the same scalar more than once. if (checkAttrMutualExclusion<FPGAScalarInterfaceWrapperAttr>( S, D, "s_axilite", Attr.getRange(), Attr.getName(), true)) { return; } auto Adaptor = Attr.getArgAsIdent(1)->Ident->getName(); Expr *Offset = nullptr; if (Attr.getNumArgs() == 3) { Offset = Attr.getArgAsExpr(2); if (S.CheckFPGAScalarInterfaceWrapperExprs(Offset, Attr.getLoc(), Attr.getName()->getName())) return; } // ignore the offset if the Adaptor is not specified. if (Adaptor.empty() && Offset) { S.Diag(Attr.getLoc(), diag::warn_xlx_attribute_ignore_option) << Attr.getName() << "offset" << "Adaptor is not specified"; Offset = createIntegerLiteral(-1, S); } // set offset to an invalid value if not specified. // Codegen will ingore the invalid offset. // FIXME: maybe fixing the optional in tablegen is better. if (Offset == nullptr) { Offset = createIntegerLiteral(-1, S); } D->addAttr(::new (S.Context) FPGAScalarInterfaceWrapperAttr( Attr.getRange(), S.Context, Mode, Adaptor, Offset, Attr.getAttributeSpellingListIndex())); } static void handleFPGAFunctionCtrlInterfaceAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (checkAttrMutualExclusion<FPGAFunctionCtrlInterfaceAttr>( S, D, Attr.getRange(), Attr.getName(), true)) { return; } auto Mode = Attr.getArgAsIdent(0)->Ident->getName(); uint32_t IsReg; if (!checkICEArgument(S, Attr, Attr.getArgAsExpr(1), IsReg, 1)) { D->setInvalidDecl(); return; } auto Rtlname = Attr.getArgAsIdent(2)->Ident->getName(); D->addAttr(::new (S.Context) FPGAFunctionCtrlInterfaceAttr( Attr.getRange(), S.Context, Mode, IsReg, Rtlname, Attr.getAttributeSpellingListIndex())); } static void handleCodeGenTypeAttr(Sema &S, Decl *D, const AttributeList &Attr) { auto *TD = dyn_cast<TagDecl>(D); if (!TD) { S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); return; } if (!Attr.hasParsedType()) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 1; return; } TypeSourceInfo *ParmTSI = nullptr; QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI); assert(ParmTSI && "no type source info for attribute argument"); if (auto *A = D->getAttr<CodeGenTypeAttr>()) { if (!S.Context.hasSameType(A->getType(), ParmType)) { S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); return; } return; } // FIXME: Check they have the same size and alignment D->addAttr(::new (S.Context) CodeGenTypeAttr(Attr.getRange(), S.Context, ParmTSI, Attr.getAttributeSpellingListIndex())); } static void handleDataFlowAttr(Sema &S, Decl *D, const AttributeList &Attr) { if (D->isInvalidDecl()) return; if (Attr.getNumArgs() > 1) { S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr.getName() << 1; return; } if (auto *CurFD = S.getCurFunctionDecl()) { if (CurFD->hasAttr<OpenCLKernelAttr>() && S.CheckSPMDDataflow(CurFD, Attr.getRange().getBegin())) return; } XCLDataFlowAttr::PropagationType Type = XCLDataFlowAttr::StartPropagation; if (Attr.getNumArgs() == 1) { if (!Attr.isArgIdent(0)) return; auto TypeStr = Attr.getArgAsIdent(0)->Ident->getName(); if (!XCLDataFlowAttr::ConvertStrToPropagationType(TypeStr, Type)) return; } D->addAttr(::new (S.Context) XCLDataFlowAttr( Attr.getRange(), S.Context, Type, Attr.getAttributeSpellingListIndex())); } static void handleFunctionDependenceAttr(Sema &S, Decl*D, const AttributeList &A) { if( A.getNumArgs() != 6 ) { S.Diag(A.getLoc(), diag::err_attribute_wrong_number_arguments) << A.getName() << 6; return; } Expr* dep_variable = NULL ; XlxDependenceAttr::XlxDepClass dep_class = XlxDependenceAttr::NO_CLASS; XlxDependenceAttr::XlxDepType dep_type = XlxDependenceAttr::inter; XlxDependenceAttr::XlxDepDirection dep_direction = XlxDependenceAttr::NO_DIRECTION; int64_t dep_distance = -1; int dep_compel = 0; /* variable( optional ), poiner/array( optional ), inter/intra, raw/war/waw, INTCONST, bool */ if( A.getArgAsExpr(0) ) { dep_variable = A.getArgAsExpr(0); } else { auto &Ctx = S.getASTContext(); auto IntTy = Ctx.IntTy; auto Width = Ctx.getIntWidth(IntTy); auto Int = llvm::APInt(Width, 0); dep_variable = IntegerLiteral::Create(Ctx, Int, IntTy, A.getLoc()); } if( A.getArgAsIdent( 1 ) ) XlxDependenceAttr::ConvertStrToXlxDepClass( A.getArgAsIdent(1)->Ident->getName(), dep_class ); if( A.getArgAsIdent( 2 ) ) XlxDependenceAttr::ConvertStrToXlxDepType( A.getArgAsIdent(2)->Ident->getName(), dep_type ); if( A.getArgAsIdent( 3 ) ) XlxDependenceAttr::ConvertStrToXlxDepDirection( A.getArgAsIdent(3)->Ident->getName(), dep_direction ); if( A.getArgAsExpr( 4 ) ) { llvm::APSInt Int(32); Expr* E = A.getArgAsExpr(4); auto ICE = S.VerifyIntegerConstantExpression(E, &Int); if (ICE.isInvalid()) { S.Diag(A.getLoc(), diag::err_attribute_argument_n_type) << "'dependence'" << 4 << AANT_ArgumentIntegerConstant << E->getSourceRange(); return ; } dep_distance = Int.getSExtValue(); } if( A.getArgAsExpr( 5 ) ){ llvm::APSInt Int(32); Expr* E = A.getArgAsExpr(5); auto ICE = S.VerifyIntegerConstantExpression(E, &Int); if (ICE.isInvalid()) { S.Diag(A.getLoc(), diag::err_attribute_argument_n_type) << "'dependence'" << 5 << AANT_ArgumentIntegerConstant << E->getSourceRange(); return ; } dep_compel = Int.getSExtValue(); } D->addAttr( ::new(S.Context) XlxDependenceAttr( A.getRange(), S.Context, dep_variable, dep_class, dep_type, dep_direction, dep_distance, (bool)dep_compel, A.getAttributeSpellingListIndex())); } //===----------------------------------------------------------------------===// // Top Level Sema Entry Points //===----------------------------------------------------------------------===// /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if /// the attribute applies to decls. If the attribute is a type attribute, just /// silently ignore it if a GNU attribute. static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const AttributeList &Attr, bool IncludeCXX11Attributes) { if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute) return; // Ignore C++11 attributes on declarator chunks: they appertain to the type // instead. if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes) return; // Unknown attributes are automatically warned on. Target-specific attributes // which do not apply to the current target architecture are treated as // though they were unknown attributes. if (Attr.getKind() == AttributeList::UnknownAttribute || !Attr.existsInTarget(S.Context.getTargetInfo())) { S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() ? diag::warn_unhandled_ms_attribute_ignored : diag::warn_unknown_attribute_ignored) << Attr.getName(); return; } if (handleCommonAttributeFeatures(S, scope, D, Attr)) return; switch (Attr.getKind()) { default: if (S.ProcessXlxDeclAttributes(scope, D, Attr)) break; if (!Attr.isStmtAttr()) { // Type attributes are handled elsewhere; silently move on. assert(Attr.isTypeAttr() && "Non-type attribute not handled"); break; } S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl) << Attr.getName() << D->getLocation(); break; case AttributeList::AT_Interrupt: handleInterruptAttr(S, D, Attr); break; case AttributeList::AT_X86ForceAlignArgPointer: handleX86ForceAlignArgPointerAttr(S, D, Attr); break; case AttributeList::AT_DLLExport: case AttributeList::AT_DLLImport: handleDLLAttr(S, D, Attr); break; case AttributeList::AT_XCLDataFlow: handleDataFlowAttr(S, D, Attr); break; case AttributeList::AT_XlxDependence: handleFunctionDependenceAttr(S, D, Attr); break; case AttributeList::AT_XCLInline: handleEnableAttribute<XCLInlineAttr>(S, D, Attr, false); break; case AttributeList::AT_XlxFuncInstantiate: handleSimpleAttribute<XlxFuncInstantiateAttr>(S, D, Attr); break; case AttributeList::AT_XlxVarReset: handleEnableAttribute<XlxVarResetAttr>(S, D, Attr); break; case AttributeList::AT_XlxExprBalance: handleEnableAttribute<XlxExprBalanceAttr>(S, D, Attr); break; case AttributeList::AT_XlxMergeLoop: handleEnableAttribute<XlxMergeLoopAttr>(S, D, Attr, false); break; case AttributeList::AT_FPGARegister: handleSimpleAttribute<FPGARegisterAttr>(S, D, Attr); break; case AttributeList::AT_FPGASignalName: handleFPGASignalNameAttr(S, D, Attr); break; case AttributeList::AT_FPGADataFootPrintHint: handleFPGADataFootPrintHintAttr(S, D, Attr); break; case AttributeList::AT_FPGAMaxiMaxWidenBitwidth: handleFPGAMaxiMaxWidenBitwidthAttr(S, D, Attr); break; case AttributeList::AT_FPGAMaxiLatency: handleFPGAMaxiLatencyAttr(S, D, Attr); break; case AttributeList::AT_FPGAMaxiNumRdOutstand: handleFPGAMaxiNumRdOutstandAttr(S, D, Attr); break; case AttributeList::AT_FPGAMaxiNumWtOutstand: handleFPGAMaxiNumWtOutstandAttr(S, D, Attr); break; case AttributeList::AT_FPGAMaxiRdBurstLen: handleFPGAMaxiRdBurstLenAttr(S, D, Attr); break; case AttributeList::AT_FPGAMaxiWtBurstLen: handleFPGAMaxiWtBurstLenAttr(S, D, Attr); break; case AttributeList::AT_FPGAAddressInterface: handleFPGAAddressInterfaceAttr(S, D, Attr); break; case AttributeList::AT_FPGAScalarInterface: handleFPGAScalarInterfaceAttr(S, D, Attr); break; case AttributeList::AT_FPGAScalarInterfaceWrapper: handleFPGAScalarInterfaceWrapperAttr(S, D, Attr); break; case AttributeList::AT_FPGAFunctionCtrlInterface: handleFPGAFunctionCtrlInterfaceAttr(S, D, Attr); break; case AttributeList::AT_XCLReqdPipeDepth: handleXCLReqdPipeDepthAttr(S, D, Attr); break; case AttributeList::AT_MAXIAdaptor: handleMAXIAdaptorAttr(S, D, Attr); break; case AttributeList::AT_AXISAdaptor: handleAXISAdaptorAttr(S, D, Attr); break; case AttributeList::AT_BRAMAdaptor: handleBRAMAdaptorAttr(S, D, Attr); break; case AttributeList::AT_CodeGenType: handleCodeGenTypeAttr(S, D, Attr); break; case AttributeList::AT_Unpacked: handleUnpackedAttr(S, D, Attr); break; case AttributeList::AT_Mips16: handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr, MipsInterruptAttr>(S, D, Attr); break; case AttributeList::AT_NoMips16: handleSimpleAttribute<NoMips16Attr>(S, D, Attr); break; case AttributeList::AT_MicroMips: handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, Attr); break; case AttributeList::AT_NoMicroMips: handleSimpleAttribute<NoMicroMipsAttr>(S, D, Attr); break; case AttributeList::AT_MipsLongCall: handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>( S, D, Attr); break; case AttributeList::AT_MipsShortCall: handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>( S, D, Attr); break; case AttributeList::AT_AMDGPUFlatWorkGroupSize: handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr); break; case AttributeList::AT_AMDGPUWavesPerEU: handleAMDGPUWavesPerEUAttr(S, D, Attr); break; case AttributeList::AT_AMDGPUNumSGPR: handleAMDGPUNumSGPRAttr(S, D, Attr); break; case AttributeList::AT_AMDGPUNumVGPR: handleAMDGPUNumVGPRAttr(S, D, Attr); break; case AttributeList::AT_AVRSignal: handleAVRSignalAttr(S, D, Attr); break; case AttributeList::AT_IBAction: handleSimpleAttribute<IBActionAttr>(S, D, Attr); break; case AttributeList::AT_IBOutlet: handleIBOutlet(S, D, Attr); break; case AttributeList::AT_IBOutletCollection: handleIBOutletCollection(S, D, Attr); break; case AttributeList::AT_IFunc: handleIFuncAttr(S, D, Attr); break; case AttributeList::AT_Alias: handleAliasAttr(S, D, Attr); break; case AttributeList::AT_Aligned: handleAlignedAttr(S, D, Attr); break; case AttributeList::AT_AlignValue: handleAlignValueAttr(S, D, Attr); break; case AttributeList::AT_AllocSize: handleAllocSizeAttr(S, D, Attr); break; case AttributeList::AT_AlwaysInline: handleAlwaysInlineAttr(S, D, Attr); break; case AttributeList::AT_AnalyzerNoReturn: handleAnalyzerNoReturnAttr(S, D, Attr); break; case AttributeList::AT_TLSModel: handleTLSModelAttr(S, D, Attr); break; case AttributeList::AT_Annotate: handleAnnotateAttr(S, D, Attr); break; case AttributeList::AT_Availability: handleAvailabilityAttr(S, D, Attr); break; case AttributeList::AT_CarriesDependency: handleDependencyAttr(S, scope, D, Attr); break; case AttributeList::AT_Common: handleCommonAttr(S, D, Attr); break; case AttributeList::AT_CUDAConstant: handleConstantAttr(S, D, Attr); break; case AttributeList::AT_PassObjectSize: handlePassObjectSizeAttr(S, D, Attr); break; case AttributeList::AT_Constructor: handleConstructorAttr(S, D, Attr); break; case AttributeList::AT_CXX11NoReturn: handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr); break; case AttributeList::AT_Deprecated: handleDeprecatedAttr(S, D, Attr); break; case AttributeList::AT_Destructor: handleDestructorAttr(S, D, Attr); break; case AttributeList::AT_EnableIf: handleEnableIfAttr(S, D, Attr); break; case AttributeList::AT_DiagnoseIf: handleDiagnoseIfAttr(S, D, Attr); break; case AttributeList::AT_ExtVectorType: handleExtVectorTypeAttr(S, scope, D, Attr); break; case AttributeList::AT_ExternalSourceSymbol: handleExternalSourceSymbolAttr(S, D, Attr); break; case AttributeList::AT_MinSize: handleMinSizeAttr(S, D, Attr); break; case AttributeList::AT_OptimizeNone: handleOptimizeNoneAttr(S, D, Attr); break; case AttributeList::AT_FlagEnum: handleSimpleAttribute<FlagEnumAttr>(S, D, Attr); break; case AttributeList::AT_EnumExtensibility: handleEnumExtensibilityAttr(S, D, Attr); break; case AttributeList::AT_Flatten: handleSimpleAttribute<FlattenAttr>(S, D, Attr); break; case AttributeList::AT_Format: handleFormatAttr(S, D, Attr); break; case AttributeList::AT_FormatArg: handleFormatArgAttr(S, D, Attr); break; case AttributeList::AT_CUDAGlobal: handleGlobalAttr(S, D, Attr); break; case AttributeList::AT_CUDADevice: handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D, Attr); break; case AttributeList::AT_CUDAHost: handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, Attr); break; case AttributeList::AT_GNUInline: handleGNUInlineAttr(S, D, Attr); break; case AttributeList::AT_CUDALaunchBounds: handleLaunchBoundsAttr(S, D, Attr); break; case AttributeList::AT_Restrict: handleRestrictAttr(S, D, Attr); break; case AttributeList::AT_MayAlias: handleSimpleAttribute<MayAliasAttr>(S, D, Attr); break; case AttributeList::AT_Mode: handleModeAttr(S, D, Attr); break; case AttributeList::AT_NoAlias: handleSimpleAttribute<NoAliasAttr>(S, D, Attr); break; case AttributeList::AT_NoCommon: handleSimpleAttribute<NoCommonAttr>(S, D, Attr); break; case AttributeList::AT_NoSplitStack: handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr); break; case AttributeList::AT_NonNull: if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D)) handleNonNullAttrParameter(S, PVD, Attr); else handleNonNullAttr(S, D, Attr); break; case AttributeList::AT_ReturnsNonNull: handleReturnsNonNullAttr(S, D, Attr); break; case AttributeList::AT_NoEscape: handleNoEscapeAttr(S, D, Attr); break; case AttributeList::AT_AssumeAligned: handleAssumeAlignedAttr(S, D, Attr); break; case AttributeList::AT_AllocAlign: handleAllocAlignAttr(S, D, Attr); break; case AttributeList::AT_Overloadable: handleSimpleAttribute<OverloadableAttr>(S, D, Attr); break; case AttributeList::AT_Ownership: handleOwnershipAttr(S, D, Attr); break; case AttributeList::AT_Cold: handleColdAttr(S, D, Attr); break; case AttributeList::AT_Hot: handleHotAttr(S, D, Attr); break; case AttributeList::AT_Naked: handleNakedAttr(S, D, Attr); break; case AttributeList::AT_NoReturn: handleNoReturnAttr(S, D, Attr); break; case AttributeList::AT_NoThrow: handleSimpleAttribute<NoThrowAttr>(S, D, Attr); break; case AttributeList::AT_CUDAShared: handleSharedAttr(S, D, Attr); break; case AttributeList::AT_VecReturn: handleVecReturnAttr(S, D, Attr); break; case AttributeList::AT_ObjCOwnership: handleObjCOwnershipAttr(S, D, Attr); break; case AttributeList::AT_ObjCPreciseLifetime: handleObjCPreciseLifetimeAttr(S, D, Attr); break; case AttributeList::AT_ObjCReturnsInnerPointer: handleObjCReturnsInnerPointerAttr(S, D, Attr); break; case AttributeList::AT_ObjCRequiresSuper: handleObjCRequiresSuperAttr(S, D, Attr); break; case AttributeList::AT_ObjCBridge: handleObjCBridgeAttr(S, scope, D, Attr); break; case AttributeList::AT_ObjCBridgeMutable: handleObjCBridgeMutableAttr(S, scope, D, Attr); break; case AttributeList::AT_ObjCBridgeRelated: handleObjCBridgeRelatedAttr(S, scope, D, Attr); break; case AttributeList::AT_ObjCDesignatedInitializer: handleObjCDesignatedInitializer(S, D, Attr); break; case AttributeList::AT_ObjCRuntimeName: handleObjCRuntimeName(S, D, Attr); break; case AttributeList::AT_ObjCRuntimeVisible: handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr); break; case AttributeList::AT_ObjCBoxable: handleObjCBoxable(S, D, Attr); break; case AttributeList::AT_CFAuditedTransfer: handleCFAuditedTransferAttr(S, D, Attr); break; case AttributeList::AT_CFUnknownTransfer: handleCFUnknownTransferAttr(S, D, Attr); break; case AttributeList::AT_CFConsumed: case AttributeList::AT_NSConsumed: handleNSConsumedAttr(S, D, Attr); break; case AttributeList::AT_NSConsumesSelf: handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr); break; case AttributeList::AT_NSReturnsAutoreleased: case AttributeList::AT_NSReturnsNotRetained: case AttributeList::AT_CFReturnsNotRetained: case AttributeList::AT_NSReturnsRetained: case AttributeList::AT_CFReturnsRetained: handleNSReturnsRetainedAttr(S, D, Attr); break; case AttributeList::AT_WorkGroupSizeHint: handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr); break; case AttributeList::AT_ReqdWorkGroupSize: handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr); break; case AttributeList::AT_OpenCLIntelReqdSubGroupSize: handleSubGroupSize(S, D, Attr); break; case AttributeList::AT_VecTypeHint: handleVecTypeHint(S, D, Attr); break; case AttributeList::AT_RequireConstantInit: handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr); break; case AttributeList::AT_InitPriority: handleInitPriorityAttr(S, D, Attr); break; case AttributeList::AT_Packed: handlePackedAttr(S, D, Attr); break; case AttributeList::AT_Section: handleSectionAttr(S, D, Attr); break; case AttributeList::AT_Target: handleTargetAttr(S, D, Attr); break; case AttributeList::AT_Unavailable: handleAttrWithMessage<UnavailableAttr>(S, D, Attr); break; case AttributeList::AT_ArcWeakrefUnavailable: handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr); break; case AttributeList::AT_ObjCRootClass: handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr); break; case AttributeList::AT_ObjCSubclassingRestricted: handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr); break; case AttributeList::AT_ObjCExplicitProtocolImpl: handleObjCSuppresProtocolAttr(S, D, Attr); break; case AttributeList::AT_ObjCRequiresPropertyDefs: handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr); break; case AttributeList::AT_Unused: handleUnusedAttr(S, D, Attr); break; case AttributeList::AT_ReturnsTwice: handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr); break; case AttributeList::AT_NotTailCalled: handleNotTailCalledAttr(S, D, Attr); break; case AttributeList::AT_DisableTailCalls: handleDisableTailCallsAttr(S, D, Attr); break; case AttributeList::AT_Used: handleUsedAttr(S, D, Attr); break; case AttributeList::AT_Visibility: handleVisibilityAttr(S, D, Attr, false); break; case AttributeList::AT_TypeVisibility: handleVisibilityAttr(S, D, Attr, true); break; case AttributeList::AT_WarnUnused: handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr); break; case AttributeList::AT_WarnUnusedResult: handleWarnUnusedResult(S, D, Attr); break; case AttributeList::AT_Weak: handleSimpleAttribute<WeakAttr>(S, D, Attr); break; case AttributeList::AT_WeakRef: handleWeakRefAttr(S, D, Attr); break; case AttributeList::AT_WeakImport: handleWeakImportAttr(S, D, Attr); break; case AttributeList::AT_TransparentUnion: handleTransparentUnionAttr(S, D, Attr); break; case AttributeList::AT_ObjCException: handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr); break; case AttributeList::AT_ObjCMethodFamily: handleObjCMethodFamilyAttr(S, D, Attr); break; case AttributeList::AT_ObjCNSObject: handleObjCNSObject(S, D, Attr); break; case AttributeList::AT_ObjCIndependentClass: handleObjCIndependentClass(S, D, Attr); break; case AttributeList::AT_Blocks: handleBlocksAttr(S, D, Attr); break; case AttributeList::AT_Sentinel: handleSentinelAttr(S, D, Attr); break; case AttributeList::AT_Const: handleSimpleAttribute<ConstAttr>(S, D, Attr); break; case AttributeList::AT_Pure: handleSimpleAttribute<PureAttr>(S, D, Attr); break; case AttributeList::AT_Cleanup: handleCleanupAttr(S, D, Attr); break; case AttributeList::AT_NoDebug: handleNoDebugAttr(S, D, Attr); break; case AttributeList::AT_NoDuplicate: handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr); break; case AttributeList::AT_Convergent: handleSimpleAttribute<ConvergentAttr>(S, D, Attr); break; case AttributeList::AT_NoInline: handleSimpleAttribute<NoInlineAttr>(S, D, Attr); break; case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg. handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr); break; case AttributeList::AT_StdCall: case AttributeList::AT_CDecl: case AttributeList::AT_FastCall: case AttributeList::AT_ThisCall: case AttributeList::AT_Pascal: case AttributeList::AT_RegCall: case AttributeList::AT_SwiftCall: case AttributeList::AT_VectorCall: case AttributeList::AT_MSABI: case AttributeList::AT_SysVABI: case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc: case AttributeList::AT_PreserveMost: case AttributeList::AT_PreserveAll: handleCallConvAttr(S, D, Attr); break; case AttributeList::AT_Suppress: handleSuppressAttr(S, D, Attr); break; case AttributeList::AT_OpenCLKernel: handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr); break; case AttributeList::AT_OpenCLAccess: handleOpenCLAccessAttr(S, D, Attr); break; case AttributeList::AT_OpenCLNoSVM: handleOpenCLNoSVMAttr(S, D, Attr); break; case AttributeList::AT_SwiftContext: handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext); break; case AttributeList::AT_SwiftErrorResult: handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult); break; case AttributeList::AT_SwiftIndirectResult: handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult); break; case AttributeList::AT_InternalLinkage: handleInternalLinkageAttr(S, D, Attr); break; case AttributeList::AT_LTOVisibilityPublic: handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr); break; // Microsoft attributes: case AttributeList::AT_EmptyBases: handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr); break; case AttributeList::AT_LayoutVersion: handleLayoutVersion(S, D, Attr); break; case AttributeList::AT_MSNoVTable: handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr); break; case AttributeList::AT_MSStruct: handleSimpleAttribute<MSStructAttr>(S, D, Attr); break; case AttributeList::AT_Uuid: handleUuidAttr(S, D, Attr); break; case AttributeList::AT_MSInheritance: handleMSInheritanceAttr(S, D, Attr); break; case AttributeList::AT_SelectAny: handleSimpleAttribute<SelectAnyAttr>(S, D, Attr); break; case AttributeList::AT_Thread: handleDeclspecThreadAttr(S, D, Attr); break; case AttributeList::AT_AbiTag: handleAbiTagAttr(S, D, Attr); break; // Thread safety attributes: case AttributeList::AT_AssertExclusiveLock: handleAssertExclusiveLockAttr(S, D, Attr); break; case AttributeList::AT_AssertSharedLock: handleAssertSharedLockAttr(S, D, Attr); break; case AttributeList::AT_GuardedVar: handleSimpleAttribute<GuardedVarAttr>(S, D, Attr); break; case AttributeList::AT_PtGuardedVar: handlePtGuardedVarAttr(S, D, Attr); break; case AttributeList::AT_ScopedLockable: handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr); break; case AttributeList::AT_NoSanitize: handleNoSanitizeAttr(S, D, Attr); break; case AttributeList::AT_NoSanitizeSpecific: handleNoSanitizeSpecificAttr(S, D, Attr); break; case AttributeList::AT_NoThreadSafetyAnalysis: handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr); break; case AttributeList::AT_GuardedBy: handleGuardedByAttr(S, D, Attr); break; case AttributeList::AT_PtGuardedBy: handlePtGuardedByAttr(S, D, Attr); break; case AttributeList::AT_ExclusiveTrylockFunction: handleExclusiveTrylockFunctionAttr(S, D, Attr); break; case AttributeList::AT_LockReturned: handleLockReturnedAttr(S, D, Attr); break; case AttributeList::AT_LocksExcluded: handleLocksExcludedAttr(S, D, Attr); break; case AttributeList::AT_SharedTrylockFunction: handleSharedTrylockFunctionAttr(S, D, Attr); break; case AttributeList::AT_AcquiredBefore: handleAcquiredBeforeAttr(S, D, Attr); break; case AttributeList::AT_AcquiredAfter: handleAcquiredAfterAttr(S, D, Attr); break; // Capability analysis attributes. case AttributeList::AT_Capability: case AttributeList::AT_Lockable: handleCapabilityAttr(S, D, Attr); break; case AttributeList::AT_RequiresCapability: handleRequiresCapabilityAttr(S, D, Attr); break; case AttributeList::AT_AssertCapability: handleAssertCapabilityAttr(S, D, Attr); break; case AttributeList::AT_AcquireCapability: handleAcquireCapabilityAttr(S, D, Attr); break; case AttributeList::AT_ReleaseCapability: handleReleaseCapabilityAttr(S, D, Attr); break; case AttributeList::AT_TryAcquireCapability: handleTryAcquireCapabilityAttr(S, D, Attr); break; // Consumed analysis attributes. case AttributeList::AT_Consumable: handleConsumableAttr(S, D, Attr); break; case AttributeList::AT_ConsumableAutoCast: handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr); break; case AttributeList::AT_ConsumableSetOnRead: handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr); break; case AttributeList::AT_CallableWhen: handleCallableWhenAttr(S, D, Attr); break; case AttributeList::AT_ParamTypestate: handleParamTypestateAttr(S, D, Attr); break; case AttributeList::AT_ReturnTypestate: handleReturnTypestateAttr(S, D, Attr); break; case AttributeList::AT_SetTypestate: handleSetTypestateAttr(S, D, Attr); break; case AttributeList::AT_TestTypestate: handleTestTypestateAttr(S, D, Attr); break; // Type safety attributes. case AttributeList::AT_ArgumentWithTypeTag: handleArgumentWithTypeTagAttr(S, D, Attr); break; case AttributeList::AT_TypeTagForDatatype: handleTypeTagForDatatypeAttr(S, D, Attr); break; case AttributeList::AT_AnyX86NoCallerSavedRegisters: handleNoCallerSavedRegsAttr(S, D, Attr); break; case AttributeList::AT_RenderScriptKernel: handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr); break; // XRay attributes. case AttributeList::AT_XRayInstrument: handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr); break; case AttributeList::AT_XRayLogArgs: handleXRayLogArgsAttr(S, D, Attr); break; } } /// ProcessDeclAttributeList - Apply all the decl attributes in the specified /// attribute list to the specified decl, ignoring any type attributes. void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AttrList, bool IncludeCXX11Attributes) { for (const AttributeList* l = AttrList; l; l = l->getNext()) ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes); // FIXME: We should be able to handle these cases in TableGen. // GCC accepts // static int a9 __attribute__((weakref)); // but that looks really pointless. We reject it. if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) << cast<NamedDecl>(D); D->dropAttr<WeakRefAttr>(); return; } // FIXME: We should be able to handle this in TableGen as well. It would be // good to have a way to specify "these attributes must appear as a group", // for these. Additionally, it would be good to have a way to specify "these // attribute must never appear as a group" for attributes like cold and hot. if (!D->hasAttr<OpenCLKernelAttr>()) { // These attributes cannot be applied to a non-kernel function. if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { // FIXME: This emits a different error message than // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) { Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) { Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) { Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << A << ExpectedKernelFunction; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) { Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << A << ExpectedKernelFunction; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) { Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << A << ExpectedKernelFunction; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) { Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) << A << ExpectedKernelFunction; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<XCLMaxWorkGroupSizeAttr>()) { Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<XCLZeroGlobalWorkOffsetAttr>()) { Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } else if (Attr *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; D->setInvalidDecl(); } // check incompatible attributes if (getLangOpts().HLSExt && D->hasAttrs()) CheckForIncompatibleXlxAttributes(D->getAttrs()); return; } if (auto *XDF = D->getAttr<XCLDataFlowAttr>()) { if (D->hasAttr<OpenCLKernelAttr>()) { // xcl_dataflow can only apply to (1,1,1) kernel if (CheckSPMDDataflow(D, XDF->getLocation())) D->setInvalidDecl(); } } } // Helper for delayed processing TransparentUnion attribute. void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) { for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext()) if (Attr->getKind() == AttributeList::AT_TransparentUnion) { handleTransparentUnionAttr(*this, D, *Attr); break; } } // Annotation attributes are the only attributes allowed after an access // specifier. bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const AttributeList *AttrList) { for (const AttributeList* l = AttrList; l; l = l->getNext()) { if (l->getKind() == AttributeList::AT_Annotate) { ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute()); } else { Diag(l->getLoc(), diag::err_only_annotate_after_access_spec); return true; } } return false; } /// checkUnusedDeclAttributes - Check a list of attributes to see if it /// contains any decl attributes that we should warn about. static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) { for ( ; A; A = A->getNext()) { // Only warn if the attribute is an unignored, non-type attribute. if (A->isUsedAsTypeAttr() || A->isInvalid()) continue; if (A->getKind() == AttributeList::IgnoredAttribute) continue; if (A->getKind() == AttributeList::UnknownAttribute) { S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored) << A->getName() << A->getRange(); } else { S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl) << A->getName() << A->getRange(); } } } /// checkUnusedDeclAttributes - Given a declarator which is not being /// used to build a declaration, complain about any decl attributes /// which might be lying around on it. void Sema::checkUnusedDeclAttributes(Declarator &D) { ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList()); ::checkUnusedDeclAttributes(*this, D.getAttributes()); for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); } /// DeclClonePragmaWeak - clone existing decl (maybe definition), /// \#pragma weak needs a non-definition decl and source may not have one. NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc) { assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); NamedDecl *NewD = nullptr; if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { FunctionDecl *NewFD; // FIXME: Missing call to CheckFunctionDeclaration(). // FIXME: Mangling? // FIXME: Is the qualifier info correct? // FIXME: Is the DeclContext correct? NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(), Loc, Loc, DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None, false/*isInlineSpecified*/, FD->hasPrototype(), false/*isConstexprSpecified*/); NewD = NewFD; if (FD->getQualifier()) NewFD->setQualifierInfo(FD->getQualifierLoc()); // Fake up parameter variables; they are declared as if this were // a typedef. QualType FDTy = FD->getType(); if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) { SmallVector<ParmVarDecl*, 16> Params; for (const auto &AI : FT->param_types()) { ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); Param->setScopeInfo(0, Params.size()); Params.push_back(Param); } NewFD->setParams(Params); } } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) { NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), VD->getInnerLocStart(), VD->getLocation(), II, VD->getType(), VD->getTypeSourceInfo(), VD->getStorageClass()); if (VD->getQualifier()) { VarDecl *NewVD = cast<VarDecl>(NewD); NewVD->setQualifierInfo(VD->getQualifierLoc()); } } return NewD; } /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak /// applied to it, possibly with an alias. void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { if (W.getUsed()) return; // only do this once W.setUsed(true); if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) IdentifierInfo *NDId = ND->getIdentifier(); NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation())); NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); WeakTopLevelDecl.push_back(NewD); // FIXME: "hideous" code from Sema::LazilyCreateBuiltin // to insert Decl at TU scope, sorry. DeclContext *SavedContext = CurContext; CurContext = Context.getTranslationUnitDecl(); NewD->setDeclContext(CurContext); NewD->setLexicalDeclContext(CurContext); PushOnScopeChains(NewD, S); CurContext = SavedContext; } else { // just add weak to existing ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); } } void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { // It's valid to "forward-declare" #pragma weak, in which case we // have to do this. LoadExternalWeakUndeclaredIdentifiers(); if (!WeakUndeclaredIdentifiers.empty()) { NamedDecl *ND = nullptr; if (VarDecl *VD = dyn_cast<VarDecl>(D)) if (VD->isExternC()) ND = VD; if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) if (FD->isExternC()) ND = FD; if (ND) { if (IdentifierInfo *Id = ND->getIdentifier()) { auto I = WeakUndeclaredIdentifiers.find(Id); if (I != WeakUndeclaredIdentifiers.end()) { WeakInfo W = I->second; DeclApplyPragmaWeak(S, ND, W); WeakUndeclaredIdentifiers[Id] = W; } } } } } /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in /// it, apply them to D. This is a bit tricky because PD can have attributes /// specified in many different places, and we need to find and apply them all. void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { // Apply decl attributes from the DeclSpec if present. if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList()) ProcessDeclAttributeList(S, D, Attrs); // Walk the declarator structure, applying decl attributes that were in a type // position to the decl itself. This handles cases like: // int *__attr__(x)** D; // when X is a decl attribute. for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs()) ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false); // Finally, apply any attributes on the decl itself. if (const AttributeList *Attrs = PD.getAttributes()) ProcessDeclAttributeList(S, D, Attrs); // Apply additional attributes specified by '#pragma clang attribute'. AddPragmaAttributes(S, D); } /// Is the given declaration allowed to use a forbidden type? /// If so, it'll still be annotated with an attribute that makes it /// illegal to actually use. static bool isForbiddenTypeAllowed(Sema &S, Decl *decl, const DelayedDiagnostic &diag, UnavailableAttr::ImplicitReason &reason) { // Private ivars are always okay. Unfortunately, people don't // always properly make their ivars private, even in system headers. // Plus we need to make fields okay, too. if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) && !isa<FunctionDecl>(decl)) return false; // Silently accept unsupported uses of __weak in both user and system // declarations when it's been disabled, for ease of integration with // -fno-objc-arc files. We do have to take some care against attempts // to define such things; for now, we've only done that for ivars // and properties. if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) { if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { reason = UnavailableAttr::IR_ForbiddenWeak; return true; } } // Allow all sorts of things in system headers. if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) { // Currently, all the failures dealt with this way are due to ARC // restrictions. reason = UnavailableAttr::IR_ARCForbiddenType; return true; } return false; } /// Handle a delayed forbidden-type diagnostic. static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag, Decl *decl) { auto reason = UnavailableAttr::IR_None; if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) { assert(reason && "didn't set reason?"); decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason, diag.Loc)); return; } if (S.getLangOpts().ObjCAutoRefCount) if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) { // FIXME: we may want to suppress diagnostics for all // kind of forbidden type messages on unavailable functions. if (FD->hasAttr<UnavailableAttr>() && diag.getForbiddenTypeDiagnostic() == diag::err_arc_array_param_no_ownership) { diag.Triggered = true; return; } } S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic()) << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument(); diag.Triggered = true; } static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context, const Decl *D) { // Check each AvailabilityAttr to find the one for this platform. for (const auto *A : D->attrs()) { if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) { // FIXME: this is copied from CheckAvailability. We should try to // de-duplicate. // Check if this is an App Extension "platform", and if so chop off // the suffix for matching with the actual platform. StringRef ActualPlatform = Avail->getPlatform()->getName(); StringRef RealizedPlatform = ActualPlatform; if (Context.getLangOpts().AppExt) { size_t suffix = RealizedPlatform.rfind("_app_extension"); if (suffix != StringRef::npos) RealizedPlatform = RealizedPlatform.slice(0, suffix); } StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); // Match the platform name. if (RealizedPlatform == TargetPlatform) return Avail; } } return nullptr; } /// The diagnostic we should emit for \c D, and the declaration that /// originated it, or \c AR_Available. /// /// \param D The declaration to check. /// \param Message If non-null, this will be populated with the message from /// the availability attribute that is selected. static std::pair<AvailabilityResult, const NamedDecl *> ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message) { AvailabilityResult Result = D->getAvailability(Message); // For typedefs, if the typedef declaration appears available look // to the underlying type to see if it is more restrictive. while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { if (Result == AR_Available) { if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { D = TT->getDecl(); Result = D->getAvailability(Message); continue; } } break; } // Forward class declarations get their attributes from their definition. if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { if (IDecl->getDefinition()) { D = IDecl->getDefinition(); Result = D->getAvailability(Message); } } if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) if (Result == AR_Available) { const DeclContext *DC = ECD->getDeclContext(); if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) { Result = TheEnumDecl->getAvailability(Message); D = TheEnumDecl; } } return {Result, D}; } /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in /// the context of \c Ctx. For example, we should emit an unavailable diagnostic /// in a deprecated context, but not the other way around. static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K, VersionTuple DeclVersion, Decl *Ctx) { assert(K != AR_Available && "Expected an unavailable declaration here!"); // Checks if we should emit the availability diagnostic in the context of C. auto CheckContext = [&](const Decl *C) { if (K == AR_NotYetIntroduced) { if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C)) if (AA->getIntroduced() >= DeclVersion) return true; } else if (K == AR_Deprecated) if (C->isDeprecated()) return true; if (C->isUnavailable()) return true; return false; }; // FIXME: This is a temporary workaround! Some existing Apple headers depends // on nested declarations in an @interface having the availability of the // interface when they really shouldn't: they are members of the enclosing // context, and can referenced from there. if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) { auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext); if (CheckContext(OrigCtx)) return false; // An implementation implicitly has the availability of the interface. if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) { if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface()) if (CheckContext(Interface)) return false; } // A category implicitly has the availability of the interface. else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx)) if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) if (CheckContext(Interface)) return false; } do { if (CheckContext(Ctx)) return false; // An implementation implicitly has the availability of the interface. if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) { if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface()) if (CheckContext(Interface)) return false; } // A category implicitly has the availability of the interface. else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx)) if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) if (CheckContext(Interface)) return false; } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext()))); return true; } static bool shouldDiagnoseAvailabilityByDefault(const ASTContext &Context, const VersionTuple &DeploymentVersion, const VersionTuple &DeclVersion) { const auto &Triple = Context.getTargetInfo().getTriple(); VersionTuple ForceAvailabilityFromVersion; switch (Triple.getOS()) { case llvm::Triple::IOS: case llvm::Triple::TvOS: ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11); break; case llvm::Triple::WatchOS: ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4); break; case llvm::Triple::Darwin: case llvm::Triple::MacOSX: ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13); break; default: // New targets should always warn about availability. return Triple.getVendor() == llvm::Triple::Apple; } return DeploymentVersion >= ForceAvailabilityFromVersion || DeclVersion >= ForceAvailabilityFromVersion; } static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) { for (Decl *Ctx = OrigCtx; Ctx; Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) { if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx)) return cast<NamedDecl>(Ctx); if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) { if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx)) return Imp->getClassInterface(); return CD; } } return dyn_cast<NamedDecl>(OrigCtx); } namespace { struct AttributeInsertion { StringRef Prefix; SourceLocation Loc; StringRef Suffix; static AttributeInsertion createInsertionAfter(const NamedDecl *D) { return {" ", D->getLocEnd(), ""}; } static AttributeInsertion createInsertionAfter(SourceLocation Loc) { return {" ", Loc, ""}; } static AttributeInsertion createInsertionBefore(const NamedDecl *D) { return {"", D->getLocStart(), "\n"}; } }; } // end anonymous namespace /// Returns a source location in which it's appropriate to insert a new /// attribute for the given declaration \D. static Optional<AttributeInsertion> createAttributeInsertion(const NamedDecl *D, const SourceManager &SM, const LangOptions &LangOpts) { if (isa<ObjCPropertyDecl>(D)) return AttributeInsertion::createInsertionAfter(D); if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { if (MD->hasBody()) return None; return AttributeInsertion::createInsertionAfter(D); } if (const auto *TD = dyn_cast<TagDecl>(D)) { SourceLocation Loc = Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts); if (Loc.isInvalid()) return None; // Insert after the 'struct'/whatever keyword. return AttributeInsertion::createInsertionAfter(Loc); } return AttributeInsertion::createInsertionBefore(D); } /// Actually emit an availability diagnostic for a reference to an unavailable /// decl. /// /// \param Ctx The context that the reference occurred in /// \param ReferringDecl The exact declaration that was referenced. /// \param OffendingDecl A related decl to \c ReferringDecl that has an /// availability attribute corrisponding to \c K attached to it. Note that this /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl /// and OffendingDecl is the EnumDecl. static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K, Decl *Ctx, const NamedDecl *ReferringDecl, const NamedDecl *OffendingDecl, StringRef Message, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass, const ObjCPropertyDecl *ObjCProperty, bool ObjCPropertyAccess) { // Diagnostics for deprecated or unavailable. unsigned diag, diag_message, diag_fwdclass_message; unsigned diag_available_here = diag::note_availability_specified_here; SourceLocation NoteLocation = OffendingDecl->getLocation(); // Matches 'diag::note_property_attribute' options. unsigned property_note_select; // Matches diag::note_availability_specified_here. unsigned available_here_select_kind; VersionTuple DeclVersion; if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl)) DeclVersion = AA->getIntroduced(); if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx)) return; // The declaration can have multiple availability attributes, we are looking // at one of them. const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl); if (A && A->isInherited()) { for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl; Redecl = Redecl->getPreviousDecl()) { const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context, Redecl); if (AForRedecl && !AForRedecl->isInherited()) { // If D is a declaration with inherited attributes, the note should // point to the declaration with actual attributes. NoteLocation = Redecl->getLocation(); break; } } } switch (K) { case AR_NotYetIntroduced: { // We would like to emit the diagnostic even if -Wunguarded-availability is // not specified for deployment targets >= to iOS 11 or equivalent or // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or // later. const AvailabilityAttr *AA = getAttrForPlatform(S.getASTContext(), OffendingDecl); VersionTuple Introduced = AA->getIntroduced(); bool UseNewWarning = shouldDiagnoseAvailabilityByDefault( S.Context, S.Context.getTargetInfo().getPlatformMinVersion(), Introduced); unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new : diag::warn_unguarded_availability; S.Diag(Loc, Warning) << OffendingDecl << AvailabilityAttr::getPrettyPlatformName( S.getASTContext().getTargetInfo().getPlatformName()) << Introduced.getAsString(); S.Diag(OffendingDecl->getLocation(), diag::note_availability_specified_here) << OffendingDecl << /* partial */ 3; if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) { if (auto *TD = dyn_cast<TagDecl>(Enclosing)) if (TD->getDeclName().isEmpty()) { S.Diag(TD->getLocation(), diag::note_decl_unguarded_availability_silence) << /*Anonymous*/ 1 << TD->getKindName(); return; } auto FixitNoteDiag = S.Diag(Enclosing->getLocation(), diag::note_decl_unguarded_availability_silence) << /*Named*/ 0 << Enclosing; // Don't offer a fixit for declarations with availability attributes. if (Enclosing->hasAttr<AvailabilityAttr>()) return; if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE")) return; Optional<AttributeInsertion> Insertion = createAttributeInsertion( Enclosing, S.getSourceManager(), S.getLangOpts()); if (!Insertion) return; std::string PlatformName = AvailabilityAttr::getPlatformNameSourceSpelling( S.getASTContext().getTargetInfo().getPlatformName()) .lower(); std::string Introduced = OffendingDecl->getVersionIntroduced().getAsString(); FixitNoteDiag << FixItHint::CreateInsertion( Insertion->Loc, (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName + "(" + Introduced + "))" + Insertion->Suffix) .str()); } return; } case AR_Deprecated: diag = !ObjCPropertyAccess ? diag::warn_deprecated : diag::warn_property_method_deprecated; diag_message = diag::warn_deprecated_message; diag_fwdclass_message = diag::warn_deprecated_fwdclass_message; property_note_select = /* deprecated */ 0; available_here_select_kind = /* deprecated */ 2; if (const auto *Attr = OffendingDecl->getAttr<DeprecatedAttr>()) NoteLocation = Attr->getLocation(); break; case AR_Unavailable: diag = !ObjCPropertyAccess ? diag::err_unavailable : diag::err_property_method_unavailable; diag_message = diag::err_unavailable_message; diag_fwdclass_message = diag::warn_unavailable_fwdclass_message; property_note_select = /* unavailable */ 1; available_here_select_kind = /* unavailable */ 0; if (auto Attr = OffendingDecl->getAttr<UnavailableAttr>()) { if (Attr->isImplicit() && Attr->getImplicitReason()) { // Most of these failures are due to extra restrictions in ARC; // reflect that in the primary diagnostic when applicable. auto flagARCError = [&] { if (S.getLangOpts().ObjCAutoRefCount && S.getSourceManager().isInSystemHeader( OffendingDecl->getLocation())) diag = diag::err_unavailable_in_arc; }; switch (Attr->getImplicitReason()) { case UnavailableAttr::IR_None: break; case UnavailableAttr::IR_ARCForbiddenType: flagARCError(); diag_available_here = diag::note_arc_forbidden_type; break; case UnavailableAttr::IR_ForbiddenWeak: if (S.getLangOpts().ObjCWeakRuntime) diag_available_here = diag::note_arc_weak_disabled; else diag_available_here = diag::note_arc_weak_no_runtime; break; case UnavailableAttr::IR_ARCForbiddenConversion: flagARCError(); diag_available_here = diag::note_performs_forbidden_arc_conversion; break; case UnavailableAttr::IR_ARCInitReturnsUnrelated: flagARCError(); diag_available_here = diag::note_arc_init_returns_unrelated; break; case UnavailableAttr::IR_ARCFieldWithOwnership: flagARCError(); diag_available_here = diag::note_arc_field_with_ownership; break; } } } break; case AR_Available: llvm_unreachable("Warning for availability of available declaration?"); } CharSourceRange UseRange; StringRef Replacement; if (K == AR_Deprecated) { if (auto Attr = OffendingDecl->getAttr<DeprecatedAttr>()) Replacement = Attr->getReplacement(); if (auto Attr = getAttrForPlatform(S.Context, OffendingDecl)) Replacement = Attr->getReplacement(); if (!Replacement.empty()) UseRange = CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); } if (!Message.empty()) { S.Diag(Loc, diag_message) << ReferringDecl << Message << (UseRange.isValid() ? FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); if (ObjCProperty) S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) << ObjCProperty->getDeclName() << property_note_select; } else if (!UnknownObjCClass) { S.Diag(Loc, diag) << ReferringDecl << (UseRange.isValid() ? FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); if (ObjCProperty) S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) << ObjCProperty->getDeclName() << property_note_select; } else { S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << (UseRange.isValid() ? FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class); } S.Diag(NoteLocation, diag_available_here) << OffendingDecl << available_here_select_kind; } static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, Decl *Ctx) { assert(DD.Kind == DelayedDiagnostic::Availability && "Expected an availability diagnostic here"); DD.Triggered = true; DoEmitAvailabilityWarning( S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(), DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(), DD.getObjCProperty(), false); } void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { assert(DelayedDiagnostics.getCurrentPool()); DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); DelayedDiagnostics.popWithoutEmitting(state); // When delaying diagnostics to run in the context of a parsed // declaration, we only want to actually emit anything if parsing // succeeds. if (!decl) return; // We emit all the active diagnostics in this pool or any of its // parents. In general, we'll get one pool for the decl spec // and a child pool for each declarator; in a decl group like: // deprecated_typedef foo, *bar, baz(); // only the declarator pops will be passed decls. This is correct; // we really do need to consider delayed diagnostics from the decl spec // for each of the different declarations. const DelayedDiagnosticPool *pool = &poppedPool; do { for (DelayedDiagnosticPool::pool_iterator i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { // This const_cast is a bit lame. Really, Triggered should be mutable. DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); if (diag.Triggered) continue; switch (diag.Kind) { case DelayedDiagnostic::Availability: // Don't bother giving deprecation/unavailable diagnostics if // the decl is invalid. if (!decl->isInvalidDecl()) handleDelayedAvailabilityCheck(*this, diag, decl); break; case DelayedDiagnostic::Access: HandleDelayedAccessCheck(diag, decl); break; case DelayedDiagnostic::ForbiddenType: handleDelayedForbiddenType(*this, diag, decl); break; } } } while ((pool = pool->getParent())); } /// Given a set of delayed diagnostics, re-emit them as if they had /// been delayed in the current context instead of in the given pool. /// Essentially, this just moves them to the current pool. void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); assert(curPool && "re-emitting in undelayed context not supported"); curPool->steal(pool); } static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR, const NamedDecl *ReferringDecl, const NamedDecl *OffendingDecl, StringRef Message, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass, const ObjCPropertyDecl *ObjCProperty, bool ObjCPropertyAccess) { // Delay if we're currently parsing a declaration. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { S.DelayedDiagnostics.add( DelayedDiagnostic::makeAvailability( AR, Loc, ReferringDecl, OffendingDecl, UnknownObjCClass, ObjCProperty, Message, ObjCPropertyAccess)); return; } Decl *Ctx = cast<Decl>(S.getCurLexicalContext()); DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl, Message, Loc, UnknownObjCClass, ObjCProperty, ObjCPropertyAccess); } namespace { /// Returns true if the given statement can be a body-like child of \p Parent. bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) { switch (Parent->getStmtClass()) { case Stmt::IfStmtClass: return cast<IfStmt>(Parent)->getThen() == S || cast<IfStmt>(Parent)->getElse() == S; case Stmt::WhileStmtClass: return cast<WhileStmt>(Parent)->getBody() == S; case Stmt::DoStmtClass: return cast<DoStmt>(Parent)->getBody() == S; case Stmt::ForStmtClass: return cast<ForStmt>(Parent)->getBody() == S; case Stmt::CXXForRangeStmtClass: return cast<CXXForRangeStmt>(Parent)->getBody() == S; case Stmt::ObjCForCollectionStmtClass: return cast<ObjCForCollectionStmt>(Parent)->getBody() == S; case Stmt::CaseStmtClass: case Stmt::DefaultStmtClass: return cast<SwitchCase>(Parent)->getSubStmt() == S; default: return false; } } class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> { const Stmt *Target; public: bool VisitStmt(Stmt *S) { return S != Target; } /// Returns true if the given statement is present in the given declaration. static bool isContained(const Stmt *Target, const Decl *D) { StmtUSEFinder Visitor; Visitor.Target = Target; return !Visitor.TraverseDecl(const_cast<Decl *>(D)); } }; /// Traverses the AST and finds the last statement that used a given /// declaration. class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> { const Decl *D; public: bool VisitDeclRefExpr(DeclRefExpr *DRE) { if (DRE->getDecl() == D) return false; return true; } static const Stmt *findLastStmtThatUsesDecl(const Decl *D, const CompoundStmt *Scope) { LastDeclUSEFinder Visitor; Visitor.D = D; for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) { const Stmt *S = *I; if (!Visitor.TraverseStmt(const_cast<Stmt *>(S))) return S; } return nullptr; } }; /// \brief This class implements -Wunguarded-availability. /// /// This is done with a traversal of the AST of a function that makes reference /// to a partially available declaration. Whenever we encounter an \c if of the /// form: \c if(@available(...)), we use the version from the condition to visit /// the then statement. class DiagnoseUnguardedAvailability : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> { typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base; Sema &SemaRef; Decl *Ctx; /// Stack of potentially nested 'if (@available(...))'s. SmallVector<VersionTuple, 8> AvailabilityStack; SmallVector<const Stmt *, 16> StmtStack; void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range); public: DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx) : SemaRef(SemaRef), Ctx(Ctx) { AvailabilityStack.push_back( SemaRef.Context.getTargetInfo().getPlatformMinVersion()); } bool TraverseDecl(Decl *D) { // Avoid visiting nested functions to prevent duplicate warnings. if (!D || isa<FunctionDecl>(D)) return true; return Base::TraverseDecl(D); } bool TraverseStmt(Stmt *S) { if (!S) return true; StmtStack.push_back(S); bool Result = Base::TraverseStmt(S); StmtStack.pop_back(); return Result; } void IssueDiagnostics(Stmt *S) { TraverseStmt(S); } bool TraverseIfStmt(IfStmt *If); bool TraverseLambdaExpr(LambdaExpr *E) { return true; } // for 'case X:' statements, don't bother looking at the 'X'; it can't lead // to any useful diagnostics. bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); } bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) { if (PRE->isClassReceiver()) DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation()); return true; } bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) { if (ObjCMethodDecl *D = Msg->getMethodDecl()) DiagnoseDeclAvailability( D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd())); return true; } bool VisitDeclRefExpr(DeclRefExpr *DRE) { DiagnoseDeclAvailability(DRE->getDecl(), SourceRange(DRE->getLocStart(), DRE->getLocEnd())); return true; } bool VisitMemberExpr(MemberExpr *ME) { DiagnoseDeclAvailability(ME->getMemberDecl(), SourceRange(ME->getLocStart(), ME->getLocEnd())); return true; } bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { SemaRef.Diag(E->getLocStart(), diag::warn_at_available_unchecked_use) << (!SemaRef.getLangOpts().ObjC1); return true; } bool VisitTypeLoc(TypeLoc Ty); }; void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability( NamedDecl *D, SourceRange Range) { AvailabilityResult Result; const NamedDecl *OffendingDecl; std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(D, nullptr); if (Result != AR_Available) { // All other diagnostic kinds have already been handled in // DiagnoseAvailabilityOfDecl. if (Result != AR_NotYetIntroduced) return; const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl); VersionTuple Introduced = AA->getIntroduced(); if (AvailabilityStack.back() >= Introduced) return; // If the context of this function is less available than D, we should not // emit a diagnostic. if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx)) return; // We would like to emit the diagnostic even if -Wunguarded-availability is // not specified for deployment targets >= to iOS 11 or equivalent or // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or // later. unsigned DiagKind = shouldDiagnoseAvailabilityByDefault( SemaRef.Context, SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced) ? diag::warn_unguarded_availability_new : diag::warn_unguarded_availability; SemaRef.Diag(Range.getBegin(), DiagKind) << Range << D << AvailabilityAttr::getPrettyPlatformName( SemaRef.getASTContext().getTargetInfo().getPlatformName()) << Introduced.getAsString(); SemaRef.Diag(OffendingDecl->getLocation(), diag::note_availability_specified_here) << OffendingDecl << /* partial */ 3; auto FixitDiag = SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence) << Range << D << (SemaRef.getLangOpts().ObjC1 ? /*@available*/ 0 : /*__builtin_available*/ 1); // Find the statement which should be enclosed in the if @available check. if (StmtStack.empty()) return; const Stmt *StmtOfUse = StmtStack.back(); const CompoundStmt *Scope = nullptr; for (const Stmt *S : llvm::reverse(StmtStack)) { if (const auto *CS = dyn_cast<CompoundStmt>(S)) { Scope = CS; break; } if (isBodyLikeChildStmt(StmtOfUse, S)) { // The declaration won't be seen outside of the statement, so we don't // have to wrap the uses of any declared variables in if (@available). // Therefore we can avoid setting Scope here. break; } StmtOfUse = S; } const Stmt *LastStmtOfUse = nullptr; if (isa<DeclStmt>(StmtOfUse) && Scope) { for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) { if (StmtUSEFinder::isContained(StmtStack.back(), D)) { LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope); break; } } } const SourceManager &SM = SemaRef.getSourceManager(); SourceLocation IfInsertionLoc = SM.getExpansionLoc(StmtOfUse->getLocStart()); SourceLocation StmtEndLoc = SM.getExpansionRange( (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getLocEnd()) .second; if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc)) return; StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM); const char *ExtraIndentation = " "; std::string FixItString; llvm::raw_string_ostream FixItOS(FixItString); FixItOS << "if (" << (SemaRef.getLangOpts().ObjC1 ? "@available" : "__builtin_available") << "(" << AvailabilityAttr::getPlatformNameSourceSpelling( SemaRef.getASTContext().getTargetInfo().getPlatformName()) << " " << Introduced.getAsString() << ", *)) {\n" << Indentation << ExtraIndentation; FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str()); SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken( StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(), /*SkipTrailingWhitespaceAndNewLine=*/false); if (ElseInsertionLoc.isInvalid()) ElseInsertionLoc = Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts()); FixItOS.str().clear(); FixItOS << "\n" << Indentation << "} else {\n" << Indentation << ExtraIndentation << "// Fallback on earlier versions\n" << Indentation << "}"; FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str()); } } bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) { const Type *TyPtr = Ty.getTypePtr(); SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()}; if (Range.isInvalid()) return true; if (const TagType *TT = dyn_cast<TagType>(TyPtr)) { TagDecl *TD = TT->getDecl(); DiagnoseDeclAvailability(TD, Range); } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) { TypedefNameDecl *D = TD->getDecl(); DiagnoseDeclAvailability(D, Range); } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) { if (NamedDecl *D = ObjCO->getInterface()) DiagnoseDeclAvailability(D, Range); } return true; } bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) { VersionTuple CondVersion; if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) { CondVersion = E->getVersion(); // If we're using the '*' case here or if this check is redundant, then we // use the enclosing version to check both branches. if (CondVersion.empty() || CondVersion <= AvailabilityStack.back()) return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse()); } else { // This isn't an availability checking 'if', we can just continue. return Base::TraverseIfStmt(If); } AvailabilityStack.push_back(CondVersion); bool ShouldContinue = TraverseStmt(If->getThen()); AvailabilityStack.pop_back(); return ShouldContinue && TraverseStmt(If->getElse()); } } // end anonymous namespace void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) { Stmt *Body = nullptr; if (auto *FD = D->getAsFunction()) { // FIXME: We only examine the pattern decl for availability violations now, // but we should also examine instantiated templates. if (FD->isTemplateInstantiation()) return; Body = FD->getBody(); } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) Body = MD->getBody(); else if (auto *BD = dyn_cast<BlockDecl>(D)) Body = BD->getBody(); assert(Body && "Need a body here!"); DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body); } void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks) { std::string Message; AvailabilityResult Result; const NamedDecl* OffendingDecl; // See if this declaration is unavailable, deprecated, or partial. std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(D, &Message); if (Result == AR_Available) return; if (Result == AR_NotYetIntroduced) { if (AvoidPartialAvailabilityChecks) return; // We need to know the @available context in the current function to // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that // when we're done parsing the current function. if (getCurFunctionOrMethodDecl()) { getEnclosingFunction()->HasPotentialAvailabilityViolations = true; return; } else if (getCurBlock() || getCurLambda()) { getCurFunction()->HasPotentialAvailabilityViolations = true; return; } } const ObjCPropertyDecl *ObjCPDecl = nullptr; if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { AvailabilityResult PDeclResult = PD->getAvailability(nullptr); if (PDeclResult == Result) ObjCPDecl = PD; } } EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Loc, UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess); }
;************************************************** ; Author: Henry Allard ; c Henry Allard 2020 ; Bootloader for CDs ;************************************************** ; Note: Here, we are executed like a normal ; COM program, but we are still in Ring 0. ; We will use this loader to set up 32 bit ; mode and basic exception handling ; This loaded program will be our 32 bit Kernel. ; We do not have the limitation of 512 bytes here, ; so we can add anything we want here! bits 16 ; we are still in real mode org 0xe000 ; Bootable area ; we are loaded at address 0x7c00 ;*************************************************; ; OEM Parameter block(for floppies) ;*************************************************; ; Error Fix 2 - Removing the ugly TIMES directive (actually needed??) ------------------------------------- ;TIMES 0Bh-$+start DB 0 ; The OEM Parameter Block is exactally 3 bytes ; from where we are loaded at. This fills in those ; 3 bytes, along with 8 more. Why? ;bpbOEM db "My OS " ; This member must be exactally 8 bytes. It is just ; the name of your OS :) Everything else remains the same. ;bpbBytesPerSector: DW 512 ;bpbSectorsPerCluster: DB 1 ;bpbReservedSectors: DW 1 ;bpbNumberOfFATs: DB 2 ;bpbRootEntries: DW 224 ;bpbTotalSectors: DW 2880 ;bpbMedia: DB 0xF0 ;bpbSectorsPerFAT: DW 9 ;bpbSectorsPerTrack: DW 18 ;bpbHeadsPerCylinder: DW 2 ;bpbHiddenSectors: DD 0 ;bpbTotalSectorsBig: DD 0 ;bsDriveNumber: DB 0 ;bsUnused: DB 0 ;bsExtBootSignature: DB 0x29 ;bsSerialNumber: DD 0xa0a1a2a3 ;bsVolumeLabel: DB "MOS FLOPPY " ;bsFileSystem: DB "FAT12 " ;*************************************************; ; Prints a string ; DS=>SI: 0 terminated string ;************************************************; Print: lodsb ; load next byte from string from SI to AL or al, al ; Does AL=0? jz PrintDone ; Yep, null terminator found-bail out mov ah, 0eh ; Nope-Print the character int 10h jmp Print ; Repeat until null terminator found PrintDone: ret ; we are done, so return ;*************************************************; ; Second Stage Loader Entry Point ;************************************************; main: ;;cli ; clear interrupts ;;push cs ; Insure DS=CS ;pop ds xor ax, ax ; Setup segments to insure they are 0. Remember that mov ds, ax ; we have ORG 0x7c00. This means all addresses are based mov es, ax ; from 0x7c00:0. Because the data segments are within the same ; code segment, null em. mov si, welcome call Print mov si, Msg call Print xor ax, ax ; clear ax int 0x12 ; get the amount of KB from the BIOS mov eax, 0xCAFEBABE cli ; clear interrupts to prevent triple faults hlt ; hault the system ;;times 510 - ($-$$) db 0 ;;dw 0xAA55 ; Boot Signature ;*************************************************; ; Data Section ;************************************************; welcome db `Welcome to my Operating System!`,13,10,0 Msg db `Preparing to load operating system...`,13,10,0
/** * Copyright (C) 2022 Elisha Riedlinger * * This software is provided 'as-is', without any express or implied warranty. In no event will the * authors be held liable for any damages arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, including commercial * applications, and to alter it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the * original software. If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as * being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include "patches.h" #include "Common\Utils.h" #include "Logging\Logging.h" // Run SH2 code to fix the rotating Mannequin glitch void RunRotatingMannequin() { // Get flashlight acquired Address static DWORD *FlashlightAcquiredAddr = nullptr; if (!FlashlightAcquiredAddr) { RUNONCE(); // Get address constexpr BYTE SearchBytes[]{ 0x8D, 0x50, 0x1C, 0x8B, 0x0A, 0x89, 0x0D }; FlashlightAcquiredAddr = (DWORD*)ReadSearchedAddresses(0x0045507D, 0x004552DD, 0x004552DD, SearchBytes, sizeof(SearchBytes), 0x56); // Checking address pointer if (!FlashlightAcquiredAddr) { Logging::Log() << __FUNCTION__ << " Error: failed to find memory address!"; return; } } // Get Mannequin state Address static DWORD *MannequinStateAddr = nullptr; if (!MannequinStateAddr) { RUNONCE(); // Get address constexpr BYTE SearchBytes[]{ 0x68, 0x00, 0x02, 0x00, 0x00, 0x33, 0xF6, 0x33, 0xDB, 0x50, 0x89, 0x94, 0x24, 0x50, 0x04, 0x00, 0x00 }; MannequinStateAddr = (DWORD*)ReadSearchedAddresses(0x0048CBC5, 0x0048CE65, 0x0048D075, SearchBytes, sizeof(SearchBytes), 0x34); // Checking address pointer if (!MannequinStateAddr) { Logging::Log() << __FUNCTION__ << " Error: failed to find memory address!"; return; } MannequinStateAddr = (DWORD*)((DWORD)MannequinStateAddr + 0x60); } LOG_ONCE("Fixing the rotating Mannequin glitch..."); // Static updates static bool ValueSet = false; if (GetRoomID() == 0x15 && *MannequinStateAddr != 0x00 && (*FlashlightAcquiredAddr & 0x40000)) { if (!ValueSet && *MannequinStateAddr == 0x206) { DWORD Value = 0x207; UpdateMemoryAddress(MannequinStateAddr, &Value, sizeof(DWORD)); } ValueSet = true; } else if (ValueSet) { ValueSet = false; } }
; void tshr_scroll_up(uchar prows, uchar attr) SECTION code_clib SECTION code_arch PUBLIC tshr_scroll_up EXTERN asm_tshr_scroll_up tshr_scroll_up: pop af pop hl pop de push de push hl push af jp asm_tshr_scroll_up
;; -------------------------------------------------------------------------------- ;; jz/jnz example ;; -------------------------------------------------------------------------------- .data val sw 10 .code load val push 10 sub jz on_zero_flag stat halt on_zero_flag: push 255 stor val inc jnz not_a_zero stat halt not_a_zero: load val push 3840 add stor val ; if all ok, we store #{0FFF} stat halt
[org 0x7c00] KERNEL_OFFSET equ 0x1000 ; The same one we used when linking the kernel mov [BOOT_DRIVE], dl ; Remember that the BIOS sets us the boot drive in 'dl' on boot mov bp, 0x9000 mov sp, bp mov bx, MSG_REAL_MODE call print_string call print_nl call load_kernel ; read the kernel from disk call switch_to_pm ; disable interrupts, load GDT, etc. Finally jumps to 'BEGIN_PM' jmp $ ; Never executed %include "boot/disk_load.asm" %include "boot/print_string.asm" %include "boot/pm/gdt.asm" %include "boot/pm/print_string_pm.asm" %include "boot/pm/switch_to_pm.asm" [bits 16] load_kernel: mov bx, MSG_LOAD_KERNEL call print_string call print_nl mov bx, KERNEL_OFFSET ; Read from disk and store in 0x1000 mov dh, 50 ; Kernel size (number of sectors to read); 1 sector = 512 bytes mov dl, [BOOT_DRIVE] call disk_load ret [bits 32] begin_pm: mov ebx, MSG_PROT_MODE call print_string_pm call KERNEL_OFFSET ; Give control to the kernel jmp $ ; Stay here when the kernel returns control to us (if ever) BOOT_DRIVE: db 0 ; It is a good idea to store it in memory because 'dl' may get overwritten MSG_REAL_MODE: db "Started in 16-bit Real Mode", 0 MSG_PROT_MODE: db "Landed in 32-bit Protected Mode", 0 MSG_LOAD_KERNEL: db "Loading kernel into memory", 0 ; padding times 510 - ($-$$) db 0 dw 0xaa55
%macro print 2 mov rax,01; mov rdi,01; mov rsi,%1; mov rdx,%2; syscall; %endmacro %macro read 2 mov rax,00; mov rdi,00; mov rsi,%1; mov rdx,%2; syscall; %endmacro %macro fopen 2 mov rax,02; //SYS_OPEN mov rdi,%1; //file-name mov rsi,%2; //File-Open Mode mov rdx,0777o; //File-Permission syscall; %endmacro %macro fclose 1 mov rax,03; //SYS_CLOSE mov rdi,%1; //File-Descriptor syscall; %endmacro %macro fread 3 mov rax,00; //SYS_READ mov rdi,%1; //File-Descriptor mov rsi,%2; //Buffer mov rdx,%3; //Count syscall; %endmacro %macro fwrite 3 mov rax,01; //SYS_WRITE mov rdi,%1; //File-Descriptor mov rsi,%2; //Buffer mov rdx,%3; //Count syscall; %endmacro section .data inAscii db "0000000000000000"; outAscii db "0000000000000000"; _AsciiToHex:; //ASCII in inAscii ----> HEX in RAX mov rsi,inAscii; xor rax,rax; begin1: cmp byte[rsi],0xA; //Compare With New Line je end_AsciiToHex; rol rax,04d; mov bl,byte[rsi]; cmp bl,39h; jbe sub30 sub bl,07h; sub30: sub bl,30h; add al,bl; inc rsi; jmp begin1; end_AsciiToHex: ret; _HexToAscii:; // HEX in RAX -----> ASCII in outAscii mov rsi,outAscii+15d; mov rcx,16d begin2: xor rdx,rdx; mov rbx,10h; //16d div rbx; cmp dl,09h; jbe add30; add dl,07h; add30: add dl,30h; mov byte[rsi],dl; update: dec rsi; dec rcx; jnz begin2; end_HexToAscii: ret;
/* * FreeRTOS Kernel V10.3.1 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * 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. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #include "FreeRTOSConfig.h" #include "portasm.h" .CODE /* * The RTOS tick ISR. * * If the cooperative scheduler is in use this simply increments the tick * count. * * If the preemptive scheduler is in use a context switch can also occur. */ _vTickISR: portSAVE_CONTEXT call #_xTaskIncrementTick cmp.w #0x00, r15 jeq _SkipContextSwitch call #_vTaskSwitchContext _SkipContextSwitch: portRESTORE_CONTEXT /*-----------------------------------------------------------*/ /* * Manual context switch called by the portYIELD() macro. */ _vPortYield:: /* Mimic an interrupt by pushing the SR. */ push SR /* Now the SR is stacked we can disable interrupts. */ dint /* Save the context of the current task. */ portSAVE_CONTEXT /* Switch to the highest priority task that is ready to run. */ call #_vTaskSwitchContext /* Restore the context of the new task. */ portRESTORE_CONTEXT /*-----------------------------------------------------------*/ /* * Start off the scheduler by initialising the RTOS tick timer, then restoring * the context of the first task. */ _xPortStartScheduler:: /* Setup the hardware to generate the tick. Interrupts are disabled when this function is called. */ call #_prvSetupTimerInterrupt /* Restore the context of the first task that is going to run. */ portRESTORE_CONTEXT /*-----------------------------------------------------------*/ /* Place the tick ISR in the correct vector. */ .VECTORS .KEEP ORG TIMERA0_VECTOR DW _vTickISR END
dcode BA!,3,,BUS_SETADDR ; ( addr -- ) pla mmu $00 nxt dcode BA@,3,,BUS_GETADDR ; ( -- addr ) mmu $80 pha nxt dcode BW!,3,,BUS_SETWIN ; ( win -- ) pla mmu $01 nxt dcode BW@,3,,BUS_GETWIN ; ( win -- ) mmu $81 pha nxt dword BUS!,4,,BUS_POKE ; ( value addr -- ) .wp BUS_GETWIN .wp ADD .wp POKE .wp EXIT dword BUS@,4,,BUS_PEEK ; ( addr -- value ) .wp BUS_GETWIN .wp ADD .wp PEEK .wp EXIT dword BUSC!,5,,BUS_POKEBYTE ; ( value addr -- ) .wp BUS_GETWIN .wp ADD .wp POKEBYTE .wp EXIT dword BUSC@,5,,BUS_PEEKBYTE ; ( addr -- value ) .wp BUS_GETWIN .wp ADD .wp PEEKBYTE .wp EXIT
; https://github.com/luckytoilet/projecteuler-solutions/blob/master/Solutions.md section .text global main extern print_digits extern exit main: jmp exit ; def largest_prime_factor(n: int): ; max = int(n/2) ; largest = 0 ; for i in range(2, max): ; if n%i == 0: ; largest = i ; n /= i ; return largest g_prime_fac: ; rax is number to factorize (later rcx) push rax xor rdx, rdx ; clear high word mov rbx, 2 ; set max try to (int)rax/2 div rbx pop rcx ; number to factorize = rcx p_loop: push rax ; move rax to temp location pop rax cmp rbx, rax jle p_loop ret fib_even: ; call with 4000000 xor rbx, rbx ; sum register = 0 xor rcx, rcx ; prev = 0 mov rdx, 1 ; current = 1 e2_loop: push rax mov rax, rdx ; set rax to current and rax, 1 ; check low bit jnz e2_cont ; if odd, cont add rbx, rdx ; accumulate e2_cont: pop rax push rdx ; temp = current add rdx, rcx ; current += prev pop rcx ; prev = temp cmp rdx, rax ; continue if less than rax jl e2_loop mov rax, rbx ret sum_3_5: ; call with 1000 xor rbx, rbx ; sum register xor rcx, rcx ; counter _3loop: add rbx, rcx ; accumulate add rcx, 3 cmp rcx, rax jl _3loop ; if greater than or equal to n move to fives ; init 5 xor rcx, rcx ; 5 counter _5loop: add rbx, rcx ; accumulate add rcx, 5 cmp rcx, rax jl _5loop ; if greater than or equal to n move to 15 ; init 15 xor rcx, rcx ; 15 counter _15loop: sub rbx, rcx ; sub add rcx, 15 cmp rcx, rax jl _15loop mov rax, rbx ret
;=============================================================================== ; Copyright 2014-2020 Intel Corporation ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;=============================================================================== ; ; ; Purpose: Cryptography Primitive. ; Rijndael Key Expansion Support ; ; Content: ; SubsDword_8uT() ; ; %include "asmdefs.inc" %include "ia_32e.inc" %if (_IPP32E >= _IPP32E_M7) segment .text align=IPP_ALIGN_FACTOR %xdefine CACHE_LINE_SIZE (64) ;*************************************************************** ;* Purpose: Mitigation of the Key Expansion procedure ;* ;* Ipp32u Touch_SubsDword_8uT(Ipp32u inp, ;* const Ipp8u* pTbl, ;* int tblBytes) ;*************************************************************** align IPP_ALIGN_FACTOR IPPASM Touch_SubsDword_8uT,PUBLIC USES_GPR rsi,rdi USES_XMM COMP_ABI 3 ;; rdi: inp: DWORD, ; input dword ;; rsi: pTbl: BYTE, ; Rijndael's S-box ;; edx tblLen: DWORD ; length of table (bytes) movsxd r8, edx ; length xor rcx, rcx .touch_tbl: mov rax, [rsi+rcx] add rcx, CACHE_LINE_SIZE cmp rcx, r8 jl .touch_tbl mov rax, rdi and rax, 0FFh ; b[0] movzx rax, BYTE [rsi+rax] shr rdi, 8 mov r9, rdi and r9, 0FFh ; b[1] movzx r9, BYTE [rsi+r9] shl r9, 8 shr rdi, 8 mov rcx, rdi and rcx, 0FFh ; b[2] movzx rcx, BYTE [rsi+rcx] shl rcx, 16 shr rdi, 8 mov rdx, rdi and rdx, 0FFh ; b[3] movzx rdx, BYTE [rsi+rdx] shl rdx, 24 or rax, r9 or rax, rcx or rax, rdx REST_XMM REST_GPR ret ENDFUNC Touch_SubsDword_8uT %endif
; A055610: A companion sequence to A011896. ; 0,0,0,1,2,5,9,15,24,36,52,71,95,123,156,195,240,292,350,416,489,570,660,759,868,986,1115,1254,1404,1566,1740,1927,2126,2339,2565,2805,3060,3330,3616,3917,4235,4569,4920,5289,5676,6082,6506,6950,7413,7896 bin $0,3 add $0,2 mul $0,6 div $0,14
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2020 Intel Corporation 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 Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Function API: ; UINT32 crc32_gzip_refl_by16_10( ; UINT32 init_crc, //initial CRC value, 32 bits ; const unsigned char *buf, //buffer pointer to calculate CRC on ; UINT64 len //buffer length in bytes (64-bit data) ; ); ; ; Authors: ; Erdinc Ozturk ; Vinodh Gopal ; James Guilford ; ; Reference paper titled "Fast CRC Computation for Generic Polynomials Using PCLMULQDQ Instruction" ; URL: http://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf ; ; %include "reg_sizes.asm" %ifndef FUNCTION_NAME %define FUNCTION_NAME crc32_ieee_by16_10 %endif %if (AS_FEATURE_LEVEL) >= 10 [bits 64] default rel section .text %ifidn __OUTPUT_FORMAT__, win64 %xdefine arg1 rcx %xdefine arg2 rdx %xdefine arg3 r8 %xdefine arg1_low32 ecx %else %xdefine arg1 rdi %xdefine arg2 rsi %xdefine arg3 rdx %xdefine arg1_low32 edi %endif %define TMP 16*0 %ifidn __OUTPUT_FORMAT__, win64 %define XMM_SAVE 16*2 %define VARIABLE_OFFSET 16*12+8 %else %define VARIABLE_OFFSET 16*2+8 %endif align 16 mk_global FUNCTION_NAME, function FUNCTION_NAME: endbranch not arg1_low32 sub rsp, VARIABLE_OFFSET %ifidn __OUTPUT_FORMAT__, win64 ; push the xmm registers into the stack to maintain vmovdqa [rsp + XMM_SAVE + 16*0], xmm6 vmovdqa [rsp + XMM_SAVE + 16*1], xmm7 vmovdqa [rsp + XMM_SAVE + 16*2], xmm8 vmovdqa [rsp + XMM_SAVE + 16*3], xmm9 vmovdqa [rsp + XMM_SAVE + 16*4], xmm10 vmovdqa [rsp + XMM_SAVE + 16*5], xmm11 vmovdqa [rsp + XMM_SAVE + 16*6], xmm12 vmovdqa [rsp + XMM_SAVE + 16*7], xmm13 vmovdqa [rsp + XMM_SAVE + 16*8], xmm14 vmovdqa [rsp + XMM_SAVE + 16*9], xmm15 %endif vbroadcasti32x4 zmm18, [SHUF_MASK] cmp arg3, 256 jl .less_than_256 ; load the initial crc value vmovd xmm10, arg1_low32 ; initial crc ; crc value does not need to be byte-reflected, but it needs to be moved to the high part of the register. ; because data will be byte-reflected and will align with initial crc at correct place. vpslldq xmm10, 12 ; receive the initial 64B data, xor the initial crc value vmovdqu8 zmm0, [arg2+16*0] vmovdqu8 zmm4, [arg2+16*4] vpshufb zmm0, zmm0, zmm18 vpshufb zmm4, zmm4, zmm18 vpxorq zmm0, zmm10 vbroadcasti32x4 zmm10, [rk3] ;xmm10 has rk3 and rk4 ;imm value of pclmulqdq instruction will determine which constant to use sub arg3, 256 cmp arg3, 256 jl .fold_128_B_loop vmovdqu8 zmm7, [arg2+16*8] vmovdqu8 zmm8, [arg2+16*12] vpshufb zmm7, zmm7, zmm18 vpshufb zmm8, zmm8, zmm18 vbroadcasti32x4 zmm16, [rk_1] ;zmm16 has rk-1 and rk-2 sub arg3, 256 .fold_256_B_loop: add arg2, 256 vmovdqu8 zmm3, [arg2+16*0] vpshufb zmm3, zmm3, zmm18 vpclmulqdq zmm1, zmm0, zmm16, 0x00 vpclmulqdq zmm2, zmm0, zmm16, 0x11 vpxorq zmm0, zmm1, zmm2 vpxorq zmm0, zmm0, zmm3 vmovdqu8 zmm9, [arg2+16*4] vpshufb zmm9, zmm9, zmm18 vpclmulqdq zmm5, zmm4, zmm16, 0x00 vpclmulqdq zmm6, zmm4, zmm16, 0x11 vpxorq zmm4, zmm5, zmm6 vpxorq zmm4, zmm4, zmm9 vmovdqu8 zmm11, [arg2+16*8] vpshufb zmm11, zmm11, zmm18 vpclmulqdq zmm12, zmm7, zmm16, 0x00 vpclmulqdq zmm13, zmm7, zmm16, 0x11 vpxorq zmm7, zmm12, zmm13 vpxorq zmm7, zmm7, zmm11 vmovdqu8 zmm17, [arg2+16*12] vpshufb zmm17, zmm17, zmm18 vpclmulqdq zmm14, zmm8, zmm16, 0x00 vpclmulqdq zmm15, zmm8, zmm16, 0x11 vpxorq zmm8, zmm14, zmm15 vpxorq zmm8, zmm8, zmm17 sub arg3, 256 jge .fold_256_B_loop ;; Fold 256 into 128 add arg2, 256 vpclmulqdq zmm1, zmm0, zmm10, 0x00 vpclmulqdq zmm2, zmm0, zmm10, 0x11 vpternlogq zmm7, zmm1, zmm2, 0x96 ; xor ABC vpclmulqdq zmm5, zmm4, zmm10, 0x00 vpclmulqdq zmm6, zmm4, zmm10, 0x11 vpternlogq zmm8, zmm5, zmm6, 0x96 ; xor ABC vmovdqa32 zmm0, zmm7 vmovdqa32 zmm4, zmm8 add arg3, 128 jmp .fold_128_B_register ; at this section of the code, there is 128*x+y (0<=y<128) bytes of buffer. The fold_128_B_loop ; loop will fold 128B at a time until we have 128+y Bytes of buffer ; fold 128B at a time. This section of the code folds 8 xmm registers in parallel .fold_128_B_loop: add arg2, 128 vmovdqu8 zmm8, [arg2+16*0] vpshufb zmm8, zmm8, zmm18 vpclmulqdq zmm2, zmm0, zmm10, 0x00 vpclmulqdq zmm1, zmm0, zmm10, 0x11 vpxorq zmm0, zmm2, zmm1 vpxorq zmm0, zmm0, zmm8 vmovdqu8 zmm9, [arg2+16*4] vpshufb zmm9, zmm9, zmm18 vpclmulqdq zmm5, zmm4, zmm10, 0x00 vpclmulqdq zmm6, zmm4, zmm10, 0x11 vpxorq zmm4, zmm5, zmm6 vpxorq zmm4, zmm4, zmm9 sub arg3, 128 jge .fold_128_B_loop ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; add arg2, 128 ; at this point, the buffer pointer is pointing at the last y Bytes of the buffer, where 0 <= y < 128 ; the 128B of folded data is in 8 of the xmm registers: xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7 .fold_128_B_register: ; fold the 8 128b parts into 1 xmm register with different constants vmovdqu8 zmm16, [rk9] ; multiply by rk9-rk16 vmovdqu8 zmm11, [rk17] ; multiply by rk17-rk20, rk1,rk2, 0,0 vpclmulqdq zmm1, zmm0, zmm16, 0x00 vpclmulqdq zmm2, zmm0, zmm16, 0x11 vextracti64x2 xmm7, zmm4, 3 ; save last that has no multiplicand vpclmulqdq zmm5, zmm4, zmm11, 0x00 vpclmulqdq zmm6, zmm4, zmm11, 0x11 vmovdqa xmm10, [rk1] ; Needed later in reduction loop vpternlogq zmm1, zmm2, zmm5, 0x96 ; xor ABC vpternlogq zmm1, zmm6, zmm7, 0x96 ; xor ABC vshufi64x2 zmm8, zmm1, zmm1, 0x4e ; Swap 1,0,3,2 - 01 00 11 10 vpxorq ymm8, ymm8, ymm1 vextracti64x2 xmm5, ymm8, 1 vpxorq xmm7, xmm5, xmm8 ; instead of 128, we add 128-16 to the loop counter to save 1 instruction from the loop ; instead of a cmp instruction, we use the negative flag with the jl instruction add arg3, 128-16 jl .final_reduction_for_128 ; now we have 16+y bytes left to reduce. 16 Bytes is in register xmm7 and the rest is in memory ; we can fold 16 bytes at a time if y>=16 ; continue folding 16B at a time .16B_reduction_loop: vpclmulqdq xmm8, xmm7, xmm10, 0x11 vpclmulqdq xmm7, xmm7, xmm10, 0x00 vpxor xmm7, xmm8 vmovdqu xmm0, [arg2] vpshufb xmm0, xmm0, xmm18 vpxor xmm7, xmm0 add arg2, 16 sub arg3, 16 ; instead of a cmp instruction, we utilize the flags with the jge instruction ; equivalent of: cmp arg3, 16-16 ; check if there is any more 16B in the buffer to be able to fold jge .16B_reduction_loop ;now we have 16+z bytes left to reduce, where 0<= z < 16. ;first, we reduce the data in the xmm7 register .final_reduction_for_128: add arg3, 16 je .128_done ; here we are getting data that is less than 16 bytes. ; since we know that there was data before the pointer, we can offset ; the input pointer before the actual point, to receive exactly 16 bytes. ; after that the registers need to be adjusted. .get_last_two_xmms: vmovdqa xmm2, xmm7 vmovdqu xmm1, [arg2 - 16 + arg3] vpshufb xmm1, xmm18 ; get rid of the extra data that was loaded before ; load the shift constant lea rax, [pshufb_shf_table + 16] sub rax, arg3 vmovdqu xmm0, [rax] vpshufb xmm2, xmm0 vpxor xmm0, [mask1] vpshufb xmm7, xmm0 vpblendvb xmm1, xmm1, xmm2, xmm0 vpclmulqdq xmm8, xmm7, xmm10, 0x11 vpclmulqdq xmm7, xmm7, xmm10, 0x00 vpxor xmm7, xmm8 vpxor xmm7, xmm1 .128_done: ; compute crc of a 128-bit value vmovdqa xmm10, [rk5] vmovdqa xmm0, xmm7 ;64b fold vpclmulqdq xmm7, xmm10, 0x01 ; H*L vpslldq xmm0, 8 vpxor xmm7, xmm0 ;32b fold vmovdqa xmm0, xmm7 vpand xmm0, [mask2] vpsrldq xmm7, 12 vpclmulqdq xmm7, xmm10, 0x10 vpxor xmm7, xmm0 ;barrett reduction .barrett: vmovdqa xmm10, [rk7] ; rk7 and rk8 in xmm10 vmovdqa xmm0, xmm7 vpclmulqdq xmm7, xmm10, 0x01 vpslldq xmm7, 4 vpclmulqdq xmm7, xmm10, 0x11 vpslldq xmm7, 4 vpxor xmm7, xmm0 vpextrd eax, xmm7, 1 .cleanup: not eax %ifidn __OUTPUT_FORMAT__, win64 vmovdqa xmm6, [rsp + XMM_SAVE + 16*0] vmovdqa xmm7, [rsp + XMM_SAVE + 16*1] vmovdqa xmm8, [rsp + XMM_SAVE + 16*2] vmovdqa xmm9, [rsp + XMM_SAVE + 16*3] vmovdqa xmm10, [rsp + XMM_SAVE + 16*4] vmovdqa xmm11, [rsp + XMM_SAVE + 16*5] vmovdqa xmm12, [rsp + XMM_SAVE + 16*6] vmovdqa xmm13, [rsp + XMM_SAVE + 16*7] vmovdqa xmm14, [rsp + XMM_SAVE + 16*8] vmovdqa xmm15, [rsp + XMM_SAVE + 16*9] %endif add rsp, VARIABLE_OFFSET ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 .less_than_256: ; check if there is enough buffer to be able to fold 16B at a time cmp arg3, 32 jl .less_than_32 ; if there is, load the constants vmovdqa xmm10, [rk1] ; rk1 and rk2 in xmm10 vmovd xmm0, arg1_low32 ; get the initial crc value vpslldq xmm0, 12 ; align it to its correct place vmovdqu xmm7, [arg2] ; load the plaintext vpshufb xmm7, xmm18 ; byte-reflect the plaintext vpxor xmm7, xmm0 ; update the buffer pointer add arg2, 16 ; update the counter. subtract 32 instead of 16 to save one instruction from the loop sub arg3, 32 jmp .16B_reduction_loop align 16 .less_than_32: ; mov initial crc to the return value. this is necessary for zero-length buffers. mov eax, arg1_low32 test arg3, arg3 je .cleanup vmovd xmm0, arg1_low32 ; get the initial crc value vpslldq xmm0, 12 ; align it to its correct place cmp arg3, 16 je .exact_16_left jl .less_than_16_left vmovdqu xmm7, [arg2] ; load the plaintext vpshufb xmm7, xmm18 vpxor xmm7, xmm0 ; xor the initial crc value add arg2, 16 sub arg3, 16 vmovdqa xmm10, [rk1] ; rk1 and rk2 in xmm10 jmp .get_last_two_xmms align 16 .less_than_16_left: ; use stack space to load data less than 16 bytes, zero-out the 16B in memory first. vpxor xmm1, xmm1 mov r11, rsp vmovdqa [r11], xmm1 cmp arg3, 4 jl .only_less_than_4 ; backup the counter value mov r9, arg3 cmp arg3, 8 jl .less_than_8_left ; load 8 Bytes mov rax, [arg2] mov [r11], rax add r11, 8 sub arg3, 8 add arg2, 8 .less_than_8_left: cmp arg3, 4 jl .less_than_4_left ; load 4 Bytes mov eax, [arg2] mov [r11], eax add r11, 4 sub arg3, 4 add arg2, 4 .less_than_4_left: cmp arg3, 2 jl .less_than_2_left ; load 2 Bytes mov ax, [arg2] mov [r11], ax add r11, 2 sub arg3, 2 add arg2, 2 .less_than_2_left: cmp arg3, 1 jl .zero_left ; load 1 Byte mov al, [arg2] mov [r11], al .zero_left: vmovdqa xmm7, [rsp] vpshufb xmm7, xmm18 vpxor xmm7, xmm0 ; xor the initial crc value lea rax, [pshufb_shf_table + 16] sub rax, r9 vmovdqu xmm0, [rax] vpxor xmm0, [mask1] vpshufb xmm7,xmm0 jmp .128_done align 16 .exact_16_left: vmovdqu xmm7, [arg2] vpshufb xmm7, xmm18 vpxor xmm7, xmm0 ; xor the initial crc value jmp .128_done .only_less_than_4: cmp arg3, 3 jl .only_less_than_3 ; load 3 Bytes mov al, [arg2] mov [r11], al mov al, [arg2+1] mov [r11+1], al mov al, [arg2+2] mov [r11+2], al vmovdqa xmm7, [rsp] vpshufb xmm7, xmm18 vpxor xmm7, xmm0 ; xor the initial crc value vpsrldq xmm7, 5 jmp .barrett .only_less_than_3: cmp arg3, 2 jl .only_less_than_2 ; load 2 Bytes mov al, [arg2] mov [r11], al mov al, [arg2+1] mov [r11+1], al vmovdqa xmm7, [rsp] vpshufb xmm7, xmm18 vpxor xmm7, xmm0 ; xor the initial crc value vpsrldq xmm7, 6 jmp .barrett .only_less_than_2: ; load 1 Byte mov al, [arg2] mov [r11], al vmovdqa xmm7, [rsp] vpshufb xmm7, xmm18 vpxor xmm7, xmm0 ; xor the initial crc value vpsrldq xmm7, 7 jmp .barrett section .data align 32 %ifndef USE_CONSTS ; precomputed constants rk_1: dq 0x1851689900000000 rk_2: dq 0xa3dc855100000000 rk1: dq 0xf200aa6600000000 rk2: dq 0x17d3315d00000000 rk3: dq 0x022ffca500000000 rk4: dq 0x9d9ee22f00000000 rk5: dq 0xf200aa6600000000 rk6: dq 0x490d678d00000000 rk7: dq 0x0000000104d101df rk8: dq 0x0000000104c11db7 rk9: dq 0x6ac7e7d700000000 rk10: dq 0xfcd922af00000000 rk11: dq 0x34e45a6300000000 rk12: dq 0x8762c1f600000000 rk13: dq 0x5395a0ea00000000 rk14: dq 0x54f2d5c700000000 rk15: dq 0xd3504ec700000000 rk16: dq 0x57a8445500000000 rk17: dq 0xc053585d00000000 rk18: dq 0x766f1b7800000000 rk19: dq 0xcd8c54b500000000 rk20: dq 0xab40b71e00000000 rk_1b: dq 0xf200aa6600000000 rk_2b: dq 0x17d3315d00000000 dq 0x0000000000000000 dq 0x0000000000000000 %else INCLUDE_CONSTS %endif mask1: dq 0x8080808080808080, 0x8080808080808080 mask2: dq 0xFFFFFFFFFFFFFFFF, 0x00000000FFFFFFFF SHUF_MASK: dq 0x08090A0B0C0D0E0F, 0x0001020304050607 pshufb_shf_table: ; use these values for shift constants for the pshufb instruction ; different alignments result in values as shown: ; dq 0x8887868584838281, 0x008f8e8d8c8b8a89 ; shl 15 (16-1) / shr1 ; dq 0x8988878685848382, 0x01008f8e8d8c8b8a ; shl 14 (16-3) / shr2 ; dq 0x8a89888786858483, 0x0201008f8e8d8c8b ; shl 13 (16-4) / shr3 ; dq 0x8b8a898887868584, 0x030201008f8e8d8c ; shl 12 (16-4) / shr4 ; dq 0x8c8b8a8988878685, 0x04030201008f8e8d ; shl 11 (16-5) / shr5 ; dq 0x8d8c8b8a89888786, 0x0504030201008f8e ; shl 10 (16-6) / shr6 ; dq 0x8e8d8c8b8a898887, 0x060504030201008f ; shl 9 (16-7) / shr7 ; dq 0x8f8e8d8c8b8a8988, 0x0706050403020100 ; shl 8 (16-8) / shr8 ; dq 0x008f8e8d8c8b8a89, 0x0807060504030201 ; shl 7 (16-9) / shr9 ; dq 0x01008f8e8d8c8b8a, 0x0908070605040302 ; shl 6 (16-10) / shr10 ; dq 0x0201008f8e8d8c8b, 0x0a09080706050403 ; shl 5 (16-11) / shr11 ; dq 0x030201008f8e8d8c, 0x0b0a090807060504 ; shl 4 (16-12) / shr12 ; dq 0x04030201008f8e8d, 0x0c0b0a0908070605 ; shl 3 (16-13) / shr13 ; dq 0x0504030201008f8e, 0x0d0c0b0a09080706 ; shl 2 (16-14) / shr14 ; dq 0x060504030201008f, 0x0e0d0c0b0a090807 ; shl 1 (16-15) / shr15 dq 0x8786858483828100, 0x8f8e8d8c8b8a8988 dq 0x0706050403020100, 0x000e0d0c0b0a0908 dq 0x8080808080808080, 0x0f0e0d0c0b0a0908 dq 0x8080808080808080, 0x8080808080808080 %else ; Assembler doesn't understand these opcodes. Add empty symbol for windows. %ifidn __OUTPUT_FORMAT__, win64 global no_ %+ FUNCTION_NAME no_ %+ FUNCTION_NAME %+ : %endif %endif ; (AS_FEATURE_LEVEL) >= 10
; ; Copyright (c) 2010 The WebM 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 in the root of the source ; tree. An additional intellectual property rights grant can be found ; in the file PATENTS. All contributing project authors may ; be found in the AUTHORS file in the root of the source tree. ; %include "vpx_ports/x86_abi_support.asm" %define BLOCK_HEIGHT_WIDTH 4 %define VP8_FILTER_WEIGHT 128 %define VP8_FILTER_SHIFT 7 SECTION .text ;/************************************************************************************ ; Notes: filter_block1d_h6 applies a 6 tap filter horizontally to the input pixels. The ; input pixel array has output_height rows. This routine assumes that output_height is an ; even number. This function handles 8 pixels in horizontal direction, calculating ONE ; rows each iteration to take advantage of the 128 bits operations. ; ; This is an implementation of some of the SSE optimizations first seen in ffvp8 ; ;*************************************************************************************/ ;void vp8_filter_block1d8_h6_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; unsigned int vp8_filter_index ;) global sym(vp8_filter_block1d8_h6_ssse3) PRIVATE sym(vp8_filter_block1d8_h6_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog movsxd rdx, DWORD PTR arg(5) ;table index xor rsi, rsi shl rdx, 4 movdqa xmm7, [GLOBAL(rd)] lea rax, [GLOBAL(k0_k5)] add rax, rdx mov rdi, arg(2) ;output_ptr cmp esi, DWORD PTR [rax] je vp8_filter_block1d8_h4_ssse3 movdqa xmm4, XMMWORD PTR [rax] ;k0_k5 movdqa xmm5, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm6, XMMWORD PTR [rax+128] ;k1_k3 mov rsi, arg(0) ;src_ptr movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rcx, dword ptr arg(4) ;output_height movsxd rdx, dword ptr arg(3) ;output_pitch sub rdi, rdx ;xmm3 free .filter_block1d8_h6_rowloop_ssse3: movq xmm0, MMWORD PTR [rsi - 2] ; -2 -1 0 1 2 3 4 5 movq xmm2, MMWORD PTR [rsi + 3] ; 3 4 5 6 7 8 9 10 punpcklbw xmm0, xmm2 ; -2 3 -1 4 0 5 1 6 2 7 3 8 4 9 5 10 movdqa xmm1, xmm0 pmaddubsw xmm0, xmm4 movdqa xmm2, xmm1 pshufb xmm1, [GLOBAL(shuf2bfrom1)] pshufb xmm2, [GLOBAL(shuf3bfrom1)] pmaddubsw xmm1, xmm5 lea rdi, [rdi + rdx] pmaddubsw xmm2, xmm6 lea rsi, [rsi + rax] dec rcx paddsw xmm0, xmm1 paddsw xmm2, xmm7 paddsw xmm0, xmm2 psraw xmm0, 7 packuswb xmm0, xmm0 movq MMWORD Ptr [rdi], xmm0 jnz .filter_block1d8_h6_rowloop_ssse3 ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret vp8_filter_block1d8_h4_ssse3: movdqa xmm5, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm6, XMMWORD PTR [rax+128] ;k1_k3 movdqa xmm3, XMMWORD PTR [GLOBAL(shuf2bfrom1)] movdqa xmm4, XMMWORD PTR [GLOBAL(shuf3bfrom1)] mov rsi, arg(0) ;src_ptr movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rcx, dword ptr arg(4) ;output_height movsxd rdx, dword ptr arg(3) ;output_pitch sub rdi, rdx .filter_block1d8_h4_rowloop_ssse3: movq xmm0, MMWORD PTR [rsi - 2] ; -2 -1 0 1 2 3 4 5 movq xmm1, MMWORD PTR [rsi + 3] ; 3 4 5 6 7 8 9 10 punpcklbw xmm0, xmm1 ; -2 3 -1 4 0 5 1 6 2 7 3 8 4 9 5 10 movdqa xmm2, xmm0 pshufb xmm0, xmm3 pshufb xmm2, xmm4 pmaddubsw xmm0, xmm5 lea rdi, [rdi + rdx] pmaddubsw xmm2, xmm6 lea rsi, [rsi + rax] dec rcx paddsw xmm0, xmm7 paddsw xmm0, xmm2 psraw xmm0, 7 packuswb xmm0, xmm0 movq MMWORD Ptr [rdi], xmm0 jnz .filter_block1d8_h4_rowloop_ssse3 ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp8_filter_block1d16_h6_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; unsigned int vp8_filter_index ;) global sym(vp8_filter_block1d16_h6_ssse3) PRIVATE sym(vp8_filter_block1d16_h6_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog movsxd rdx, DWORD PTR arg(5) ;table index xor rsi, rsi shl rdx, 4 ; lea rax, [GLOBAL(k0_k5)] add rax, rdx mov rdi, arg(2) ;output_ptr mov rsi, arg(0) ;src_ptr movdqa xmm4, XMMWORD PTR [rax] ;k0_k5 movdqa xmm5, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm6, XMMWORD PTR [rax+128] ;k1_k3 movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rcx, dword ptr arg(4) ;output_height movsxd rdx, dword ptr arg(3) ;output_pitch .filter_block1d16_h6_rowloop_ssse3: movq xmm0, MMWORD PTR [rsi - 2] ; -2 -1 0 1 2 3 4 5 movq xmm3, MMWORD PTR [rsi + 3] ; 3 4 5 6 7 8 9 10 punpcklbw xmm0, xmm3 ; -2 3 -1 4 0 5 1 6 2 7 3 8 4 9 5 10 movdqa xmm1, xmm0 pmaddubsw xmm0, xmm4 movdqa xmm2, xmm1 pshufb xmm1, [GLOBAL(shuf2bfrom1)] pshufb xmm2, [GLOBAL(shuf3bfrom1)] movq xmm3, MMWORD PTR [rsi + 6] pmaddubsw xmm1, xmm5 movq xmm7, MMWORD PTR [rsi + 11] pmaddubsw xmm2, xmm6 punpcklbw xmm3, xmm7 paddsw xmm0, xmm1 movdqa xmm1, xmm3 pmaddubsw xmm3, xmm4 paddsw xmm0, xmm2 movdqa xmm2, xmm1 paddsw xmm0, [GLOBAL(rd)] pshufb xmm1, [GLOBAL(shuf2bfrom1)] pshufb xmm2, [GLOBAL(shuf3bfrom1)] psraw xmm0, 7 pmaddubsw xmm1, xmm5 pmaddubsw xmm2, xmm6 packuswb xmm0, xmm0 lea rsi, [rsi + rax] paddsw xmm3, xmm1 paddsw xmm3, xmm2 paddsw xmm3, [GLOBAL(rd)] psraw xmm3, 7 packuswb xmm3, xmm3 punpcklqdq xmm0, xmm3 movdqa XMMWORD Ptr [rdi], xmm0 lea rdi, [rdi + rdx] dec rcx jnz .filter_block1d16_h6_rowloop_ssse3 ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp8_filter_block1d4_h6_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pixels_per_line, ; unsigned char *output_ptr, ; unsigned int output_pitch, ; unsigned int output_height, ; unsigned int vp8_filter_index ;) global sym(vp8_filter_block1d4_h6_ssse3) PRIVATE sym(vp8_filter_block1d4_h6_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog movsxd rdx, DWORD PTR arg(5) ;table index xor rsi, rsi shl rdx, 4 ; lea rax, [GLOBAL(k0_k5)] add rax, rdx movdqa xmm7, [GLOBAL(rd)] cmp esi, DWORD PTR [rax] je .vp8_filter_block1d4_h4_ssse3 movdqa xmm4, XMMWORD PTR [rax] ;k0_k5 movdqa xmm5, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm6, XMMWORD PTR [rax+128] ;k1_k3 mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rcx, dword ptr arg(4) ;output_height movsxd rdx, dword ptr arg(3) ;output_pitch ;xmm3 free .filter_block1d4_h6_rowloop_ssse3: movdqu xmm0, XMMWORD PTR [rsi - 2] movdqa xmm1, xmm0 pshufb xmm0, [GLOBAL(shuf1b)] movdqa xmm2, xmm1 pshufb xmm1, [GLOBAL(shuf2b)] pmaddubsw xmm0, xmm4 pshufb xmm2, [GLOBAL(shuf3b)] pmaddubsw xmm1, xmm5 ;-- pmaddubsw xmm2, xmm6 lea rsi, [rsi + rax] ;-- paddsw xmm0, xmm1 paddsw xmm0, xmm7 pxor xmm1, xmm1 paddsw xmm0, xmm2 psraw xmm0, 7 packuswb xmm0, xmm0 movd DWORD PTR [rdi], xmm0 add rdi, rdx dec rcx jnz .filter_block1d4_h6_rowloop_ssse3 ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret .vp8_filter_block1d4_h4_ssse3: movdqa xmm5, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm6, XMMWORD PTR [rax+128] ;k1_k3 movdqa xmm0, XMMWORD PTR [GLOBAL(shuf2b)] movdqa xmm3, XMMWORD PTR [GLOBAL(shuf3b)] mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;output_ptr movsxd rax, dword ptr arg(1) ;src_pixels_per_line movsxd rcx, dword ptr arg(4) ;output_height movsxd rdx, dword ptr arg(3) ;output_pitch .filter_block1d4_h4_rowloop_ssse3: movdqu xmm1, XMMWORD PTR [rsi - 2] movdqa xmm2, xmm1 pshufb xmm1, xmm0 ;;[GLOBAL(shuf2b)] pshufb xmm2, xmm3 ;;[GLOBAL(shuf3b)] pmaddubsw xmm1, xmm5 ;-- pmaddubsw xmm2, xmm6 lea rsi, [rsi + rax] ;-- paddsw xmm1, xmm7 paddsw xmm1, xmm2 psraw xmm1, 7 packuswb xmm1, xmm1 movd DWORD PTR [rdi], xmm1 add rdi, rdx dec rcx jnz .filter_block1d4_h4_rowloop_ssse3 ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp8_filter_block1d16_v6_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; unsigned int vp8_filter_index ;) global sym(vp8_filter_block1d16_v6_ssse3) PRIVATE sym(vp8_filter_block1d16_v6_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog movsxd rdx, DWORD PTR arg(5) ;table index xor rsi, rsi shl rdx, 4 ; lea rax, [GLOBAL(k0_k5)] add rax, rdx cmp esi, DWORD PTR [rax] je .vp8_filter_block1d16_v4_ssse3 movdqa xmm5, XMMWORD PTR [rax] ;k0_k5 movdqa xmm6, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm7, XMMWORD PTR [rax+128] ;k1_k3 mov rsi, arg(0) ;src_ptr movsxd rdx, DWORD PTR arg(1) ;pixels_per_line mov rdi, arg(2) ;output_ptr %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ;out_pitch %endif mov rax, rsi movsxd rcx, DWORD PTR arg(4) ;output_height add rax, rdx .vp8_filter_block1d16_v6_ssse3_loop: movq xmm1, MMWORD PTR [rsi] ;A movq xmm2, MMWORD PTR [rsi + rdx] ;B movq xmm3, MMWORD PTR [rsi + rdx * 2] ;C movq xmm4, MMWORD PTR [rax + rdx * 2] ;D movq xmm0, MMWORD PTR [rsi + rdx * 4] ;E punpcklbw xmm2, xmm4 ;B D punpcklbw xmm3, xmm0 ;C E movq xmm0, MMWORD PTR [rax + rdx * 4] ;F pmaddubsw xmm3, xmm6 punpcklbw xmm1, xmm0 ;A F pmaddubsw xmm2, xmm7 pmaddubsw xmm1, xmm5 paddsw xmm2, xmm3 paddsw xmm2, xmm1 paddsw xmm2, [GLOBAL(rd)] psraw xmm2, 7 packuswb xmm2, xmm2 movq MMWORD PTR [rdi], xmm2 ;store the results movq xmm1, MMWORD PTR [rsi + 8] ;A movq xmm2, MMWORD PTR [rsi + rdx + 8] ;B movq xmm3, MMWORD PTR [rsi + rdx * 2 + 8] ;C movq xmm4, MMWORD PTR [rax + rdx * 2 + 8] ;D movq xmm0, MMWORD PTR [rsi + rdx * 4 + 8] ;E punpcklbw xmm2, xmm4 ;B D punpcklbw xmm3, xmm0 ;C E movq xmm0, MMWORD PTR [rax + rdx * 4 + 8] ;F pmaddubsw xmm3, xmm6 punpcklbw xmm1, xmm0 ;A F pmaddubsw xmm2, xmm7 pmaddubsw xmm1, xmm5 add rsi, rdx add rax, rdx ;-- ;-- paddsw xmm2, xmm3 paddsw xmm2, xmm1 paddsw xmm2, [GLOBAL(rd)] psraw xmm2, 7 packuswb xmm2, xmm2 movq MMWORD PTR [rdi+8], xmm2 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;out_pitch %else add rdi, r8 %endif dec rcx jnz .vp8_filter_block1d16_v6_ssse3_loop ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret .vp8_filter_block1d16_v4_ssse3: movdqa xmm6, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm7, XMMWORD PTR [rax+128] ;k1_k3 mov rsi, arg(0) ;src_ptr movsxd rdx, DWORD PTR arg(1) ;pixels_per_line mov rdi, arg(2) ;output_ptr %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ;out_pitch %endif mov rax, rsi movsxd rcx, DWORD PTR arg(4) ;output_height add rax, rdx .vp8_filter_block1d16_v4_ssse3_loop: movq xmm2, MMWORD PTR [rsi + rdx] ;B movq xmm3, MMWORD PTR [rsi + rdx * 2] ;C movq xmm4, MMWORD PTR [rax + rdx * 2] ;D movq xmm0, MMWORD PTR [rsi + rdx * 4] ;E punpcklbw xmm2, xmm4 ;B D punpcklbw xmm3, xmm0 ;C E pmaddubsw xmm3, xmm6 pmaddubsw xmm2, xmm7 movq xmm5, MMWORD PTR [rsi + rdx + 8] ;B movq xmm1, MMWORD PTR [rsi + rdx * 2 + 8] ;C movq xmm4, MMWORD PTR [rax + rdx * 2 + 8] ;D movq xmm0, MMWORD PTR [rsi + rdx * 4 + 8] ;E paddsw xmm2, [GLOBAL(rd)] paddsw xmm2, xmm3 psraw xmm2, 7 packuswb xmm2, xmm2 punpcklbw xmm5, xmm4 ;B D punpcklbw xmm1, xmm0 ;C E pmaddubsw xmm1, xmm6 pmaddubsw xmm5, xmm7 movdqa xmm4, [GLOBAL(rd)] add rsi, rdx add rax, rdx ;-- ;-- paddsw xmm5, xmm1 paddsw xmm5, xmm4 psraw xmm5, 7 packuswb xmm5, xmm5 punpcklqdq xmm2, xmm5 movdqa XMMWORD PTR [rdi], xmm2 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;out_pitch %else add rdi, r8 %endif dec rcx jnz .vp8_filter_block1d16_v4_ssse3_loop ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp8_filter_block1d8_v6_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; unsigned int vp8_filter_index ;) global sym(vp8_filter_block1d8_v6_ssse3) PRIVATE sym(vp8_filter_block1d8_v6_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog movsxd rdx, DWORD PTR arg(5) ;table index xor rsi, rsi shl rdx, 4 ; lea rax, [GLOBAL(k0_k5)] add rax, rdx movsxd rdx, DWORD PTR arg(1) ;pixels_per_line mov rdi, arg(2) ;output_ptr %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ; out_pitch %endif movsxd rcx, DWORD PTR arg(4) ;[output_height] cmp esi, DWORD PTR [rax] je .vp8_filter_block1d8_v4_ssse3 movdqa xmm5, XMMWORD PTR [rax] ;k0_k5 movdqa xmm6, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm7, XMMWORD PTR [rax+128] ;k1_k3 mov rsi, arg(0) ;src_ptr mov rax, rsi add rax, rdx .vp8_filter_block1d8_v6_ssse3_loop: movq xmm1, MMWORD PTR [rsi] ;A movq xmm2, MMWORD PTR [rsi + rdx] ;B movq xmm3, MMWORD PTR [rsi + rdx * 2] ;C movq xmm4, MMWORD PTR [rax + rdx * 2] ;D movq xmm0, MMWORD PTR [rsi + rdx * 4] ;E punpcklbw xmm2, xmm4 ;B D punpcklbw xmm3, xmm0 ;C E movq xmm0, MMWORD PTR [rax + rdx * 4] ;F movdqa xmm4, [GLOBAL(rd)] pmaddubsw xmm3, xmm6 punpcklbw xmm1, xmm0 ;A F pmaddubsw xmm2, xmm7 pmaddubsw xmm1, xmm5 add rsi, rdx add rax, rdx ;-- ;-- paddsw xmm2, xmm3 paddsw xmm2, xmm1 paddsw xmm2, xmm4 psraw xmm2, 7 packuswb xmm2, xmm2 movq MMWORD PTR [rdi], xmm2 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;[out_pitch] %else add rdi, r8 %endif dec rcx jnz .vp8_filter_block1d8_v6_ssse3_loop ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret .vp8_filter_block1d8_v4_ssse3: movdqa xmm6, XMMWORD PTR [rax+256] ;k2_k4 movdqa xmm7, XMMWORD PTR [rax+128] ;k1_k3 movdqa xmm5, [GLOBAL(rd)] mov rsi, arg(0) ;src_ptr mov rax, rsi add rax, rdx .vp8_filter_block1d8_v4_ssse3_loop: movq xmm2, MMWORD PTR [rsi + rdx] ;B movq xmm3, MMWORD PTR [rsi + rdx * 2] ;C movq xmm4, MMWORD PTR [rax + rdx * 2] ;D movq xmm0, MMWORD PTR [rsi + rdx * 4] ;E punpcklbw xmm2, xmm4 ;B D punpcklbw xmm3, xmm0 ;C E pmaddubsw xmm3, xmm6 pmaddubsw xmm2, xmm7 add rsi, rdx add rax, rdx ;-- ;-- paddsw xmm2, xmm3 paddsw xmm2, xmm5 psraw xmm2, 7 packuswb xmm2, xmm2 movq MMWORD PTR [rdi], xmm2 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;[out_pitch] %else add rdi, r8 %endif dec rcx jnz .vp8_filter_block1d8_v4_ssse3_loop ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp8_filter_block1d4_v6_ssse3 ;( ; unsigned char *src_ptr, ; unsigned int src_pitch, ; unsigned char *output_ptr, ; unsigned int out_pitch, ; unsigned int output_height, ; unsigned int vp8_filter_index ;) global sym(vp8_filter_block1d4_v6_ssse3) PRIVATE sym(vp8_filter_block1d4_v6_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 GET_GOT rbx push rsi push rdi ; end prolog movsxd rdx, DWORD PTR arg(5) ;table index xor rsi, rsi shl rdx, 4 ; lea rax, [GLOBAL(k0_k5)] add rax, rdx movsxd rdx, DWORD PTR arg(1) ;pixels_per_line mov rdi, arg(2) ;output_ptr %if ABI_IS_32BIT=0 movsxd r8, DWORD PTR arg(3) ; out_pitch %endif movsxd rcx, DWORD PTR arg(4) ;[output_height] cmp esi, DWORD PTR [rax] je .vp8_filter_block1d4_v4_ssse3 movq mm5, MMWORD PTR [rax] ;k0_k5 movq mm6, MMWORD PTR [rax+256] ;k2_k4 movq mm7, MMWORD PTR [rax+128] ;k1_k3 mov rsi, arg(0) ;src_ptr mov rax, rsi add rax, rdx .vp8_filter_block1d4_v6_ssse3_loop: movd mm1, DWORD PTR [rsi] ;A movd mm2, DWORD PTR [rsi + rdx] ;B movd mm3, DWORD PTR [rsi + rdx * 2] ;C movd mm4, DWORD PTR [rax + rdx * 2] ;D movd mm0, DWORD PTR [rsi + rdx * 4] ;E punpcklbw mm2, mm4 ;B D punpcklbw mm3, mm0 ;C E movd mm0, DWORD PTR [rax + rdx * 4] ;F movq mm4, [GLOBAL(rd)] pmaddubsw mm3, mm6 punpcklbw mm1, mm0 ;A F pmaddubsw mm2, mm7 pmaddubsw mm1, mm5 add rsi, rdx add rax, rdx ;-- ;-- paddsw mm2, mm3 paddsw mm2, mm1 paddsw mm2, mm4 psraw mm2, 7 packuswb mm2, mm2 movd DWORD PTR [rdi], mm2 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;[out_pitch] %else add rdi, r8 %endif dec rcx jnz .vp8_filter_block1d4_v6_ssse3_loop ; begin epilog pop rdi pop rsi RESTORE_GOT UNSHADOW_ARGS pop rbp ret .vp8_filter_block1d4_v4_ssse3: movq mm6, MMWORD PTR [rax+256] ;k2_k4 movq mm7, MMWORD PTR [rax+128] ;k1_k3 movq mm5, MMWORD PTR [GLOBAL(rd)] mov rsi, arg(0) ;src_ptr mov rax, rsi add rax, rdx .vp8_filter_block1d4_v4_ssse3_loop: movd mm2, DWORD PTR [rsi + rdx] ;B movd mm3, DWORD PTR [rsi + rdx * 2] ;C movd mm4, DWORD PTR [rax + rdx * 2] ;D movd mm0, DWORD PTR [rsi + rdx * 4] ;E punpcklbw mm2, mm4 ;B D punpcklbw mm3, mm0 ;C E pmaddubsw mm3, mm6 pmaddubsw mm2, mm7 add rsi, rdx add rax, rdx ;-- ;-- paddsw mm2, mm3 paddsw mm2, mm5 psraw mm2, 7 packuswb mm2, mm2 movd DWORD PTR [rdi], mm2 %if ABI_IS_32BIT add rdi, DWORD PTR arg(3) ;[out_pitch] %else add rdi, r8 %endif dec rcx jnz .vp8_filter_block1d4_v4_ssse3_loop ; begin epilog pop rdi pop rsi RESTORE_GOT UNSHADOW_ARGS pop rbp ret ;void vp8_bilinear_predict16x16_ssse3 ;( ; unsigned char *src_ptr, ; int src_pixels_per_line, ; int xoffset, ; int yoffset, ; unsigned char *dst_ptr, ; int dst_pitch ;) global sym(vp8_bilinear_predict16x16_ssse3) PRIVATE sym(vp8_bilinear_predict16x16_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog lea rcx, [GLOBAL(vp8_bilinear_filters_ssse3)] movsxd rax, dword ptr arg(2) ; xoffset cmp rax, 0 ; skip first_pass filter if xoffset=0 je .b16x16_sp_only shl rax, 4 lea rax, [rax + rcx] ; HFilter mov rdi, arg(4) ; dst_ptr mov rsi, arg(0) ; src_ptr movsxd rdx, dword ptr arg(5) ; dst_pitch movdqa xmm1, [rax] movsxd rax, dword ptr arg(3) ; yoffset cmp rax, 0 ; skip second_pass filter if yoffset=0 je .b16x16_fp_only shl rax, 4 lea rax, [rax + rcx] ; VFilter lea rcx, [rdi+rdx*8] lea rcx, [rcx+rdx*8] movsxd rdx, dword ptr arg(1) ; src_pixels_per_line movdqa xmm2, [rax] %if ABI_IS_32BIT=0 movsxd r8, dword ptr arg(5) ; dst_pitch %endif movq xmm3, [rsi] ; 00 01 02 03 04 05 06 07 movq xmm5, [rsi+1] ; 01 02 03 04 05 06 07 08 punpcklbw xmm3, xmm5 ; 00 01 01 02 02 03 03 04 04 05 05 06 06 07 07 08 movq xmm4, [rsi+8] ; 08 09 10 11 12 13 14 15 movq xmm5, [rsi+9] ; 09 10 11 12 13 14 15 16 lea rsi, [rsi + rdx] ; next line pmaddubsw xmm3, xmm1 ; 00 02 04 06 08 10 12 14 punpcklbw xmm4, xmm5 ; 08 09 09 10 10 11 11 12 12 13 13 14 14 15 15 16 pmaddubsw xmm4, xmm1 ; 01 03 05 07 09 11 13 15 paddw xmm3, [GLOBAL(rd)] ; xmm3 += round value psraw xmm3, VP8_FILTER_SHIFT ; xmm3 /= 128 paddw xmm4, [GLOBAL(rd)] ; xmm4 += round value psraw xmm4, VP8_FILTER_SHIFT ; xmm4 /= 128 movdqa xmm7, xmm3 packuswb xmm7, xmm4 ; 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 .next_row: movq xmm6, [rsi] ; 00 01 02 03 04 05 06 07 movq xmm5, [rsi+1] ; 01 02 03 04 05 06 07 08 punpcklbw xmm6, xmm5 movq xmm4, [rsi+8] ; 08 09 10 11 12 13 14 15 movq xmm5, [rsi+9] ; 09 10 11 12 13 14 15 16 lea rsi, [rsi + rdx] ; next line pmaddubsw xmm6, xmm1 punpcklbw xmm4, xmm5 pmaddubsw xmm4, xmm1 paddw xmm6, [GLOBAL(rd)] ; xmm6 += round value psraw xmm6, VP8_FILTER_SHIFT ; xmm6 /= 128 paddw xmm4, [GLOBAL(rd)] ; xmm4 += round value psraw xmm4, VP8_FILTER_SHIFT ; xmm4 /= 128 packuswb xmm6, xmm4 movdqa xmm5, xmm7 punpcklbw xmm5, xmm6 pmaddubsw xmm5, xmm2 punpckhbw xmm7, xmm6 pmaddubsw xmm7, xmm2 paddw xmm5, [GLOBAL(rd)] ; xmm5 += round value psraw xmm5, VP8_FILTER_SHIFT ; xmm5 /= 128 paddw xmm7, [GLOBAL(rd)] ; xmm7 += round value psraw xmm7, VP8_FILTER_SHIFT ; xmm7 /= 128 packuswb xmm5, xmm7 movdqa xmm7, xmm6 movdqa [rdi], xmm5 ; store the results in the destination %if ABI_IS_32BIT add rdi, DWORD PTR arg(5) ; dst_pitch %else add rdi, r8 %endif cmp rdi, rcx jne .next_row jmp .done .b16x16_sp_only: movsxd rax, dword ptr arg(3) ; yoffset shl rax, 4 lea rax, [rax + rcx] ; VFilter mov rdi, arg(4) ; dst_ptr mov rsi, arg(0) ; src_ptr movsxd rdx, dword ptr arg(5) ; dst_pitch movdqa xmm1, [rax] ; VFilter lea rcx, [rdi+rdx*8] lea rcx, [rcx+rdx*8] movsxd rax, dword ptr arg(1) ; src_pixels_per_line ; get the first horizontal line done movq xmm4, [rsi] ; load row 0 movq xmm2, [rsi + 8] ; load row 0 lea rsi, [rsi + rax] ; next line .next_row_sp: movq xmm3, [rsi] ; load row + 1 movq xmm5, [rsi + 8] ; load row + 1 punpcklbw xmm4, xmm3 punpcklbw xmm2, xmm5 pmaddubsw xmm4, xmm1 movq xmm7, [rsi + rax] ; load row + 2 pmaddubsw xmm2, xmm1 movq xmm6, [rsi + rax + 8] ; load row + 2 punpcklbw xmm3, xmm7 punpcklbw xmm5, xmm6 pmaddubsw xmm3, xmm1 paddw xmm4, [GLOBAL(rd)] pmaddubsw xmm5, xmm1 paddw xmm2, [GLOBAL(rd)] psraw xmm4, VP8_FILTER_SHIFT psraw xmm2, VP8_FILTER_SHIFT packuswb xmm4, xmm2 paddw xmm3, [GLOBAL(rd)] movdqa [rdi], xmm4 ; store row 0 paddw xmm5, [GLOBAL(rd)] psraw xmm3, VP8_FILTER_SHIFT psraw xmm5, VP8_FILTER_SHIFT packuswb xmm3, xmm5 movdqa xmm4, xmm7 movdqa [rdi + rdx],xmm3 ; store row 1 lea rsi, [rsi + 2*rax] movdqa xmm2, xmm6 lea rdi, [rdi + 2*rdx] cmp rdi, rcx jne .next_row_sp jmp .done .b16x16_fp_only: lea rcx, [rdi+rdx*8] lea rcx, [rcx+rdx*8] movsxd rax, dword ptr arg(1) ; src_pixels_per_line .next_row_fp: movq xmm2, [rsi] ; 00 01 02 03 04 05 06 07 movq xmm4, [rsi+1] ; 01 02 03 04 05 06 07 08 punpcklbw xmm2, xmm4 movq xmm3, [rsi+8] ; 08 09 10 11 12 13 14 15 pmaddubsw xmm2, xmm1 movq xmm4, [rsi+9] ; 09 10 11 12 13 14 15 16 lea rsi, [rsi + rax] ; next line punpcklbw xmm3, xmm4 pmaddubsw xmm3, xmm1 movq xmm5, [rsi] paddw xmm2, [GLOBAL(rd)] movq xmm7, [rsi+1] movq xmm6, [rsi+8] psraw xmm2, VP8_FILTER_SHIFT punpcklbw xmm5, xmm7 movq xmm7, [rsi+9] paddw xmm3, [GLOBAL(rd)] pmaddubsw xmm5, xmm1 psraw xmm3, VP8_FILTER_SHIFT punpcklbw xmm6, xmm7 packuswb xmm2, xmm3 pmaddubsw xmm6, xmm1 movdqa [rdi], xmm2 ; store the results in the destination paddw xmm5, [GLOBAL(rd)] lea rdi, [rdi + rdx] ; dst_pitch psraw xmm5, VP8_FILTER_SHIFT paddw xmm6, [GLOBAL(rd)] psraw xmm6, VP8_FILTER_SHIFT packuswb xmm5, xmm6 lea rsi, [rsi + rax] ; next line movdqa [rdi], xmm5 ; store the results in the destination lea rdi, [rdi + rdx] ; dst_pitch cmp rdi, rcx jne .next_row_fp .done: ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void vp8_bilinear_predict8x8_ssse3 ;( ; unsigned char *src_ptr, ; int src_pixels_per_line, ; int xoffset, ; int yoffset, ; unsigned char *dst_ptr, ; int dst_pitch ;) global sym(vp8_bilinear_predict8x8_ssse3) PRIVATE sym(vp8_bilinear_predict8x8_ssse3): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 6 SAVE_XMM 7 GET_GOT rbx push rsi push rdi ; end prolog ALIGN_STACK 16, rax sub rsp, 144 ; reserve 144 bytes lea rcx, [GLOBAL(vp8_bilinear_filters_ssse3)] mov rsi, arg(0) ;src_ptr movsxd rdx, dword ptr arg(1) ;src_pixels_per_line ;Read 9-line unaligned data in and put them on stack. This gives a big ;performance boost. movdqu xmm0, [rsi] lea rax, [rdx + rdx*2] movdqu xmm1, [rsi+rdx] movdqu xmm2, [rsi+rdx*2] add rsi, rax movdqu xmm3, [rsi] movdqu xmm4, [rsi+rdx] movdqu xmm5, [rsi+rdx*2] add rsi, rax movdqu xmm6, [rsi] movdqu xmm7, [rsi+rdx] movdqa XMMWORD PTR [rsp], xmm0 movdqu xmm0, [rsi+rdx*2] movdqa XMMWORD PTR [rsp+16], xmm1 movdqa XMMWORD PTR [rsp+32], xmm2 movdqa XMMWORD PTR [rsp+48], xmm3 movdqa XMMWORD PTR [rsp+64], xmm4 movdqa XMMWORD PTR [rsp+80], xmm5 movdqa XMMWORD PTR [rsp+96], xmm6 movdqa XMMWORD PTR [rsp+112], xmm7 movdqa XMMWORD PTR [rsp+128], xmm0 movsxd rax, dword ptr arg(2) ; xoffset cmp rax, 0 ; skip first_pass filter if xoffset=0 je .b8x8_sp_only shl rax, 4 add rax, rcx ; HFilter mov rdi, arg(4) ; dst_ptr movsxd rdx, dword ptr arg(5) ; dst_pitch movdqa xmm0, [rax] movsxd rax, dword ptr arg(3) ; yoffset cmp rax, 0 ; skip second_pass filter if yoffset=0 je .b8x8_fp_only shl rax, 4 lea rax, [rax + rcx] ; VFilter lea rcx, [rdi+rdx*8] movdqa xmm1, [rax] ; get the first horizontal line done movdqa xmm3, [rsp] ; 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 movdqa xmm5, xmm3 ; 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 xx psrldq xmm5, 1 lea rsp, [rsp + 16] ; next line punpcklbw xmm3, xmm5 ; 00 01 01 02 02 03 03 04 04 05 05 06 06 07 07 08 pmaddubsw xmm3, xmm0 ; 00 02 04 06 08 10 12 14 paddw xmm3, [GLOBAL(rd)] ; xmm3 += round value psraw xmm3, VP8_FILTER_SHIFT ; xmm3 /= 128 movdqa xmm7, xmm3 packuswb xmm7, xmm7 ; 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 .next_row: movdqa xmm6, [rsp] ; 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 lea rsp, [rsp + 16] ; next line movdqa xmm5, xmm6 psrldq xmm5, 1 punpcklbw xmm6, xmm5 pmaddubsw xmm6, xmm0 paddw xmm6, [GLOBAL(rd)] ; xmm6 += round value psraw xmm6, VP8_FILTER_SHIFT ; xmm6 /= 128 packuswb xmm6, xmm6 punpcklbw xmm7, xmm6 pmaddubsw xmm7, xmm1 paddw xmm7, [GLOBAL(rd)] ; xmm7 += round value psraw xmm7, VP8_FILTER_SHIFT ; xmm7 /= 128 packuswb xmm7, xmm7 movq [rdi], xmm7 ; store the results in the destination lea rdi, [rdi + rdx] movdqa xmm7, xmm6 cmp rdi, rcx jne .next_row jmp .done8x8 .b8x8_sp_only: movsxd rax, dword ptr arg(3) ; yoffset shl rax, 4 lea rax, [rax + rcx] ; VFilter mov rdi, arg(4) ;dst_ptr movsxd rdx, dword ptr arg(5) ; dst_pitch movdqa xmm0, [rax] ; VFilter movq xmm1, XMMWORD PTR [rsp] movq xmm2, XMMWORD PTR [rsp+16] movq xmm3, XMMWORD PTR [rsp+32] punpcklbw xmm1, xmm2 movq xmm4, XMMWORD PTR [rsp+48] punpcklbw xmm2, xmm3 movq xmm5, XMMWORD PTR [rsp+64] punpcklbw xmm3, xmm4 movq xmm6, XMMWORD PTR [rsp+80] punpcklbw xmm4, xmm5 movq xmm7, XMMWORD PTR [rsp+96] punpcklbw xmm5, xmm6 ; Because the source register (xmm0) is always treated as signed by ; pmaddubsw, the constant '128' is treated as '-128'. pmaddubsw xmm1, xmm0 pmaddubsw xmm2, xmm0 pmaddubsw xmm3, xmm0 pmaddubsw xmm4, xmm0 pmaddubsw xmm5, xmm0 punpcklbw xmm6, xmm7 pmaddubsw xmm6, xmm0 paddw xmm1, [GLOBAL(rd)] paddw xmm2, [GLOBAL(rd)] psraw xmm1, VP8_FILTER_SHIFT paddw xmm3, [GLOBAL(rd)] psraw xmm2, VP8_FILTER_SHIFT paddw xmm4, [GLOBAL(rd)] psraw xmm3, VP8_FILTER_SHIFT paddw xmm5, [GLOBAL(rd)] psraw xmm4, VP8_FILTER_SHIFT paddw xmm6, [GLOBAL(rd)] psraw xmm5, VP8_FILTER_SHIFT psraw xmm6, VP8_FILTER_SHIFT ; Having multiplied everything by '-128' and obtained negative ; numbers, the unsigned saturation truncates those values to 0, ; resulting in incorrect handling of xoffset == 0 && yoffset == 0 packuswb xmm1, xmm1 packuswb xmm2, xmm2 movq [rdi], xmm1 packuswb xmm3, xmm3 movq [rdi+rdx], xmm2 packuswb xmm4, xmm4 movq xmm1, XMMWORD PTR [rsp+112] lea rdi, [rdi + 2*rdx] movq xmm2, XMMWORD PTR [rsp+128] packuswb xmm5, xmm5 movq [rdi], xmm3 packuswb xmm6, xmm6 movq [rdi+rdx], xmm4 lea rdi, [rdi + 2*rdx] punpcklbw xmm7, xmm1 movq [rdi], xmm5 pmaddubsw xmm7, xmm0 movq [rdi+rdx], xmm6 punpcklbw xmm1, xmm2 pmaddubsw xmm1, xmm0 paddw xmm7, [GLOBAL(rd)] psraw xmm7, VP8_FILTER_SHIFT paddw xmm1, [GLOBAL(rd)] psraw xmm1, VP8_FILTER_SHIFT packuswb xmm7, xmm7 packuswb xmm1, xmm1 lea rdi, [rdi + 2*rdx] movq [rdi], xmm7 movq [rdi+rdx], xmm1 lea rsp, [rsp + 144] jmp .done8x8 .b8x8_fp_only: lea rcx, [rdi+rdx*8] .next_row_fp: movdqa xmm1, XMMWORD PTR [rsp] movdqa xmm3, XMMWORD PTR [rsp+16] movdqa xmm2, xmm1 movdqa xmm5, XMMWORD PTR [rsp+32] psrldq xmm2, 1 movdqa xmm7, XMMWORD PTR [rsp+48] movdqa xmm4, xmm3 psrldq xmm4, 1 movdqa xmm6, xmm5 psrldq xmm6, 1 punpcklbw xmm1, xmm2 pmaddubsw xmm1, xmm0 punpcklbw xmm3, xmm4 pmaddubsw xmm3, xmm0 punpcklbw xmm5, xmm6 pmaddubsw xmm5, xmm0 movdqa xmm2, xmm7 psrldq xmm2, 1 punpcklbw xmm7, xmm2 pmaddubsw xmm7, xmm0 paddw xmm1, [GLOBAL(rd)] psraw xmm1, VP8_FILTER_SHIFT paddw xmm3, [GLOBAL(rd)] psraw xmm3, VP8_FILTER_SHIFT paddw xmm5, [GLOBAL(rd)] psraw xmm5, VP8_FILTER_SHIFT paddw xmm7, [GLOBAL(rd)] psraw xmm7, VP8_FILTER_SHIFT packuswb xmm1, xmm1 packuswb xmm3, xmm3 packuswb xmm5, xmm5 movq [rdi], xmm1 packuswb xmm7, xmm7 movq [rdi+rdx], xmm3 lea rdi, [rdi + 2*rdx] movq [rdi], xmm5 lea rsp, [rsp + 4*16] movq [rdi+rdx], xmm7 lea rdi, [rdi + 2*rdx] cmp rdi, rcx jne .next_row_fp lea rsp, [rsp + 16] .done8x8: ;add rsp, 144 pop rsp ; begin epilog pop rdi pop rsi RESTORE_GOT RESTORE_XMM UNSHADOW_ARGS pop rbp ret SECTION_RODATA align 16 shuf1b: db 0, 5, 1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 6, 11, 7, 12 shuf2b: db 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11 shuf3b: db 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10 align 16 shuf2bfrom1: db 4, 8, 6, 1, 8, 3, 1, 5, 3, 7, 5, 9, 7,11, 9,13 align 16 shuf3bfrom1: db 2, 6, 4, 8, 6, 1, 8, 3, 1, 5, 3, 7, 5, 9, 7,11 align 16 rd: times 8 dw 0x40 align 16 k0_k5: times 8 db 0, 0 ;placeholder times 8 db 0, 0 times 8 db 2, 1 times 8 db 0, 0 times 8 db 3, 3 times 8 db 0, 0 times 8 db 1, 2 times 8 db 0, 0 k1_k3: times 8 db 0, 0 ;placeholder times 8 db -6, 12 times 8 db -11, 36 times 8 db -9, 50 times 8 db -16, 77 times 8 db -6, 93 times 8 db -8, 108 times 8 db -1, 123 k2_k4: times 8 db 128, 0 ;placeholder times 8 db 123, -1 times 8 db 108, -8 times 8 db 93, -6 times 8 db 77, -16 times 8 db 50, -9 times 8 db 36, -11 times 8 db 12, -6 align 16 vp8_bilinear_filters_ssse3: times 8 db 128, 0 times 8 db 112, 16 times 8 db 96, 32 times 8 db 80, 48 times 8 db 64, 64 times 8 db 48, 80 times 8 db 32, 96 times 8 db 16, 112
0x0000 (0x000000) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x0001 (0x000002) 0x291A- f:00024 d: 282 | OR[282] = A 0x0002 (0x000004) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x0003 (0x000006) 0x2919- f:00024 d: 281 | OR[281] = A 0x0004 (0x000008) 0x2118- f:00020 d: 280 | A = OR[280] 0x0005 (0x00000A) 0x2910- f:00024 d: 272 | OR[272] = A 0x0006 (0x00000C) 0x2048- f:00020 d: 72 | A = OR[72] 0x0007 (0x00000E) 0x1402- f:00012 d: 2 | A = A + 2 (0x0002) 0x0008 (0x000010) 0x290D- f:00024 d: 269 | OR[269] = A 0x0009 (0x000012) 0x1007- f:00010 d: 7 | A = 7 (0x0007) 0x000A (0x000014) 0x1401- f:00012 d: 1 | A = A + 1 (0x0001) 0x000B (0x000016) 0x290E- f:00024 d: 270 | OR[270] = A 0x000C (0x000018) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x000D (0x00001A) 0x290F- f:00024 d: 271 | OR[271] = A 0x000E (0x00001C) 0x210F- f:00020 d: 271 | A = OR[271] 0x000F (0x00001E) 0x2710- f:00023 d: 272 | A = A - OR[272] 0x0010 (0x000020) 0x8410- f:00102 d: 16 | P = P + 16 (0x0020), A = 0 0x0011 (0x000022) 0x210E- f:00020 d: 270 | A = OR[270] 0x0012 (0x000024) 0x840E- f:00102 d: 14 | P = P + 14 (0x0020), A = 0 0x0013 (0x000026) 0x210D- f:00020 d: 269 | A = OR[269] 0x0014 (0x000028) 0x1406- f:00012 d: 6 | A = A + 6 (0x0006) 0x0015 (0x00002A) 0x2908- f:00024 d: 264 | OR[264] = A 0x0016 (0x00002C) 0x3108- f:00030 d: 264 | A = (OR[264]) 0x0017 (0x00002E) 0x290F- f:00024 d: 271 | OR[271] = A 0x0018 (0x000030) 0x210F- f:00020 d: 271 | A = OR[271] 0x0019 (0x000032) 0x2710- f:00023 d: 272 | A = A - OR[272] 0x001A (0x000034) 0x8602- f:00103 d: 2 | P = P + 2 (0x001C), A # 0 0x001B (0x000036) 0x7004- f:00070 d: 4 | P = P + 4 (0x001F) 0x001C (0x000038) 0x1007- f:00010 d: 7 | A = 7 (0x0007) 0x001D (0x00003A) 0x2B0D- f:00025 d: 269 | OR[269] = A + OR[269] 0x001E (0x00003C) 0x2F0E- f:00027 d: 270 | OR[270] = OR[270] - 1 0x001F (0x00003E) 0x7211- f:00071 d: 17 | P = P - 17 (0x000E) 0x0020 (0x000040) 0x210E- f:00020 d: 270 | A = OR[270] 0x0021 (0x000042) 0x8403- f:00102 d: 3 | P = P + 3 (0x0024), A = 0 0x0022 (0x000044) 0x210D- f:00020 d: 269 | A = OR[269] 0x0023 (0x000046) 0x2919- f:00024 d: 281 | OR[281] = A 0x0024 (0x000048) 0x2119- f:00020 d: 281 | A = OR[281] 0x0025 (0x00004A) 0x8603- f:00103 d: 3 | P = P + 3 (0x0028), A # 0 0x0026 (0x00004C) 0x1001- f:00010 d: 1 | A = 1 (0x0001) 0x0027 (0x00004E) 0x291A- f:00024 d: 282 | OR[282] = A 0x0028 (0x000050) 0x211A- f:00020 d: 282 | A = OR[282] 0x0029 (0x000052) 0x8402- f:00102 d: 2 | P = P + 2 (0x002B), A = 0 0x002A (0x000054) 0x7006- f:00070 d: 6 | P = P + 6 (0x0030) 0x002B (0x000056) 0x2119- f:00020 d: 281 | A = OR[281] 0x002C (0x000058) 0x1406- f:00012 d: 6 | A = A + 6 (0x0006) 0x002D (0x00005A) 0x2908- f:00024 d: 264 | OR[264] = A 0x002E (0x00005C) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x002F (0x00005E) 0x3908- f:00034 d: 264 | (OR[264]) = A 0x0030 (0x000060) 0x2005- f:00020 d: 5 | A = OR[5] 0x0031 (0x000062) 0x1406- f:00012 d: 6 | A = A + 6 (0x0006) 0x0032 (0x000064) 0x2908- f:00024 d: 264 | OR[264] = A 0x0033 (0x000066) 0x211A- f:00020 d: 282 | A = OR[282] 0x0034 (0x000068) 0x3908- f:00034 d: 264 | (OR[264]) = A 0x0035 (0x00006A) 0x102A- f:00010 d: 42 | A = 42 (0x002A) 0x0036 (0x00006C) 0x291D- f:00024 d: 285 | OR[285] = A 0x0037 (0x00006E) 0x111D- f:00010 d: 285 | A = 285 (0x011D) 0x0038 (0x000070) 0x5800- f:00054 d: 0 | B = A 0x0039 (0x000072) 0x1000- f:00010 d: 0 | A = 0 (0x0000) 0x003A (0x000074) 0x7C09- f:00076 d: 9 | R = OR[9] 0x003B (0x000076) 0x0000- f:00000 d: 0 | PASS 0x003C (0x000078) 0x0000- f:00000 d: 0 | PASS 0x003D (0x00007A) 0x0000- f:00000 d: 0 | PASS 0x003E (0x00007C) 0x0000- f:00000 d: 0 | PASS 0x003F (0x00007E) 0x0000- f:00000 d: 0 | PASS
/* * @Description: Lidar measurement preprocess node * @Author: Ge Yao * @Date: 2020-11-12 15:14:07 */ #include <ros/ros.h> #include "glog/logging.h" #include "lidar_localization/global_defination/global_defination.h" #include "lidar_localization/data_pretreat/lidar_preprocess_flow.hpp" using namespace lidar_localization; int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); FLAGS_log_dir = WORK_SPACE_PATH + "/Log"; FLAGS_alsologtostderr = 1; ros::init(argc, argv, "lidar_preprocess_node"); ros::NodeHandle nh; std::string synced_cloud_topic; nh.param<std::string>("cloud_topic", synced_cloud_topic, "/synced_cloud"); // subscribe to // a. raw Velodyne measurement // b. raw GNSS/IMU measurement // publish // a. synced lidar measurement for ESKF fusion std::shared_ptr<LidarPreprocessFlow> lidar_preprocess_flow_ptr = std::make_shared<LidarPreprocessFlow>(nh, synced_cloud_topic); // pre-process lidar point cloud at 100Hz: ros::Rate rate(100); while (ros::ok()) { ros::spinOnce(); lidar_preprocess_flow_ptr->Run(); rate.sleep(); } return 0; }
/* * Copyright 2018- The Pixie Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #include <gtest/gtest.h> #include <utility> #include <vector> #include "src/common/event/api_impl.h" #include "src/common/event/libuv.h" #include "src/common/event/nats.h" #include "src/common/system/config_mock.h" #include "src/common/testing/event/simulated_time_system.h" #include "src/shared/metadatapb/metadata.pb.h" #include "src/vizier/messages/messagespb/messages.pb.h" #include "src/vizier/services/agent/manager/manager.h" #include "src/vizier/services/agent/manager/registration.h" #include "src/vizier/services/agent/manager/test_utils.h" #include "src/common/testing/testing.h" namespace px { namespace vizier { namespace agent { using ::px::table_store::schema::Relation; using ::px::testing::proto::EqualsProto; using ::px::testing::proto::Partially; using shared::metadatapb::MetadataType; using ::testing::Return; using ::testing::ReturnRef; using ::testing::UnorderedElementsAreArray; class RegistrationHandlerTest : public ::testing::Test { protected: void TearDown() override { dispatcher_->Exit(); } RegistrationHandlerTest() { start_monotonic_time_ = std::chrono::steady_clock::now(); start_system_time_ = std::chrono::system_clock::now(); time_system_ = std::make_unique<event::SimulatedTimeSystem>(start_monotonic_time_, start_system_time_); api_ = std::make_unique<px::event::APIImpl>(time_system_.get()); dispatcher_ = api_->AllocateDispatcher("manager"); nats_conn_ = std::make_unique<FakeNATSConnector<px::vizier::messages::VizierMessage>>(); agent_info_ = agent::Info{}; agent_info_.agent_id = sole::uuid4(); agent_info_.hostname = "hostname"; agent_info_.address = "address"; agent_info_.pod_name = "pod_name"; agent_info_.host_ip = "host_ip"; agent_info_.capabilities.set_collects_data(true); auto register_hook = [this](uint32_t asid) -> Status { called_register_++; agent_info_.asid = asid; register_asid_ = asid; return Status::OK(); }; auto reregister_hook = [this](uint32_t asid) -> Status { called_reregister_++; reregister_asid_ = asid; return Status::OK(); }; registration_handler_ = std::make_unique<RegistrationHandler>( dispatcher_.get(), &agent_info_, nats_conn_.get(), register_hook, reregister_hook); } event::MonotonicTimePoint start_monotonic_time_; event::SystemTimePoint start_system_time_; std::unique_ptr<event::SimulatedTimeSystem> time_system_; std::unique_ptr<event::APIImpl> api_; std::unique_ptr<event::Dispatcher> dispatcher_; std::unique_ptr<RegistrationHandler> registration_handler_; std::unique_ptr<FakeNATSConnector<px::vizier::messages::VizierMessage>> nats_conn_; agent::Info agent_info_; int32_t called_register_ = 0; int32_t called_reregister_ = 0; uint32_t register_asid_ = 0; uint32_t reregister_asid_ = 0; }; TEST_F(RegistrationHandlerTest, RegisterAgent) { dispatcher_->Run(event::Dispatcher::RunType::NonBlock); registration_handler_->RegisterAgent(); // Advance the clock to account for the random wait time. time_system_->SetMonotonicTime(start_monotonic_time_ + std::chrono::milliseconds(60 * 1000)); dispatcher_->Run(event::Dispatcher::RunType::NonBlock); EXPECT_EQ(1, nats_conn_->published_msgs().size()); // Check contents of registration msg. auto msg = nats_conn_->published_msgs()[0]; EXPECT_TRUE(msg.has_register_agent_request()); auto req = msg.register_agent_request(); EXPECT_TRUE(req.info().capabilities().collects_data()); auto uuid = ParseUUID(req.info().agent_id()).ConsumeValueOrDie(); EXPECT_EQ(agent_info_.agent_id, uuid); EXPECT_EQ(agent_info_.address, req.info().ip_address()); EXPECT_EQ(agent_info_.hostname, req.info().host_info().hostname()); EXPECT_EQ(agent_info_.pod_name, req.info().host_info().pod_name()); EXPECT_EQ(agent_info_.host_ip, req.info().host_info().host_ip()); auto registration_ack = std::make_unique<messages::VizierMessage>(); registration_ack->mutable_register_agent_response()->set_asid(10); EXPECT_OK(registration_handler_->HandleMessage(std::move(registration_ack))); EXPECT_EQ(1, called_register_); EXPECT_EQ(10, register_asid_); } TEST_F(RegistrationHandlerTest, RegisterAndReregisterAgent) { // Agent registration setup dispatcher_->Run(event::Dispatcher::RunType::NonBlock); registration_handler_->RegisterAgent(); time_system_->SetMonotonicTime(start_monotonic_time_ + std::chrono::milliseconds(60 * 1000 + 1)); dispatcher_->Run(event::Dispatcher::RunType::NonBlock); EXPECT_EQ(1, nats_conn_->published_msgs().size()); auto registration_ack = std::make_unique<messages::VizierMessage>(); registration_ack->mutable_register_agent_response()->set_asid(10); EXPECT_OK(registration_handler_->HandleMessage(std::move(registration_ack))); EXPECT_EQ(1, called_register_); EXPECT_EQ(10, register_asid_); // Now reregister the agent. registration_handler_->ReregisterAgent(); time_system_->SetMonotonicTime(start_monotonic_time_ + std::chrono::milliseconds(120 * 1000 + 1)); dispatcher_->Run(event::Dispatcher::RunType::NonBlock); EXPECT_EQ(2, nats_conn_->published_msgs().size()); // Check that the ASID got sent again. auto msg = nats_conn_->published_msgs()[1]; EXPECT_TRUE(msg.has_register_agent_request()); EXPECT_EQ(10, msg.register_agent_request().asid()); auto reregistration_ack = std::make_unique<messages::VizierMessage>(); reregistration_ack->mutable_register_agent_response()->set_asid(10); EXPECT_OK(registration_handler_->HandleMessage(std::move(reregistration_ack))); EXPECT_EQ(1, called_reregister_); EXPECT_EQ(10, reregister_asid_); } TEST_F(RegistrationHandlerTest, RegisterAgentTimeout) { dispatcher_->Run(event::Dispatcher::RunType::NonBlock); registration_handler_->RegisterAgent(); // Advance the clock to account for the random wait time. time_system_->SetMonotonicTime(start_monotonic_time_ + std::chrono::milliseconds(60 * 1000)); dispatcher_->Run(event::Dispatcher::RunType::NonBlock); EXPECT_EQ(1, nats_conn_->published_msgs().size()); time_system_->SetMonotonicTime(start_monotonic_time_ + std::chrono::milliseconds(120 * 1000)); ASSERT_DEATH(dispatcher_->Run(event::Dispatcher::RunType::NonBlock), "Timeout waiting for registration ack"); } } // namespace agent } // namespace vizier } // namespace px
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: PC GEOS MODULE: Printer Drivers FILE: jobEndRedwood.asm AUTHOR: Dave Durran ROUTINES: Name Description ---- ----------- PrintEndJob Cleanup done at end of print job REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 11/92 Initial revision DESCRIPTION: $Id: jobEndRedwood.asm,v 1.1 97/04/18 11:51:01 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PrintEndJob %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do post-job cleanup CALLED BY: GLOBAL PASS: bp - segment of locked PState RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 11/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrintEndJob proc far uses es,bx,dx,di .enter mov es,bp ; es--->PState if 0 mov bx,es:[PS_redwoodSpecific].[RS_DMAHandle] tst bx jz exit ;if no DMA driver loaded yet, exit. mov dl, REDWOOD_DMA_CHANNEL_MASK mov di, DR_RELEASE_CHANNEL ;free up this channel. INT_OFF call es:[PS_redwoodSpecific].[RS_DMADriver] ;free up this channel. INT_ON call GeodeFreeDriver endif exit: clc ; no problems .leave ret PrintEndJob endp
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r14 push %r15 push %rax push %rsi lea addresses_WC_ht+0xda53, %rsi nop nop nop nop nop add $62729, %r10 mov $0x6162636465666768, %r11 movq %r11, %xmm5 movups %xmm5, (%rsi) nop cmp %r10, %r10 lea addresses_normal_ht+0x8343, %rax clflush (%rax) nop nop nop dec %r15 mov (%rax), %r14 nop nop nop dec %r14 pop %rsi pop %rax pop %r15 pop %r14 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r8 push %rbp // Faulty Load lea addresses_UC+0x1e053, %rbp clflush (%rbp) add %r10, %r10 mov (%rbp), %r8 lea oracles, %r10 and $0xff, %r8 shlq $12, %r8 mov (%r10,%r8,1), %r8 pop %rbp pop %r8 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
#pragma once #include <vector> #include <iostream> #include <omp.h> #include <string> #include <string.h> #include <iomanip> #include <vector> #include <map> #include <fstream> #include <cmath> #include <assert.h> #include "defs.h" namespace UTBasic { constexpr real sqr(real x) { return x * x; } constexpr real cube(real x) { return x * x * x; } constexpr real sign(real x) { return x > 0 ? 1 : -1; } constexpr real max(real x, real y) { return x > y ? x : y; } inline real dis2(real x0, real y0, real x1, real y1) { return sqrt(sqr(x0 - x1) + sqr(y0 - y1)); } template <int dim> struct utype { real v[dim]; utype() { for (int i = 0; i < dim; i++) v[i] = 0; } utype(real x) { for (int i = 0; i < dim; i++) v[i] = x; } utype(const real x[dim]) { for (int i = 0; i < dim; i++) v[i] = x[i]; } utype(const utype<dim> &R) { for (int i = 0; i < dim; i++) v[i] = R.v[i]; } real &operator[](int i) { return v[i]; } real operator[](int i) const { return v[i]; } utype<dim> operator+(const utype<dim> &R) const //add R { utype<dim> ret; for (int i = 0; i < dim; i++) ret.v[i] = R.v[i] + v[i]; return ret; } utype<dim> operator-(const utype<dim> &R) const //minus R { utype<dim> ret; for (int i = 0; i < dim; i++) ret.v[i] = v[i] - R.v[i]; return ret; } utype<dim> operator*(const real R) const //times scalar { utype<dim> ret; for (int i = 0; i < dim; i++) ret.v[i] = v[i] * R; return ret; } utype<dim> operator*(const utype<dim> &R) const //times R { utype<dim> ret; for (int i = 0; i < dim; i++) ret.v[i] = v[i] * R[i]; return ret; } void operator+=(const utype<dim> &R) //add by R { for (int i = 0; i < dim; i++) v[i] += R.v[i]; } void operator-=(const utype<dim> &R) //minus by R { for (int i = 0; i < dim; i++) v[i] -= R.v[i]; } void operator/=(const utype<dim> &R) //divide by R { for (int i = 0; i < dim; i++) v[i] /= R.v[i]; } utype<dim> operator/(const utype<dim> &R) //divide by R { utype<dim> ret(*this); for (int i = 0; i < dim; i++) ret[i] /= R.v[i]; return ret; } void operator*=(real R) //times scalar { for (int i = 0; i < dim; i++) v[i] *= R; } void set(const real *a) //set uniform { for (int i = 0; i < dim; i++) v[i] = a[i]; } void set0() { for (int i = 0; i < dim; i++) v[i] = 0; } utype<dim> operator-() //negative of { utype<dim> ret; for (int i = 0; i < dim; i++) ret.v[i] = -v[i]; return ret; } utype<dim> abs() const { utype<dim> ret(*this); for (int i = 0; i < dim; i++) ret[i] = std::abs(ret[i]); return ret; } utype<dim> max(const utype<dim> &R) const //max by component { utype<dim> ret(*this); for (int i = 0; i < dim; i++) ret[i] = std::max(v[i], R[i]); return ret; } utype<dim> min(const utype<dim> &R) const //min by component { utype<dim> ret(*this); for (int i = 0; i < dim; i++) ret[i] = std::min(v[i], R[i]); return ret; } real minelem() { real ret = v[0]; for (int i = 1; i < dim; i++) ret = std::min(v[i], ret); return ret; } real dot(const utype<dim> &R) const { real ans = 0.; for (int i = 0; i < dim; i++) ans += R[i] * v[i]; return ans; } real norm2() const { real ans = 0.; for (int i = 0; i < dim; i++) ans += v[i] * v[i]; return std::sqrt(ans); } void normalize() { real dn2 = 1.0 / norm2(); for (int i = 0; i < dim; i++) v[i] *= dn2; } }; utype<3> crossUT3(const utype<3> &L, const utype<3> &R) { utype<3> ret; ret[0] = L[1] * R[2] - L[2] * R[1]; ret[1] = L[2] * R[0] - L[0] * R[2]; ret[2] = L[0] * R[1] - L[1] * R[0]; return ret; } template <size col, size row> struct mtype { real v[col][row]; mtype() { for (size i = 0; i < col; i++) for (size j = 0; j < row; j++) v[i][j] = 0; } mtype(const mtype<col, row> &R) { for (size i = 0; i < col; i++) for (size j = 0; j < row; j++) v[i][j] = R(i, j); } void set0() { for (size i = 0; i < col; i++) for (size j = 0; j < row; j++) v[i][j] = 0; } real &operator()(const size m, const size n) { return v[m][n]; } utype<col> operator*(const utype<row> &r) { utype<col> ret; for (size i = 0; i < col; i++) for (size j = 0; j < row; j++) ret[i] += r[j] * v[i][j]; return ret; } }; mtype<2, 2> a; #define DIM 3 #define FDIM 5 typedef utype<FDIM> ut; template <unsigned dim> utype<dim + 2> TVDFunc(const utype<dim + 2> &dl, const utype<dim + 2> &dr) { utype<dim + 2> ret; for (int i = 0; i < dim + 2; i++) if ((dl[i] <= 0 && dr[i] >= 0) || (dl[i] >= 0 && dr[i] <= 0)) ret[i] = 0; else ret[i] = 2 * dr[i] / (dl[i] + dr[i]); return ret; } void operator*=(std::vector<ut> &a, real R) { #ifndef OMP_ON for (auto &x : a) x *= R; #endif #ifdef OMP_ON #pragma omp parallel for for (size i = 0; i < a.size(); i++) a[i] *= R; #endif } void operator*=(std::vector<utype<4>> &a, real R) { #ifndef OMP_ON for (auto &x : a) x *= R; #endif #ifdef OMP_ON #pragma omp parallel for for (size i = 0; i < a.size(); i++) a[i] *= R; #endif } void operator+=(std::vector<ut> &a, const std::vector<ut> &R) //warning, R size not checked { #ifdef OMP_ON #pragma omp parallel for #endif for (size i = 0; i < a.size(); i++) a[i] += R[i]; } void operator+=(std::vector<utype<4>> &a, const std::vector<utype<4>> &R) //warning, R size not checked { #ifdef OMP_ON #pragma omp parallel for #endif for (size i = 0; i < a.size(); i++) a[i] += R[i]; } void operator-=(std::vector<ut> &a, const std::vector<ut> &R) //warning, R size not checked { #ifdef OMP_ON #pragma omp parallel for #endif for (size i = 0; i < a.size(); i++) a[i] -= R[i]; } void operator-=(std::vector<utype<4>> &a, const std::vector<utype<4>> &R) //warning, R size not checked { #ifdef OMP_ON #pragma omp parallel for #endif for (size i = 0; i < a.size(); i++) a[i] -= R[i]; } template <unsigned dim> utype<dim> maxabs(const std::vector<utype<dim>> &a) { utype<dim> ret(0.0); for (size i = 0; i < a.size(); i++) ret = ret.max(a[i].abs()); return ret; } real triangleArea2nd(utype<3> a, utype<3> b, utype<3> c) { return crossUT3(b - a, c - a).norm2(); } utype<3> triangleBary(utype<3> a, utype<3> b, utype<3> c) { return a + ((b - a) + (c - a)) * (1.0 / 3.0); } real tetraVolume6th(utype<3> a, utype<3> b, utype<3> c, utype<3> d) { return std::abs(crossUT3(b - a, c - a).dot(d - a)); } real pointToLine(real x, real y, real x0, real y0, real x1, real y1) { real area = fabs((x0 - x) * (y1 - y) - (x1 - x) * (y0 - y)); return area / sqrt(sqr(x0 - x1) + sqr(y0 - y1)); } real pointToFace(utype<3> p, utype<3> a, utype<3> b, utype<3> c) { return tetraVolume6th(p, a, b, c) / triangleArea2nd(a, b, c); } enum __ntype__ { inner = 0, infinity = 1, // CFD wall = 2, // CFD pressure = 3, // CFD freesurf = 2001, // CSD fixed = 2002, // CSD pressuresurf = 2003, // CSD cross = 9003, // currently unused inter = 66, // interaction for FSI. wall for CFD and force/free for CSD unknown = 10203 }; #ifdef INF_FIRST __ntype__ deriveFtype3(__ntype__ t1, __ntype__ t2, __ntype__ t3) { if (t1 && t2 && t3) { if ((t1 == infinity) && (t2 == infinity) && (t3 == infinity)) return infinity; if ((t1 == pressure) && (t2 == pressure) && (t3 == pressure)) return pressure; if ((t1 == fixed) && (t2 == fixed) && (t3 == fixed)) return fixed; if ((t1 == wall) || (t2 == wall) || (t3 == wall)) return wall; if ((t1 == pressuresurf) || (t2 == pressuresurf) || (t3 == pressuresurf)) return pressuresurf; // TODO should discuss here if ((t1 == inter) || (t2 == inter) || (t3 == inter)) return inter; if ((t1 == freesurf) || (t2 == freesurf) || (t3 == freesurf)) return freesurf; if ((t1 == cross) || (t2 == cross) || (t3 == cross)) return cross; return unknown; } return inner; } #else __ntype__ deriveFtype3(__ntype__ t1, __ntype__ t2, __ntype__ t3) { if (t1 && t2 && t3) { if ((t1 == infinity) || (t2 == infinity) || (t3 == infinity)) return infinity; if ((t1 == pressure) || (t2 == pressure) || (t3 == pressure)) return pressure; if ((t1 == fixed) && (t2 == fixed) && (t3 == fixed)) return fixed; if ((t1 == wall) || (t2 == wall) || (t3 == wall)) return wall; if ((t1 == pressuresurf) || (t2 == pressuresurf) || (t3 == pressuresurf)) return pressuresurf; // TODO should discuss here if ((t1 == inter) || (t2 == inter) || (t3 == inter)) return inter; if ((t1 == freesurf) || (t2 == freesurf) || (t3 == freesurf)) return freesurf; if ((t1 == cross) || (t2 == cross) || (t3 == cross)) return cross; return unknown; } return inner; } #endif #ifdef INF_FIRST size deriveNbound3(__ntype__ t1, __ntype__ t2, __ntype__ t3, size n1, size n2, size n3) //when all are not inner { if ((t1 == infinity) && (t2 == infinity) && (t3 == infinity)) return n1; if ((t1 == pressure) && (t2 == pressure) && (t3 == pressure)) return n1; if (t1 == wall || t1 == inter || t1 == pressuresurf) return n1; if (t2 == wall || t2 == inter || t2 == pressuresurf) return n2; if (t3 == wall || t3 == inter || t3 == pressuresurf) return n3; return 0; } typedef __ntype__ ntype; #else size deriveNbound3(__ntype__ t1, __ntype__ t2, __ntype__ t3, size n1, size n2, size n3) //when all are not inner { if ((t1 == wall) && (t2 == wall) && (t3 == wall)) return n1; if ((t1 == inter) && (t2 == inter) && (t3 == inter)) return n1; if (t1 == infinity || t1 == pressure || t1 == pressuresurf) return n1; if (t2 == infinity || t2 == pressure || t2 == pressuresurf) return n2; if (t3 == infinity || t3 == pressure || t3 == pressuresurf) return n3; return 0; } #endif typedef __ntype__ ntype; template <size dim> bool inbox(const utype<dim> p, const utype<dim> lb, const utype<dim> ub) { for (int i = 0; i < dim; i++) if (p[i] < lb[i] || p[i] > ub[i]) return false; return true; } void TransAddTo(utype<5> &U, const utype<3> &velo) { U[1] += velo[0] * U[0]; U[2] += velo[1] * U[0]; U[3] += velo[2] * U[0]; } // WHY ??? template <size d> std::ostream &operator<<(std::ostream &out, const utype<d> &u) { for (size i = 0; i < d; i++) out << u[i] << '\t'; return out; } std::ostream &operator<<(std::ostream &out, const utype<5> &u) { for (size i = 0; i < 5; i++) out << u[i] << '\t'; return out; } std::ostream &operator<<(std::ostream &out, const utype<3> &u) { for (size i = 0; i < 3; i++) out << u[i] << '\t'; return out; } /////// template <size d> std::istream &operator>>(std::istream &in, utype<d> &u) { for (size i = 0; i < d; i++) in >> u[i]; return in; } template <typename T> void SaveVector(const std::vector<T> &vec, std::ostream &out) { out << "\nVECTOR " << std::scientific << std::setprecision(16) << std::setw(20) << vec.size() << '\n'; for (size i = 0; i < vec.size(); i++) out << vec[i] << "\n"; } template <typename T> bool ReadVector(std::vector<T> &vec, std::istream &in) { std::string name; in >> name; if (name != "VECTOR") { std::cerr << "VECTOR READ FALILIURE\n" << std::endl; return false; } size vsize; in >> vsize; vec.resize(vsize); for (size i = 0; i < vec.size(); i++) in >> vec[i]; return true; } template <typename T> std::istream &operator>>(std::istream &in, std::vector<T> &vec) { ReadVector(vec, in); return in; } template <typename T> std::ostream &operator<<(std::ostream &out, const std::vector<T> &vec) { SaveVector(vec, out); return out; } const real pi = std::acos(-1.0); }
SECTION code_clib SECTION code_l PUBLIC l_jrbc ; 8080 relative 16-bit jump ; call with twos complement offset in bc ; ; ld bc,destination-origin ; call l_jrbc ; .origin l_jrbc: ex (sp),hl add hl,bc ex (sp),hl ret
DanaPhoneCalleeScript: ; gettrainername STRING_BUFFER_3, LASS, DANA1 checkflag ENGINE_DANA iftrue .WantsBattle farscall PhoneScript_AnswerPhone_Female checkflag ENGINE_DANA_THURSDAY_NIGHT iftrue .NotThursday checkflag ENGINE_DANA_HAS_THUNDERSTONE iftrue .HasThunderstone readvar VAR_WEEKDAY ifnotequal THURSDAY, .NotThursday checktime NITE iftrue DanaThursdayNight .NotThursday: farsjump UnknownScript_0xa0978 .WantsBattle: getlandmarkname STRING_BUFFER_5, ROUTE_38 farsjump UnknownScript_0xa0a78 .HasThunderstone: getlandmarkname STRING_BUFFER_5, ROUTE_38 farsjump UnknownScript_0xa0acd DanaPhoneCallerScript: ; gettrainername STRING_BUFFER_3, LASS, DANA1 farscall PhoneScript_GreetPhone_Female checkflag ENGINE_DANA iftrue .Generic checkflag ENGINE_DANA_THURSDAY_NIGHT iftrue .Generic checkflag ENGINE_DANA_HAS_THUNDERSTONE iftrue .Generic farscall PhoneScript_Random3 ifequal 0, DanaWantsBattle checkevent EVENT_DANA_GAVE_THUNDERSTONE iftrue .Thunderstone farscall PhoneScript_Random2 ifequal 0, DanaHasThunderstone .Thunderstone: farscall PhoneScript_Random11 ifequal 0, DanaHasThunderstone .Generic: farscall PhoneScript_Random3 ifequal 0, DanaFoundRare farsjump Phone_GenericCall_Female DanaThursdayNight: setflag ENGINE_DANA_THURSDAY_NIGHT DanaWantsBattle: getlandmarkname STRING_BUFFER_5, ROUTE_38 setflag ENGINE_DANA farsjump PhoneScript_WantsToBattle_Female DanaFoundRare: farsjump Phone_CheckIfUnseenRare_Female DanaHasThunderstone: setflag ENGINE_DANA_HAS_THUNDERSTONE getlandmarkname STRING_BUFFER_5, ROUTE_38 farsjump PhoneScript_FoundItem_Female
;-------------------------------------------------------- ; File Created by SDCC : free open source ANSI-C Compiler ; Version 4.0.7 #12017 (Linux) ;-------------------------------------------------------- ; Processed by Z88DK ;-------------------------------------------------------- EXTERN __divschar EXTERN __divschar_callee EXTERN __divsint EXTERN __divsint_callee EXTERN __divslong EXTERN __divslong_callee EXTERN __divslonglong EXTERN __divslonglong_callee EXTERN __divsuchar EXTERN __divsuchar_callee EXTERN __divuchar EXTERN __divuchar_callee EXTERN __divuint EXTERN __divuint_callee EXTERN __divulong EXTERN __divulong_callee EXTERN __divulonglong EXTERN __divulonglong_callee EXTERN __divuschar EXTERN __divuschar_callee EXTERN __modschar EXTERN __modschar_callee EXTERN __modsint EXTERN __modsint_callee EXTERN __modslong EXTERN __modslong_callee EXTERN __modslonglong EXTERN __modslonglong_callee EXTERN __modsuchar EXTERN __modsuchar_callee EXTERN __moduchar EXTERN __moduchar_callee EXTERN __moduint EXTERN __moduint_callee EXTERN __modulong EXTERN __modulong_callee EXTERN __modulonglong EXTERN __modulonglong_callee EXTERN __moduschar EXTERN __moduschar_callee EXTERN __mulint EXTERN __mulint_callee EXTERN __mullong EXTERN __mullong_callee EXTERN __mullonglong EXTERN __mullonglong_callee EXTERN __mulschar EXTERN __mulschar_callee EXTERN __mulsuchar EXTERN __mulsuchar_callee EXTERN __muluchar EXTERN __muluchar_callee EXTERN __muluschar EXTERN __muluschar_callee EXTERN __rlslonglong EXTERN __rlslonglong_callee EXTERN __rlulonglong EXTERN __rlulonglong_callee EXTERN __rrslonglong EXTERN __rrslonglong_callee EXTERN __rrulonglong EXTERN __rrulonglong_callee EXTERN ___sdcc_call_hl EXTERN ___sdcc_call_iy EXTERN ___sdcc_enter_ix EXTERN banked_call EXTERN _banked_ret EXTERN ___fs2schar EXTERN ___fs2schar_callee EXTERN ___fs2sint EXTERN ___fs2sint_callee EXTERN ___fs2slong EXTERN ___fs2slong_callee EXTERN ___fs2slonglong EXTERN ___fs2slonglong_callee EXTERN ___fs2uchar EXTERN ___fs2uchar_callee EXTERN ___fs2uint EXTERN ___fs2uint_callee EXTERN ___fs2ulong EXTERN ___fs2ulong_callee EXTERN ___fs2ulonglong EXTERN ___fs2ulonglong_callee EXTERN ___fsadd EXTERN ___fsadd_callee EXTERN ___fsdiv EXTERN ___fsdiv_callee EXTERN ___fseq EXTERN ___fseq_callee EXTERN ___fsgt EXTERN ___fsgt_callee EXTERN ___fslt EXTERN ___fslt_callee EXTERN ___fsmul EXTERN ___fsmul_callee EXTERN ___fsneq EXTERN ___fsneq_callee EXTERN ___fssub EXTERN ___fssub_callee EXTERN ___schar2fs EXTERN ___schar2fs_callee EXTERN ___sint2fs EXTERN ___sint2fs_callee EXTERN ___slong2fs EXTERN ___slong2fs_callee EXTERN ___slonglong2fs EXTERN ___slonglong2fs_callee EXTERN ___uchar2fs EXTERN ___uchar2fs_callee EXTERN ___uint2fs EXTERN ___uint2fs_callee EXTERN ___ulong2fs EXTERN ___ulong2fs_callee EXTERN ___ulonglong2fs EXTERN ___ulonglong2fs_callee EXTERN ____sdcc_2_copy_src_mhl_dst_deix EXTERN ____sdcc_2_copy_src_mhl_dst_bcix EXTERN ____sdcc_4_copy_src_mhl_dst_deix EXTERN ____sdcc_4_copy_src_mhl_dst_bcix EXTERN ____sdcc_4_copy_src_mhl_dst_mbc EXTERN ____sdcc_4_ldi_nosave_bc EXTERN ____sdcc_4_ldi_save_bc EXTERN ____sdcc_4_push_hlix EXTERN ____sdcc_4_push_mhl EXTERN ____sdcc_lib_setmem_hl EXTERN ____sdcc_ll_add_de_bc_hl EXTERN ____sdcc_ll_add_de_bc_hlix EXTERN ____sdcc_ll_add_de_hlix_bc EXTERN ____sdcc_ll_add_de_hlix_bcix EXTERN ____sdcc_ll_add_deix_bc_hl EXTERN ____sdcc_ll_add_deix_hlix EXTERN ____sdcc_ll_add_hlix_bc_deix EXTERN ____sdcc_ll_add_hlix_deix_bc EXTERN ____sdcc_ll_add_hlix_deix_bcix EXTERN ____sdcc_ll_asr_hlix_a EXTERN ____sdcc_ll_asr_mbc_a EXTERN ____sdcc_ll_copy_src_de_dst_hlix EXTERN ____sdcc_ll_copy_src_de_dst_hlsp EXTERN ____sdcc_ll_copy_src_deix_dst_hl EXTERN ____sdcc_ll_copy_src_deix_dst_hlix EXTERN ____sdcc_ll_copy_src_deixm_dst_hlsp EXTERN ____sdcc_ll_copy_src_desp_dst_hlsp EXTERN ____sdcc_ll_copy_src_hl_dst_de EXTERN ____sdcc_ll_copy_src_hlsp_dst_de EXTERN ____sdcc_ll_copy_src_hlsp_dst_deixm EXTERN ____sdcc_ll_lsl_hlix_a EXTERN ____sdcc_ll_lsl_mbc_a EXTERN ____sdcc_ll_lsr_hlix_a EXTERN ____sdcc_ll_lsr_mbc_a EXTERN ____sdcc_ll_push_hlix EXTERN ____sdcc_ll_push_mhl EXTERN ____sdcc_ll_sub_de_bc_hl EXTERN ____sdcc_ll_sub_de_bc_hlix EXTERN ____sdcc_ll_sub_de_hlix_bc EXTERN ____sdcc_ll_sub_de_hlix_bcix EXTERN ____sdcc_ll_sub_deix_bc_hl EXTERN ____sdcc_ll_sub_deix_hlix EXTERN ____sdcc_ll_sub_hlix_bc_deix EXTERN ____sdcc_ll_sub_hlix_deix_bc EXTERN ____sdcc_ll_sub_hlix_deix_bcix EXTERN ____sdcc_load_debc_deix EXTERN ____sdcc_load_dehl_deix EXTERN ____sdcc_load_debc_mhl EXTERN ____sdcc_load_hlde_mhl EXTERN ____sdcc_store_dehl_bcix EXTERN ____sdcc_store_debc_hlix EXTERN ____sdcc_store_debc_mhl EXTERN ____sdcc_cpu_pop_ei EXTERN ____sdcc_cpu_pop_ei_jp EXTERN ____sdcc_cpu_push_di EXTERN ____sdcc_outi EXTERN ____sdcc_outi_128 EXTERN ____sdcc_outi_256 EXTERN ____sdcc_ldi EXTERN ____sdcc_ldi_128 EXTERN ____sdcc_ldi_256 EXTERN ____sdcc_4_copy_srcd_hlix_dst_deix EXTERN ____sdcc_4_and_src_mbc_mhl_dst_deix EXTERN ____sdcc_4_or_src_mbc_mhl_dst_deix EXTERN ____sdcc_4_xor_src_mbc_mhl_dst_deix EXTERN ____sdcc_4_or_src_dehl_dst_bcix EXTERN ____sdcc_4_xor_src_dehl_dst_bcix EXTERN ____sdcc_4_and_src_dehl_dst_bcix EXTERN ____sdcc_4_xor_src_mbc_mhl_dst_debc EXTERN ____sdcc_4_or_src_mbc_mhl_dst_debc EXTERN ____sdcc_4_and_src_mbc_mhl_dst_debc EXTERN ____sdcc_4_cpl_src_mhl_dst_debc EXTERN ____sdcc_4_xor_src_debc_mhl_dst_debc EXTERN ____sdcc_4_or_src_debc_mhl_dst_debc EXTERN ____sdcc_4_and_src_debc_mhl_dst_debc EXTERN ____sdcc_4_and_src_debc_hlix_dst_debc EXTERN ____sdcc_4_or_src_debc_hlix_dst_debc EXTERN ____sdcc_4_xor_src_debc_hlix_dst_debc ;-------------------------------------------------------- ; Public variables in this module ;-------------------------------------------------------- GLOBAL _m32_logf ;-------------------------------------------------------- ; Externals used ;-------------------------------------------------------- GLOBAL _m32_polyf GLOBAL _m32_hypotf GLOBAL _m32_ldexpf GLOBAL _m32_frexpf GLOBAL _m32_invsqrtf GLOBAL _m32_sqrtf GLOBAL _m32_invf GLOBAL _m32_sqrf GLOBAL _m32_div2f GLOBAL _m32_mul2f GLOBAL _m32_modff GLOBAL _m32_fmodf GLOBAL _m32_roundf GLOBAL _m32_floorf GLOBAL _m32_fabsf GLOBAL _m32_ceilf GLOBAL _m32_powf GLOBAL _m32_log10f GLOBAL _m32_log2f GLOBAL _m32_exp10f GLOBAL _m32_exp2f GLOBAL _m32_expf GLOBAL _m32_atanhf GLOBAL _m32_acoshf GLOBAL _m32_asinhf GLOBAL _m32_tanhf GLOBAL _m32_coshf GLOBAL _m32_sinhf GLOBAL _m32_atan2f GLOBAL _m32_atanf GLOBAL _m32_acosf GLOBAL _m32_asinf GLOBAL _m32_tanf GLOBAL _m32_cosf GLOBAL _m32_sinf GLOBAL _poly_callee GLOBAL _poly GLOBAL _exp10_fastcall GLOBAL _exp10 GLOBAL _mul10u_fastcall GLOBAL _mul10u GLOBAL _mul2_fastcall GLOBAL _mul2 GLOBAL _div2_fastcall GLOBAL _div2 GLOBAL _invsqrt_fastcall GLOBAL _invsqrt GLOBAL _inv_fastcall GLOBAL _inv GLOBAL _sqr_fastcall GLOBAL _sqr GLOBAL _isunordered_callee GLOBAL _isunordered GLOBAL _islessgreater_callee GLOBAL _islessgreater GLOBAL _islessequal_callee GLOBAL _islessequal GLOBAL _isless_callee GLOBAL _isless GLOBAL _isgreaterequal_callee GLOBAL _isgreaterequal GLOBAL _isgreater_callee GLOBAL _isgreater GLOBAL _fma_callee GLOBAL _fma GLOBAL _fmin_callee GLOBAL _fmin GLOBAL _fmax_callee GLOBAL _fmax GLOBAL _fdim_callee GLOBAL _fdim GLOBAL _nexttoward_callee GLOBAL _nexttoward GLOBAL _nextafter_callee GLOBAL _nextafter GLOBAL _nan_fastcall GLOBAL _nan GLOBAL _copysign_callee GLOBAL _copysign GLOBAL _remquo_callee GLOBAL _remquo GLOBAL _remainder_callee GLOBAL _remainder GLOBAL _fmod_callee GLOBAL _fmod GLOBAL _modf_callee GLOBAL _modf GLOBAL _trunc_fastcall GLOBAL _trunc GLOBAL _lround_fastcall GLOBAL _lround GLOBAL _round_fastcall GLOBAL _round GLOBAL _lrint_fastcall GLOBAL _lrint GLOBAL _rint_fastcall GLOBAL _rint GLOBAL _nearbyint_fastcall GLOBAL _nearbyint GLOBAL _floor_fastcall GLOBAL _floor GLOBAL _ceil_fastcall GLOBAL _ceil GLOBAL _tgamma_fastcall GLOBAL _tgamma GLOBAL _lgamma_fastcall GLOBAL _lgamma GLOBAL _erfc_fastcall GLOBAL _erfc GLOBAL _erf_fastcall GLOBAL _erf GLOBAL _cbrt_fastcall GLOBAL _cbrt GLOBAL _sqrt_fastcall GLOBAL _sqrt GLOBAL _pow_callee GLOBAL _pow GLOBAL _hypot_callee GLOBAL _hypot GLOBAL _fabs_fastcall GLOBAL _fabs GLOBAL _logb_fastcall GLOBAL _logb GLOBAL _log2_fastcall GLOBAL _log2 GLOBAL _log1p_fastcall GLOBAL _log1p GLOBAL _log10_fastcall GLOBAL _log10 GLOBAL _log_fastcall GLOBAL _log GLOBAL _scalbln_callee GLOBAL _scalbln GLOBAL _scalbn_callee GLOBAL _scalbn GLOBAL _ldexp_callee GLOBAL _ldexp GLOBAL _ilogb_fastcall GLOBAL _ilogb GLOBAL _frexp_callee GLOBAL _frexp GLOBAL _expm1_fastcall GLOBAL _expm1 GLOBAL _exp2_fastcall GLOBAL _exp2 GLOBAL _exp_fastcall GLOBAL _exp GLOBAL _tanh_fastcall GLOBAL _tanh GLOBAL _sinh_fastcall GLOBAL _sinh GLOBAL _cosh_fastcall GLOBAL _cosh GLOBAL _atanh_fastcall GLOBAL _atanh GLOBAL _asinh_fastcall GLOBAL _asinh GLOBAL _acosh_fastcall GLOBAL _acosh GLOBAL _tan_fastcall GLOBAL _tan GLOBAL _sin_fastcall GLOBAL _sin GLOBAL _cos_fastcall GLOBAL _cos GLOBAL _atan2_callee GLOBAL _atan2 GLOBAL _atan_fastcall GLOBAL _atan GLOBAL _asin_fastcall GLOBAL _asin GLOBAL _acos_fastcall GLOBAL _acos GLOBAL _m32_coeff_logf ;-------------------------------------------------------- ; special function registers ;-------------------------------------------------------- ;-------------------------------------------------------- ; ram data ;-------------------------------------------------------- SECTION bss_compiler ;-------------------------------------------------------- ; ram data ;-------------------------------------------------------- IF 0 ; .area _INITIALIZED removed by z88dk ENDIF ;-------------------------------------------------------- ; absolute external ram data ;-------------------------------------------------------- SECTION IGNORE ;-------------------------------------------------------- ; global & static initialisations ;-------------------------------------------------------- SECTION code_crt_init ;-------------------------------------------------------- ; Home ;-------------------------------------------------------- SECTION IGNORE ;-------------------------------------------------------- ; code ;-------------------------------------------------------- SECTION code_compiler ; --------------------------------- ; Function m32_logf ; --------------------------------- _m32_logf: push ix ld ix,0 add ix,sp ld c, l ld b, h ld hl, -18 add hl, sp ld sp, hl ld (ix-6),c ld (ix-5),b ld (ix-4),e ld l, e ld (ix-3),d ld h,d push hl ld l,(ix-6) ld h,(ix-5) push hl ld hl,0x0000 push hl push hl call ___fslt_callee bit 0,l jr NZ,l_m32_logf_00102 ld de,0xff00 ld hl,0x0000 jp l_m32_logf_00106 l_m32_logf_00102: ld hl,16 add hl, sp push hl ld l,(ix-4) ld h,(ix-3) push hl ld l,(ix-6) ld h,(ix-5) push hl call _m32_frexpf push hl ld c,l ld b,h push de ld hl,0x3f35 push hl ld hl,0x04f3 push hl push de push bc call ___fslt_callee pop de pop bc ld a,l or a, a jr Z,l_m32_logf_00104 ld l,(ix-2) ld h,(ix-1) dec hl ld (ix-2),l ld (ix-1),h ld l, c ld h, b call _m32_mul2f ld bc,0x3f80 push bc ld bc,0x0000 push bc push de push hl call ___fssub_callee ex (sp),hl ld (ix-16),e ld (ix-15),d jr l_m32_logf_00105 l_m32_logf_00104: ld hl,0x3f80 push hl ld hl,0x0000 push hl push de push bc call ___fssub_callee ex (sp),hl ld (ix-16),e ld (ix-15),d l_m32_logf_00105: ld l,(ix-18) ld h,(ix-17) ld e,(ix-16) ld d,(ix-15) call _m32_sqrf ld (ix-14),l ld (ix-13),h ld (ix-12),e ld (ix-11),d ld hl,0x0009 push hl ld hl,_m32_coeff_logf push hl ld l,(ix-16) ld h,(ix-15) push hl ld l,(ix-18) ld h,(ix-17) push hl call _m32_polyf ld c, l ld l,(ix-12) ld b,h ld h,(ix-11) push hl ld l,(ix-14) ld h,(ix-13) push hl push de push bc call ___fsmul_callee ld (ix-6),l ld (ix-5),h ld (ix-4),e ld (ix-3),d ld l,(ix-2) ld h,(ix-1) push hl call ___sint2fs_callee ld (ix-10),l ld (ix-9),h ld (ix-8),e ld l, e ld (ix-7),d ld h,d push hl ld l,(ix-10) ld h,(ix-9) push hl ld hl,0xb95e push hl ld hl,0x8083 push hl call ___fsmul_callee push de push hl ld l,(ix-4) ld h,(ix-3) push hl ld l,(ix-6) ld h,(ix-5) push hl call ___fsadd_callee ld (ix-6),l ld (ix-5),h ld (ix-4),e ld (ix-3),d ld l,(ix-14) ld h,(ix-13) ld e,(ix-12) ld d,(ix-11) call _m32_div2f push de push hl ld l,(ix-4) ld h,(ix-3) push hl ld l,(ix-6) ld h,(ix-5) push hl call ___fssub_callee push de push hl ld l,(ix-16) ld h,(ix-15) push hl ld l,(ix-18) ld h,(ix-17) push hl call ___fsadd_callee ld (ix-6),l ld (ix-5),h ld (ix-4),e ld (ix-3),d ld l,(ix-8) ld h,(ix-7) push hl ld l,(ix-10) ld h,(ix-9) push hl ld hl,0x3f31 push hl ld hl,0x8000 push hl call ___fsmul_callee push de push hl ld l,(ix-4) ld h,(ix-3) push hl ld l,(ix-6) ld h,(ix-5) push hl call ___fsadd_callee l_m32_logf_00106: ld sp, ix pop ix ret SECTION IGNORE
/* Copyright (c) 2012-2014 The SSDB 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 "version.h" #include "util/log.h" #include "util/strings.h" #include "serv.h" #include "net/proc.h" #include "net/server.h" // 声明命令处理函数的宏,宏在net/proc.h中定义 DEF_PROC(get); DEF_PROC(set); DEF_PROC(setx); DEF_PROC(setnx); DEF_PROC(getset); DEF_PROC(getbit); DEF_PROC(setbit); DEF_PROC(countbit); DEF_PROC(substr); DEF_PROC(getrange); DEF_PROC(strlen); DEF_PROC(bitcount); DEF_PROC(del); DEF_PROC(incr); DEF_PROC(decr); DEF_PROC(scan); DEF_PROC(rscan); DEF_PROC(keys); DEF_PROC(rkeys); DEF_PROC(exists); DEF_PROC(multi_exists); DEF_PROC(multi_get); DEF_PROC(multi_set); DEF_PROC(multi_del); DEF_PROC(ttl); DEF_PROC(expire); DEF_PROC(hsize); DEF_PROC(hget); DEF_PROC(hset); DEF_PROC(hdel); DEF_PROC(hincr); DEF_PROC(hdecr); DEF_PROC(hclear); DEF_PROC(hgetall); DEF_PROC(hscan); DEF_PROC(hrscan); DEF_PROC(hkeys); DEF_PROC(hvals); DEF_PROC(hlist); DEF_PROC(hrlist); DEF_PROC(hexists); DEF_PROC(multi_hexists); DEF_PROC(multi_hsize); DEF_PROC(multi_hget); DEF_PROC(multi_hset); DEF_PROC(multi_hdel); DEF_PROC(zrank); DEF_PROC(zrrank); DEF_PROC(zrange); DEF_PROC(zrrange); DEF_PROC(zsize); DEF_PROC(zget); DEF_PROC(zset); DEF_PROC(zdel); DEF_PROC(zincr); DEF_PROC(zdecr); DEF_PROC(zclear); DEF_PROC(zscan); DEF_PROC(zrscan); DEF_PROC(zkeys); DEF_PROC(zlist); DEF_PROC(zrlist); DEF_PROC(zcount); DEF_PROC(zsum); DEF_PROC(zavg); DEF_PROC(zexists); DEF_PROC(zremrangebyrank); DEF_PROC(zremrangebyscore); DEF_PROC(multi_zexists); DEF_PROC(multi_zsize); DEF_PROC(multi_zget); DEF_PROC(multi_zset); DEF_PROC(multi_zdel); DEF_PROC(zpop_front); DEF_PROC(zpop_back); DEF_PROC(qsize); DEF_PROC(qfront); DEF_PROC(qback); DEF_PROC(qpush); DEF_PROC(qpush_front); DEF_PROC(qpush_back); DEF_PROC(qpop); DEF_PROC(qpop_front); DEF_PROC(qpop_back); DEF_PROC(qtrim_front); DEF_PROC(qtrim_back); DEF_PROC(qfix); DEF_PROC(qclear); DEF_PROC(qlist); DEF_PROC(qrlist); DEF_PROC(qslice); DEF_PROC(qrange); DEF_PROC(qget); DEF_PROC(qset); DEF_PROC(dump); DEF_PROC(sync140); DEF_PROC(info); DEF_PROC(version); DEF_PROC(dbsize); DEF_PROC(compact); DEF_PROC(clear_binlog); DEF_PROC(get_key_range); DEF_PROC(ignore_key_range); DEF_PROC(get_kv_range); DEF_PROC(set_kv_range); DEF_PROC(cluster_add_kv_node); DEF_PROC(cluster_del_kv_node); DEF_PROC(cluster_kv_node_list); DEF_PROC(cluster_set_kv_range); DEF_PROC(cluster_set_kv_status); DEF_PROC(cluster_migrate_kv_data); // 用于注册命令处理汉书的宏 #define REG_PROC(c, f) net->proc_map.set_proc(#c, f, proc_##c) // 向网络服务器的命令影射map中注册命令处理汉书,注册时要指定命令类型, // 读命令/写命令/线程中运行的命令/后台命令等。 void SSDBServer::reg_procs(NetworkServer *net){ REG_PROC(get, "r"); REG_PROC(set, "wt"); REG_PROC(del, "wt"); REG_PROC(setx, "wt"); REG_PROC(setnx, "wt"); REG_PROC(getset, "wt"); REG_PROC(getbit, "r"); REG_PROC(setbit, "wt"); REG_PROC(countbit, "r"); REG_PROC(substr, "r"); REG_PROC(getrange, "r"); REG_PROC(strlen, "r"); REG_PROC(bitcount, "r"); REG_PROC(incr, "wt"); REG_PROC(decr, "wt"); REG_PROC(scan, "rt"); REG_PROC(rscan, "rt"); REG_PROC(keys, "rt"); REG_PROC(rkeys, "rt"); REG_PROC(exists, "r"); REG_PROC(multi_exists, "r"); REG_PROC(multi_get, "rt"); REG_PROC(multi_set, "wt"); REG_PROC(multi_del, "wt"); REG_PROC(ttl, "r"); REG_PROC(expire, "wt"); REG_PROC(hsize, "r"); REG_PROC(hget, "r"); REG_PROC(hset, "wt"); REG_PROC(hdel, "wt"); REG_PROC(hincr, "wt"); REG_PROC(hdecr, "wt"); REG_PROC(hclear, "wt"); REG_PROC(hgetall, "rt"); REG_PROC(hscan, "rt"); REG_PROC(hrscan, "rt"); REG_PROC(hkeys, "rt"); REG_PROC(hvals, "rt"); REG_PROC(hlist, "rt"); REG_PROC(hrlist, "rt"); REG_PROC(hexists, "r"); REG_PROC(multi_hexists, "r"); REG_PROC(multi_hsize, "r"); REG_PROC(multi_hget, "rt"); REG_PROC(multi_hset, "wt"); REG_PROC(multi_hdel, "wt"); // because zrank may be extremly slow, execute in a seperate thread REG_PROC(zrank, "rt"); REG_PROC(zrrank, "rt"); REG_PROC(zrange, "rt"); REG_PROC(zrrange, "rt"); REG_PROC(zsize, "r"); REG_PROC(zget, "rt"); REG_PROC(zset, "wt"); REG_PROC(zdel, "wt"); REG_PROC(zincr, "wt"); REG_PROC(zdecr, "wt"); REG_PROC(zclear, "wt"); REG_PROC(zscan, "rt"); REG_PROC(zrscan, "rt"); REG_PROC(zkeys, "rt"); REG_PROC(zlist, "rt"); REG_PROC(zrlist, "rt"); REG_PROC(zcount, "rt"); REG_PROC(zsum, "rt"); REG_PROC(zavg, "rt"); REG_PROC(zremrangebyrank, "wt"); REG_PROC(zremrangebyscore, "wt"); REG_PROC(zexists, "r"); REG_PROC(multi_zexists, "r"); REG_PROC(multi_zsize, "r"); REG_PROC(multi_zget, "rt"); REG_PROC(multi_zset, "wt"); REG_PROC(multi_zdel, "wt"); REG_PROC(zpop_front, "wt"); REG_PROC(zpop_back, "wt"); REG_PROC(qsize, "r"); REG_PROC(qfront, "r"); REG_PROC(qback, "r"); REG_PROC(qpush, "wt"); REG_PROC(qpush_front, "wt"); REG_PROC(qpush_back, "wt"); REG_PROC(qpop, "wt"); REG_PROC(qpop_front, "wt"); REG_PROC(qpop_back, "wt"); REG_PROC(qtrim_front, "wt"); REG_PROC(qtrim_back, "wt"); REG_PROC(qfix, "wt"); REG_PROC(qclear, "wt"); REG_PROC(qlist, "rt"); REG_PROC(qrlist, "rt"); REG_PROC(qslice, "rt"); REG_PROC(qrange, "rt"); REG_PROC(qget, "r"); REG_PROC(qset, "wt"); REG_PROC(clear_binlog, "wt"); REG_PROC(dump, "b"); REG_PROC(sync140, "b"); REG_PROC(info, "r"); REG_PROC(version, "r"); REG_PROC(dbsize, "r"); // doing compaction in a reader thread, because we have only one // writer thread(for performance reason); we don't want to block writes REG_PROC(compact, "rt"); REG_PROC(ignore_key_range, "r"); REG_PROC(get_key_range, "r"); REG_PROC(get_kv_range, "r"); REG_PROC(set_kv_range, "r"); REG_PROC(cluster_add_kv_node, "r"); REG_PROC(cluster_del_kv_node, "r"); REG_PROC(cluster_kv_node_list, "r"); REG_PROC(cluster_set_kv_range, "r"); REG_PROC(cluster_set_kv_status, "r"); REG_PROC(cluster_migrate_kv_data, "r"); } SSDBServer::SSDBServer(SSDB *ssdb, SSDB *meta, const Config &conf, NetworkServer *net){ this->ssdb = (SSDBImpl *)ssdb; this->meta = meta; // 将网络服务器的data指针指向ssdb服务对象,这样在处理函数中就可以通过网络服务器 // 获取到SSDB服务对象,从而实现其他操作 net->data = this; // 注册处理函数,会将各个命令的处理函数注册到网络服务器 this->reg_procs(net); // 同步速度?看看在那里用到吧 int sync_speed = conf.get_num("replication.sync_speed"); // 用于进行后台dump的对象 backend_dump = new BackendDump(this->ssdb); // 用于进行后台同步的对象 backend_sync = new BackendSync(this->ssdb, sync_speed); // 用于判断命令是否超时的? expiration = new ExpirationHandler(this->ssdb); // 集群对象,一启动就是集群模式? cluster = new Cluster(this->ssdb); if(cluster->init() == -1){ log_fatal("cluster init failed!"); exit(1); } // 配置主从同步 { // slaves // 读取配置 const Config *repl_conf = conf.get("replication"); if(repl_conf != NULL){ std::vector<Config *> children = repl_conf->children; for(std::vector<Config *>::iterator it = children.begin(); it != children.end(); it++){ Config *c = *it; if(c->key != "slaveof"){ continue; } std::string ip = c->get_str("ip"); int port = c->get_num("port"); if(ip == "" || port <= 0 || port > 65535){ continue; } bool is_mirror = false; std::string type = c->get_str("type"); // 两种类型有啥区别与联系? if(type == "mirror"){ is_mirror = true; }else{ type = "sync"; is_mirror = false; } std::string id = c->get_str("id"); log_info("slaveof: %s:%d, type: %s", ip.c_str(), port, type.c_str()); // 新建一个slave对象。这里很有意思,slaveof的意思指定的应该是master吧,为啥 // 要叫slave? Slave *slave = new Slave(ssdb, meta, ip.c_str(), port, is_mirror); if(!id.empty()){ slave->set_id(id); } slave->auth = c->get_str("auth"); // 开始slave之后,将在新的线程重接受master的操作日志并同步到当前slave数据库中 slave->start(); slaves.push_back(slave); } } } // load kv_range int ret = this->get_kv_range(&this->kv_range_s, &this->kv_range_e); if(ret == -1){ log_fatal("load key_range failed!"); exit(1); } log_info("key_range.kv: \"%s\", \"%s\"", str_escape(this->kv_range_s).c_str(), str_escape(this->kv_range_e).c_str() ); } SSDBServer::~SSDBServer(){ std::vector<Slave *>::iterator it; // 销毁所有的slave for(it = slaves.begin(); it != slaves.end(); it++){ Slave *slave = *it; slave->stop(); delete slave; } delete backend_dump; delete backend_sync; delete expiration; delete cluster; log_debug("SSDBServer finalized"); } int SSDBServer::set_kv_range(const std::string &start, const std::string &end){ if(meta->hset("key_range", "kv_s", start) == -1){ return -1; } if(meta->hset("key_range", "kv_e", end) == -1){ return -1; } kv_range_s = start; kv_range_e = end; return 0; } int SSDBServer::get_kv_range(std::string *start, std::string *end){ if(meta->hget("key_range", "kv_s", start) == -1){ return -1; } if(meta->hget("key_range", "kv_e", end) == -1){ return -1; } return 0; } bool SSDBServer::in_kv_range(const Bytes &key){ if((this->kv_range_s.size() && this->kv_range_s >= key) || (this->kv_range_e.size() && this->kv_range_e < key)) { return false; } return true; } bool SSDBServer::in_kv_range(const std::string &key){ if((this->kv_range_s.size() && this->kv_range_s >= key) || (this->kv_range_e.size() && this->kv_range_e < key)) { return false; } return true; } /*********************/ int proc_clear_binlog(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; serv->ssdb->binlogs->flush(); resp->push_back("ok"); return 0; } int proc_dump(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; serv->backend_dump->proc(link); return PROC_BACKEND; } int proc_sync140(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; serv->backend_sync->proc(link); return PROC_BACKEND; } int proc_compact(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; serv->ssdb->compact(); resp->push_back("ok"); return 0; } // ignore_key_range的处理函数。这个函数会给客户端连接设置一个属性,在哪里用到还不知道 int proc_ignore_key_range(NetworkServer *net, Link *link, const Request &req, Response *resp){ link->ignore_key_range = true; resp->push_back("ok"); return 0; } // get kv_range, hash_range, zset_range, list_range int proc_get_key_range(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; std::string s, e; int ret = serv->get_kv_range(&s, &e); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); resp->push_back(s); resp->push_back(e); // TODO: hash_range, zset_range, list_range } return 0; } int proc_get_kv_range(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; std::string s, e; int ret = serv->get_kv_range(&s, &e); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); resp->push_back(s); resp->push_back(e); } return 0; } int proc_set_kv_range(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; if(req.size() != 3){ resp->push_back("client_error"); }else{ serv->set_kv_range(req[1].String(), req[2].String()); resp->push_back("ok"); } return 0; } int proc_dbsize(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; uint64_t size = serv->ssdb->size(); resp->push_back("ok"); resp->push_back(str(size)); return 0; } int proc_version(NetworkServer *net, Link *link, const Request &req, Response *resp){ resp->push_back("ok"); resp->push_back(SSDB_VERSION); return 0; } int proc_info(NetworkServer *net, Link *link, const Request &req, Response *resp){ SSDBServer *serv = (SSDBServer *)net->data; resp->push_back("ok"); resp->push_back("ssdb-server"); resp->push_back("version"); resp->push_back(SSDB_VERSION); { resp->push_back("links"); resp->add(net->link_count); } { int64_t calls = 0; proc_map_t::iterator it; for(it=net->proc_map.begin(); it!=net->proc_map.end(); it++){ Command *cmd = it->second; calls += cmd->calls; } resp->push_back("total_calls"); resp->add(calls); } { uint64_t size = serv->ssdb->size(); resp->push_back("dbsize"); resp->push_back(str(size)); } { std::string s = serv->ssdb->binlogs->stats(); resp->push_back("binlogs"); resp->push_back(s); } { std::vector<std::string> syncs = serv->backend_sync->stats(); std::vector<std::string>::iterator it; for(it = syncs.begin(); it != syncs.end(); it++){ std::string s = *it; resp->push_back("replication"); resp->push_back(s); } } { std::vector<Slave *>::iterator it; for(it = serv->slaves.begin(); it != serv->slaves.end(); it++){ Slave *slave = *it; std::string s = slave->stats(); resp->push_back("replication"); resp->push_back(s); } } { std::string val; std::string s, e; serv->get_kv_range(&s, &e); char buf[512]; { snprintf(buf, sizeof(buf), " kv : \"%s\" - \"%s\"", str_escape(s).c_str(), str_escape(e).c_str() ); val.append(buf); } { snprintf(buf, sizeof(buf), "\n hash: \"\" - \"\""); val.append(buf); } { snprintf(buf, sizeof(buf), "\n zset: \"\" - \"\""); val.append(buf); } { snprintf(buf, sizeof(buf), "\n list: \"\" - \"\""); val.append(buf); } resp->push_back("serv_key_range"); resp->push_back(val); } if(req.size() == 1 || req[1] == "range"){ std::string val; std::vector<std::string> tmp; int ret = serv->ssdb->key_range(&tmp); if(ret == 0){ char buf[512]; snprintf(buf, sizeof(buf), " kv : \"%s\" - \"%s\"", hexmem(tmp[0].data(), tmp[0].size()).c_str(), hexmem(tmp[1].data(), tmp[1].size()).c_str() ); val.append(buf); snprintf(buf, sizeof(buf), "\n hash: \"%s\" - \"%s\"", hexmem(tmp[2].data(), tmp[2].size()).c_str(), hexmem(tmp[3].data(), tmp[3].size()).c_str() ); val.append(buf); snprintf(buf, sizeof(buf), "\n zset: \"%s\" - \"%s\"", hexmem(tmp[4].data(), tmp[4].size()).c_str(), hexmem(tmp[5].data(), tmp[5].size()).c_str() ); val.append(buf); snprintf(buf, sizeof(buf), "\n list: \"%s\" - \"%s\"", hexmem(tmp[6].data(), tmp[6].size()).c_str(), hexmem(tmp[7].data(), tmp[7].size()).c_str() ); val.append(buf); } resp->push_back("data_key_range"); resp->push_back(val); } if(req.size() == 1 || req[1] == "leveldb"){ std::vector<std::string> tmp = serv->ssdb->info(); for(int i=0; i<(int)tmp.size(); i++){ std::string block = tmp[i]; resp->push_back(block); } } if(req.size() > 1 && req[1] == "cmd"){ proc_map_t::iterator it; for(it=net->proc_map.begin(); it!=net->proc_map.end(); it++){ Command *cmd = it->second; resp->push_back("cmd." + cmd->name); char buf[128]; snprintf(buf, sizeof(buf), "calls: %" PRIu64 "\ttime_wait: %.0f\ttime_proc: %.0f", cmd->calls, cmd->time_wait, cmd->time_proc); resp->push_back(buf); } } return 0; }
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2015 Intel Corporation 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 Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; gf_4vect_dot_prod_avx(len, vec, *g_tbls, **buffs, **dests); ;;; %include "reg_sizes.asm" %ifidn __OUTPUT_FORMAT__, elf64 %define arg0 rdi %define arg1 rsi %define arg2 rdx %define arg3 rcx %define arg4 r8 %define arg5 r9 %define tmp r11 %define tmp2 r10 %define tmp3 r13 ; must be saved and restored %define tmp4 r12 ; must be saved and restored %define tmp5 r14 ; must be saved and restored %define tmp6 r15 ; must be saved and restored %define return rax %macro SLDR 2 %endmacro %define SSTR SLDR %define PS 8 %define LOG_PS 3 %define func(x) x: %macro FUNC_SAVE 0 push r12 push r13 push r14 push r15 %endmacro %macro FUNC_RESTORE 0 pop r15 pop r14 pop r13 pop r12 %endmacro %endif %ifidn __OUTPUT_FORMAT__, win64 %define arg0 rcx %define arg1 rdx %define arg2 r8 %define arg3 r9 %define arg4 r12 ; must be saved, loaded and restored %define arg5 r15 ; must be saved and restored %define tmp r11 %define tmp2 r10 %define tmp3 r13 ; must be saved and restored %define tmp4 r14 ; must be saved and restored %define tmp5 rdi ; must be saved and restored %define tmp6 rsi ; must be saved and restored %define return rax %macro SLDR 2 %endmacro %define SSTR SLDR %define PS 8 %define LOG_PS 3 %define stack_size 9*16 + 7*8 ; must be an odd multiple of 8 %define arg(x) [rsp + stack_size + PS + PS*x] %define func(x) proc_frame x %macro FUNC_SAVE 0 alloc_stack stack_size save_xmm128 xmm6, 0*16 save_xmm128 xmm7, 1*16 save_xmm128 xmm8, 2*16 save_xmm128 xmm9, 3*16 save_xmm128 xmm10, 4*16 save_xmm128 xmm11, 5*16 save_xmm128 xmm12, 6*16 save_xmm128 xmm13, 7*16 save_xmm128 xmm14, 8*16 save_reg r12, 9*16 + 0*8 save_reg r13, 9*16 + 1*8 save_reg r14, 9*16 + 2*8 save_reg r15, 9*16 + 3*8 save_reg rdi, 9*16 + 4*8 save_reg rsi, 9*16 + 5*8 end_prolog mov arg4, arg(4) %endmacro %macro FUNC_RESTORE 0 vmovdqa xmm6, [rsp + 0*16] vmovdqa xmm7, [rsp + 1*16] vmovdqa xmm8, [rsp + 2*16] vmovdqa xmm9, [rsp + 3*16] vmovdqa xmm10, [rsp + 4*16] vmovdqa xmm11, [rsp + 5*16] vmovdqa xmm12, [rsp + 6*16] vmovdqa xmm13, [rsp + 7*16] vmovdqa xmm14, [rsp + 8*16] mov r12, [rsp + 9*16 + 0*8] mov r13, [rsp + 9*16 + 1*8] mov r14, [rsp + 9*16 + 2*8] mov r15, [rsp + 9*16 + 3*8] mov rdi, [rsp + 9*16 + 4*8] mov rsi, [rsp + 9*16 + 5*8] add rsp, stack_size %endmacro %endif %ifidn __OUTPUT_FORMAT__, elf32 ;;;================== High Address; ;;; arg4 ;;; arg3 ;;; arg2 ;;; arg1 ;;; arg0 ;;; return ;;;<================= esp of caller ;;; ebp ;;;<================= ebp = esp ;;; var0 ;;; var1 ;;; var2 ;;; var3 ;;; esi ;;; edi ;;; ebx ;;;<================= esp of callee ;;; ;;;================== Low Address; %define PS 4 %define LOG_PS 2 %define func(x) x: %define arg(x) [ebp + PS*2 + PS*x] %define var(x) [ebp - PS - PS*x] %define trans ecx %define trans2 esi %define arg0 trans ;trans and trans2 are for the variables in stack %define arg0_m arg(0) %define arg1 ebx %define arg2 arg2_m %define arg2_m arg(2) %define arg3 trans %define arg3_m arg(3) %define arg4 trans %define arg4_m arg(4) %define arg5 trans2 %define tmp edx %define tmp2 edi %define tmp3 trans2 %define tmp3_m var(0) %define tmp4 trans2 %define tmp4_m var(1) %define tmp5 trans2 %define tmp5_m var(2) %define tmp6 trans2 %define tmp6_m var(3) %define return eax %macro SLDR 2 ;stack load/restore mov %1, %2 %endmacro %define SSTR SLDR %macro FUNC_SAVE 0 push ebp mov ebp, esp sub esp, PS*4 ;4 local variables push esi push edi push ebx mov arg1, arg(1) %endmacro %macro FUNC_RESTORE 0 pop ebx pop edi pop esi add esp, PS*4 ;4 local variables pop ebp %endmacro %endif ; output formats %define len arg0 %define vec arg1 %define mul_array arg2 %define src arg3 %define dest1 arg4 %define ptr arg5 %define vec_i tmp2 %define dest2 tmp3 %define dest3 tmp4 %define dest4 tmp5 %define vskip3 tmp6 %define pos return %ifidn PS,4 ;32-bit code %define len_m arg0_m %define src_m arg3_m %define dest1_m arg4_m %define dest2_m tmp3_m %define dest3_m tmp4_m %define dest4_m tmp5_m %define vskip3_m tmp6_m %endif %ifndef EC_ALIGNED_ADDR ;;; Use Un-aligned load/store %define XLDR vmovdqu %define XSTR vmovdqu %else ;;; Use Non-temporal load/stor %ifdef NO_NT_LDST %define XLDR vmovdqa %define XSTR vmovdqa %else %define XLDR vmovntdqa %define XSTR vmovntdq %endif %endif %ifidn PS,8 ; 64-bit code default rel [bits 64] %endif section .text %ifidn PS,8 ;64-bit code %define xmask0f xmm14 %define xgft1_lo xmm13 %define xgft1_hi xmm12 %define xgft2_lo xmm11 %define xgft2_hi xmm10 %define xgft3_lo xmm9 %define xgft3_hi xmm8 %define xgft4_lo xmm7 %define xgft4_hi xmm6 %define x0 xmm0 %define xtmpa xmm1 %define xp1 xmm2 %define xp2 xmm3 %define xp3 xmm4 %define xp4 xmm5 %else %define xmm_trans xmm7 ;reuse xmask0f and xgft1_lo %define xmask0f xmm_trans %define xgft1_lo xmm_trans %define xgft1_hi xmm6 %define xgft2_lo xgft1_lo %define xgft2_hi xgft1_hi %define xgft3_lo xgft1_lo %define xgft3_hi xgft1_hi %define xgft4_lo xgft1_lo %define xgft4_hi xgft1_hi %define x0 xmm0 %define xtmpa xmm1 %define xp1 xmm2 %define xp2 xmm3 %define xp3 xmm4 %define xp4 xmm5 %endif align 16 global gf_4vect_dot_prod_avx:function func(gf_4vect_dot_prod_avx) FUNC_SAVE SLDR len, len_m sub len, 16 SSTR len_m, len jl .return_fail xor pos, pos vmovdqa xmask0f, [mask0f] ;Load mask of lower nibble in each byte mov vskip3, vec imul vskip3, 96 SSTR vskip3_m, vskip3 sal vec, LOG_PS ;vec *= PS. Make vec_i count by PS SLDR dest1, dest1_m mov dest2, [dest1+PS] SSTR dest2_m, dest2 mov dest3, [dest1+2*PS] SSTR dest3_m, dest3 mov dest4, [dest1+3*PS] SSTR dest4_m, dest4 mov dest1, [dest1] SSTR dest1_m, dest1 .loop16: vpxor xp1, xp1 vpxor xp2, xp2 vpxor xp3, xp3 vpxor xp4, xp4 mov tmp, mul_array xor vec_i, vec_i .next_vect: SLDR src, src_m mov ptr, [src+vec_i] %ifidn PS,8 ;64-bit code vmovdqu xgft1_lo, [tmp] ;Load array Ax{00}, Ax{01}, ..., Ax{0f} vmovdqu xgft1_hi, [tmp+16] ; " Ax{00}, Ax{10}, ..., Ax{f0} vmovdqu xgft2_lo, [tmp+vec*(32/PS)] ;Load array Bx{00}, Bx{01}, ..., Bx{0f} vmovdqu xgft2_hi, [tmp+vec*(32/PS)+16] ; " Bx{00}, Bx{10}, ..., Bx{f0} vmovdqu xgft3_lo, [tmp+vec*(64/PS)] ;Load array Cx{00}, Cx{01}, ..., Cx{0f} vmovdqu xgft3_hi, [tmp+vec*(64/PS)+16] ; " Cx{00}, Cx{10}, ..., Cx{f0} vmovdqu xgft4_lo, [tmp+vskip3] ;Load array Dx{00}, Dx{01}, ..., Dx{0f} vmovdqu xgft4_hi, [tmp+vskip3+16] ; " Dx{00}, Dx{10}, ..., Dx{f0} XLDR x0, [ptr+pos] ;Get next source vector add tmp, 32 add vec_i, PS vpand xtmpa, x0, xmask0f ;Mask low src nibble in bits 4-0 vpsraw x0, x0, 4 ;Shift to put high nibble into bits 4-0 vpand x0, x0, xmask0f ;Mask high src nibble in bits 4-0 %else ;32-bit code XLDR x0, [ptr+pos] ;Get next source vector vmovdqa xmask0f, [mask0f] ;Load mask of lower nibble in each byte vpand xtmpa, x0, xmask0f ;Mask low src nibble in bits 4-0 vpsraw x0, x0, 4 ;Shift to put high nibble into bits 4-0 vpand x0, x0, xmask0f ;Mask high src nibble in bits 4-0 vmovdqu xgft1_lo, [tmp] ;Load array Ax{00}, Ax{01}, ..., Ax{0f} vmovdqu xgft1_hi, [tmp+16] ; " Ax{00}, Ax{10}, ..., Ax{f0} %endif vpshufb xgft1_hi, x0 ;Lookup mul table of high nibble vpshufb xgft1_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft1_hi, xgft1_lo ;GF add high and low partials vpxor xp1, xgft1_hi ;xp1 += partial %ifidn PS,4 ;32-bit code vmovdqu xgft2_lo, [tmp+vec*(32/PS)] ;Load array Bx{00}, Bx{01}, ..., Bx{0f} vmovdqu xgft2_hi, [tmp+vec*(32/PS)+16] ; " Bx{00}, Bx{10}, ..., Bx{f0} %endif vpshufb xgft2_hi, x0 ;Lookup mul table of high nibble vpshufb xgft2_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft2_hi, xgft2_lo ;GF add high and low partials vpxor xp2, xgft2_hi ;xp2 += partial %ifidn PS,4 ;32-bit code sal vec, 1 vmovdqu xgft3_lo, [tmp+vec*(32/PS)] ;Load array Cx{00}, Cx{01}, ..., Cx{0f} vmovdqu xgft3_hi, [tmp+vec*(32/PS)+16] ; " Cx{00}, Cx{10}, ..., Cx{f0} sar vec, 1 %endif vpshufb xgft3_hi, x0 ;Lookup mul table of high nibble vpshufb xgft3_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft3_hi, xgft3_lo ;GF add high and low partials vpxor xp3, xgft3_hi ;xp3 += partial %ifidn PS,4 ;32-bit code SLDR vskip3, vskip3_m vmovdqu xgft4_lo, [tmp+vskip3] ;Load array Dx{00}, Dx{01}, ..., Dx{0f} vmovdqu xgft4_hi, [tmp+vskip3+16] ; " Dx{00}, Dx{10}, ..., Dx{f0} add tmp, 32 add vec_i, PS %endif vpshufb xgft4_hi, x0 ;Lookup mul table of high nibble vpshufb xgft4_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft4_hi, xgft4_lo ;GF add high and low partials vpxor xp4, xgft4_hi ;xp4 += partial cmp vec_i, vec jl .next_vect SLDR dest1, dest1_m SLDR dest2, dest2_m XSTR [dest1+pos], xp1 XSTR [dest2+pos], xp2 SLDR dest3, dest3_m XSTR [dest3+pos], xp3 SLDR dest4, dest4_m XSTR [dest4+pos], xp4 SLDR len, len_m add pos, 16 ;Loop on 16 bytes at a time cmp pos, len jle .loop16 lea tmp, [len + 16] cmp pos, tmp je .return_pass ;; Tail len mov pos, len ;Overlapped offset length-16 jmp .loop16 ;Do one more overlap pass .return_pass: mov return, 0 FUNC_RESTORE ret .return_fail: mov return, 1 FUNC_RESTORE ret endproc_frame section .data align 16 mask0f: ddq 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f ;;; func core, ver, snum slversion gf_4vect_dot_prod_avx, 02, 05, 0193
; A245624: Sequence of distinct least positive numbers such that the average of the first n terms is a cube. ; 1,15,8,84,27,249,64,552,125,1035,216,1740,343,2709,512,3984,729,5607,1000,7620,1331,10065,1728,12984,2197,16419,2744,20412,3375,25005,4096,30240,4913,36159,5832,42804,6859,50217,8000,58440,9261,67515,10648,77484,12167,88389,13824,100272,15625,113175,17576,127140,19683,142209,21952,158424,24389,175827,27000,194460,29791,214365,32768,235584,35937,258159,39304,282132,42875,307545,46656,334440,50653,362859,54872,392844,59319,424437,64000,457680,68921,492615,74088,529284,79507,567729,85184,607992,91125,650115,97336,694140,103823,740109,110592,788064,117649,838047,125000,890100,132651,944265,140608,1000584,148877,1059099,157464,1119852,166375,1182885,175616,1248240,185193,1315959,195112,1386084,205379,1458657,216000,1533720,226981,1611315,238328,1691484,250047,1774269,262144,1859712,274625,1947855,287496,2038740,300763,2132409,314432,2228904,328509,2328267,343000,2430540,357911,2535765,373248,2643984,389017,2755239,405224,2869572,421875,2987025,438976,3107640,456533,3231459,474552,3358524,493039,3488877,512000,3622560,531441,3759615,551368,3900084,571787,4044009,592704,4191432,614125,4342395,636056,4496940,658503,4655109,681472,4816944,704969,4982487,729000,5151780,753571,5324865,778688,5501784,804357,5682579,830584,5867292,857375,6055965,884736,6248640,912673,6445359,941192,6646164,970299,6851097,1000000,7060200,1030301,7273515,1061208,7491084,1092727,7712949,1124864,7939152,1157625,8169735,1191016,8404740,1225043,8644209,1259712,8888184,1295029,9136707,1331000,9389820,1367631,9647565,1404928,9909984,1442897,10177119,1481544,10449012,1520875,10725705,1560896,11007240,1601613,11293659,1643032,11585004,1685159,11881317,1728000,12182640,1771561,12489015,1815848,12800484,1860867,13117089,1906624,13438872,1953125,13765875 mov $3,2 mov $7,$0 lpb $3 mov $0,$7 sub $3,1 add $0,$3 sub $0,1 mov $4,3 add $4,$0 mov $5,0 add $5,$0 add $0,1 mov $2,$3 div $4,2 pow $4,3 add $5,$0 add $5,1 mul $5,$4 mov $6,$5 lpb $2 mov $1,$6 sub $2,1 lpe lpe lpb $7 sub $1,$6 mov $7,0 lpe sub $1,2 div $1,2 add $1,1
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 6, 0x90 Lpoly: .quad 0xffffffff, 0xffffffff00000000, 0xfffffffffffffffe .quad 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff LOne: .long 1,1,1,1,1,1,1,1 LTwo: .long 2,2,2,2,2,2,2,2 LThree: .long 3,3,3,3,3,3,3,3 .p2align 6, 0x90 .globl p384r1_mul_by_2 .type p384r1_mul_by_2, @function p384r1_mul_by_2: push %r12 xor %r11, %r11 movq (%rsi), %rax movq (8)(%rsi), %rcx movq (16)(%rsi), %rdx movq (24)(%rsi), %r8 movq (32)(%rsi), %r9 movq (40)(%rsi), %r10 shld $(1), %r10, %r11 shld $(1), %r9, %r10 movq %r10, (40)(%rdi) shld $(1), %r8, %r9 movq %r9, (32)(%rdi) shld $(1), %rdx, %r8 movq %r8, (24)(%rdi) shld $(1), %rcx, %rdx movq %rdx, (16)(%rdi) shld $(1), %rax, %rcx movq %rcx, (8)(%rdi) shl $(1), %rax movq %rax, (%rdi) subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rcx sbbq Lpoly+16(%rip), %rdx sbbq Lpoly+24(%rip), %r8 sbbq Lpoly+32(%rip), %r9 sbbq Lpoly+40(%rip), %r10 sbb $(0), %r11 movq (%rdi), %r12 cmovne %r12, %rax movq (8)(%rdi), %r12 cmovne %r12, %rcx movq (16)(%rdi), %r12 cmovne %r12, %rdx movq (24)(%rdi), %r12 cmovne %r12, %r8 movq (32)(%rdi), %r12 cmovne %r12, %r9 movq (40)(%rdi), %r12 cmovne %r12, %r10 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rdx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) vzeroupper pop %r12 ret .Lfe1: .size p384r1_mul_by_2, .Lfe1-(p384r1_mul_by_2) .p2align 6, 0x90 .globl p384r1_div_by_2 .type p384r1_div_by_2, @function p384r1_div_by_2: push %r12 movq (%rsi), %rax movq (8)(%rsi), %rcx movq (16)(%rsi), %rdx movq (24)(%rsi), %r8 movq (32)(%rsi), %r9 movq (40)(%rsi), %r10 xor %r12, %r12 xor %r11, %r11 addq Lpoly+0(%rip), %rax adcq Lpoly+8(%rip), %rcx adcq Lpoly+16(%rip), %rdx adcq Lpoly+24(%rip), %r8 adcq Lpoly+32(%rip), %r9 adcq Lpoly+40(%rip), %r10 adc $(0), %r11 test $(1), %rax cmovne %r12, %r11 movq (%rsi), %r12 cmovne %r12, %rax movq (8)(%rsi), %r12 cmovne %r12, %rcx movq (16)(%rsi), %r12 cmovne %r12, %rdx movq (24)(%rsi), %r12 cmovne %r12, %r8 movq (32)(%rsi), %r12 cmovne %r12, %r9 movq (40)(%rsi), %r12 cmovne %r12, %r10 shrd $(1), %rcx, %rax shrd $(1), %rdx, %rcx shrd $(1), %r8, %rdx shrd $(1), %r9, %r8 shrd $(1), %r10, %r9 shrd $(1), %r11, %r10 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rdx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) vzeroupper pop %r12 ret .Lfe2: .size p384r1_div_by_2, .Lfe2-(p384r1_div_by_2) .p2align 6, 0x90 .globl p384r1_mul_by_3 .type p384r1_mul_by_3, @function p384r1_mul_by_3: push %r12 push %r13 sub $(56), %rsp xor %r11, %r11 movq (%rsi), %rax movq (8)(%rsi), %rcx movq (16)(%rsi), %rdx movq (24)(%rsi), %r8 movq (32)(%rsi), %r9 movq (40)(%rsi), %r10 shld $(1), %r10, %r11 shld $(1), %r9, %r10 movq %r10, (40)(%rsp) shld $(1), %r8, %r9 movq %r9, (32)(%rsp) shld $(1), %rdx, %r8 movq %r8, (24)(%rsp) shld $(1), %rcx, %rdx movq %rdx, (16)(%rsp) shld $(1), %rax, %rcx movq %rcx, (8)(%rsp) shl $(1), %rax movq %rax, (%rsp) subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rcx sbbq Lpoly+16(%rip), %rdx sbbq Lpoly+24(%rip), %r8 sbbq Lpoly+32(%rip), %r9 sbbq Lpoly+40(%rip), %r10 sbb $(0), %r11 movq (%rsp), %r12 cmovb %r12, %rax movq (8)(%rsp), %r12 cmovb %r12, %rcx movq (16)(%rsp), %r12 cmovb %r12, %rdx movq (24)(%rsp), %r12 cmovb %r12, %r8 movq (32)(%rsp), %r12 cmovb %r12, %r9 movq (40)(%rsp), %r12 cmovb %r12, %r10 xor %r11, %r11 addq (%rsi), %rax movq %rax, (%rsp) adcq (8)(%rsi), %rcx movq %rcx, (8)(%rsp) adcq (16)(%rsi), %rdx movq %rdx, (16)(%rsp) adcq (24)(%rsi), %r8 movq %r8, (24)(%rsp) adcq (32)(%rsi), %r9 movq %r9, (32)(%rsp) adcq (40)(%rsi), %r10 movq %r10, (40)(%rsp) adc $(0), %r11 subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rcx sbbq Lpoly+16(%rip), %rdx sbbq Lpoly+24(%rip), %r8 sbbq Lpoly+32(%rip), %r9 sbbq Lpoly+40(%rip), %r10 sbb $(0), %r11 movq (%rsp), %r12 cmovb %r12, %rax movq (8)(%rsp), %r12 cmovb %r12, %rcx movq (16)(%rsp), %r12 cmovb %r12, %rdx movq (24)(%rsp), %r12 cmovb %r12, %r8 movq (32)(%rsp), %r12 cmovb %r12, %r9 movq (40)(%rsp), %r12 cmovb %r12, %r10 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rdx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) add $(56), %rsp vzeroupper pop %r13 pop %r12 ret .Lfe3: .size p384r1_mul_by_3, .Lfe3-(p384r1_mul_by_3) .p2align 6, 0x90 .globl p384r1_add .type p384r1_add, @function p384r1_add: push %rbx push %r12 xor %r11, %r11 movq (%rsi), %rax movq (8)(%rsi), %rcx movq (16)(%rsi), %rbx movq (24)(%rsi), %r8 movq (32)(%rsi), %r9 movq (40)(%rsi), %r10 addq (%rdx), %rax adcq (8)(%rdx), %rcx adcq (16)(%rdx), %rbx adcq (24)(%rdx), %r8 adcq (32)(%rdx), %r9 adcq (40)(%rdx), %r10 adc $(0), %r11 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rbx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) subq Lpoly+0(%rip), %rax sbbq Lpoly+8(%rip), %rcx sbbq Lpoly+16(%rip), %rbx sbbq Lpoly+24(%rip), %r8 sbbq Lpoly+32(%rip), %r9 sbbq Lpoly+40(%rip), %r10 sbb $(0), %r11 movq (%rdi), %r12 cmovb %r12, %rax movq (8)(%rdi), %r12 cmovb %r12, %rcx movq (16)(%rdi), %r12 cmovb %r12, %rbx movq (24)(%rdi), %r12 cmovb %r12, %r8 movq (32)(%rdi), %r12 cmovb %r12, %r9 movq (40)(%rdi), %r12 cmovb %r12, %r10 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rbx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) vzeroupper pop %r12 pop %rbx ret .Lfe4: .size p384r1_add, .Lfe4-(p384r1_add) .p2align 6, 0x90 .globl p384r1_sub .type p384r1_sub, @function p384r1_sub: push %rbx push %r12 xor %r11, %r11 movq (%rsi), %rax movq (8)(%rsi), %rcx movq (16)(%rsi), %rbx movq (24)(%rsi), %r8 movq (32)(%rsi), %r9 movq (40)(%rsi), %r10 subq (%rdx), %rax sbbq (8)(%rdx), %rcx sbbq (16)(%rdx), %rbx sbbq (24)(%rdx), %r8 sbbq (32)(%rdx), %r9 sbbq (40)(%rdx), %r10 sbb $(0), %r11 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rbx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) addq Lpoly+0(%rip), %rax adcq Lpoly+8(%rip), %rcx adcq Lpoly+16(%rip), %rbx adcq Lpoly+24(%rip), %r8 adcq Lpoly+32(%rip), %r9 adcq Lpoly+40(%rip), %r10 test %r11, %r11 movq (%rdi), %r12 cmove %r12, %rax movq (8)(%rdi), %r12 cmove %r12, %rcx movq (16)(%rdi), %r12 cmove %r12, %rbx movq (24)(%rdi), %r12 cmove %r12, %r8 movq (32)(%rdi), %r12 cmove %r12, %r9 movq (40)(%rdi), %r12 cmove %r12, %r10 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rbx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) vzeroupper pop %r12 pop %rbx ret .Lfe5: .size p384r1_sub, .Lfe5-(p384r1_sub) .p2align 6, 0x90 .globl p384r1_neg .type p384r1_neg, @function p384r1_neg: push %r12 xor %r11, %r11 xor %rax, %rax xor %rcx, %rcx xor %rdx, %rdx xor %r8, %r8 xor %r9, %r9 xor %r10, %r10 subq (%rsi), %rax sbbq (8)(%rsi), %rcx sbbq (16)(%rsi), %rdx sbbq (24)(%rsi), %r8 sbbq (32)(%rsi), %r9 sbbq (40)(%rsi), %r10 sbb $(0), %r11 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rdx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) addq Lpoly+0(%rip), %rax adcq Lpoly+8(%rip), %rcx adcq Lpoly+16(%rip), %rdx adcq Lpoly+24(%rip), %r8 adcq Lpoly+32(%rip), %r9 adcq Lpoly+40(%rip), %r10 test %r11, %r11 movq (%rdi), %r12 cmove %r12, %rax movq (8)(%rdi), %r12 cmove %r12, %rcx movq (16)(%rdi), %r12 cmove %r12, %rdx movq (24)(%rdi), %r12 cmove %r12, %r8 movq (32)(%rdi), %r12 cmove %r12, %r9 movq (40)(%rdi), %r12 cmove %r12, %r10 movq %rax, (%rdi) movq %rcx, (8)(%rdi) movq %rdx, (16)(%rdi) movq %r8, (24)(%rdi) movq %r9, (32)(%rdi) movq %r10, (40)(%rdi) vzeroupper pop %r12 ret .Lfe6: .size p384r1_neg, .Lfe6-(p384r1_neg) .p2align 6, 0x90 .globl p384r1_mred .type p384r1_mred, @function p384r1_mred: push %r12 push %r13 push %r14 push %r15 xor %rdx, %rdx movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 movq (32)(%rsi), %r12 movq (40)(%rsi), %r13 movq (48)(%rsi), %r14 mov %r8, %rax shl $(32), %rax add %r8, %rax mov %rax, %r15 shr $(32), %r15 push %r15 mov %rax, %rcx shl $(32), %rcx push %rcx sub %rax, %rcx sbb $(0), %r15 add %rcx, %r8 pop %rcx adc %r15, %r9 pop %r15 sbb $(0), %r15 sub %rcx, %r9 mov $(0), %rcx sbb %r15, %r10 adc $(0), %rcx sub %rax, %r10 adc $(0), %rcx sub %rcx, %r11 sbb $(0), %r12 sbb $(0), %r13 sbb $(0), %rax add %rdx, %rax mov $(0), %rdx adc $(0), %rdx add %rax, %r14 adc $(0), %rdx movq (56)(%rsi), %r8 mov %r9, %rax shl $(32), %rax add %r9, %rax mov %rax, %r15 shr $(32), %r15 push %r15 mov %rax, %rcx shl $(32), %rcx push %rcx sub %rax, %rcx sbb $(0), %r15 add %rcx, %r9 pop %rcx adc %r15, %r10 pop %r15 sbb $(0), %r15 sub %rcx, %r10 mov $(0), %rcx sbb %r15, %r11 adc $(0), %rcx sub %rax, %r11 adc $(0), %rcx sub %rcx, %r12 sbb $(0), %r13 sbb $(0), %r14 sbb $(0), %rax add %rdx, %rax mov $(0), %rdx adc $(0), %rdx add %rax, %r8 adc $(0), %rdx movq (64)(%rsi), %r9 mov %r10, %rax shl $(32), %rax add %r10, %rax mov %rax, %r15 shr $(32), %r15 push %r15 mov %rax, %rcx shl $(32), %rcx push %rcx sub %rax, %rcx sbb $(0), %r15 add %rcx, %r10 pop %rcx adc %r15, %r11 pop %r15 sbb $(0), %r15 sub %rcx, %r11 mov $(0), %rcx sbb %r15, %r12 adc $(0), %rcx sub %rax, %r12 adc $(0), %rcx sub %rcx, %r13 sbb $(0), %r14 sbb $(0), %r8 sbb $(0), %rax add %rdx, %rax mov $(0), %rdx adc $(0), %rdx add %rax, %r9 adc $(0), %rdx movq (72)(%rsi), %r10 mov %r11, %rax shl $(32), %rax add %r11, %rax mov %rax, %r15 shr $(32), %r15 push %r15 mov %rax, %rcx shl $(32), %rcx push %rcx sub %rax, %rcx sbb $(0), %r15 add %rcx, %r11 pop %rcx adc %r15, %r12 pop %r15 sbb $(0), %r15 sub %rcx, %r12 mov $(0), %rcx sbb %r15, %r13 adc $(0), %rcx sub %rax, %r13 adc $(0), %rcx sub %rcx, %r14 sbb $(0), %r8 sbb $(0), %r9 sbb $(0), %rax add %rdx, %rax mov $(0), %rdx adc $(0), %rdx add %rax, %r10 adc $(0), %rdx movq (80)(%rsi), %r11 mov %r12, %rax shl $(32), %rax add %r12, %rax mov %rax, %r15 shr $(32), %r15 push %r15 mov %rax, %rcx shl $(32), %rcx push %rcx sub %rax, %rcx sbb $(0), %r15 add %rcx, %r12 pop %rcx adc %r15, %r13 pop %r15 sbb $(0), %r15 sub %rcx, %r13 mov $(0), %rcx sbb %r15, %r14 adc $(0), %rcx sub %rax, %r14 adc $(0), %rcx sub %rcx, %r8 sbb $(0), %r9 sbb $(0), %r10 sbb $(0), %rax add %rdx, %rax mov $(0), %rdx adc $(0), %rdx add %rax, %r11 adc $(0), %rdx movq (88)(%rsi), %r12 mov %r13, %rax shl $(32), %rax add %r13, %rax mov %rax, %r15 shr $(32), %r15 push %r15 mov %rax, %rcx shl $(32), %rcx push %rcx sub %rax, %rcx sbb $(0), %r15 add %rcx, %r13 pop %rcx adc %r15, %r14 pop %r15 sbb $(0), %r15 sub %rcx, %r14 mov $(0), %rcx sbb %r15, %r8 adc $(0), %rcx sub %rax, %r8 adc $(0), %rcx sub %rcx, %r9 sbb $(0), %r10 sbb $(0), %r11 sbb $(0), %rax add %rdx, %rax mov $(0), %rdx adc $(0), %rdx add %rax, %r12 adc $(0), %rdx movq %r14, (%rdi) movq %r8, (8)(%rdi) movq %r9, (16)(%rdi) movq %r10, (24)(%rdi) movq %r11, (32)(%rdi) movq %r12, (40)(%rdi) subq Lpoly+0(%rip), %r14 sbbq Lpoly+8(%rip), %r8 sbbq Lpoly+16(%rip), %r9 sbbq Lpoly+24(%rip), %r10 sbbq Lpoly+32(%rip), %r11 sbbq Lpoly+40(%rip), %r12 sbb $(0), %rdx movq (%rdi), %rax cmovne %rax, %r14 movq (8)(%rdi), %rax cmovne %rax, %r8 movq (16)(%rdi), %rax cmovne %rax, %r9 movq (24)(%rdi), %rax cmovne %rax, %r10 movq (32)(%rdi), %rax cmovne %rax, %r11 movq (40)(%rdi), %rax cmovne %rax, %r12 movq %r14, (%rdi) movq %r8, (8)(%rdi) movq %r9, (16)(%rdi) movq %r10, (24)(%rdi) movq %r11, (32)(%rdi) movq %r12, (40)(%rdi) vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 ret .Lfe7: .size p384r1_mred, .Lfe7-(p384r1_mred) .p2align 6, 0x90 .globl p384r1_select_pp_w5 .type p384r1_select_pp_w5, @function p384r1_select_pp_w5: push %r12 push %r13 movdqa LOne(%rip), %xmm10 movd %edx, %xmm9 pshufd $(0), %xmm9, %xmm9 pxor %xmm0, %xmm0 pxor %xmm1, %xmm1 pxor %xmm2, %xmm2 pxor %xmm3, %xmm3 pxor %xmm4, %xmm4 pxor %xmm5, %xmm5 pxor %xmm6, %xmm6 pxor %xmm7, %xmm7 pxor %xmm8, %xmm8 mov $(16), %rcx .Lselect_loopgas_8: movdqa %xmm10, %xmm11 pcmpeqd %xmm9, %xmm11 paddd LOne(%rip), %xmm10 movdqa %xmm11, %xmm12 pand (%rsi), %xmm12 por %xmm12, %xmm0 movdqa %xmm11, %xmm12 pand (16)(%rsi), %xmm12 por %xmm12, %xmm1 movdqa %xmm11, %xmm12 pand (32)(%rsi), %xmm12 por %xmm12, %xmm2 movdqa %xmm11, %xmm12 pand (48)(%rsi), %xmm12 por %xmm12, %xmm3 movdqa %xmm11, %xmm12 pand (64)(%rsi), %xmm12 por %xmm12, %xmm4 movdqa %xmm11, %xmm12 pand (80)(%rsi), %xmm12 por %xmm12, %xmm5 movdqa %xmm11, %xmm12 pand (96)(%rsi), %xmm12 por %xmm12, %xmm6 movdqa %xmm11, %xmm12 pand (112)(%rsi), %xmm12 por %xmm12, %xmm7 movdqa %xmm11, %xmm12 pand (128)(%rsi), %xmm12 por %xmm12, %xmm8 add $(144), %rsi dec %rcx jnz .Lselect_loopgas_8 movdqu %xmm0, (%rdi) movdqu %xmm1, (16)(%rdi) movdqu %xmm2, (32)(%rdi) movdqu %xmm3, (48)(%rdi) movdqu %xmm4, (64)(%rdi) movdqu %xmm5, (80)(%rdi) movdqu %xmm6, (96)(%rdi) movdqu %xmm7, (112)(%rdi) movdqu %xmm8, (128)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe8: .size p384r1_select_pp_w5, .Lfe8-(p384r1_select_pp_w5) .p2align 6, 0x90 .globl p384r1_select_ap_w5 .type p384r1_select_ap_w5, @function p384r1_select_ap_w5: push %r12 push %r13 movdqa LOne(%rip), %xmm13 movd %edx, %xmm12 pshufd $(0), %xmm12, %xmm12 pxor %xmm0, %xmm0 pxor %xmm1, %xmm1 pxor %xmm2, %xmm2 pxor %xmm3, %xmm3 pxor %xmm4, %xmm4 pxor %xmm5, %xmm5 mov $(16), %rcx .Lselect_loopgas_9: movdqa %xmm13, %xmm14 pcmpeqd %xmm12, %xmm14 paddd LOne(%rip), %xmm13 movdqa (%rsi), %xmm6 movdqa (16)(%rsi), %xmm7 movdqa (32)(%rsi), %xmm8 movdqa (48)(%rsi), %xmm9 movdqa (64)(%rsi), %xmm10 movdqa (80)(%rsi), %xmm11 add $(96), %rsi pand %xmm14, %xmm6 pand %xmm14, %xmm7 pand %xmm14, %xmm8 pand %xmm14, %xmm9 pand %xmm14, %xmm10 pand %xmm14, %xmm11 por %xmm6, %xmm0 por %xmm7, %xmm1 por %xmm8, %xmm2 por %xmm9, %xmm3 por %xmm10, %xmm4 por %xmm11, %xmm5 dec %rcx jnz .Lselect_loopgas_9 movdqu %xmm0, (%rdi) movdqu %xmm1, (16)(%rdi) movdqu %xmm2, (32)(%rdi) movdqu %xmm3, (48)(%rdi) movdqu %xmm4, (64)(%rdi) movdqu %xmm5, (80)(%rdi) vzeroupper pop %r13 pop %r12 ret .Lfe9: .size p384r1_select_ap_w5, .Lfe9-(p384r1_select_ap_w5)
// Copyright (c) 2016-2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/json/ #ifndef TAOCPP_JSON_INCLUDE_TRAITS_HPP #define TAOCPP_JSON_INCLUDE_TRAITS_HPP #include <map> #include <string> #include <vector> #include "type.hpp" namespace tao { namespace json { template< template< typename... > class Traits > class basic_value; // note: traits< ... >::assign() is always called with needs_discard(v) == false template< typename T, typename = void > struct traits { static_assert( sizeof( T ) == 0, "no traits specialization found" ); template< typename V, typename U > static void assign( V&, U&& ); }; template<> struct traits< null_t > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, null_t ) noexcept { v.unsafe_assign_null(); } }; template<> struct traits< bool > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const bool b ) noexcept { v.unsafe_assign_bool( b ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, bool& b ) { b = v.get_boolean(); } }; namespace internal { template< template< typename... > class Traits, typename T > void unchecked_extract_number( const basic_value< Traits >& v, T& i ) { switch( v.type() ) { case type::SIGNED: i = v.unsafe_get_signed(); break; case type::UNSIGNED: i = v.unsafe_get_unsigned(); break; case type::DOUBLE: i = v.unsafe_get_double(); break; default: TAOCPP_JSON_THROW_TYPE_ERROR( v.type() ); } } } template<> struct traits< signed char > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const signed char i ) noexcept { v.unsafe_assign_signed( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, signed char& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< unsigned char > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const unsigned char i ) noexcept { v.unsafe_assign_unsigned( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, unsigned char& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< signed short > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const signed short i ) noexcept { v.unsafe_assign_signed( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, signed short& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< unsigned short > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const unsigned short i ) noexcept { v.unsafe_assign_unsigned( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, unsigned short& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< signed int > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const signed int i ) noexcept { v.unsafe_assign_signed( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, signed int& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< unsigned int > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const unsigned int i ) noexcept { v.unsafe_assign_unsigned( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, unsigned int& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< signed long > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const signed long i ) noexcept { v.unsafe_assign_signed( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, signed long& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< unsigned long > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const unsigned long i ) noexcept { v.unsafe_assign_unsigned( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, unsigned long& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< signed long long > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const signed long long i ) noexcept { v.unsafe_assign_signed( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, signed long long& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< unsigned long long > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const unsigned long long i ) noexcept { v.unsafe_assign_unsigned( i ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, unsigned long long& i ) { internal::unchecked_extract_number( v, i ); } }; template<> struct traits< float > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const float f ) { v.unsafe_assign_double( f ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, float& f ) { internal::unchecked_extract_number( v, f ); } }; template<> struct traits< double > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const double d ) { v.unsafe_assign_double( d ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, double& f ) { internal::unchecked_extract_number( v, f ); } }; template<> struct traits< empty_binary_t > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, empty_binary_t ) { v.unsafe_emplace_binary(); } }; template<> struct traits< empty_array_t > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, empty_array_t ) { v.unsafe_emplace_array(); } }; template<> struct traits< empty_object_t > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, empty_object_t ) { v.unsafe_emplace_object(); } }; template<> struct traits< std::string > { template< template< typename... > class Traits, typename T > static void assign( basic_value< Traits >& v, T&& s ) { v.unsafe_emplace_string( std::forward< T >( s ) ); } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, std::string& s ) { s = v.get_string(); } }; template<> struct traits< const std::string& > { template< template< typename... > class Traits > static const std::string& extract( const basic_value< Traits >& v ) { return v.get_string(); } }; template<> struct traits< const char* > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const char* s ) { v.unsafe_emplace_string( s ); } template< template< typename... > class Traits > static const char* extract( const basic_value< Traits >& v ) { return v.get_string().c_str(); } }; template<> struct traits< std::vector< byte > > { template< template< typename... > class Traits, typename T > static void assign( basic_value< Traits >& v, T&& b ) { v.unsafe_emplace_binary( std::forward< T >( b ) ); } }; template< template< typename... > class Traits > struct traits< std::vector< basic_value< Traits > > > { template< typename T > static void assign( basic_value< Traits >& v, T&& a ) { v.unsafe_emplace_array( std::forward< T >( a ) ); } }; template< template< typename... > class Traits > struct traits< std::map< std::string, basic_value< Traits > > > { template< typename T > static void assign( basic_value< Traits >& v, T&& o ) { v.unsafe_emplace_object( std::forward< T >( o ) ); } }; template< template< typename... > class Traits > struct traits< const basic_value< Traits >* > { static void assign( basic_value< Traits >& v, const basic_value< Traits >* p ) noexcept { v.unsafe_assign_pointer( p ); } }; template< template< typename... > class Traits > struct traits< basic_value< Traits >* > { static void assign( basic_value< Traits >& v, const basic_value< Traits >* p ) noexcept { v.unsafe_assign_pointer( p ); } }; template<> struct traits< std::nullptr_t > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, std::nullptr_t ) noexcept { v.unsafe_assign_pointer( nullptr ); } }; template< typename T > struct traits< optional< T > > { template< template< typename... > class Traits > static void assign( basic_value< Traits >& v, const optional< T >& o ) noexcept { if( o ) { v = *o; } else { v = null; } } template< template< typename... > class Traits > static void extract( const basic_value< Traits >& v, optional< T >& o ) { if( v.is_null() ) { o = nullopt; } else { o = v.template as< T >(); } } }; } // namespace json } // namespace tao #endif
<% from pwnlib import shellcraft %> <%page args="filename, flags='O_RDONLY', mode=0"/> <%docstring> Opens a file </%docstring> <% AT_FDCWD=-100 %> ${shellcraft.pushstr(filename)} ${shellcraft.syscall('SYS_openat', AT_FDCWD, 'sp', flags, mode)}
; A213485: Number of (w,x,y) with all terms in {0,...,n} and |w-x|+|x-y|+|y-w| != w+x+y. ; 0,4,20,54,109,191,309,469,674,930,1246,1628,2079,2605,3215,3915,4708,5600,6600,7714,8945,10299,11785,13409,15174,17086,19154,21384,23779,26345,29091,32023,35144,38460,41980,45710,49653,53815,58205 mov $2,$0 lpb $0,1 add $1,$0 sub $0,1 lpe add $0,3 mul $1,$0 div $1,2 mul $1,3 mov $3,$2 mul $3,$2 mul $3,$2 add $1,$3
//------------------------------------------------------------------------------------------------ // Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). // All rights reserved. //------------------------------------------------------------------------------------------------ /******************************************************************************************************************************************************************************************* * LICENSE NOTICE ******************************************************************************************************************************************************************************************** * By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change * this code. ******************************************************************************************************************************************************************************************** * 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at * g.iannello@unicampus.it for further details. * 2. You agree to appropriately cite this work in your related studies and publications. * 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- * ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the * copyright owners, University Campus Bio-Medico, 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;reasonable royalties; or business interruption) however caused and on any theory of liabil- * ity, 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. * 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without * specific prior written permission. ********************************************************************************************************************************************************************************************/ /****************** * CHANGELOG * ******************* * 2015-08-27. Giluio. @ADDED control on coherence between block lenghts and filenames in 'check' method * 2015-07-30. Giluio. @FIXED bug in applyReference system. * 2015-07-30. Giluio. @FIXED bug in extractCoordinates. * 2015-07-22. Giluio. @ADDED support for spase data (see comments below). * 2015-06-12. Giulio @ADDED 'check' method to check completeness and coherence of a volume * 2015-02-26. Giulio. @ADDED implementation of initChannels private method to initialize fields DIM_C and BYTESxCHAN * 2015-01-17. Alessandro. @FIXED missing throw(iom::exception) declaration in loadXML and initFromXML methods. * 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). * 2014-11-06. Giulio. @ADDED saved reference system into XML file * 2014-09-20. Alessandro. @ADDED overwrite_mdata flag to the XML-based constructor. * 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to <TeraStitcher> XML node * 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. * 2014-09-09. Alessandro. @FIXED. Added default reference system if volume is imported from xml. * 2014-09-09. Alessandro. @FIXED both 'init()' and 'initFromXML()' methods to deal with empty stacks. Added call of 'normalize_stacks_attributes()' method. * 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) * 2014-09-02. Alessandro. @FIXED both 'loadBinaryMetadata()' and 'saveBinaryMetadata()' as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. */ /**************************** * Management of sparse data * ***************************** * * If --sparse_data flag is set, in the import step, after reading files names missing blocks are detected * * Each tile is a list of blocks some of which may be empty * empty blocks have a null pointer as file name, but have first index and size correctly set * this structure is binarized into the mdata.bin file * the z_ranges variable store for each tile the intervals corresponding to exisiting blocks * thi information is stored into the xml file * both internal tile structure and z_ranges field are set every time the volume is created */ #ifdef _WIN32 #include "dirent_win.h" #else #include <dirent.h> #endif #include <list> #include <fstream> #include <sstream> #include <set> #include "vmBlockVolume.h" #include "S_config.h" //#include <string> using namespace std; using namespace iom; using namespace vm; // 2014-09-10. Alessandro. @ADDED plugin creation/registration functions to make 'StackedVolume' a volume format plugin. const std::string BlockVolume::id = "TiledXY|3Dseries"; const std::string BlockVolume::creator_id1 = volumemanager::VirtualVolumeFactory::registerPluginCreatorXML(&createFromXML, BlockVolume::id); const std::string BlockVolume::creator_id2 = volumemanager::VirtualVolumeFactory::registerPluginCreatorData(&createFromData, BlockVolume::id); BlockVolume::BlockVolume(const char* _stacks_dir, vm::ref_sys _reference_system, float VXL_1, float VXL_2, float VXL_3, bool overwrite_mdata) throw (iom::exception) : VirtualVolume(_stacks_dir, _reference_system, VXL_1, VXL_2, VXL_3) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::BlockVolume(_stacks_dir=%s, reference_system = {%d,%d,%d}, VXL_1 = %.2f, VXL_2 = %.2f, VXL_3 = %.2f)\n", _stacks_dir,reference_system.first, reference_system.second, reference_system.third, VXL_1, VXL_2, VXL_3); #endif //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved char mdata_filepath[VM_STATIC_STRINGS_SIZE]; sprintf(mdata_filepath, "%s/%s", stacks_dir, vm::BINARY_METADATA_FILENAME.c_str()); if(fileExists(mdata_filepath) && !overwrite_mdata) loadBinaryMetadata(mdata_filepath); else { if(_reference_system.first == vm::axis_invalid || _reference_system.second == vm::axis_invalid || _reference_system.third == vm::axis_invalid || VXL_1 == 0 || VXL_2 == 0 || VXL_3 == 0) throw iom::exception("in BlockVolume::BlockVolume(...): invalid importing parameters"); reference_system = _reference_system; // GI_140501: stores the refrence system to generate the mdata.bin file for the output volumes init(); applyReferenceSystem(reference_system, VXL_1, VXL_2, VXL_3); saveBinaryMetadata(mdata_filepath); } initChannels(); // check all stacks have the same number of slices (@ADDED by Giulio on 2015-07-22) if(!vm::SPARSE_DATA) { for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++) { if(BLOCKS[i][j]->getDEPTH() != N_SLICES) { throw iom::exception(iom::strprintf("in BlockVolume::StackedVolume(): unequal number of slices detected. Stack \"%s\" has %d, stack \"%s\" has %d. " "Please activate the sparse data option if stacks are not complete", BLOCKS[0][0]->getDIR_NAME(), BLOCKS[0][0]->getDEPTH(), BLOCKS[i][j]->getDIR_NAME(), BLOCKS[i][j]->getDEPTH()).c_str()); } } } } BlockVolume::BlockVolume(const char *xml_filepath, bool overwrite_mdata) throw (iom::exception) : VirtualVolume(xml_filepath) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::BlockVolume(xml_filepath=%s)\n", xml_filepath); #endif //extracting <stacks_dir> field from XML TiXmlDocument xml; if(!xml.LoadFile(xml_filepath)) { char errMsg[2000]; sprintf(errMsg,"in BlockVolume::BlockVolume(xml_filepath = \"%s\") : unable to load xml", xml_filepath); throw iom::exception(errMsg); } TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); this->stacks_dir = new char[strlen(pelem->Attribute("value"))+1]; strcpy(this->stacks_dir, pelem->Attribute("value")); //trying to unserialize an already existing metadata file, if it doesn't exist the full initialization procedure is performed and metadata is saved char mdata_filepath[2000]; sprintf(mdata_filepath, "%s/%s", stacks_dir, vm::BINARY_METADATA_FILENAME.c_str()); // 2014-09-20. Alessandro. @ADDED overwrite_mdata flag if(fileExists(mdata_filepath) && !overwrite_mdata) { // load mdata.bin content and xml content, also perform consistency check between mdata.bin and xml content loadBinaryMetadata(mdata_filepath); loadXML(xml_filepath); } else { // load xml content and generate mdata.bin initFromXML(xml_filepath); saveBinaryMetadata(mdata_filepath); } initChannels(); // check all stacks have the same number of slices (@ADDED by Giulio on 2015-07-22) if(!vm::SPARSE_DATA) { for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++) { if(BLOCKS[i][j]->getDEPTH() != N_SLICES) { throw iom::exception(iom::strprintf("in BlockVolume::StackedVolume(): unequal number of slices detected. Stack \"%s\" has %d, stack \"%s\" has %d. " "Please activate the sparse data option if stacks are not complete", BLOCKS[0][0]->getDIR_NAME(), BLOCKS[0][0]->getDEPTH(), BLOCKS[i][j]->getDIR_NAME(), BLOCKS[i][j]->getDEPTH()).c_str()); } } } } BlockVolume::~BlockVolume() { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::~BlockVolume(void)\n"); #endif if(stacks_dir) delete[] stacks_dir; if(BLOCKS) { for(int row=0; row<N_ROWS; row++) { for(int col=0; col<N_COLS; col++) delete BLOCKS[row][col]; delete[] BLOCKS[row]; } delete[] BLOCKS; } } void BlockVolume::init() throw (iom::exception) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::init()\n"); #endif //LOCAL VARIABLES string tmp_path; //string that contains temp paths during computation string tmp; //string that contains temp data during computation string tmp2; //string that contains temp data during computation DIR *cur_dir_lev1; //pointer to DIR, the data structure that represents a DIRECTORY (level 1 of hierarchical structure) DIR *cur_dir_lev2; //pointer to DIR, the data structure that represents a DIRECTORY (level 2 of hierarchical structure) dirent *entry_lev1; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 1) dirent *entry_lev2; //pointer to DIRENT, the data structure that represents a DIRECTORY ENTRY inside a directory (level 2) int i=0,j=0; //for counting of N_ROWS, N_COLS list<Block*> stacks_list; //each stack found in the hierarchy is pushed into this list list<string> entries_lev1; //list of entries of first level of hierarchy list<string>::iterator entry_i; //iterator for list 'entries_lev1' list<string> entries_lev2; //list of entries of second level of hierarchy list<string>::iterator entry_j; //iterator for list 'entries_lev2' char stack_i_j_path[S_STATIC_STRINGS_SIZE]; //obtaining DIR pointer to stacks_dir (=NULL if directory doesn't exist) if (!(cur_dir_lev1=opendir(stacks_dir))) { char msg[S_STATIC_STRINGS_SIZE]; sprintf(msg,"in BlockVolume::init(...): Unable to open directory \"%s\"", stacks_dir); throw iom::exception(msg); } //scanning first level of hierarchy which entries need to be ordered alphabetically. This is done using STL. while ((entry_lev1=readdir(cur_dir_lev1))) { tmp=entry_lev1->d_name; if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) entries_lev1.push_front(entry_lev1->d_name); } closedir(cur_dir_lev1); entries_lev1.sort(); N_ROWS = (uint16) entries_lev1.size(); N_COLS = 0; if(N_ROWS == 0) throw iom::exception("in BlockVolume::init(...): Unable to find stacks in the given directory"); //for each entry of first level, scanning second level for(entry_i = entries_lev1.begin(), i=0; entry_i!= entries_lev1.end(); entry_i++, i++) { //building absolute path of first level entry to be used for "opendir(...)" tmp_path=stacks_dir; tmp_path.append("/"); tmp_path.append(*entry_i); cur_dir_lev2 = opendir(tmp_path.c_str()); if (!cur_dir_lev2) throw iom::exception("in BlockVolume::init(...): A problem occurred during scanning of subdirectories"); //scanning second level of hierarchy which entries need to be ordered alphabetically. This is done using STL. while ((entry_lev2=readdir(cur_dir_lev2))) { tmp=entry_lev2->d_name; if(tmp.find(".") == string::npos && tmp.find(" ") == string::npos) entries_lev2.push_back(entry_lev2->d_name); } closedir(cur_dir_lev2); entries_lev2.sort(); //for each entry of the second level, allocating a new Stack for(entry_j = entries_lev2.begin(), j=0; entry_j!= entries_lev2.end(); entry_j++, j++) { //allocating new stack sprintf(stack_i_j_path,"%s/%s",(*entry_i).c_str(), (*entry_j).c_str()); Block *new_stk = new Block(this,i,j,stack_i_j_path); stacks_list.push_back(new_stk); } entries_lev2.clear(); if(N_COLS == 0) N_COLS = j; else if(j != N_COLS) throw iom::exception("in BlockVolume::init(...): Number of second-level directories is not the same for all first-level directories!"); } entries_lev1.clear(); //intermediate check if(N_ROWS == 0 || N_COLS == 0) throw iom::exception("in BlockVolume::init(...): Unable to find stacks in the given directory"); // 2015-07-22. Giulio. @ADDED sparse data support // precondition: files must be named according to one of the two formats supported (see 'name2coordZ()') if(SPARSE_DATA) { // compute N_SLICES as the cardinality of the set of all Z-coordinates extracted from the filenames of the entire volume int start_z = 999999; //atoi(name2coordZ(stacks_list.front()->FILENAMES[0]).c_str()); int end_z = 0; int start_cur, end_cur; N_SLICES = 0; for(list<Block*>::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) { if ( (*i)->N_BLOCKS ) { start_cur = atoi(name2coordZ((*i)->FILENAMES[0]).c_str()); if ( start_cur < start_z ) start_z = start_cur; end_cur = atoi(name2coordZ((*i)->FILENAMES[(*i)->N_BLOCKS-1]).c_str()) + (int)floor((*i)->BLOCK_SIZE[(*i)->N_BLOCKS-1] * 10 * VXL_D + 0.5); if ( end_cur > end_z ) end_z = end_cur; if ( N_SLICES < (*i)->DEPTH ) N_SLICES = (*i)->DEPTH; } } // check if no stacks are complete // WARNING: VXL_D is assumed positive, it should be used the absolute value if ( N_SLICES < ((int)floor((float)(end_z - start_z) / (10 * VXL_D) + 0.5)) ) N_SLICES = (int)floor((float)(end_z - start_z) / (10 * VXL_D) + 0.5); // check non-zero N_SLICES if (N_SLICES == 0) throw iom::exception("in BlockVolume::init(...): Unable to find image files in the given directory"); // set the origin along D direction to overcome the possible incompleteness of first block ORG_D = start_z/10000.0F; // for each tile, compute the range of available slices std::pair<int,int> z_coords(start_z,end_z); for(list<Block*>::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) { (*i)->compute_z_ranges(&z_coords); } } //converting stacks_list (STL list of Stack*) into STACKS (2-D array of Stack*) BLOCKS = new Block**[N_ROWS]; for(int row=0; row < N_ROWS; row++) BLOCKS[row] = new Block*[N_COLS]; for(list<Block*>::iterator i = stacks_list.begin(); i != stacks_list.end(); i++) BLOCKS[(*i)->getROW_INDEX()][(*i)->getCOL_INDEX()] = (*i); // 2014-09-09. Alessandro. @FIXED both 'init()' and 'initFromXML()' methods to deal with empty stacks. Added call of 'normalize_stacks_attributes()' method. // make stacks have the same attributes normalize_stacks_attributes(); } void BlockVolume::initChannels() throw (iom::exception) { DIM_C = BLOCKS[0][0]->getN_CHANS(); BYTESxCHAN = BLOCKS[0][0]->getN_BYTESxCHAN(); } void BlockVolume::applyReferenceSystem(vm::ref_sys reference_system, float VXL_1, float VXL_2, float VXL_3) throw (iom::exception) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::applyReferenceSystem(reference_system = {%d,%d,%d}, VXL_1 = %.2f, VXL_2 = %.2f, VXL_3 = %.2f)\n", reference_system.first, reference_system.second, reference_system.third, VXL_1, VXL_2, VXL_3); #endif /******************* 2) SETTING THE REFERENCE SYSTEM ******************** The entire application uses a vertical-horizontal reference system, so it is necessary to fit the original reference system into the new one. *************************************************************************/ //adjusting possible sign mismatch between reference system and VXL //in these cases VXL is adjusted to match with reference system if(SIGN(reference_system.first) != SIGN(VXL_1)) VXL_1*=-1.0f; if(SIGN(reference_system.second) != SIGN(VXL_2)) VXL_2*=-1.0f; if(SIGN(reference_system.third) != SIGN(VXL_3)) VXL_3*=-1.0f; //HVD --> VHD if (abs(reference_system.first)==2 && abs(reference_system.second)==1 && reference_system.third==3) { this->rotate(90); this->mirror(vm::axis(2)); if(reference_system.first == -2) this->mirror(vm::axis(2)); if(reference_system.second == -1) this->mirror(vm::axis(1)); int computed_ORG_1, computed_ORG_2, computed_ORG_3; // 2015-07-30. Giulio. @FIXED bug: sparse data support if(SPARSE_DATA) { extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2); } else { // 2014-09-01. Alessandro. @FIXED: check that this tile has a slice at z=0. Otherwise it's not possible to compute the origin. if(BLOCKS[0][0]->isComplete(0,0) == false) throw iom::exception(vm::strprintf("in StackedVolume::applyReferenceSystem(): cannot compute origin. Tile (0,0) [%s] has no slice at z=0", BLOCKS[0][0]->getDIR_NAME()).c_str()); extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); ORG_D = computed_ORG_3/10000.0F; } ORG_V = computed_ORG_2/10000.0F; // 2015-08-03. Giulio. @FIXED bug ORG_H = computed_ORG_1/10000.0F; VXL_V = VXL_2 ; VXL_H = VXL_1 ; VXL_D = VXL_3 ; int tmp_coord_1, tmp_coord_2, tmp_coord_4, tmp_coord_5; extractCoordinates(BLOCKS[0][0], 0, &tmp_coord_1, &tmp_coord_2); if(N_ROWS > 1) { extractCoordinates(BLOCKS[1][0], 0, &tmp_coord_4, &tmp_coord_5); this->MEC_V = (tmp_coord_5 - tmp_coord_2)/10.0F; } else this->MEC_V = getStacksHeight()*VXL_V; if(N_COLS > 1) { extractCoordinates(BLOCKS[0][1], 0, &tmp_coord_4, &tmp_coord_5); this->MEC_H = (tmp_coord_4 - tmp_coord_1)/10.0F; } else this->MEC_H = getStacksWidth()*VXL_H; this->N_SLICES = BLOCKS[0][0]->getDEPTH(); } //VHD --> VHD else if (abs(reference_system.first)==1 && abs(reference_system.second)==2 && reference_system.third==3) { if(reference_system.first == -1) this->mirror(vm::axis(1)); if(reference_system.second == -2) this->mirror(vm::axis(2)); int computed_ORG_1, computed_ORG_2, computed_ORG_3; // 2015-07-22. Giulio. @ADDED sparse data support if(SPARSE_DATA) { extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2); } else { // 2014-09-01. Alessandro. @FIXED: check that this tile has a slice at z=0. Otherwise it's not possible to compute the origin. if(BLOCKS[0][0]->isComplete(0,0) == false) throw iom::exception(vm::strprintf("in StackedVolume::applyReferenceSystem(): cannot compute origin. Tile (0,0) [%s] has no slice at z=0", BLOCKS[0][0]->getDIR_NAME()).c_str()); extractCoordinates(BLOCKS[0][0], 0, &computed_ORG_1, &computed_ORG_2, &computed_ORG_3); ORG_D = computed_ORG_3/10000.0F; } ORG_V = computed_ORG_1/10000.0F; ORG_H = computed_ORG_2/10000.0F; VXL_V = VXL_1; VXL_H = VXL_2; VXL_D = VXL_3; int tmp_coord_1, tmp_coord_2, tmp_coord_4, tmp_coord_5; extractCoordinates(BLOCKS[0][0], 0, &tmp_coord_1, &tmp_coord_2); if(N_ROWS > 1) { extractCoordinates(BLOCKS[1][0], 0, &tmp_coord_4, &tmp_coord_5); this->MEC_V = (tmp_coord_4 - tmp_coord_1)/10.0F; } else this->MEC_V = getStacksHeight()*VXL_V; if(N_COLS > 1) { extractCoordinates(BLOCKS[0][1], 0, &tmp_coord_4, &tmp_coord_5); this->MEC_H = (tmp_coord_5 - tmp_coord_2)/10.0F; } else this->MEC_H = getStacksWidth()*VXL_H; this->N_SLICES = BLOCKS[0][0]->getDEPTH(); } else //unsupported reference system { char msg[500]; sprintf(msg, "in BlockVolume::init(...): the reference system {%d,%d,%d} is not supported.", reference_system.first, reference_system.second, reference_system.third); throw iom::exception(msg); } //some little adjustments of the origin if(VXL_V < 0) ORG_V -= (BLOCKS[0][0]->getHEIGHT()-1)* VXL_V/1000.0F; if(VXL_H < 0) ORG_H -= (BLOCKS[0][0]->getWIDTH() -1)* VXL_H/1000.0F; //inserting motorized stages coordinates for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++) { if(i!=0) BLOCKS[i][j]->setABS_V(BLOCKS[i-1][j]->getABS_V() + getDEFAULT_DISPLACEMENT_V()); else BLOCKS[i][j]->setABS_V(0); if(j!=0) BLOCKS[i][j]->setABS_H(BLOCKS[i][j-1]->getABS_H() + getDEFAULT_DISPLACEMENT_H()); else BLOCKS[i][j]->setABS_H(0); BLOCKS[i][j]->setABS_D(getDEFAULT_DISPLACEMENT_D()); } } void BlockVolume::saveBinaryMetadata(char *metadata_filepath) throw (iom::exception) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::saveBinaryMetadata(char *metadata_filepath = %s)\n", metadata_filepath); #endif //LOCAL VARIABLES uint16 str_size; FILE *file; int i,j; if(!(file = fopen(metadata_filepath, "wb"))) throw iom::exception("in BlockVolume::saveBinaryMetadata(...): unable to save binary metadata file"); str_size = (uint16) strlen(stacks_dir) + 1; fwrite(&str_size, sizeof(uint16), 1, file); fwrite(stacks_dir, str_size, 1, file); fwrite(&reference_system.first, sizeof(vm::axis), 1, file); // GI_140501 fwrite(&reference_system.second, sizeof(vm::axis), 1, file); // GI_140501 fwrite(&reference_system.third, sizeof(vm::axis), 1, file); // GI_140501 fwrite(&VXL_V, sizeof(float), 1, file); fwrite(&VXL_H, sizeof(float), 1, file); fwrite(&VXL_D, sizeof(float), 1, file); fwrite(&ORG_V, sizeof(float), 1, file); fwrite(&ORG_H, sizeof(float), 1, file); fwrite(&ORG_D, sizeof(float), 1, file); fwrite(&MEC_V, sizeof(float), 1, file); fwrite(&MEC_H, sizeof(float), 1, file); fwrite(&N_ROWS, sizeof(uint16), 1, file); fwrite(&N_COLS, sizeof(uint16), 1, file); // 2014-09-02. Alessandro. @FIXED as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. fwrite(&N_SLICES, sizeof(int), 1, file); for(i = 0; i < N_ROWS; i++) for(j = 0; j < N_COLS; j++) BLOCKS[i][j]->binarizeInto(file); fclose(file); } void BlockVolume::loadBinaryMetadata(char *metadata_filepath) throw (iom::exception) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::loadBinaryMetadata(char *metadata_filepath = %s)\n", metadata_filepath); #endif //LOCAL VARIABLES uint16 str_size; char *temp; // GI_140425 bool regen = false; FILE *file; int i,j; size_t fread_return_val; if(!(file = fopen(metadata_filepath, "rb"))) throw iom::exception("in BlockVolume::loadBinaryMetadata(...): unable to load binary metadata file"); // str_size = (uint16) strlen(stacks_dir) + 1; // GI_140425 remodev because has with no effect fread_return_val = fread(&str_size, sizeof(uint16), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } // GI_140425 a check has been introduced to avoid that an out-of-date mdata.bin contains a wrong rood directory temp = new char[str_size]; fread_return_val = fread(temp, str_size, 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } if ( !strcmp(temp,stacks_dir) ) // the two strings are equal delete []temp; else { // GI_140626: allow moving mdata.bin to other machine delete []temp; regen = true; //fclose(file); //throw iom::iom::exception("in BlockVolume::loadBinaryMetadata(...): binary metadata file is out-of-date"); #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::loadBinaryMetadata(...): binary metadata file is out-of-date\n"); #endif } // GI_140501 fread_return_val = fread(&reference_system.first, sizeof(vm::axis), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::unBinarizeFrom(...): error while reading binary metadata file"); } // GI_140501 fread_return_val = fread(&reference_system.second, sizeof(vm::axis), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::unBinarizeFrom(...): error while reading binary metadata file"); } // GI_140501 fread_return_val = fread(&reference_system.third, sizeof(vm::axis), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::unBinarizeFrom(...): error while reading binary metadata file"); } fread_return_val = fread(&VXL_V, sizeof(float), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&VXL_H, sizeof(float), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&VXL_D, sizeof(float), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&ORG_V, sizeof(float), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&ORG_H, sizeof(float), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&ORG_D, sizeof(float), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&MEC_V, sizeof(float), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&MEC_H, sizeof(float), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&N_ROWS, sizeof(uint16), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } fread_return_val = fread(&N_COLS, sizeof(uint16), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } // 2014-09-02. Alessandro. @FIXED as 'N_SLICES' changed from 'uint16' to 'int' type. See vmVirtualVolume.h. fread_return_val = fread(&N_SLICES, sizeof(int), 1, file); if(fread_return_val != 1) { fclose(file); throw iom::exception("in BlockVolume::loadBinaryMetadata(...) error while reading binary metadata file"); } BLOCKS = new Block **[N_ROWS]; for(i = 0; i < N_ROWS; i++) { BLOCKS[i] = new Block *[N_COLS]; for(j = 0; j < N_COLS; j++) BLOCKS[i][j] = new Block(this, i, j, file); } fclose(file); if ( regen ) { // GI_140626: directory name is changed, mdata.bin must be regenerated saveBinaryMetadata(metadata_filepath); } } //rotate stacks matrix around D vm::axis (accepted values are theta=0,90,180,270) void BlockVolume::rotate(int theta) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::rotate(theta = %d)\n", theta); #endif Block*** new_STACK_2D_ARRAY = NULL; int new_N_ROWS=0, new_N_COLS=0; switch(theta) { case(0): break; case(90): { new_N_COLS = N_ROWS; new_N_ROWS = N_COLS; //allocating new_STACK_2D_ARRAY new_STACK_2D_ARRAY = new Block**[new_N_ROWS]; for(int i=0; i<new_N_ROWS; i++) new_STACK_2D_ARRAY[i] = new Block*[new_N_COLS]; //populating new_STACK_2D_ARRAY for(int i=0; i<new_N_ROWS; i++) for(int j=0; j<new_N_COLS; j++){ new_STACK_2D_ARRAY[i][j] = BLOCKS[N_ROWS-1-j][i]; new_STACK_2D_ARRAY[i][j]->setROW_INDEX(i); new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); } break; } case(180): { new_N_COLS=N_COLS; new_N_ROWS=N_ROWS; //allocating new_STACK_2D_ARRAY new_STACK_2D_ARRAY = new Block**[new_N_ROWS]; for(int i=0; i<new_N_ROWS; i++) new_STACK_2D_ARRAY[i] = new Block*[new_N_COLS]; //populating new_STACK_2D_ARRAY for(int i=0; i<new_N_ROWS; i++) for(int j=0; j<new_N_COLS; j++){ new_STACK_2D_ARRAY[i][j] = BLOCKS[N_ROWS-1-i][N_COLS-1-j]; new_STACK_2D_ARRAY[i][j]->setROW_INDEX(i); new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); } break; } case(270): { new_N_COLS=N_ROWS; new_N_ROWS=N_COLS; //allocating new_STACK_2D_ARRAY new_STACK_2D_ARRAY = new Block**[new_N_ROWS]; for(int i=0; i<new_N_ROWS; i++) new_STACK_2D_ARRAY[i] = new Block*[new_N_COLS]; //populating new_STACK_2D_ARRAY for(int i=0; i<new_N_ROWS; i++) for(int j=0; j<new_N_COLS; j++){ new_STACK_2D_ARRAY[i][j] = BLOCKS[j][N_COLS-1-i]; new_STACK_2D_ARRAY[i][j]->setROW_INDEX(i); new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); } break; } } //deallocating current STACK_2DARRAY object for(int row=0; row<N_ROWS; row++) delete[] BLOCKS[row]; delete[] BLOCKS; BLOCKS = new_STACK_2D_ARRAY; N_COLS = new_N_COLS; N_ROWS = new_N_ROWS; } //mirror stacks matrix along mrr_axis (accepted values are mrr_axis=1,2,3) void BlockVolume::mirror(vm::axis mrr_axis) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::mirror(mrr_axis = %d)\n", mrr_axis); #endif if(mrr_axis!= 1 && mrr_axis != 2) { char msg[1000]; sprintf(msg,"in BlockVolume::mirror(vm::axis mrr_axis=%d): unsupported vm::axis mirroring", mrr_axis); throw iom::exception(msg); } Block*** new_STACK_2D_ARRAY; switch(mrr_axis) { case(1): { //allocating new_STACK_2D_ARRAY new_STACK_2D_ARRAY = new Block**[N_ROWS]; for(int i=0; i<N_ROWS; i++) new_STACK_2D_ARRAY[i] = new Block*[N_COLS]; //populating new_STACK_2D_ARRAY for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++){ new_STACK_2D_ARRAY[i][j]=BLOCKS[N_ROWS-1-i][j]; new_STACK_2D_ARRAY[i][j]->setROW_INDEX(i); new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); } break; } case(2): { //allocating new_STACK_2D_ARRAY new_STACK_2D_ARRAY = new Block**[N_ROWS]; for(int i=0; i<N_ROWS; i++) new_STACK_2D_ARRAY[i] = new Block*[N_COLS]; //populating new_STACK_2D_ARRAY for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++){ new_STACK_2D_ARRAY[i][j] = BLOCKS[i][N_COLS-1-j]; new_STACK_2D_ARRAY[i][j]->setROW_INDEX(i); new_STACK_2D_ARRAY[i][j]->setCOL_INDEX(j); } break; } default: break; } //deallocating current STACK_2DARRAY object for(int row=0; row<N_ROWS; row++) delete[] BLOCKS[row]; delete[] BLOCKS; BLOCKS = new_STACK_2D_ARRAY; } //check if volume is complete and coherent bool BlockVolume::check(const char *errlogFileName) throw (iom::exception) { bool ok = true; FILE *errlogf; int depth = BLOCKS[0][0]->getDEPTH(); for ( int i=0; i<N_ROWS; i++ ) { for ( int j=0; j<N_COLS; j++ ) { // 2015-08-27. Giuio. check if stack [i,j] is coherent and complete int f_slice, l_slice; Block *current = BLOCKS[i][j]; bool coherent = true; int k = 0; while ( k<(current->getN_BLOCKS()-1) && coherent ) { if ( current->getFILENAMES()[k] && current->getFILENAMES()[k+1] ) { // block is not empty and it is immediately followed by a non empty block f_slice = atoi(name2coordZ(current->getFILENAMES()[k]).c_str()); l_slice = atoi(name2coordZ(current->getFILENAMES()[k+1]).c_str()); coherent = ( current->getBLOCK_SIZE()[k] == (int)floor( ((l_slice - f_slice) / (this->VXL_D * 10)) + 0.5 ) ); } k++; } if ( !coherent || (depth != BLOCKS[i][j]->getDEPTH()) ) { if ( ok ) { // first anomaly: open and initialize the errlog file if ( errlogFileName ) { if ( (errlogf = fopen(errlogFileName,"w")) == 0 ) { char errMsg[2000]; sprintf(errMsg,"in BlockVolume::check(errlogFileName = \"%s\") : unable to open log file", errlogFileName); throw iom::exception(errMsg); } fprintf(errlogf,"errlog file of volume (BlockVolume): \"%s\"\n",stacks_dir); fprintf(errlogf,"\tdepth: %d\n",depth); } ok = false; } if ( errlogFileName && depth != BLOCKS[i][j]->getDEPTH() ) // reports error on stack depth fprintf(errlogf,"\trow=%d, col=%d, depth=%d\n",i,j,BLOCKS[i][j]->getDEPTH()); if ( errlogFileName && !coherent ) // reports error on coherence between block lenghts and filenames fprintf(errlogf,"\trow=%d, col=%d, block lengths and filenames are not coherent\n",i,j); } } } if ( errlogFileName && !ok ) // there are anomalies: close the errlog file fclose(errlogf); return ok; } void BlockVolume::loadXML(const char *xml_filepath) throw (iom::exception) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::loadXML(char *xml_filepath = %s)\n", xml_filepath); #endif TiXmlDocument xml; if(!xml.LoadFile(xml_filepath)) { char errMsg[2000]; sprintf(errMsg,"in BlockVolume::loadXML(xml_filepath = \"%s\") : unable to load xml", xml_filepath); throw iom::exception(errMsg); } //setting ROOT element (that is the first child, i.e. <TeraStitcher> node) TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to <TeraStitcher> XML node const char *volformat = hRoot.ToElement()->Attribute("volume_format"); if(volformat && strcmp(volformat, id.c_str()) != 0) throw iom::exception(vm::strprintf("in StackedVolume::initFromXML(): unsupported volume_format = \"%s\" (current format is \"%s\")", volformat, id.c_str()).c_str()); //reading fields and checking coherence with metadata previously read from VM_BIN_METADATA_FILE_NAME TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); if(strcmp(pelem->Attribute("value"), stacks_dir) != 0) { char errMsg[2000]; sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in <stacks_dir> field between xml file (=\"%s\") and %s (=\"%s\").", pelem->Attribute("value"), vm::BINARY_METADATA_FILENAME.c_str(), stacks_dir); throw iom::exception(errMsg); } // 2014-11-06. Giulio. @ADDED saved reference system into XML file vm::ref_sys reference_system_read; if ( (pelem = hRoot.FirstChildElement("ref_sys").Element()) != 0 ) { // skip if not present (for compatibility with previous versions) pelem->QueryIntAttribute("ref1", (int *) &reference_system_read.first); pelem->QueryIntAttribute("ref2", (int *) &reference_system_read.second); pelem->QueryIntAttribute("ref3", (int *) &reference_system_read.third); if (reference_system_read.first != reference_system.first || reference_system_read.second != reference_system.second || reference_system_read.third != reference_system.third ) { char errMsg[2000]; sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in <erf_sys> field between xml file (= (%d,%d,%d) ) and %s (= (%d,%d,%d) ).", reference_system_read.first, reference_system_read.second, reference_system_read.third, vm::BINARY_METADATA_FILENAME.c_str(), reference_system.first, reference_system.second, reference_system.third); throw iom::exception(errMsg); } } pelem = hRoot.FirstChildElement("voxel_dims").Element(); float VXL_V_read=0.0f, VXL_H_read=0.0f, VXL_D_read=0.0f; pelem->QueryFloatAttribute("V", &VXL_V_read); pelem->QueryFloatAttribute("H", &VXL_H_read); pelem->QueryFloatAttribute("D", &VXL_D_read); if(VXL_V_read != VXL_V || VXL_H_read != VXL_H || VXL_D_read != VXL_D) { char errMsg[2000]; sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in <voxel_dims> field between xml file (= %.2f x %.2f x %.2f ) and %s (= %.2f x %.2f x %.2f ).", VXL_V_read, VXL_H_read, VXL_D_read, vm::BINARY_METADATA_FILENAME.c_str(), VXL_V, VXL_H, VXL_D); throw iom::exception(errMsg); } pelem = hRoot.FirstChildElement("origin").Element(); float ORG_V_read=0.0f, ORG_H_read=0.0f, ORG_D_read=0.0f; pelem->QueryFloatAttribute("V", &ORG_V_read); pelem->QueryFloatAttribute("H", &ORG_H_read); pelem->QueryFloatAttribute("D", &ORG_D_read); /*if(ORG_V_read != ORG_V || ORG_H_read != ORG_H || ORG_D_read != ORG_D) { char errMsg[2000]; sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in <origin> field between xml file (= {%.7f, %.7f, %.7f} ) and %s (= {%.7f, %.7f, %.7f} ).", ORG_V_read, ORG_H_read, ORG_D_read, VM_BIN_METADATA_FILE_NAME, ORG_V, ORG_H, ORG_D); throw iom::iom::exception(errMsg); } @TODO: bug with float precision causes often mismatch */ pelem = hRoot.FirstChildElement("mechanical_displacements").Element(); float MEC_V_read=0.0f, MEC_H_read=0.0f; pelem->QueryFloatAttribute("V", &MEC_V_read); pelem->QueryFloatAttribute("H", &MEC_H_read); if(MEC_V_read != MEC_V || MEC_H_read != MEC_H) { char errMsg[2000]; sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch in <mechanical_displacements> field between xml file (= %.1f x %.1f ) and %s (= %.1f x %.1f ).", MEC_V_read, MEC_H_read, vm::BINARY_METADATA_FILENAME.c_str(), MEC_V, MEC_H); throw iom::exception(errMsg); } pelem = hRoot.FirstChildElement("dimensions").Element(); int N_ROWS_read, N_COLS_read, N_SLICES_read; pelem->QueryIntAttribute("stack_rows", &N_ROWS_read); pelem->QueryIntAttribute("stack_columns", &N_COLS_read); pelem->QueryIntAttribute("stack_slices", &N_SLICES_read); if(N_ROWS_read != N_ROWS || N_COLS_read != N_COLS || N_SLICES_read != N_SLICES) { char errMsg[2000]; sprintf(errMsg, "in BlockVolume::loadXML(...): Mismatch between in <dimensions> field xml file (= %d x %d ) and %s (= %d x %d ).", N_ROWS_read, N_COLS_read, vm::BINARY_METADATA_FILENAME.c_str(), N_ROWS, N_COLS); throw iom::exception(errMsg); } pelem = hRoot.FirstChildElement("STACKS").Element()->FirstChildElement(); int i,j; for(i=0; i<N_ROWS; i++) for(j=0; j<N_COLS; j++, pelem = pelem->NextSiblingElement()) BLOCKS[i][j]->loadXML(pelem, N_SLICES); } void BlockVolume::initFromXML(const char *xml_filepath) throw (iom::exception) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::initFromXML(char *xml_filename = %s)\n", xml_filename); #endif TiXmlDocument xml; if(!xml.LoadFile(xml_filepath)) { char errMsg[2000]; sprintf(errMsg,"in BlockVolume::initFromXML(xml_filepath = \"%s\") : unable to load xml", xml_filepath); throw iom::exception(errMsg); } //setting ROOT element (that is the first child, i.e. <TeraStitcher> node) TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to <TeraStitcher> XML node const char *volformat = hRoot.ToElement()->Attribute("volume_format"); if(volformat && strcmp(volformat, id.c_str()) != 0) throw iom::exception(vm::strprintf("in StackedVolume::initFromXML(): unsupported volume_format = \"%s\" (current format is \"%s\")", volformat, id.c_str()).c_str()); //reading fields TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); // 2014-11-06. Giulio. @ADDED saved reference system into XML file if ( (pelem = hRoot.FirstChildElement("ref_sys").Element()) != 0 ) { // skip if not present (for compatibility with previous versions) pelem->QueryIntAttribute("ref1", (int *) &reference_system.first); pelem->QueryIntAttribute("ref2", (int *) &reference_system.second); pelem->QueryIntAttribute("ref3", (int *) &reference_system.third); } else { // 2014-11-06. Giulio. @MOVED in case XML is old // 2014-09-09. Alessandro. @FIXED. Added default reference system if volume is imported from xml. reference_system = vm::ref_sys(vm::vertical,vm::horizontal,vm::depth); } pelem = hRoot.FirstChildElement("voxel_dims").Element(); pelem->QueryFloatAttribute("V", &VXL_V); pelem->QueryFloatAttribute("H", &VXL_H); pelem->QueryFloatAttribute("D", &VXL_D); pelem = hRoot.FirstChildElement("origin").Element(); pelem->QueryFloatAttribute("V", &ORG_V); pelem->QueryFloatAttribute("H", &ORG_H); pelem->QueryFloatAttribute("D", &ORG_D); pelem = hRoot.FirstChildElement("mechanical_displacements").Element(); pelem->QueryFloatAttribute("V", &MEC_V); pelem->QueryFloatAttribute("H", &MEC_H); pelem = hRoot.FirstChildElement("dimensions").Element(); int nrows, ncols, nslices; pelem->QueryIntAttribute("stack_rows", &nrows); pelem->QueryIntAttribute("stack_columns", &ncols); pelem->QueryIntAttribute("stack_slices", &nslices); N_ROWS = nrows; N_COLS = ncols; N_SLICES = nslices; pelem = hRoot.FirstChildElement("STACKS").Element()->FirstChildElement(); BLOCKS = new Block **[N_ROWS]; for(int i = 0; i < N_ROWS; i++) { BLOCKS[i] = new Block *[N_COLS]; for(int j = 0; j < N_COLS; j++, pelem = pelem->NextSiblingElement()) { // 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only). BLOCKS[i][j] = new Block(this, i, j, pelem, N_SLICES); //BLOCKS[i][j] = new Block(this, i, j, pelem->Attribute("DIR_NAME")); //BLOCKS[i][j]->loadXML(pelem, N_SLICES); } } // 2014-09-09. Alessandro. @FIXED both 'init()' and 'initFromXML()' methods to deal with empty stacks. Added call of 'normalize_stacks_attributes()' method. // make stacks have the same attributes normalize_stacks_attributes(); } void BlockVolume::saveXML(const char *xml_filename, const char *xml_filepath) throw (iom::exception) { #if VM_VERBOSE > 3 printf("\t\t\t\tin BlockVolume::saveXML(char *xml_filename = %s)\n", xml_filename); #endif //LOCAL VARIABLES char xml_abs_path[S_STATIC_STRINGS_SIZE]; TiXmlDocument xml; TiXmlElement * root; TiXmlElement * pelem; int i,j; //obtaining XML absolute path if(xml_filename) sprintf(xml_abs_path, "%s/%s.xml", stacks_dir, xml_filename); else if(xml_filepath) strcpy(xml_abs_path, xml_filepath); else throw iom::exception("in BlockVolume::saveXML(...): no xml path provided"); //initializing XML file with DTD declaration fstream XML_FILE(xml_abs_path, ios::out); XML_FILE<<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"<<endl; XML_FILE<<"<!DOCTYPE TeraStitcher SYSTEM \"TeraStitcher.DTD\">"<<endl; XML_FILE.close(); //loading previously initialized XML file if(!xml.LoadFile(xml_abs_path)) { char errMsg[5000]; sprintf(errMsg, "in BlockVolume::saveToXML(...) : unable to load xml file at \"%s\"", xml_abs_path); throw iom::exception(errMsg); } //inserting root node <TeraStitcher> and children nodes root = new TiXmlElement("TeraStitcher"); xml.LinkEndChild( root ); // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to <TeraStitcher> XML node root->SetAttribute("volume_format", id.c_str()); pelem = new TiXmlElement("stacks_dir"); pelem->SetAttribute("value", stacks_dir); root->LinkEndChild(pelem); // 2014-11-06. Giulio. @ADDED saved reference system into XML file pelem = new TiXmlElement("ref_sys"); pelem->SetAttribute("ref1", reference_system.first); pelem->SetAttribute("ref2", reference_system.second); pelem->SetAttribute("ref3", reference_system.third); root->LinkEndChild(pelem); pelem = new TiXmlElement("voxel_dims"); pelem->SetDoubleAttribute("V", VXL_V); pelem->SetDoubleAttribute("H", VXL_H); pelem->SetDoubleAttribute("D", VXL_D); root->LinkEndChild(pelem); pelem = new TiXmlElement("origin"); pelem->SetDoubleAttribute("V", ORG_V); pelem->SetDoubleAttribute("H", ORG_H); pelem->SetDoubleAttribute("D", ORG_D); root->LinkEndChild(pelem); pelem = new TiXmlElement("mechanical_displacements"); pelem->SetDoubleAttribute("V", MEC_V); pelem->SetDoubleAttribute("H", MEC_H); root->LinkEndChild(pelem); pelem = new TiXmlElement("dimensions"); pelem->SetAttribute("stack_rows", N_ROWS); pelem->SetAttribute("stack_columns", N_COLS); pelem->SetAttribute("stack_slices", N_SLICES); root->LinkEndChild(pelem); //inserting stack nodes pelem = new TiXmlElement("STACKS"); for(i=0; i<N_ROWS; i++) for(j=0; j<N_COLS; j++) pelem->LinkEndChild(BLOCKS[i][j]->getXML()); root->LinkEndChild(pelem); //saving the file xml.SaveFile(); } //counts the total number of displacements and the number of displacements per stack void BlockVolume::countDisplacements(int& total, float& per_stack_pair) { /* PRECONDITIONS: none */ total = 0; per_stack_pair = 0.0f; for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++) { total+= static_cast<int>(BLOCKS[i][j]->getEAST().size()); total+= static_cast<int>(BLOCKS[i][j]->getSOUTH().size()); per_stack_pair += static_cast<int>(BLOCKS[i][j]->getEAST().size()); per_stack_pair += static_cast<int>(BLOCKS[i][j]->getSOUTH().size()); } per_stack_pair /= 2*(N_ROWS*N_COLS) - N_ROWS - N_COLS; } //counts the number of single-direction displacements having a reliability measure above the given threshold void BlockVolume::countReliableSingleDirectionDisplacements(float threshold, int& total, int& reliable) { /* PRECONDITIONS: * - for each pair of adjacent stacks one and only one displacement exists (CHECKED) */ total = reliable = 0; for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++) { if(j != (N_COLS-1) && BLOCKS[i][j]->getEAST().size()==1) { total+=3; reliable += BLOCKS[i][j]->getEAST()[0]->getReliability(dir_vertical) >= threshold; reliable += BLOCKS[i][j]->getEAST()[0]->getReliability(dir_horizontal) >= threshold; reliable += BLOCKS[i][j]->getEAST()[0]->getReliability(dir_depth) >= threshold; } if(i != (N_ROWS-1) && BLOCKS[i][j]->getSOUTH().size()==1) { total+=3; reliable += BLOCKS[i][j]->getSOUTH()[0]->getReliability(dir_vertical) >= threshold; reliable += BLOCKS[i][j]->getSOUTH()[0]->getReliability(dir_horizontal) >= threshold; reliable += BLOCKS[i][j]->getSOUTH()[0]->getReliability(dir_depth) >= threshold; } } } //counts the number of stitchable stacks given the reliability threshold int BlockVolume::countStitchableStacks(float threshold) { /* PRECONDITIONS: * - for each pair of adjacent stacks one and only one displacement exists (CHECKED) */ //stitchable stacks are stacks that have at least one reliable single-direction displacement int stitchables = 0; bool stitchable; for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++) { stitchable = false; Block* stk = BLOCKS[i][j]; if(i!= 0 && BLOCKS[i][j]->getNORTH().size()==1) for(int k=0; k<3; k++) stitchable = stitchable || (stk->getNORTH()[0]->getReliability(direction(k)) >= threshold); if(j!= (N_COLS -1) && BLOCKS[i][j]->getEAST().size()==1) for(int k=0; k<3; k++) stitchable = stitchable || (stk->getEAST()[0]->getReliability(direction(k)) >= threshold); if(i!= (N_ROWS -1) && BLOCKS[i][j]->getSOUTH().size()==1) for(int k=0; k<3; k++) stitchable = stitchable || (stk->getSOUTH()[0]->getReliability(direction(k)) >= threshold); if(j!= 0 && BLOCKS[i][j]->getWEST().size()==1) for(int k=0; k<3; k++) stitchable = stitchable || (stk->getWEST()[0]->getReliability(direction(k)) >= threshold); stitchables += stitchable; } return stitchables; } // 2014-09-05. Alessandro. @ADDED 'normalize_stacks_attributes()' method to normalize stacks attributes (width, height, etc.) void BlockVolume::normalize_stacks_attributes() throw (iom::exception) { std::set<int> heights, widths, nbytes, nchans; for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++) { // exclude empty stacks (that are expected to have invalid WIDTH and HEIGHT) if(BLOCKS[i][j]->isEmpty()) continue; heights.insert(BLOCKS[i][j]->HEIGHT); widths.insert(BLOCKS[i][j]->WIDTH); nbytes.insert(BLOCKS[i][j]->N_BYTESxCHAN); nchans.insert(BLOCKS[i][j]->N_CHANS); } // make the checks if(heights.size() != 1) throw iom::exception("in BlockVolume::check_stacks_same_dims(...): Stacks have unequal 'HEIGHT' attribute. This feature is not supported yet."); if(widths.size() != 1) throw iom::exception("in BlockVolume::check_stacks_same_dims(...): Stacks have unequal 'WIDTH' attribute. This feature is not supported yet."); if(nbytes.size() != 1) throw iom::exception("in BlockVolume::check_stacks_same_dims(...): Stacks have unequal 'N_BYTESxCHAN' attribute. This feature is not supported yet."); if(nchans.size() != 1) throw iom::exception("in BlockVolume::check_stacks_same_dims(...): Stacks have unequal 'N_CHANS' attribute. This feature is not supported yet."); // make empty stacks having the same attributes of other stacks for(int i=0; i<N_ROWS; i++) for(int j=0; j<N_COLS; j++) if(BLOCKS[i][j]->isEmpty()) { BLOCKS[i][j]->HEIGHT = *(heights.begin()); BLOCKS[i][j]->WIDTH = *(widths.begin()); BLOCKS[i][j]->N_CHANS = *(nchans.begin()); BLOCKS[i][j]->N_BYTESxCHAN = *(nbytes.begin()); } }
BEG TST1 CRD CBF - 1 PRT PBF - 1 PCH UBF - 1 ORG 0373 EOF +2 /* STA * EXECUTE TESTS GO JR T01 XF HLT T01 JX R01 XF REA LA1 EOF,2 CHECK FOR LAST CARD CA1 CBF,2 JEA R01 EOF FOUND, WE'RE DONE LPR CBF,80 PRINT THE RECORD JUST READ XF PR1 J T01 R01 J $ END GO
; =============================================================== ; Dec 2012 by Einar Saukas & Urusergi ; "Turbo" version (89 bytes, 25% faster) ; =============================================================== ; ; void dzx7_turbo(void *src, void *dst) ; ; Decompress the compressed block at address src to address dst. ; ; =============================================================== INCLUDE "config_private.inc" SECTION code_clib SECTION code_compress_zx7 PUBLIC asm_dzx7_turbo EXTERN l_ret asm_dzx7_turbo: ; enter : hl = void *src ; de = void *dst ; ; exit : hl = & following uncompressed block ; ; uses : af, bc, de, hl ld a, $80 dzx7t_copy_byte_loop: ldi ; copy literal byte dzx7t_main_loop: add a, a ; check next bit call z, dzx7t_load_bits ; no more bits left? jr nc, dzx7t_copy_byte_loop ; next bit indicates either literal or sequence ; determine number of bits used for length (Elias gamma coding) push de ld bc, 1 ld d, b dzx7t_len_size_loop: inc d add a, a ; check next bit call z, dzx7t_load_bits ; no more bits left? jr nc, dzx7t_len_size_loop jp dzx7t_len_value_start ; determine length dzx7t_len_value_loop: add a, a ; check next bit call z, dzx7t_load_bits ; no more bits left? rl c rl b ;; jr c, dzx7t_exit ; check end marker jp c, l_ret - 1 dzx7t_len_value_start: dec d jr nz, dzx7t_len_value_loop inc bc ; adjust length ; determine offset ld e, (hl) ; load offset flag (1 bit) + offset value (7 bits) inc hl IF __CPU_INFO & $01 defb $cb, $33 ; opcode for undocumented instruction "SLL E" aka "SLS E" ELSE sla e inc e ENDIF jr nc, dzx7t_offset_end ; if offset flag is set, load 4 extra bits add a, a ; check next bit call z, dzx7t_load_bits ; no more bits left? rl d ; insert first bit into D add a, a ; check next bit call z, dzx7t_load_bits ; no more bits left? rl d ; insert second bit into D add a, a ; check next bit call z, dzx7t_load_bits ; no more bits left? rl d ; insert third bit into D add a, a ; check next bit call z, dzx7t_load_bits ; no more bits left? ccf jr c, dzx7t_offset_end inc d ; equivalent to adding 128 to DE dzx7t_offset_end: rr e ; insert inverted fourth bit into E ; copy previous sequence ex (sp), hl ; store source, restore destination push hl ; store destination sbc hl, de ; HL = destination - offset - 1 pop de ; DE = destination ldir dzx7t_exit: pop hl ; restore source address (compressed data) jp nc, dzx7t_main_loop dzx7t_load_bits: ld a, (hl) ; load another group of 8 bits inc hl rla ret
EXTERN mainTextProc1ReturnAddress: QWORD EXTERN mainTextProc2ReturnAddress: QWORD EXTERN mainTextProc2BufferAddress: QWORD EXTERN mainTextProc3ReturnAddress1: QWORD EXTERN mainTextProc3ReturnAddress2: QWORD EXTERN mainTextProc4ReturnAddress: QWORD ESCAPE_SEQ_1 = 10h ESCAPE_SEQ_2 = 11h ESCAPE_SEQ_3 = 12h ESCAPE_SEQ_4 = 13h LOW_SHIFT = 0Eh HIGH_SHIFT = 9h SHIFT_2 = LOW_SHIFT SHIFT_3 = 900h SHIFT_4 = 8F2h NO_FONT = 98Fh NOT_DEF = 2026h ;temporary space for code point .DATA mainTextProc2TmpCharacter DD 0 .CODE mainTextProc1 PROC movsxd rax, edi; cmp byte ptr[rax + rbx], ESCAPE_SEQ_1; jz JMP_A; cmp byte ptr[rax + rbx], ESCAPE_SEQ_2; jz JMP_B; cmp byte ptr[rax + rbx], ESCAPE_SEQ_3; jz JMP_C; cmp byte ptr[rax + rbx], ESCAPE_SEQ_4; jz JMP_D; movzx eax, byte ptr [rax+rbx]; jmp JMP_E; JMP_A: movzx eax, word ptr[rax + rbx + 1]; jmp JMP_F; JMP_B: movzx eax, word ptr[rax + rbx + 1]; sub eax, SHIFT_2; jmp JMP_F; JMP_C: movzx eax, word ptr[rax + rbx + 1]; add eax, SHIFT_3; jmp JMP_F; JMP_D: movzx eax, word ptr[rax + rbx + 1]; add eax, SHIFT_4; JMP_F: movzx eax, ax; add edi, 2; cmp eax, NO_FONT; ja JMP_E; mov eax, NOT_DEF; JMP_E: movss xmm3, dword ptr [r15+848h]; mov rbx, qword ptr [r15+rax*8]; mov qword ptr [rbp+100h], rbx; push mainTextProc1ReturnAddress; ret; mainTextProc1 ENDP ;-------------------------------------------; mainTextProc2 PROC movsxd rdx, edi; movsxd rcx, r14d; mov r10, [rsp+858h-7E0h]; movzx eax, byte ptr [rdx+r10]; mov r9, mainTextProc2BufferAddress; mov byte ptr [rcx+r9], al; inc r14d; inc rcx; cmp al, ESCAPE_SEQ_1; jz JMP_A; cmp al, ESCAPE_SEQ_2; jz JMP_B; cmp al, ESCAPE_SEQ_3; jz JMP_C; cmp al, ESCAPE_SEQ_4; jz JMP_D; jmp JMP_E; JMP_A: movzx eax, word ptr[rdx+r10+1]; mov word ptr [rcx+r9], ax; jmp JMP_F; JMP_B: movzx eax, word ptr[rdx+r10+1]; mov word ptr [rcx+r9], ax; sub eax, SHIFT_2; jmp JMP_F; JMP_C: movzx eax, word ptr [rdx+r10+1]; mov word ptr [rcx+r9], ax; add eax, SHIFT_3; jmp JMP_F; JMP_D: movzx eax, word ptr [rdx+r10+1]; mov word ptr [rcx+r9], ax; add eax, SHIFT_4; JMP_F: movzx eax, ax; add r14d, 2; add rcx,2; cmp eax, NO_FONT; ja JMP_G; mov eax, NOT_DEF; JMP_G: add rdx, 2; add edi, 2; JMP_E: mov mainTextProc2TmpCharacter, eax; push mainTextProc2ReturnAddress; ret; mainTextProc2 ENDP ;-------------------------------------------; mainTextProc2_v131 PROC movsxd rdx, edi; movsxd rcx, r14d; mov r10, [rbp+750h-7D0h]; movzx eax, byte ptr [rdx+r10]; mov r9, mainTextProc2BufferAddress; mov byte ptr [rcx+r9], al; inc r14d; inc rcx; cmp al, ESCAPE_SEQ_1; jz JMP_A; cmp al, ESCAPE_SEQ_2; jz JMP_B; cmp al, ESCAPE_SEQ_3; jz JMP_C; cmp al, ESCAPE_SEQ_4; jz JMP_D; jmp JMP_E; JMP_A: movzx eax, word ptr[rdx+r10+1]; mov word ptr [rcx+r9], ax; jmp JMP_F; JMP_B: movzx eax, word ptr[rdx+r10+1]; mov word ptr [rcx+r9], ax; sub eax, SHIFT_2; jmp JMP_F; JMP_C: movzx eax, word ptr [rdx+r10+1]; mov word ptr [rcx+r9], ax; add eax, SHIFT_3; jmp JMP_F; JMP_D: movzx eax, word ptr [rdx+r10+1]; mov word ptr [rcx+r9], ax; add eax, SHIFT_4; JMP_F: movzx eax, ax; add r14d, 2; add rcx,2; cmp eax, NO_FONT; ja JMP_G; mov eax, NOT_DEF; JMP_G: add rdx, 2; add edi, 2; JMP_E: mov mainTextProc2TmpCharacter, eax; push mainTextProc2ReturnAddress; ret; mainTextProc2_v131 ENDP ;-------------------------------------------; mainTextProc3 PROC cmp word ptr [rcx+6],0; jnz JMP_A; jmp JMP_B; JMP_A: cmp mainTextProc2TmpCharacter, 00FFh; ja JMP_B; push mainTextProc3ReturnAddress2; ret; JMP_B: lea eax, dword ptr [rbx+rbx]; movd xmm1, eax; push mainTextProc3ReturnAddress1; ret; mainTextProc3 ENDP ;-------------------------------------------; mainTextProc4 PROC ; check code point saved proc1 cmp mainTextProc2TmpCharacter, 00FFh; ja JMP_A; movzx eax, byte ptr[rdx + r10]; jmp JMP_B; JMP_A: mov eax, mainTextProc2TmpCharacter; JMP_B: mov rcx, qword ptr [r15 + rax*8]; mov qword ptr [rbp-60h],rcx; test rcx,rcx; push mainTextProc4ReturnAddress; ret; mainTextProc4 ENDP END
; A127960: a(n) = n^2*3^n. ; 0,3,36,243,1296,6075,26244,107163,419904,1594323,5904900,21434787,76527504,269440587,937461924,3228504075,11019960576,37321507107,125524238436,419576389587,1394713760400,4613015762523,15188432850756,49801741599483,162679413013056,529555380901875,1718301299950404,5559060566555523,17935405284689424,57718147363866603,185302018885184100,593584133828873067,1897492673384285184,6053816956978964547,19278822044814553764,61288642746274641075,194522647344910860816,616438667164775389947 mov $1,3 pow $1,$0 mul $1,$0 mul $1,$0 mov $0,$1
/* MIT License Copyright (c) 2021 Attila Kiss 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. */ $NOMOD51 $INCLUDE(ALIASES.INC) $INCLUDE(CONFIG.INC) $INCLUDE(REG552.INC) $INCLUDE(MACROS.INC) $INCLUDE(EXTERNALS.INC) NAME ISR_TIMER2_OVERFLOW $IF (ASSEMBLE_ISR_ALL = 1) $IF (ASSEMBLE_ISR_T2_OVF = 1) $IF IN_PIR_LAB <> 1 CSEG AT 0073H $ELSE CSEG AT MONITOR_PROGRAM_OFFSET+0073H $ENDIF LJMP ISR_VECT_TIMER_2_OVF ISR_TIMER2_OVF SEGMENT CODE RSEG ISR_TIMER2_OVF ISR_VECT_TIMER_2_OVF: USING 0 CLR T2OV RETI $ENDIF $ENDIF END
; Copyright 2019 Google LLC ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; https://www.apache.org/licenses/LICENSE-2.0 ; ; 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. BITS 64 buffer: resw 256 header: movzx rbx, byte [rax] inc rax lea rdx, [rel buffer] movsx rcx, word [rdx + 2 * rbx] imul rcx, 0x226 add rcx, header add rdx, rcx jmp rdx
package asm.com.warmthdawn.mod.gugu_utils.asm.mixin; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ConstantDynamic; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.RecordComponentVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.TypePath; public class AMRTDump implements Opcodes { public static byte[] dump() throws Exception { ClassWriter classWriter = new ClassWriter(0); FieldVisitor fieldVisitor; RecordComponentVisitor recordComponentVisitor; MethodVisitor methodVisitor; AnnotationVisitor annotationVisitor0; classWriter.visit(V1_8, ACC_PUBLIC | ACC_SUPER, "com/warmthdawn/mod/gugu_utils/asm/mixin/AMRT", null, "java/lang/Object", null); classWriter.visitSource("AMRT.java", null); classWriter.visitInnerClass("hellfirepvp/modularmachinery/common/tiles/TileMachineController$CraftingStatus", "hellfirepvp/modularmachinery/common/tiles/TileMachineController", "CraftingStatus", ACC_PUBLIC | ACC_STATIC); classWriter.visitInnerClass("hellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext$CraftingCheckResult", "hellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext", "CraftingCheckResult", ACC_PUBLIC | ACC_STATIC); { fieldVisitor = classWriter.visitField(ACC_PRIVATE, "tick", "I", null, null); fieldVisitor.visitEnd(); } { methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); methodVisitor.visitCode(); Label label0 = new Label(); methodVisitor.visitLabel(label0); methodVisitor.visitLineNumber(9, label0); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); Label label1 = new Label(); methodVisitor.visitLabel(label1); methodVisitor.visitLineNumber(10, label1); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(ICONST_0); methodVisitor.visitFieldInsn(PUTFIELD, "com/warmthdawn/mod/gugu_utils/asm/mixin/AMRT", "tick", "I"); methodVisitor.visitInsn(RETURN); Label label2 = new Label(); methodVisitor.visitLabel(label2); methodVisitor.visitLocalVariable("this", "Lcom/warmthdawn/mod/gugu_utils/asm/mixin/AMRT;", null, label0, label2, 0); methodVisitor.visitMaxs(2, 1); methodVisitor.visitEnd(); } { methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "tick", "(Lhellfirepvp/modularmachinery/common/tiles/TileMachineController;Lhellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext;)Lhellfirepvp/modularmachinery/common/tiles/TileMachineController$CraftingStatus;", null, null); methodVisitor.visitCode(); Label label0 = new Label(); methodVisitor.visitLabel(label0); methodVisitor.visitLineNumber(13, label0); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitVarInsn(ALOAD, 1); methodVisitor.visitVarInsn(ALOAD, 2); methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "com/warmthdawn/mod/gugu_utils/asm/mixin/AMRT", "isCompleted", "(Lhellfirepvp/modularmachinery/common/tiles/TileMachineController;Lhellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext;)Z", false); Label label1 = new Label(); methodVisitor.visitJumpInsn(IFEQ, label1); Label label2 = new Label(); methodVisitor.visitLabel(label2); methodVisitor.visitLineNumber(14, label2); methodVisitor.visitMethodInsn(INVOKESTATIC, "hellfirepvp/modularmachinery/common/tiles/TileMachineController$CraftingStatus", "working", "()Lhellfirepvp/modularmachinery/common/tiles/TileMachineController$CraftingStatus;", false); methodVisitor.visitInsn(ARETURN); methodVisitor.visitLabel(label1); methodVisitor.visitLineNumber(18, label1); methodVisitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null); methodVisitor.visitVarInsn(ALOAD, 2); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitFieldInsn(GETFIELD, "com/warmthdawn/mod/gugu_utils/asm/mixin/AMRT", "tick", "I"); methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "hellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext", "ioTick", "(I)Lhellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext$CraftingCheckResult;", false); methodVisitor.visitInsn(DUP); methodVisitor.visitVarInsn(ASTORE, 3); Label label3 = new Label(); methodVisitor.visitLabel(label3); methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "hellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext$CraftingCheckResult", "isFailure", "()Z", false); Label label4 = new Label(); methodVisitor.visitJumpInsn(IFNE, label4); Label label5 = new Label(); methodVisitor.visitLabel(label5); methodVisitor.visitLineNumber(19, label5); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitInsn(DUP); methodVisitor.visitFieldInsn(GETFIELD, "com/warmthdawn/mod/gugu_utils/asm/mixin/AMRT", "tick", "I"); methodVisitor.visitInsn(ICONST_1); methodVisitor.visitInsn(IADD); methodVisitor.visitFieldInsn(PUTFIELD, "com/warmthdawn/mod/gugu_utils/asm/mixin/AMRT", "tick", "I"); Label label6 = new Label(); methodVisitor.visitLabel(label6); methodVisitor.visitLineNumber(20, label6); methodVisitor.visitMethodInsn(INVOKESTATIC, "hellfirepvp/modularmachinery/common/tiles/TileMachineController$CraftingStatus", "working", "()Lhellfirepvp/modularmachinery/common/tiles/TileMachineController$CraftingStatus;", false); methodVisitor.visitInsn(ARETURN); methodVisitor.visitLabel(label4); methodVisitor.visitLineNumber(22, label4); methodVisitor.visitFrame(Opcodes.F_APPEND, 1, new Object[]{"hellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext$CraftingCheckResult"}, 0, null); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitVarInsn(ALOAD, 0); methodVisitor.visitFieldInsn(GETFIELD, "com/warmthdawn/mod/gugu_utils/asm/mixin/AMRT", "tick", "I"); methodVisitor.visitMethodInsn(INVOKESTATIC, "com/warmthdawn/mod/gugu_utils/asm/mixin/MixinActiveMachineRecipe", "inject_tick_onFailure", "(I)I", false); methodVisitor.visitFieldInsn(PUTFIELD, "com/warmthdawn/mod/gugu_utils/asm/mixin/AMRT", "tick", "I"); Label label7 = new Label(); methodVisitor.visitLabel(label7); methodVisitor.visitLineNumber(23, label7); methodVisitor.visitVarInsn(ALOAD, 3); Label label8 = new Label(); methodVisitor.visitLabel(label8); methodVisitor.visitLineNumber(24, label8); methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "hellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext$CraftingCheckResult", "getUnlocalizedErrorMessages", "()Ljava/util/List;", false); methodVisitor.visitLdcInsn(""); methodVisitor.visitMethodInsn(INVOKESTATIC, "com/google/common/collect/Iterables", "getFirst", "(Ljava/lang/Iterable;Ljava/lang/Object;)Ljava/lang/Object;", false); methodVisitor.visitTypeInsn(CHECKCAST, "java/lang/String"); Label label9 = new Label(); methodVisitor.visitLabel(label9); methodVisitor.visitLineNumber(23, label9); methodVisitor.visitMethodInsn(INVOKESTATIC, "hellfirepvp/modularmachinery/common/tiles/TileMachineController$CraftingStatus", "failure", "(Ljava/lang/String;)Lhellfirepvp/modularmachinery/common/tiles/TileMachineController$CraftingStatus;", false); methodVisitor.visitInsn(ARETURN); Label label10 = new Label(); methodVisitor.visitLabel(label10); methodVisitor.visitLocalVariable("this", "Lcom/warmthdawn/mod/gugu_utils/asm/mixin/AMRT;", null, label0, label10, 0); methodVisitor.visitLocalVariable("ctrl", "Lhellfirepvp/modularmachinery/common/tiles/TileMachineController;", null, label0, label10, 1); methodVisitor.visitLocalVariable("context", "Lhellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext;", null, label0, label10, 2); methodVisitor.visitLocalVariable("check", "Lhellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext$CraftingCheckResult;", null, label3, label10, 3); methodVisitor.visitMaxs(3, 4); methodVisitor.visitEnd(); } { methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "isCompleted", "(Lhellfirepvp/modularmachinery/common/tiles/TileMachineController;Lhellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext;)Z", null, null); methodVisitor.visitCode(); Label label0 = new Label(); methodVisitor.visitLabel(label0); methodVisitor.visitLineNumber(29, label0); methodVisitor.visitInsn(ICONST_0); methodVisitor.visitInsn(IRETURN); Label label1 = new Label(); methodVisitor.visitLabel(label1); methodVisitor.visitLocalVariable("this", "Lcom/warmthdawn/mod/gugu_utils/asm/mixin/AMRT;", null, label0, label1, 0); methodVisitor.visitLocalVariable("controller", "Lhellfirepvp/modularmachinery/common/tiles/TileMachineController;", null, label0, label1, 1); methodVisitor.visitLocalVariable("context", "Lhellfirepvp/modularmachinery/common/crafting/helper/RecipeCraftingContext;", null, label0, label1, 2); methodVisitor.visitMaxs(1, 3); methodVisitor.visitEnd(); } classWriter.visitEnd(); return classWriter.toByteArray(); } }
; A167467: a(n) = 25*n^3 - n*(5*n+1)/2 + 1. ; 23,190,652,1559,3061,5308,8450,12637,18019,24746,32968,42835,54497,68104,83806,101753,122095,144982,170564,198991,230413,264980,302842,344149,389051,437698,490240,546827,607609,672736,742358,816625,895687,979694,1068796,1163143,1262885,1368172,1479154,1595981,1718803,1847770,1983032,2124739,2273041,2428088,2590030,2759017,2935199,3118726,3309748,3508415,3714877,3929284,4151786,4382533,4621675,4869362,5125744,5390971,5665193,5948560,6241222,6543329,6855031,7176478,7507820,7849207,8200789,8562716 add $0,1 mul $0,10 mov $1,$0 bin $1,2 sub $1,1 mul $0,$1 mul $0,2 sub $0,880 div $0,40 add $0,23
Name: yst_en_edit.asm Type: file Size: 52334 Last-Modified: '2016-05-13T04:52:56Z' SHA-1: 0695381BE140785420FC08A00D702ADEC9962EBF Description: null
/** * \file NormalGravity.cpp * \brief Implementation for GeographicLib::NormalGravity class * * Copyright (c) Charles Karney (2011-2018) <charles@karney.com> and licensed * under the MIT/X11 License. For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ #include <GeographicLib/NormalGravity.hpp> #if defined(_MSC_VER) // Squelch warnings about constant conditional expressions # pragma warning (disable: 4127) #endif namespace GeographicLib { using namespace std; void NormalGravity::Initialize(real a, real GM, real omega, real f_J2, bool geometricp) { _a = a; if (!(Math::isfinite(_a) && _a > 0)) throw GeographicErr("Equatorial radius is not positive"); _GM = GM; if (!Math::isfinite(_GM)) throw GeographicErr("Gravitational constant is not finite"); _omega = omega; _omega2 = Math::sq(_omega); _aomega2 = Math::sq(_omega * _a); if (!(Math::isfinite(_omega2) && Math::isfinite(_aomega2))) throw GeographicErr("Rotation velocity is not finite"); _f = geometricp ? f_J2 : J2ToFlattening(_a, _GM, _omega, f_J2); _b = _a * (1 - _f); if (!(Math::isfinite(_b) && _b > 0)) throw GeographicErr("Polar semi-axis is not positive"); _J2 = geometricp ? FlatteningToJ2(_a, _GM, _omega, f_J2) : f_J2; _e2 = _f * (2 - _f); _ep2 = _e2 / (1 - _e2); real ex2 = _f < 0 ? -_e2 : _ep2; _Q0 = Qf(ex2, _f < 0); _earth = Geocentric(_a, _f); _E = _a * sqrt(abs(_e2)); // H+M, Eq 2-54 // H+M, Eq 2-61 _U0 = _GM * atanzz(ex2, _f < 0) / _b + _aomega2 / 3; real P = Hf(ex2, _f < 0) / (6 * _Q0); // H+M, Eq 2-73 _gammae = _GM / (_a * _b) - (1 + P) * _a * _omega2; // H+M, Eq 2-74 _gammap = _GM / (_a * _a) + 2 * P * _b * _omega2; // k = gammae * (b * gammap / (a * gammae) - 1) // = (b * gammap - a * gammae) / a _k = -_e2 * _GM / (_a * _b) + _omega2 * (P * (_a + 2 * _b * (1 - _f)) + _a); // f* = (gammap - gammae) / gammae _fstar = (-_f * _GM / (_a * _b) + _omega2 * (P * (_a + 2 * _b) + _a)) / _gammae; } NormalGravity::NormalGravity(real a, real GM, real omega, real f_J2, bool geometricp) { Initialize(a, GM, omega, f_J2, geometricp); } const NormalGravity& NormalGravity::WGS84() { static const NormalGravity wgs84(Constants::WGS84_a(), Constants::WGS84_GM(), Constants::WGS84_omega(), Constants::WGS84_f(), true); return wgs84; } const NormalGravity& NormalGravity::GRS80() { static const NormalGravity grs80(Constants::GRS80_a(), Constants::GRS80_GM(), Constants::GRS80_omega(), Constants::GRS80_J2(), false); return grs80; } Math::real NormalGravity::atan7series(real x) { // compute -sum( (-x)^n/(2*n+7), n, 0, inf) // = -1/7 + x/9 - x^2/11 + x^3/13 ... // = (atan(sqrt(x))/sqrt(x)-(1-x/3+x^2/5)) / x^3 (x > 0) // = (atanh(sqrt(-x))/sqrt(-x)-(1-x/3+x^2/5)) / x^3 (x < 0) // require abs(x) < 1/2, but better to restrict calls to abs(x) < 1/4 static const real lg2eps_ = -log(numeric_limits<real>::epsilon() / 2) / log(real(2)); int e; frexp(x, &e); e = max(-e, 1); // Here's where abs(x) < 1/2 is assumed // x = [0.5,1) * 2^(-e) // estimate n s.t. x^n/n < 1/7 * epsilon/2 // a stronger condition is x^n < epsilon/2 // taking log2 of both sides, a stronger condition is n*(-e) < -lg2eps; // or n*e > lg2eps or n > ceiling(lg2eps/e) int n = int(ceil(lg2eps_ / e)); Math::real v = 0; while (n--) // iterating from n-1 down to 0 v = - x * v - 1/Math::real(2*n + 7); return v; } Math::real NormalGravity::atan5series(real x) { // Compute Taylor series approximations to // (atan(z)-(z-z^3/3))/z^5, // z = sqrt(x) // require abs(x) < 1/2, but better to restrict calls to abs(x) < 1/4 return 1/real(5) + x * atan7series(x); } Math::real NormalGravity::Qf(real x, bool alt) { // Compute // Q(z) = (((1 + 3/z^2) * atan(z) - 3/z)/2) / z^3 // = q(z)/z^3 with q(z) defined by H+M, Eq 2-57 with z = E/u // z = sqrt(x) real y = alt ? -x / (1 + x) : x; return !(4 * abs(y) < 1) ? // Backwards test to allow NaNs through ((1 + 3/y) * atanzz(x, alt) - 3/y) / (2 * y) : (3 * (3 + y) * atan5series(y) - 1) / 6; } Math::real NormalGravity::Hf(real x, bool alt) { // z = sqrt(x) // Compute // H(z) = (3*Q(z)+z*diff(Q(z),z))*(1+z^2) // = (3 * (1 + 1/z^2) * (1 - atan(z)/z) - 1) / z^2 // = q'(z)/z^2, with q'(z) defined by H+M, Eq 2-67, with z = E/u real y = alt ? -x / (1 + x) : x; return !(4 * abs(y) < 1) ? // Backwards test to allow NaNs through (3 * (1 + 1/y) * (1 - atanzz(x, alt)) - 1) / y : 1 - 3 * (1 + y) * atan5series(y); } Math::real NormalGravity::QH3f(real x, bool alt) { // z = sqrt(x) // (Q(z) - H(z)/3) / z^2 // = - (1+z^2)/(3*z) * d(Q(z))/dz - Q(z) // = ((15+9*z^2)*atan(z)-4*z^3-15*z)/(6*z^7) // = ((25+15*z^2)*atan7+3)/10 real y = alt ? -x / (1 + x) : x; return !(4 * abs(y) < 1) ? // Backwards test to allow NaNs through ((9 + 15/y) * atanzz(x, alt) - 4 - 15/y) / (6 * Math::sq(y)) : ((25 + 15*y) * atan7series(y) + 3)/10; } Math::real NormalGravity::Jn(int n) const { // Note Jn(0) = -1; Jn(2) = _J2; Jn(odd) = 0 if (n & 1 || n < 0) return 0; n /= 2; real e2n = 1; // Perhaps this should just be e2n = pow(-_e2, n); for (int j = n; j--;) e2n *= -_e2; return // H+M, Eq 2-92 -3 * e2n * ((1 - n) + 5 * n * _J2 / _e2) / ((2 * n + 1) * (2 * n + 3)); } Math::real NormalGravity::SurfaceGravity(real lat) const { real sphi = Math::sind(Math::LatFix(lat)); // H+M, Eq 2-78 return (_gammae + _k * Math::sq(sphi)) / sqrt(1 - _e2 * Math::sq(sphi)); } Math::real NormalGravity::V0(real X, real Y, real Z, real& GammaX, real& GammaY, real& GammaZ) const { // See H+M, Sec 6-2 real p = Math::hypot(X, Y), clam = p != 0 ? X/p : 1, slam = p != 0 ? Y/p : 0, r = Math::hypot(p, Z); if (_f < 0) swap(p, Z); real Q = Math::sq(r) - Math::sq(_E), t2 = Math::sq(2 * _E * Z), disc = sqrt(Math::sq(Q) + t2), // This is H+M, Eq 6-8a, but generalized to deal with Q negative // accurately. u = sqrt((Q >= 0 ? (Q + disc) : t2 / (disc - Q)) / 2), uE = Math::hypot(u, _E), // H+M, Eq 6-8b sbet = u != 0 ? Z * uE : Math::copysign(sqrt(-Q), Z), cbet = u != 0 ? p * u : p, s = Math::hypot(cbet, sbet); sbet = s != 0 ? sbet/s : 1; cbet = s != 0 ? cbet/s : 0; real z = _E/u, z2 = Math::sq(z), den = Math::hypot(u, _E * sbet); if (_f < 0) { swap(sbet, cbet); swap(u, uE); } real invw = uE / den, // H+M, Eq 2-63 bu = _b / (u != 0 || _f < 0 ? u : _E), // Qf(z2->inf, false) = pi/(4*z^3) q = ((u != 0 || _f < 0 ? Qf(z2, _f < 0) : Math::pi() / 4) / _Q0) * bu * Math::sq(bu), qp = _b * Math::sq(bu) * (u != 0 || _f < 0 ? Hf(z2, _f < 0) : 2) / _Q0, ang = (Math::sq(sbet) - 1/real(3)) / 2, // H+M, Eqs 2-62 + 6-9, but omitting last (rotational) term. Vres = _GM * (u != 0 || _f < 0 ? atanzz(z2, _f < 0) / u : Math::pi() / (2 * _E)) + _aomega2 * q * ang, // H+M, Eq 6-10 gamu = - (_GM + (_aomega2 * qp * ang)) * invw / Math::sq(uE), gamb = _aomega2 * q * sbet * cbet * invw / uE, t = u * invw / uE, gamp = t * cbet * gamu - invw * sbet * gamb; // H+M, Eq 6-12 GammaX = gamp * clam; GammaY = gamp * slam; GammaZ = invw * sbet * gamu + t * cbet * gamb; return Vres; } Math::real NormalGravity::Phi(real X, real Y, real& fX, real& fY) const { fX = _omega2 * X; fY = _omega2 * Y; // N.B. fZ = 0; return _omega2 * (Math::sq(X) + Math::sq(Y)) / 2; } Math::real NormalGravity::U(real X, real Y, real Z, real& gammaX, real& gammaY, real& gammaZ) const { real fX, fY; real Ures = V0(X, Y, Z, gammaX, gammaY, gammaZ) + Phi(X, Y, fX, fY); gammaX += fX; gammaY += fY; return Ures; } Math::real NormalGravity::Gravity(real lat, real h, real& gammay, real& gammaz) const { real X, Y, Z; real M[Geocentric::dim2_]; _earth.IntForward(lat, 0, h, X, Y, Z, M); real gammaX, gammaY, gammaZ, Ures = U(X, Y, Z, gammaX, gammaY, gammaZ); // gammax = M[0] * gammaX + M[3] * gammaY + M[6] * gammaZ; gammay = M[1] * gammaX + M[4] * gammaY + M[7] * gammaZ; gammaz = M[2] * gammaX + M[5] * gammaY + M[8] * gammaZ; return Ures; } Math::real NormalGravity::J2ToFlattening(real a, real GM, real omega, real J2) { // Solve // f = e^2 * (1 - K * e/q0) - 3 * J2 = 0 // for e^2 using Newton's method static const real maxe_ = 1 - numeric_limits<real>::epsilon(); static const real eps2_ = sqrt(numeric_limits<real>::epsilon()) / 100; real K = 2 * Math::sq(a * omega) * a / (15 * GM), J0 = (1 - 4 * K / Math::pi()) / 3; if (!(GM > 0 && Math::isfinite(K) && K >= 0)) return Math::NaN(); if (!(Math::isfinite(J2) && J2 <= J0)) return Math::NaN(); if (J2 == J0) return 1; // Solve e2 - f1 * f2 * K / Q0 - 3 * J2 = 0 for J2 close to J0; // subst e2 = ep2/(1+ep2), f2 = 1/(1+ep2), f1 = 1/sqrt(1+ep2), J2 = J0-dJ2, // Q0 = pi/(4*z^3) - 2/z^4 + (3*pi)/(4*z^5), z = sqrt(ep2), and balance two // leading terms to give real ep2 = max(Math::sq(32 * K / (3 * Math::sq(Math::pi()) * (J0 - J2))), -maxe_), e2 = min(ep2 / (1 + ep2), maxe_); for (int j = 0; j < maxit_ || GEOGRAPHICLIB_PANIC; ++j) { real e2a = e2, ep2a = ep2, f2 = 1 - e2, // (1 - f)^2 f1 = sqrt(f2), // (1 - f) Q0 = Qf(e2 < 0 ? -e2 : ep2, e2 < 0), h = e2 - f1 * f2 * K / Q0 - 3 * J2, dh = 1 - 3 * f1 * K * QH3f(e2 < 0 ? -e2 : ep2, e2 < 0) / (2 * Math::sq(Q0)); e2 = min(e2a - h / dh, maxe_); ep2 = max(e2 / (1 - e2), -maxe_); if (abs(h) < eps2_ || e2 == e2a || ep2 == ep2a) break; } return e2 / (1 + sqrt(1 - e2)); } Math::real NormalGravity::FlatteningToJ2(real a, real GM, real omega, real f) { real K = 2 * Math::sq(a * omega) * a / (15 * GM), f1 = 1 - f, f2 = Math::sq(f1), e2 = f * (2 - f); // H+M, Eq 2-90 + 2-92' return (e2 - K * f1 * f2 / Qf(f < 0 ? -e2 : e2 / f2, f < 0)) / 3; } } // namespace GeographicLib
; A057780: Multiples of 3 that are one less than a perfect square. ; 0,3,15,24,48,63,99,120,168,195,255,288,360,399,483,528,624,675,783,840,960,1023,1155,1224,1368,1443,1599,1680,1848,1935,2115,2208,2400,2499,2703,2808,3024,3135,3363,3480,3720,3843,4095,4224,4488,4623,4899,5040,5328,5475,5775,5928,6240,6399,6723,6888,7224,7395,7743,7920,8280,8463,8835,9024,9408,9603,9999,10200,10608,10815,11235,11448,11880,12099,12543,12768,13224,13455,13923,14160,14640,14883,15375,15624,16128,16383,16899,17160,17688,17955,18495,18768,19320,19599,20163,20448,21024,21315,21903 mul $0,3 div $0,2 mov $1,2 add $1,$0 mul $1,$0 mov $0,$1
#include "mainwindow.h" #include "sender.h" #include "sender2.h" #include "receiver.h" #include <QtDebug> #include <QPushButton> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QPushButton *btn = new QPushButton; btn->setText("按钮"); btn->setFixedSize(100, 40); btn->setParent(this); // connect(btn, &QPushButton::clicked, [](){ // qDebug() << "点击了按钮"; // }); connect(btn, &QPushButton::clicked, this, &MainWindow::handleClick); Sender *sender = new Sender; Sender2 *sender2 = new Sender2; Receiver *receiver = new Receiver; //connect(btn, &QPushButton::clicked, sender2, &Sender2::exit2); // connect(sender, &Sender::exit, // receiver, &Receiver::handleExit); // qDebug() << emit sender->exit(10, 20); //使用Lambda处理信号 // connect(sender, &Sender::exit, [](int n1, int n2){ // qDebug() << "Lambda" << n1 << n2; // }); //emit sender->exit(10, 20); connect(sender2, &Sender2::exit2, [](){ qDebug() << "Lambda"; }); //emit sender->exit2( true); delete sender; delete sender2; delete receiver; } void MainWindow::handleClick() { qDebug() << "点击了按钮-handleClick"; } MainWindow::~MainWindow() { }
; size_t b_array_erase_block_callee(b_array_t *a, size_t idx, size_t n) SECTION code_adt_b_array PUBLIC _b_array_erase_block_callee _b_array_erase_block_callee: pop af pop hl pop bc pop de push af INCLUDE "adt/b_array/z80/asm_b_array_erase_block.asm"
; stdio_out_M ; 07.2009 aralbrec PUBLIC stdio_out_capm EXTERN stdio_numprec, stdio_outcommon INCLUDE "../../stdio.def" ; output %M parameter ; ; EUI-48 / MAC-48 address in paired hex notation ; ; * width and justification applies to entire address ; * # selects '-' separator for bytes ; ; enter : ix = FILE * ; a = precision (default 1) ; b = width (default 0) ; c = flags [-+ O#PLN] ; de = 16-bit parameter (most significant word if long) ; hl = & parameter list ; bc' = total num chars output on stream thus far ; carry flag reset (important for %x, %lx) ; stack = output buffer, ptr in format string, ret ; on exit : bc' = total num chars output on stream thus far ; hl = & parameter list ; carry set if error on stream, ERRNO set appropriately .stdio_out_capm push hl ; save & parameter list push bc ; save width and flags ld hl,STDIO_TEMPBUFSIZE + 7 + 1 add hl,sp ; hl = & last char in temporary buffer + 1 ld a,6 ; six bytes in MAC address ld bc,16 ; 0 chars in buffer, radix = 16 .loop dec hl push af ; save loop counter push de ; save mac address pointer ld a,(de) ld e,a ld d,0 ; de = byte for output ld a,2 ; precision is two for byte call stdio_numprec ; output hex byte to buffer pop de ; de = mac address pointer pop af ; a = loop counter dec a jr z, exit_loop inc de ; next byte in mac address ld (hl),':' ; write byte separator inc b ; number of chars in temp buffer++ bit 3,c ; confirm default separator is selected jp z, loop ld (hl),'-' ; use alternate byte separator jp loop .exit_loop ; now output buffer onto stream with width and justification applied pop de ; d = width, e = flags [-+ O#PLN] call stdio_outcommon pop hl ; hl = & parameter list ret
; A246134: Binomial(2n, n) - 2 mod n^4. ; Submitted by Jamie Morken(s1.) ; 0,4,18,68,250,922,1029,580,2691,4754,2662,8474,4394,10294,2518,49732,29478,65074,123462,128818,6535,93174,36501,12058,187750,162582,297936,273782,536558,741422,59582,16964,118477,540434,132305,136130,1114366,1138598,2214594,2381618,1860867,2795686,1828661,1775622,2683618,1435710,1557345,3882778,1179920,6247254,3281902,7157894,3424171,563710,3201305,6872182,8834410,8633710,11706603,5212654,11576031,10665182,4083670,9716292,1887473,7379986,14436624,4392290,21048928,11746598,25053770,7749826 mov $1,1 add $1,$0 add $0,$1 bin $0,$1 mul $0,2 sub $0,2 pow $1,4 mod $0,$1
<% from pwnlib.shellcraft.aarch64.linux import syscall %> <%page args="pipedes, flags"/> <%docstring> Invokes the syscall pipe2. See 'man 2 pipe2' for more information. Arguments: pipedes(int): pipedes flags(int): flags </%docstring> ${syscall('SYS_pipe2', pipedes, flags)}
; A017591: (12n+5)^11. ; 48828125,34271896307633,12200509765705829,550329031716248441,9269035929372191597,87507831740087890625,564154396389137449973,2775173073766990340489,11156683466653165551101,38358611506121121577937 mul $0,12 add $0,5 pow $0,11
; A328881: a(n+3) = 2^n - a(n), a(0)=a(2)=1, a(1)=0 for n >= 0. ; 1,0,1,0,2,3,8,14,29,56,114,227,456,910,1821,3640,7282,14563,29128,58254,116509,233016,466034,932067,1864136,3728270,7456541,14913080,29826162,59652323,119304648,238609294,477218589,954437176,1908874354,3817748707,7635497416,15270994830,30541989661,61083979320,122167958642,244335917283,488671834568,977343669134,1954687338269,3909374676536,7818749353074,15637498706147,31274997412296,62549994824590,125099989649181,250199979298360,500399958596722,1000799917193443,2001599834386888,4003199668773774,8006399337547549,16012798675095096,32025597350190194,64051194700380387,128102389400760776,256204778801521550,512409557603043101,1024819115206086200,2049638230412172402,4099276460824344803,8198552921648689608,16397105843297379214,32794211686594758429,65588423373189516856,131176846746379033714,262353693492758067427,524707386985516134856,1049414773971032269710,2098829547942064539421,4197659095884129078840,8395318191768258157682,16790636383536516315363,33581272767073032630728,67162545534146065261454,134325091068292130522909,268650182136584261045816,537300364273168522091634,1074600728546337044183267,2149201457092674088366536,4298402914185348176733070,8596805828370696353466141,17193611656741392706932280,34387223313482785413864562,68774446626965570827729123,137548893253931141655458248,275097786507862283310916494,550195573015724566621832989,1100391146031449133243665976,2200782292062898266487331954,4401564584125796532974663907,8803129168251593065949327816,17606258336503186131898655630,35212516673006372263797311261,70425033346012744527594622520 mov $1,$0 add $0,1 mov $2,2 pow $2,$1 sub $2,$1 lpb $0 mod $0,2 lpe add $1,$2 lpb $1 div $1,9 add $1,$0 mov $0,$1 lpe
; A192217: a(1)=1; a(n) = n*lcm(n, a(n-1)) for n > 1. ; Submitted by Jamie Morken(l1) ; 1,4,36,144,3600,21600,1058400,8467200,76204800,762048000,92207808000,1106493696000,186997434624000,2617964084736000,39269461271040000,628311380336640000,181581988917288960000,3268475800511201280000,1179919763984543662080000,23598395279690873241600000,495566300873508338073600000,10902458619217183437619200000,5767400609565890038500556800000,138417614629581360924013363200000,3460440365739534023100334080000000,89971449509227884600608686080000000,2429229136749152884216434524160000000 mov $2,$0 mov $0,1 mov $1,1 lpb $2 add $1,1 dif $0,$1 mul $0,$1 mul $0,$1 sub $2,1 lpe
GetHardwareVer: call BankSwapper_INIT ;D= 0=msx 1=MSX2 2=MSX2+ 3=TurboR 4=WSX ;E= 0= No memory Mapper / 1=has memory mapper with 128k+ di ld a,(&002D) ld d,a ld e,0 cp 2 jr nz,GetHardwareVerSwappertest ld a,8 out (64),a ;Get current device id in a,(64) cp 247 ;247=CPL of 8 jr nz,GetHardwareVerSwappertest ld d,4 GetHardwareVerSwappertest: ;FCH to FFH memory mapper for banks 1-4 ld a,&69 ld (&C000),a ld a,4 out (&FF),a ;Switch to bank 4 in top bank ld a,(&C000) cp &69 ;Did it work? ret z ld a,&69 ld (&C000),a ld a,(&C000) cp &69 ;is the current bank writable ret nz ;if no then we don't have extra ram xor a out (&FF),a ;Yes we have a 128k memory mapper! inc e ret CHGCPU equ &0180 ;Turbo R ON EnableFastCPU: ;Kick in the turbo-R ld A,(CHGCPU) cp &C3 ;See if this is a Turbo-R ld a,&82 jp z,CHGCPU ;Call the 'Turbo' Firmware function ;Panasonic FS-A1WX turbo mode ld a,(&002D) cp 2 ;See if we're on a MSX2+ ret nz ;No? then give up ld a,8 out (64),a ;See if this is a WSX in a,(64) cp 247 ;CPL of the 8 we sent ret nz ;No? then return xor a out (65),a ;Turn on 6mhz ret
# mp_limb_t mulredc5(mp_limb_t * z, const mp_limb_t * x, const mp_limb_t * y, # const mp_limb_t *m, mp_limb_t inv_m); # # Stack: # inv_m ## parameters # m # y # x # z (4*(2k+7))%esp # ??? (1 limb???) # ebp ## pushed registers (4*(2k+5))%esp # edi # esi # ebx # ... ## counter (1 mp_limb_t) (4*(2k+1))%esp # ... ## tmp space (2*k+1 mp_limb_t) include(`config.m4') TEXT GLOBL GSYM_PREFIX`'mulredc5 TYPE(GSYM_PREFIX`'mulredc5,`function') GSYM_PREFIX`'mulredc5: pushl %ebp pushl %edi pushl %esi pushl %ebx subl $48, %esp movl %esp, %edi ### set tmp[0..2k+1[ to 0 movl $0, (%edi) movl $0, 4(%edi) movl $0, 8(%edi) movl $0, 12(%edi) movl $0, 16(%edi) movl $0, 20(%edi) movl $0, 24(%edi) movl $0, 28(%edi) movl $0, 32(%edi) movl $0, 36(%edi) movl $0, 40(%edi) ########################################### movl $5, 44(%esp) .align 32 Loop: ## compute u and store in %ebp movl 72(%esp), %eax movl 76(%esp), %esi movl (%eax), %eax mull (%esi) addl (%edi), %eax mull 84(%esp) movl %eax, %ebp movl 80(%esp), %esi ### addmul1: src[0] is (%esi) ### dst[0] is (%edi) ### mult is %ebp ### k is 5 ### kills %eax, %edx and mmx regs ### dst[0,k[ += mult*src[0,k[ plus carry put in ecx pxor %mm0, %mm0 movd %ebp, %mm7 movd (%esi), %mm1 movd (%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, (%edi) psrlq $32, %mm0 movd 4(%esi), %mm1 movd 4(%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, 4(%edi) psrlq $32, %mm0 movd 8(%esi), %mm1 movd 8(%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, 8(%edi) psrlq $32, %mm0 movd 12(%esi), %mm1 movd 12(%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, 12(%edi) psrlq $32, %mm0 movd 16(%esi), %mm1 movd 16(%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, 16(%edi) psrlq $32, %mm0 movd %mm0, %ecx ### carry limb is in %ecx addl %ecx, 20(%edi) adcl $0, 24(%edi) movl 72(%esp), %eax movl (%eax), %ebp movl 76(%esp), %esi ### addmul1: src[0] is (%esi) ### dst[0] is (%edi) ### mult is %ebp ### k is 5 ### kills %eax, %edx and mmx regs ### dst[0,k[ += mult*src[0,k[ plus carry put in ecx pxor %mm0, %mm0 movd %ebp, %mm7 movd (%esi), %mm1 movd (%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, (%edi) psrlq $32, %mm0 movd 4(%esi), %mm1 movd 4(%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, 4(%edi) psrlq $32, %mm0 movd 8(%esi), %mm1 movd 8(%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, 8(%edi) psrlq $32, %mm0 movd 12(%esi), %mm1 movd 12(%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, 12(%edi) psrlq $32, %mm0 movd 16(%esi), %mm1 movd 16(%edi), %mm2 pmuludq %mm7, %mm1 paddq %mm1, %mm2 paddq %mm2, %mm0 movd %mm0, 16(%edi) psrlq $32, %mm0 movd %mm0, %ecx ### carry limb is in %ecx addl %ecx, 20(%edi) adcl $0, 24(%edi) addl $4, 72(%esp) addl $4, %edi decl 44(%esp) jnz Loop ########################################### ### Copy result in z movl 68(%esp), %ebx movl (%edi), %eax movl %eax, (%ebx) movl 4(%edi), %eax movl %eax, 4(%ebx) movl 8(%edi), %eax movl %eax, 8(%ebx) movl 12(%edi), %eax movl %eax, 12(%ebx) movl 16(%edi), %eax movl %eax, 16(%ebx) movl 20(%edi), %eax # carry addl $48, %esp popl %ebx popl %esi popl %edi popl %ebp emms ret
; A344721: a(n) = Sum_{k=1..n} (-1)^(k+1) * floor(n/k)^3. ; Submitted by Christian Krause ; 1,7,27,56,118,196,324,448,685,901,1233,1549,2019,2445,3157,3664,4482,5262,6290,7128,8536,9598,11118,12392,14255,15743,18087,19711,22149,24417,27209,29251,32771,35327,39087,42048,46046,49244,54180,57512,62434,66838,72258,76246,83116,87814,94302,99414,106599,112365,120853,126419,134689,141949,151253,157675,168299,175787,186055,194559,205541,214103,227447,235632,248644,259480,272748,282262,297878,309434,324346,336040,351810,364026,383190,395074,413090,428222,446710,460024,481809,496821,517241 add $0,1 mov $2,$0 lpb $0 max $0,1 mul $1,-1 mov $3,$2 div $3,$0 sub $0,1 pow $3,3 add $1,$3 lpe mov $0,$1
SECTION code_clib SECTION code_l PUBLIC l_hex_nibble PUBLIC l_hex_nibble_hi, l_hex_nibble_lo l_hex_nibble_hi: ; translate top nibble of byte into a uppercase ascii hex digit ; ; enter : a = number ; ; exit : a = hex character representing top nibble of number ; ; uses : af rra rra rra rra l_hex_nibble: l_hex_nibble_lo: ; translate bottom nibble of byte into a uppercase ascii hex digit ; ; enter : a = number ; ; exit : a = hex character representing bottom nibble of number ; ; uses : af or $f0 daa add a,$a0 adc a,$40 ret
/* -- MAGMA (version 2.1.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date August 2016 @precisions normal z -> s d c @author Hartwig Anzt */ #include "magmasparse_internal.h" #define RTOLERANCE lapackf77_dlamch( "E" ) #define ATOLERANCE lapackf77_dlamch( "E" ) /** Purpose ------- Solves a system of linear equations A * X = B where A is a complex N-by-N general matrix. This is a GPU implementation of the preconditioned Biconjugate Gradient Stabelized method. Arguments --------- @param[in] A magma_z_matrix input matrix A @param[in] b magma_z_matrix RHS b @param[in,out] x magma_z_matrix* solution approximation @param[in,out] solver_par magma_z_solver_par* solver parameters @param[in] precond_par magma_z_preconditioner* preconditioner parameters @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_zgesv ********************************************************************/ extern "C" magma_int_t magma_zpbicgstab( magma_z_matrix A, magma_z_matrix b, magma_z_matrix *x, magma_z_solver_par *solver_par, magma_z_preconditioner *precond_par, magma_queue_t queue ) { magma_int_t info = MAGMA_NOTCONVERGED; // prepare solver feedback solver_par->solver = Magma_PBICGSTAB; solver_par->numiter = 0; solver_par->spmv_count = 0; // some useful variables magmaDoubleComplex c_zero = MAGMA_Z_ZERO; magmaDoubleComplex c_one = MAGMA_Z_ONE; magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE; magma_int_t dofs = A.num_rows*b.num_cols; // workspace magma_z_matrix r={Magma_CSR}, rr={Magma_CSR}, p={Magma_CSR}, v={Magma_CSR}, s={Magma_CSR}, t={Magma_CSR}, ms={Magma_CSR}, mt={Magma_CSR}, y={Magma_CSR}, z={Magma_CSR}; CHECK( magma_zvinit( &r, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &rr,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &p, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &v, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &s, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &t, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &ms,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &mt,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &y, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &z, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); // solver variables magmaDoubleComplex alpha, beta, omega, rho_old, rho_new; double betanom, nom0, r0, res, nomb; res=0; //double den; // solver setup CHECK( magma_zresidualvec( A, b, *x, &r, &nom0, queue)); magma_zcopy( dofs, r.dval, 1, rr.dval, 1, queue ); // rr = r betanom = nom0; rho_new = omega = alpha = MAGMA_Z_MAKE( 1.0, 0. ); solver_par->init_res = nom0; nomb = magma_dznrm2( dofs, b.dval, 1, queue ); if ( nomb == 0.0 ){ nomb=1.0; } if ( (r0 = nomb * solver_par->rtol) < ATOLERANCE ){ r0 = ATOLERANCE; } solver_par->final_res = solver_par->init_res; solver_par->iter_res = solver_par->init_res; if ( solver_par->verbose > 0 ) { solver_par->res_vec[0] = nom0; solver_par->timing[0] = 0.0; } if ( nomb < r0 ) { info = MAGMA_SUCCESS; goto cleanup; } //Chronometry real_Double_t tempo1, tempo2; tempo1 = magma_sync_wtime( queue ); solver_par->numiter = 0; solver_par->spmv_count = 0; // start iteration do { solver_par->numiter++; rho_old = rho_new; // rho_old=rho rho_new = magma_zdotc( dofs, rr.dval, 1, r.dval, 1, queue ); // rho=<rr,r> beta = rho_new/rho_old * alpha/omega; // beta=rho/rho_old *alpha/omega if( magma_z_isnan_inf( beta ) ){ info = MAGMA_DIVERGENCE; break; } magma_zscal( dofs, beta, p.dval, 1, queue ); // p = beta*p magma_zaxpy( dofs, c_neg_one * omega * beta, v.dval, 1 , p.dval, 1, queue ); // p = p-omega*beta*v magma_zaxpy( dofs, c_one, r.dval, 1, p.dval, 1, queue ); // p = p+r // preconditioner CHECK( magma_z_applyprecond_left( MagmaNoTrans, A, p, &mt, precond_par, queue )); CHECK( magma_z_applyprecond_right( MagmaNoTrans, A, mt, &y, precond_par, queue )); CHECK( magma_z_spmv( c_one, A, y, c_zero, v, queue )); // v = Ap solver_par->spmv_count++; alpha = rho_new / magma_zdotc( dofs, rr.dval, 1, v.dval, 1, queue ); if( magma_z_isnan_inf( alpha ) ){ info = MAGMA_DIVERGENCE; break; } magma_zcopy( dofs, r.dval, 1 , s.dval, 1, queue ); // s=r magma_zaxpy( dofs, c_neg_one * alpha, v.dval, 1 , s.dval, 1, queue ); // s=s-alpha*v // preconditioner CHECK( magma_z_applyprecond_left( MagmaNoTrans, A, s, &ms, precond_par, queue )); CHECK( magma_z_applyprecond_right( MagmaNoTrans, A, ms, &z, precond_par, queue )); CHECK( magma_z_spmv( c_one, A, z, c_zero, t, queue )); // t=As solver_par->spmv_count++; // omega = <s,t>/<t,t> omega = magma_zdotc( dofs, t.dval, 1, s.dval, 1, queue ) / magma_zdotc( dofs, t.dval, 1, t.dval, 1, queue ); magma_zaxpy( dofs, alpha, y.dval, 1 , x->dval, 1, queue ); // x=x+alpha*p magma_zaxpy( dofs, omega, z.dval, 1 , x->dval, 1, queue ); // x=x+omega*s magma_zcopy( dofs, s.dval, 1 , r.dval, 1, queue ); // r=s magma_zaxpy( dofs, c_neg_one * omega, t.dval, 1 , r.dval, 1, queue ); // r=r-omega*t res = betanom = magma_dznrm2( dofs, r.dval, 1, queue ); if ( solver_par->verbose > 0 ) { tempo2 = magma_sync_wtime( queue ); if ( (solver_par->numiter)%solver_par->verbose==0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) res; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } if ( res/nomb <= solver_par->rtol || res <= solver_par->atol ){ break; } } while ( solver_par->numiter+1 <= solver_par->maxiter ); tempo2 = magma_sync_wtime( queue ); solver_par->runtime = (real_Double_t) tempo2-tempo1; double residual; CHECK( magma_zresidualvec( A, b, *x, &r, &residual, queue)); solver_par->final_res = residual; solver_par->iter_res = res; if ( solver_par->numiter < solver_par->maxiter && info == MAGMA_SUCCESS ) { info = MAGMA_SUCCESS; } else if ( solver_par->init_res > solver_par->final_res ) { if ( solver_par->verbose > 0 ) { if ( (solver_par->numiter)%solver_par->verbose==0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) betanom; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } info = MAGMA_SLOW_CONVERGENCE; if( solver_par->iter_res < solver_par->rtol*solver_par->init_res || solver_par->iter_res < solver_par->atol ) { info = MAGMA_SUCCESS; } } else { if ( solver_par->verbose > 0 ) { if ( (solver_par->numiter)%solver_par->verbose==0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) betanom; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } info = MAGMA_DIVERGENCE; } cleanup: magma_zmfree(&r, queue ); magma_zmfree(&rr, queue ); magma_zmfree(&p, queue ); magma_zmfree(&v, queue ); magma_zmfree(&s, queue ); magma_zmfree(&t, queue ); magma_zmfree(&ms, queue ); magma_zmfree(&mt, queue ); magma_zmfree(&y, queue ); magma_zmfree(&z, queue ); solver_par->info = info; return info; } /* magma_zbicgstab */
INCLUDE "data/bg_map_attributes.asm" LoadBGMapAttributes:: ld hl, BGMapAttributesPointers ld a, c ; c = which packet push af ; save for later (to determine if we're handling the trainer card or party menu) dec a ; read this code as: add a ; dec a ld e, a ; add a xor a ; ld e, a ld d, a ; ld d, 0 add hl, de ; add hl, de ld a, [hli] ; ld a, [hli] ld e, a ; ld h, [hl] ld a, [hl] ; ld l, a ld h, a ld a, e ld l, a di ld a, $1 ld [rVBK], a push hl ld a, [hl] ld c, a ; save attribute count for later ld de, $10 add hl, de ld a, h ld [rHDMA1], a ld a, l ld [rHDMA2], a ld de, vBGMap0 ld a, d ld [rHDMA3], a ld a, e ld [rHDMA4], a ld a, [rLCDC] and rLCDC_ENABLE_MASK ; is LCD off? jr z, .lcdOff ; if off, transfer immediately ; wait for VBlank if LCD is on .waitForVBlankLoop1 ld a, [rLY] cp $90 jr nz, .waitForVBlankLoop1 .waitForAccessibleVRAMLoop1 ld a, [rSTAT] and %10 ; are we in HBlank or VBlank? jr nz, .waitForAccessibleVRAMLoop1 ; loop until we're in a safe period to transfer to VRAM .lcdOff ld a, c ; number of BG attributes to transfer, plus 1 times 16 ld [rHDMA5], a ; initiate transfer call Func_3082 ; update audio so it doesn't "lag" pop hl ld a, [hli] ld c, a ; number of BG attributes to transfer, plus 1 times 16 ld a, [hli] ld e, a ld a, [hli] ld d, a ; offset of the attributes add hl, de ; hl = new pointer ld a, h ld [rHDMA1], a ld a, l ld [rHDMA2], a ld de, vBGMap1 ; copy to vBGMap1 ld a, d ld [rHDMA3], a ld a, e ld [rHDMA4], a ; LCD check again ld a, [rLCDC] and rLCDC_ENABLE_MASK ; is LCD off? jr z, .lcdOff2 ; if off, transfer immediately ; wait for VBlank if LCD is on .waitForVBlankLoop2 ld a, [rLY] cp $90 jr nz, .waitForVBlankLoop2 .waitForAccessibleVRAMLoop2 ld a, [rSTAT] and %10 ; are we in HBlank or VBlank? jr nz, .waitForAccessibleVRAMLoop2 ; loop until we're in a safe period to transfer to VRAM .lcdOff2 ld a, c ld [rHDMA5], a pop af dec a dec a dec a dec a jr nz, .checkIfHandlingPartyMenu call HandleBadgeFaceAttributes jr .done .checkIfHandlingPartyMenu dec a call z, HandlePartyHPBarAttributes .done call Func_3082 ld a, [rIF] res VBLANK, a ld [rIF], a xor a ld [rVBK], a ei ret BGMapAttributesPointers: dw BGMapAttributes_Unknown1 dw BGMapAttributes_Unknown2 dw BGMapAttributes_GameFreakIntro dw BGMapAttributes_TrainerCard dw BGMapAttributes_PartyMenu dw BGMapAttributes_NidorinoIntro dw BGMapAttributes_TitleScreen dw BGMapAttributes_Slots dw BGMapAttributes_Pokedex dw BGMapAttributes_StatusScreen dw BGMapAttributes_Battle dw BGMapAttributes_WholeScreen dw BGMapAttributes_Unknown13 dw BGMapAttributes_BattleGBC HandleBadgeFaceAttributes: ; zero out the attributes if the player doesn't have the respective badge ; BOULDERBADGE ld hl, vBGMap1 + $183 ld de, wTrainerCardBadgeAttributes + 6 * 0 ld a, [de] and a call z, ZeroOutCurrentBadgeAttributes ; CASCADEBADGE ld hl, vBGMap1 + $187 ld de, wTrainerCardBadgeAttributes + 6 * 1 ld a, [de] and a call z, ZeroOutCurrentBadgeAttributes ; THUNDERBADGE ld hl, vBGMap1 + $18b ld de, wTrainerCardBadgeAttributes + 6 * 2 ld a, [de] and a call z, ZeroOutCurrentBadgeAttributes ; RAINBOWBADGE ld hl, vBGMap1 + $18f ld de, wTrainerCardBadgeAttributes + 6 * 3 ld a, [de] and a call z, ZeroOutCurrentBadgeAttributes ; SOULBADGE ld hl, vBGMap1 + $1e3 ld de, wTrainerCardBadgeAttributes + 6 * 6 ld a, [de] and a call z, ZeroOutCurrentBadgeAttributes ; MARSHBADGE ld hl, vBGMap1 + $1e7 ld de, wTrainerCardBadgeAttributes + 6 * 7 ld a, [de] and a call z, ZeroOutCurrentBadgeAttributes ; VOLCANOBADGE ld hl, vBGMap1 + $1eb ld de, wTrainerCardBadgeAttributes + 6 * 8 ld a, [de] and a call z, ZeroOutCurrentBadgeAttributes ; EARTHBADGE ld hl, vBGMap1 + $1ef ld de, wTrainerCardBadgeAttributes + 6 * 9 ld a, [de] and a call z, ZeroOutCurrentBadgeAttributes ret ZeroOutCurrentBadgeAttributes: push hl xor a ld [hli], a ld [hl], a ld bc, $1f add hl, bc ld [hli], a ld [hl], a pop hl ret HandlePartyHPBarAttributes: ; hp bars require 3 (green, orange, red) colours, when there are only 2 "free" colours per palette ; therefore, we must transfer individual bg attributes where the locations of the hp bars are in vram ld hl, vBGMap1 + $25 ; location of start of the HP bar in vram ld de, wPartyHPBarAttributes ld c, PARTY_LENGTH .loop push bc push hl ld a, [de] and $3 ; 4 possible palettes rept 7 ; hp bar length in tiles ld [hli], a endr pop hl ld bc, $40 ; get 2nd party location add hl, bc push hl push de ; (inefficiently) copy de to hl pop hl ld bc, $6 add hl, bc ; get the next palette push hl pop de ; copy back to de pop hl pop bc dec c jr nz, .loop ret
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r13 push %r8 push %rax push %rcx push %rdi push %rsi lea addresses_normal_ht+0x1aadd, %rax nop xor $2381, %r13 mov (%rax), %r8d nop nop nop nop nop add %r11, %r11 lea addresses_UC_ht+0x122c9, %rax nop nop nop sub $11917, %r13 movl $0x61626364, (%rax) nop nop nop nop nop xor $57458, %r11 lea addresses_D_ht+0xed5b, %rsi lea addresses_WT_ht+0xb1dd, %rdi nop nop xor $59082, %r11 mov $97, %rcx rep movsw nop nop nop inc %r13 lea addresses_A_ht+0x1665d, %rsi lea addresses_normal_ht+0x8ef, %rdi nop nop nop nop nop inc %r11 mov $96, %rcx rep movsq nop nop nop nop nop sub $25409, %rsi lea addresses_A_ht+0xc5ad, %r11 nop nop nop add %rsi, %rsi mov (%r11), %rdi inc %r8 lea addresses_normal_ht+0x5a3d, %r10 nop lfence movl $0x61626364, (%r10) nop nop nop inc %r13 lea addresses_A_ht+0x1d1dd, %r10 xor %rdi, %rdi mov (%r10), %esi nop nop nop nop nop dec %r11 lea addresses_A_ht+0xb625, %rsi lea addresses_normal_ht+0xee5d, %rdi nop nop nop nop nop sub $5259, %rax mov $67, %rcx rep movsl cmp %rcx, %rcx lea addresses_WC_ht+0xe85d, %rdi and %r8, %r8 movw $0x6162, (%rdi) nop nop nop add %rdi, %rdi lea addresses_WT_ht+0xea5d, %rsi nop nop nop sub $23467, %r13 movw $0x6162, (%rsi) nop nop dec %r11 pop %rsi pop %rdi pop %rcx pop %rax pop %r8 pop %r13 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r9 push %rax push %rbx push %rcx // Store lea addresses_WT+0x937d, %rcx nop nop nop xor %r13, %r13 mov $0x5152535455565758, %rbx movq %rbx, (%rcx) nop xor %r14, %r14 // Faulty Load lea addresses_UC+0x15d, %r13 nop nop cmp $19717, %rax mov (%r13), %r9 lea oracles, %rax and $0xff, %r9 shlq $12, %r9 mov (%rax,%r9,1), %r9 pop %rcx pop %rbx pop %rax pop %r9 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': True, 'type': 'addresses_UC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WT'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 4, 'NT': True, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 0, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 2, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_normal_ht'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WT_ht'}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
#include "pch.h" #include "CppUnitTest.h" #include "core/collection/Bag.h" #include "core/collection/Stack.h" #include "TestUtils.h" #include <iostream> #include <vector> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTest { using namespace Ghurund::Core; using namespace std; struct TestClass { uint32_t val = 5; const char* text = "text"; }; TEST_CLASS(BagTest) { public: TEST_METHOD(Bag_constructor) { { Bag<uint32_t> bag; Assert::AreEqual(bag.Size, (size_t)0); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, true); } _____________________checkMemory(); { Bag<TestClass> bag; Assert::AreEqual(bag.Size, (size_t)0); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, true); } _____________________checkMemory(); } TEST_METHOD(Bag_constructor_initial) { { Bag<uint32_t> bag(20); Assert::AreEqual(bag.Size, (size_t)0); Assert::AreEqual(bag.Capacity, (size_t)20); Assert::AreEqual(bag.Empty, true); } _____________________checkMemory(); { Bag<TestClass> bag(20); Assert::AreEqual(bag.Size, (size_t)0); Assert::AreEqual(bag.Capacity, (size_t)20); Assert::AreEqual(bag.Empty, true); } _____________________checkMemory(); } TEST_METHOD(Bag_constructor_copy) { Bag<uint32_t> testBag = { 1, 2, 3 }; Bag<uint32_t> bag = Bag<uint32_t>(testBag); Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_constructor_move) { Bag<uint32_t> testBag = { 1, 2, 3 }; Bag<uint32_t> bag = std::move(testBag); Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_constructor_initializer) { Bag<uint32_t> bag = { 1, 2, 3 }; Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_constructor_initializerWithDuplicates) { Bag<uint32_t> bag = { 1, 2, 3, 2, 1 }; Assert::AreEqual(bag.Size, (size_t)5); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_referenceAssignment) { Stack<uint32_t> testStack = { 1, 2, 3 }; Bag<uint32_t> bag; bag = testStack; Assert::AreEqual(bag.Size, testStack.Size); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_setReferenceAssignment) { Bag<uint32_t> testBag = { 1, 2, 3 }; Bag<uint32_t> bag; bag = testBag; Assert::AreEqual(bag.Size, testBag.Size); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_moveAssignment) { Bag<uint32_t> testBag = { 1, 2, 3 }; Bag<uint32_t> bag; bag = std::move(testBag); Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_initializerAssignment) { { Bag<uint32_t> bag; bag = { 1, 2, 3 }; Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); } _____________________checkMemory(); } TEST_METHOD(TestBagAdd) { Bag<uint32_t> bag; bag.add(1); Assert::AreEqual(bag.Size, (size_t)1); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1 })); _____________________checkMemory(); } TEST_METHOD(TestBagAddAllInitializer) { Bag<uint32_t> bag; bag.addAll({ 1, 2, 3 }); Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_addAll_Bag) { Bag<uint32_t> bag; const Bag<uint32_t> testBag = { 1, 2, 3 }; bag.addAll(testBag); Assert::AreEqual(testBag.Size, (size_t)3); Assert::AreEqual(testBag.Capacity >= bag.Size, true); Assert::AreEqual(testBag.Empty, false); Assert::IsTrue(collectionContains(testBag, { 1, 2, 3 })); Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); Assert::AreEqual(bag.Size, testBag.Size); _____________________checkMemory(); } TEST_METHOD(Bag_addAll_ListDuplicates) { Bag<uint32_t> bag; const List<uint32_t> testList = { 1, 2, 3, 2, 1 }; bag.addAll(testList); Assert::AreEqual(testList.Size, (size_t)5); Assert::AreEqual(testList.Capacity >= bag.Size, true); Assert::AreEqual(testList.Empty, false); Assert::IsTrue(collectionContains(testList, { 1, 2, 3 })); Assert::AreEqual(bag.Size, (size_t)5); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 2, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_remove) { Bag<uint32_t> bag = { 1, 2, 3 }; bag.remove(2); Assert::AreEqual(bag.Size, (size_t)2); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, { 1, 3 })); _____________________checkMemory(); } TEST_METHOD(Bag_iterator) { { std::vector<uint32_t> testVector = { 1, 2, 3 }; Bag<uint32_t> bag = { 1, 2, 3 }; Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, testVector)); } { std::vector<uint32_t> testVector = { 1, 2, 3 }; const Bag<uint32_t> bag = { 1, 2, 3 }; Assert::AreEqual(bag.Size, (size_t)3); Assert::AreEqual(bag.Capacity >= bag.Size, true); Assert::AreEqual(bag.Empty, false); Assert::IsTrue(collectionContains(bag, testVector)); } _____________________checkMemory(); } TEST_METHOD(Bag_contains) { { Bag<uint32_t> bag = { 1, 2, 3 }; Assert::IsTrue(bag.contains(1)); Assert::IsFalse(bag.contains(4)); } { const Bag<uint32_t> bag = { 1, 2, 3 }; Assert::IsTrue(bag.contains(1)); Assert::IsFalse(bag.contains(4)); } _____________________checkMemory(); } TEST_METHOD(Bag_comparison) { Bag<uint32_t> bag = { 1, 2, 3 }; Bag<uint32_t> bag2 = { 1, 2, 3 }; Assert::IsTrue(bag == bag2); _____________________checkMemory(); } }; }
SFX_Cry02_2_Ch5: duty_cycle 0 square_note 8, 15, 5, 1152 square_note 2, 14, 1, 1504 square_note 8, 13, 1, 1500 sound_ret SFX_Cry02_2_Ch6: duty_cycle_pattern 2, 2, 1, 1 square_note 7, 9, 5, 1089 square_note 2, 8, 1, 1313 square_note 8, 6, 1, 1306 SFX_Cry02_2_Ch8: sound_ret
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r14 push %r8 push %rbx push %rcx push %rdi push %rsi lea addresses_WT_ht+0x944, %r8 nop nop nop nop nop sub %r10, %r10 movl $0x61626364, (%r8) nop and %r14, %r14 lea addresses_WT_ht+0x6024, %rcx nop nop nop nop xor %rsi, %rsi movl $0x61626364, (%rcx) nop nop nop and %rcx, %rcx lea addresses_D_ht+0x14554, %rcx clflush (%rcx) nop nop nop nop dec %r8 mov (%rcx), %esi nop nop nop and %r12, %r12 lea addresses_UC_ht+0x16154, %rbx and %r10, %r10 vmovups (%rbx), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $1, %xmm3, %r14 nop nop nop nop nop add $30529, %r12 lea addresses_D_ht+0x11b54, %rsi nop nop nop nop nop inc %r14 movb $0x61, (%rsi) nop nop and %r14, %r14 lea addresses_WT_ht+0x17d54, %r8 nop nop cmp $5752, %rcx mov (%r8), %r12 nop nop nop add $9021, %r12 lea addresses_WT_ht+0xc940, %r12 nop nop nop nop nop xor %r14, %r14 movb (%r12), %r8b nop inc %rbx lea addresses_WC_ht+0xcc24, %r12 clflush (%r12) nop nop nop nop nop sub $40824, %r8 movups (%r12), %xmm1 vpextrq $0, %xmm1, %r14 nop nop nop nop xor %r8, %r8 lea addresses_WT_ht+0x4d14, %r10 nop nop nop nop nop and $44661, %r14 movl $0x61626364, (%r10) nop and $55073, %r8 lea addresses_WT_ht+0x16854, %rsi nop nop nop nop cmp $10249, %rcx movups (%rsi), %xmm5 vpextrq $0, %xmm5, %rbx nop nop nop nop and %r12, %r12 lea addresses_normal_ht+0x1bdda, %r10 nop nop nop nop dec %r14 mov $0x6162636465666768, %rsi movq %rsi, %xmm1 and $0xffffffffffffffc0, %r10 movaps %xmm1, (%r10) nop sub $41085, %r14 lea addresses_D_ht+0x3554, %rsi lea addresses_WT_ht+0x102c4, %rdi nop nop nop xor $56702, %r12 mov $122, %rcx rep movsb nop inc %rcx lea addresses_A_ht+0x1c554, %rsi nop nop nop nop sub %rdi, %rdi movb (%rsi), %r8b inc %r10 lea addresses_WT_ht+0x9954, %rsi lea addresses_WC_ht+0x14fd4, %rdi nop cmp $20391, %r8 mov $121, %rcx rep movsb nop nop nop nop sub $29088, %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %r8 pop %r14 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r13 push %r15 push %r8 push %rbx push %rsi // Store lea addresses_WT+0xd426, %r10 nop nop dec %r11 movb $0x51, (%r10) nop nop nop nop add $59413, %rsi // Store lea addresses_RW+0xcc3b, %r15 nop nop nop nop nop sub %r13, %r13 mov $0x5152535455565758, %rbx movq %rbx, %xmm5 vmovups %ymm5, (%r15) sub %r13, %r13 // Faulty Load lea addresses_normal+0x8554, %r13 nop nop add $27625, %rsi mov (%r13), %r11d lea oracles, %rbx and $0xff, %r11 shlq $12, %r11 mov (%rbx,%r11,1), %r11 pop %rsi pop %rbx pop %r8 pop %r15 pop %r13 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1, 'same': False, 'type': 'addresses_WT'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': False, 'type': 'addresses_RW'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': True, 'type': 'addresses_normal'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'dst': {'NT': True, 'AVXalign': False, 'size': 1, 'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11, 'same': True, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'dst': {'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 5, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': True, 'size': 16, 'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'src': {'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common/test_header.hpp" #include "test_utils.hpp" #include <cylon/partition/partition.hpp> #include <cylon/util/murmur3.hpp> #include <cylon/compute/aggregates.hpp> using namespace cylon; TEST_CASE("Partition testing", "[join]") { const int rows = 12; cylon::Status status; std::shared_ptr<cylon::Table> table; std::shared_ptr<cylon::Table> output; status = cylon::test::CreateTable(ctx, rows, table); SECTION("modulo partition test") { std::vector<uint32_t> partitions, count; status = cylon::MapToHashPartitions(table, 0, WORLD_SZ, partitions, count); REQUIRE((status.is_ok() && (partitions.size() == rows) && (count.size() == (size_t) WORLD_SZ))); const std::shared_ptr<arrow::Int32Array> &arr = std::static_pointer_cast<arrow::Int32Array>(table->get_table()->column(0)->chunk(0)); for (int i = 0; i < table->Rows(); i++) { REQUIRE(partitions[i] == (uint32_t) (arr->Value(i) % WORLD_SZ)); } uint32_t sum = std::accumulate(count.begin(), count.end(), 0); REQUIRE(sum == table->Rows()); std::vector<std::shared_ptr<arrow::Table>> split_tables; status = cylon::Split(table, WORLD_SZ, partitions, count, split_tables); REQUIRE((status.is_ok() && (split_tables.size() == (size_t) WORLD_SZ))); for (int i = 0; i < WORLD_SZ; i++) { REQUIRE(split_tables[i]->num_rows() == count[i]); } } SECTION("hash partition test") { std::vector<uint32_t> partitions, count; status = cylon::MapToHashPartitions(table, 1, WORLD_SZ, partitions, count); REQUIRE((status.is_ok() && (partitions.size() == rows) && (count.size() == (size_t) WORLD_SZ))); const std::shared_ptr<arrow::DoubleArray> &arr = std::static_pointer_cast<arrow::DoubleArray>(table->get_table()->column(1)->chunk(0)); for (int i = 0; i < table->Rows(); i++) { double v = arr->Value(i); uint32_t hash = 0; cylon::util::MurmurHash3_x86_32(&v, sizeof(double), 0, &hash); REQUIRE(partitions[i] == (uint32_t) (hash % WORLD_SZ)); } uint32_t sum = std::accumulate(count.begin(), count.end(), 0); REQUIRE(sum == table->Rows()); std::vector<std::shared_ptr<arrow::Table>> split_tables; status = cylon::Split(table, WORLD_SZ, partitions, count, split_tables); REQUIRE((status.is_ok() && (split_tables.size() == (size_t) WORLD_SZ))); for (int i = 0; i < WORLD_SZ; i++) { REQUIRE(split_tables[i]->num_rows() == count[i]); } } SECTION("range partition test") { std::vector<uint32_t> partitions, count; status = cylon::MapToSortPartitions(table, 0, WORLD_SZ, partitions, count, true, table->Rows(), WORLD_SZ); LOG(INFO) << "stat " << status.get_code() << " " << status.get_msg() ; REQUIRE((status.is_ok() && (partitions.size() == rows) && (count.size() == (size_t) WORLD_SZ))); for (int i = 0; i < table->Rows() - 1; i++) { REQUIRE(partitions[i] <= partitions[i + 1]); } uint32_t sum = std::accumulate(count.begin(), count.end(), 0); REQUIRE(sum == table->Rows()); std::vector<std::shared_ptr<arrow::Table>> split_tables; status = cylon::Split(table, WORLD_SZ, partitions, count, split_tables); REQUIRE((status.is_ok() && (split_tables.size() == (size_t) WORLD_SZ))); for (int i = 0; i < WORLD_SZ; i++) { REQUIRE(split_tables[i]->num_rows() == count[i]); } } SECTION("dist sort test") { status = cylon::DistributedSort(table, 0, output, true, {(uint32_t)WORLD_SZ, (uint64_t)table->Rows(), SortOptions::REGULAR_SAMPLE}); REQUIRE((status.is_ok())); for (auto &arr: output->get_table()->column(0)->chunks()) { const std::shared_ptr<arrow::Int32Array> &carr = std::static_pointer_cast<arrow::Int32Array>(arr); for (int i = 0; i < carr->length() - 1; i++) { REQUIRE((carr->Value(i) <= carr->Value(i + 1))); } } std::shared_ptr<cylon::compute::Result> res; status = cylon::compute::Count(output, 0, res); auto scalar = std::static_pointer_cast<arrow::Int64Scalar>(res->GetResult().scalar()); REQUIRE((status.is_ok() && scalar->value == table->Rows() * WORLD_SZ)); output.reset(); status = cylon::DistributedSort(table, 1, output); REQUIRE((status.is_ok())); for (auto &arr: output->get_table()->column(1)->chunks()) { const std::shared_ptr<arrow::DoubleArray> &carr = std::static_pointer_cast<arrow::DoubleArray>(arr); for (int i = 0; i < carr->length() - 1; i++) { REQUIRE((carr->Value(i) <= carr->Value(i + 1))); } } status = cylon::compute::Count(output, 1, res); scalar = std::static_pointer_cast<arrow::Int64Scalar>(res->GetResult().scalar()); REQUIRE((status.is_ok() && scalar->value == table->Rows() * WORLD_SZ)); output.reset(); status = cylon::DistributedSort(table, {0, 1}, output, {true, false}, {(uint32_t)WORLD_SZ, (uint64_t)table->Rows(), SortOptions::REGULAR_SAMPLE}); REQUIRE((status.is_ok())); for (int c = 0; c < output->get_table()->column(0)->num_chunks(); c++) { const auto &carr1 = std::static_pointer_cast<arrow::Int32Array>(output->get_table()->column(0)->chunk(c)); const auto &carr2 = std::static_pointer_cast<arrow::DoubleArray>(output->get_table()->column(1)->chunk(c)); for (int i = 0; i < carr1->length() - 1; i++) { REQUIRE((carr1->Value(i) <= carr1->Value(i + 1))); if (carr1->Value(i) == carr1->Value(i + 1)) REQUIRE((carr2->Value(i) >= carr2->Value(i + 1))); } } status = cylon::compute::Count(output, 0, res); scalar = std::static_pointer_cast<arrow::Int64Scalar>(res->GetResult().scalar()); REQUIRE((status.is_ok() && scalar->value == table->Rows() * WORLD_SZ)); } }
;----------------------------------------------------------------------------- ; Copyright (c) 2013 GarageGames, LLC ; ; 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. ;----------------------------------------------------------------------------- segment .data matA dd 0 result dd 0 matB dd 0 segment .text %macro export_fn 1 %ifdef LINUX ; No underscore needed for ELF object files global %1 %1: %else global _%1 _%1: %endif %endmacro %define arg(x) [esp+(x*4)] ;void SSE_MatrixF_x_MatrixF(const F32 *matA, const F32 *matB, F32 *result) export_fn SSE_MatrixF_x_MatrixF mov edx, arg(1) mov ecx, arg(2) mov eax, arg(3) movss xmm0, [edx] movups xmm1, [ecx] shufps xmm0, xmm0, 0 movss xmm2, [edx+4] mulps xmm0, xmm1 shufps xmm2, xmm2, 0 movups xmm3, [ecx+10h] movss xmm7, [edx+8] mulps xmm2, xmm3 shufps xmm7, xmm7, 0 addps xmm0, xmm2 movups xmm4, [ecx+20h] movss xmm2, [edx+0Ch] mulps xmm7, xmm4 shufps xmm2, xmm2, 0 addps xmm0, xmm7 movups xmm5, [ecx+30h] movss xmm6, [edx+10h] mulps xmm2, xmm5 movss xmm7, [edx+14h] shufps xmm6, xmm6, 0 addps xmm0, xmm2 shufps xmm7, xmm7, 0 movlps [eax], xmm0 movhps [eax+8], xmm0 mulps xmm7, xmm3 movss xmm0, [edx+18h] mulps xmm6, xmm1 shufps xmm0, xmm0, 0 addps xmm6, xmm7 mulps xmm0, xmm4 movss xmm2, [edx+24h] addps xmm6, xmm0 movss xmm0, [edx+1Ch] movss xmm7, [edx+20h] shufps xmm0, xmm0, 0 shufps xmm7, xmm7, 0 mulps xmm0, xmm5 mulps xmm7, xmm1 addps xmm6, xmm0 shufps xmm2, xmm2, 0 movlps [eax+10h], xmm6 movhps [eax+18h], xmm6 mulps xmm2, xmm3 movss xmm6, [edx+28h] addps xmm7, xmm2 shufps xmm6, xmm6, 0 movss xmm2, [edx+2Ch] mulps xmm6, xmm4 shufps xmm2, xmm2, 0 addps xmm7, xmm6 mulps xmm2, xmm5 movss xmm0, [edx+34h] addps xmm7, xmm2 shufps xmm0, xmm0, 0 movlps [eax+20h], xmm7 movss xmm2, [edx+30h] movhps [eax+28h], xmm7 mulps xmm0, xmm3 shufps xmm2, xmm2, 0 movss xmm6, [edx+38h] mulps xmm2, xmm1 shufps xmm6, xmm6, 0 addps xmm2, xmm0 mulps xmm6, xmm4 movss xmm7, [edx+3Ch] shufps xmm7, xmm7, 0 addps xmm2, xmm6 mulps xmm7, xmm5 addps xmm2, xmm7 movups [eax+30h], xmm2 ret
; ; Bootle v2: A Wordle clone in a boot sector. ; ; by Oscar Toledo G. ; https://nanochess.org/ ; ; Creation date: Feb/27/2022. 12pm to 2pm. ; Revision date: Feb/27/2022. 4pm to 6pm. Integrated 2500 word list. ; Added word list verification. Shows ; word at end. ; Added loader (360 kb image). ; cpu 8086 %ifndef com_file ; If not defined create a boot sector. com_file: equ 0 %endif %if com_file org 0x0100 ; Start address for COM file. %else org 0x7c00 ; Start address for boot sector. %endif BOARD_BASE: equ 8*160+70 ; Top corner of board. HEART: equ 0x0403 ; Red heart for non-filled letters. ; ; Start of the game. ; start: %if com_file %else .23: push cs pop es mov ax,0x0208 ; Read 8 sectors mov cx,0x0002 ; Track 0, sector 2 (1st is boot) mov bx,0x7e00 mov dx,0x0000 ; Side 0 int 0x13 jb .23 .24: push cs pop es mov ax,0x0209 ; Read 9 sectors mov cx,0x0001 ; Track 0, sector 1 mov bx,0x7e00+8*512 mov dx,0x0100 ; Side 1 int 0x13 jb .24 .25: push cs pop es mov ax,0x0208 ; Read 8 sectors = 25 total sectors. mov cx,0x0101 ; Track 1, sector 1 mov bx,0x7e00+17*512 mov dx,0x0000 ; Side 0 int 0x13 jb .25 %endif mov ax,0x0002 ; Color text 80x25. int 0x10 cld push cs ; Copy the code segment address... pop ds ; ...to the data segment address. mov ax,0xb800 ; Point to video segment... mov es,ax ; ...with the extended segment address. ; ; Setup board. ; .10: es mov byte [0x0fa0],0 ; First time mov di,BOARD_BASE ; Top left corner of board. push di .0: mov cx,5 ; 5 letters. .1: mov ax,HEART ; Red hearts. stosw ; Draw on screen. inc di ; Separator (one character) inc di loop .1 add di,160-5*4 cmp di,BOARD_BASE+160*6 ; Has it completed 6 rows? jb .0 ; No, jump pop di ; Start again at top row. ; ; Try another word. ; .9: xor cx,cx ; Letters typed so far. push di ; Save pointer to start of word on the screen. .3: call read_keyboard ; Read a key. cmp al,0x0d ; Enter pressed? jz .4 ; Yes, jump. cmp al,0x08 ; Backspace pressed? jnz .2 ; Yes, jump. or cx,cx ; Letters to erase? jz .3 ; No, jump. sub di,4 mov ax,HEART ; Draw a red heart. stosw dec di ; Get pointer back. dec di dec cx ; One letter less. jmp short .3 ; Wait for more input. .2: cmp cl,5 ; Already 5 letters typed? jz .3 ; Yes, jump. mov ah,0x07 ; Draw in white (AH=Attribute, AL=Key) stosw inc di inc di inc cx ; One letter more. es cmp byte [0x0fa0],0 ; First time? jnz short .3 ; No, jump. shl si,1 ; Create a random number. in al,0x40 mov ah,0 add si,ax jmp short .3 ; Wait for more input. .4: cmp cl,5 ; Enter accepted only if all letters filled. jnz .3 ; No, jump. pop di ; Back to start of row. ; ; The first time it chooses a word. ; ; This allows the pseudo-random counter to advance while ; the user enters letters. ; es cmp byte [0x0fa0],0 ; First time? jnz .5 ; No, jump. es inc byte [0x0fa0] xchg ax,si xor dx,dx mov cx,LIST_LENGTH div cx ; Divide between list length. mov ax,5 ; Use remainder and multiply by 5. mul dx add ax,word_list xchg ax,si ; This is the current word. .5: ; ; Validates the word against the dictionary ; push si mov cx,LIST_LENGTH mov si,word_list .19: push si push di push cx mov cx,5 ; Each word is 5 letters. .20: es mov al,[di] ; Compare one letter. add di,4 inc si cmp al,[si-1] jnz .18 loop .20 .18: pop cx pop di pop si jz .21 ; Jump if matching word. add si,5 ; Go to next word. loop .19 ; Continue search. pop si ; ; Word not found in dictionary. ; push di ; Save pointer to start of row. mov cx,5 ; Restore letter count. add di,5*4 ; Restore cursor position jmp .3 .21: pop si ; ; Now find exact matching letters. ; mov cx,0x10 ; Five letters to compare (bitmask) push si ; Save in stack the word address. push di .6: es mov al,[di] ; Read a typed letter. cmp al,[si] ; Comparison against word. jnz .11 ; Jump if not matching. mov ah,2 ; Green - Exact match or ch,cl ; Set bitmask (avoid showing it as misplaced) db 0xbb ; MOV BX, to jump over two bytes .11: mov ah,5 ; Magenta - Not found. .8: stosw ; Update color on screen. inc di ; Advance to next typed letter. inc di inc si ; Advance letter pointer on dictionary. shr cl,1 jnz .6 ; Repeat until completed. pop di pop si cmp ch,0x1f ; All letters match jz .14 ; Exit the game. ; ; Now find misplaced letters. ; mov cl,0x10 mov dh,ch .17: es mov ax,[di] ; Read a typed letter test ch,cl ; Already checked? jne .12 ; Yes, jump. mov dl,0x10 ; Test against the five letters of word. mov bx,si ; Point to start of word. .16: test dh,dl ; Already checked? jne .15 ; Yes, jump. cmp al,[bx] ; Compare against word. jne .15 ; Jump if not equal. mov ah,6 ; Brown, misplaced or dh,dl ; Mark as already checked. jmp .12 ; Exit loop. .15: inc bx ; Go to next letter of word. shr dl,1 jnz .16 ; Repeat until completed. .12: stosw ; Update color on screen. inc di ; Advance to next typed letter. inc di shr cl,1 jnz .17 ; Repeat until completed. add di,160-5*4 ; Go to next row. cmp di,BOARD_BASE+160*6 ; Six chances finished? jb .9 ; No, jump. ; ; Show the word ; mov di,BOARD_BASE+7*160 mov cx,5 .22: lodsb mov ah,0x03 stosw loop .22 .14: call read_keyboard ; Wait for a key. jmp start ; Start new bootle. ; ; Read the keyboard. ; read_keyboard: push cx push si push di mov ah,0x00 ; Read keyboard. int 0x16 ; Call BIOS. ; Convert lowercase to uppercase cmp al,0x61 ; ASCII 'a' jb .1 cmp al,0x7b ; ASCII 'z' + 1 jnb .1 sub al,0x20 ; Distance between letters. .1: pop di pop si pop cx ret db "Bootle v2, by Oscar Toledo G. Feb/27/2022",0 db "360KB image runnable on qemu, VirtualBox, or original IBM PC",0 %if com_file %else times 510-($-$$) db 0x4f db 0x55,0xaa ; Make it a bootable sector %endif ; ; Word list for the game ; %include "wordlist.asm" %if com_file ; Fill to a 360K disk %else times 360*1024-($-$$) db 0xe5 %endif
#ifdef NALL_STRING_INTERNAL_HPP namespace nall { char chrlower(char c) { return (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; } char chrupper(char c) { return (c >= 'a' && c <= 'z') ? c - ('a' - 'A') : c; } int imemcmp(const char* str1, const char* str2, unsigned size) { while(size--) { if(chrlower(*str1) != chrlower(*str2)) break; str1++, str2++; } return (int)chrlower(*str1) - (int)chrlower(*str2); } int istrcmp(const char* str1, const char* str2) { while(*str1) { if(chrlower(*str1) != chrlower(*str2)) break; str1++, str2++; } return (int)chrlower(*str1) - (int)chrlower(*str2); } bool strbegin(const char* str, const char* key) { if(!str || !key) return false; int i, ssl = strlen(str), ksl = strlen(key); if(ksl > ssl) return false; return (!memcmp(str, key, ksl)); } bool istrbegin(const char* str, const char* key) { if(!str || !key) return false; int ssl = strlen(str), ksl = strlen(key); if(ksl > ssl) return false; for(int i = 0; i < ksl; i++) { if(str[i] >= 'A' && str[i] <= 'Z') { if(str[i] != key[i] && str[i]+0x20 != key[i])return false; } else if(str[i] >= 'a' && str[i] <= 'z') { if(str[i] != key[i] && str[i]-0x20 != key[i])return false; } else { if(str[i] != key[i])return false; } } return true; } bool strend(const char* str, const char* key) { if(!str || !key) return false; int ssl = strlen(str), ksl = strlen(key); if(ksl > ssl) return false; return (!memcmp(str + ssl - ksl, key, ksl)); } bool istrend(const char* str, const char* key) { if(!str || !key) return false; int ssl = strlen(str), ksl = strlen(key); if(ksl > ssl) return false; for(int i = ssl - ksl, z = 0; i < ssl; i++, z++) { if(str[i] >= 'A' && str[i] <= 'Z') { if(str[i] != key[z] && str[i]+0x20 != key[z])return false; } else if(str[i] >= 'a' && str[i] <= 'z') { if(str[i] != key[z] && str[i]-0x20 != key[z])return false; } else { if(str[i] != key[z])return false; } } return true; } } #endif
// // Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20714 // // /// // Buffer Definitions: // // cbuffer cbAllShadowData // { // // float4x4 m_mWorldViewProjection; // Offset: 0 Size: 64 [unused] // float4x4 m_mWorld; // Offset: 64 Size: 64 [unused] // float4x4 m_mWorldView; // Offset: 128 Size: 64 [unused] // float4x4 m_mShadow; // Offset: 192 Size: 64 [unused] // float4 m_vCascadeOffset[8]; // Offset: 256 Size: 128 // float4 m_vCascadeScale[8]; // Offset: 384 Size: 128 // int m_nCascadeLevels; // Offset: 512 Size: 4 [unused] // int m_iVisualizeCascades; // Offset: 516 Size: 4 // int m_iPCFBlurForLoopStart; // Offset: 520 Size: 4 // int m_iPCFBlurForLoopEnd; // Offset: 524 Size: 4 // float m_fMinBorderPadding; // Offset: 528 Size: 4 // float m_fMaxBorderPadding; // Offset: 532 Size: 4 // float m_fShadowBiasFromGUI; // Offset: 536 Size: 4 // float m_fShadowPartitionSize; // Offset: 540 Size: 4 // float m_fCascadeBlendArea; // Offset: 544 Size: 4 [unused] // float m_fTexelSize; // Offset: 548 Size: 4 // float m_fNativeTexelSizeInX; // Offset: 552 Size: 4 // float m_fPaddingForCB3; // Offset: 556 Size: 4 [unused] // float4 m_fCascadeFrustumsEyeSpaceDepthsFloat[2];// Offset: 560 Size: 32 [unused] // float4 m_fCascadeFrustumsEyeSpaceDepthsFloat4[8];// Offset: 592 Size: 128 [unused] // float3 m_vLightDir; // Offset: 720 Size: 12 // float m_fPaddingCB4; // Offset: 732 Size: 4 [unused] // // } // // // Resource Bindings: // // Name Type Format Dim Slot Elements // ------------------------------ ---------- ------- ----------- ---- -------- // g_samLinear sampler NA NA 0 1 // g_samShadow sampler_c NA NA 5 1 // g_txDiffuse texture float4 2d 0 1 // g_txShadow texture float4 2d 5 1 // cbAllShadowData cbuffer NA NA 0 1 // // // // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // NORMAL 0 xyz 0 NONE float xyz // TEXCOORD 0 xy 1 NONE float xy // TEXCOORD 3 z 1 NONE float // TEXCOORD 1 xyzw 2 NONE float xyz // SV_POSITION 0 xyzw 3 POS float // TEXCOORD 2 xyzw 4 NONE float // // // Output signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // SV_TARGET 0 xyzw 0 TARGET float xyzw // ps_4_0 dcl_immediateConstantBuffer { { 1.500000, 0, 0, 1.000000}, { 0, 1.500000, 0, 1.000000}, { 0, 0, 5.500000, 1.000000}, { 1.500000, 0, 5.500000, 1.000000}, { 1.500000, 1.500000, 0, 1.000000}, { 1.000000, 1.000000, 1.000000, 1.000000}, { 0, 1.000000, 5.500000, 1.000000}, { 0.500000, 3.500000, 0.750000, 1.000000} } dcl_constantbuffer cb0[46], dynamicIndexed dcl_sampler s0, mode_default dcl_sampler s5, mode_comparison dcl_resource_texture2d (float,float,float,float) t0 dcl_resource_texture2d (float,float,float,float) t5 dcl_input_ps linear v0.xyz dcl_input_ps linear v1.xy dcl_input_ps linear v2.xyz dcl_output o0.xyzw dcl_temps 5 sample r0.xyzw, v1.xyxx, t0.xyzw, s0 iadd r1.x, -cb0[32].z, cb0[32].w imul null, r1.x, r1.x, r1.x itof r1.x, r1.x mov r2.x, l(1) mov r1.yzw, l(0,0,0,0) mov r3.xy, l(0,0,0,0) mov r2.y, l(0) loop ilt r2.z, r2.y, l(3) ieq r2.w, r3.x, l(0) and r2.z, r2.w, r2.z breakc_z r2.z mad r1.yzw, v2.xxyz, cb0[r2.y + 24].xxyz, cb0[r2.y + 16].xxyz min r2.z, r1.z, r1.y lt r2.z, cb0[33].x, r2.z max r2.w, r1.z, r1.y lt r2.w, r2.w, cb0[33].y and r2.z, r2.w, r2.z movc r3.xy, r2.zzzz, r2.xyxx, r3.xyxx iadd r2.y, r2.y, l(1) endloop itof r2.x, r3.y mul r2.x, r2.x, cb0[33].w mad r1.y, r1.y, cb0[33].w, r2.x add r1.w, r1.w, -cb0[33].z mov r2.x, l(0) mov r2.y, cb0[32].z loop ige r2.z, r2.y, cb0[32].w breakc_nz r2.z itof r2.z, r2.y mad r4.x, r2.z, cb0[34].z, r1.y mov r2.z, r2.x mov r2.w, cb0[32].z loop ige r3.x, r2.w, cb0[32].w breakc_nz r3.x itof r3.x, r2.w mad r4.y, r3.x, cb0[34].y, r1.z sample_c_lz r3.x, r4.xyxx, t5.xxxx, s5, r1.w add r2.z, r2.z, r3.x iadd r2.w, r2.w, l(1) endloop mov r2.x, r2.z iadd r2.y, r2.y, l(1) endloop div r1.x, r2.x, r1.x mov r2.xyz, icb[r3.y + 0].xyzx mov r2.w, l(1.000000) movc r2.xyzw, cb0[32].yyyy, r2.xyzw, l(1.000000,1.000000,1.000000,1.000000) dp3_sat r1.y, l(-1.000000, 1.000000, -1.000000, 0.000000), v0.xyzx dp3_sat r1.z, l(1.000000, 1.000000, -1.000000, 0.000000), v0.xyzx mul r1.z, r1.z, l(0.050000) mad r1.y, r1.y, l(0.050000), r1.z mov_sat r1.z, -v0.y mad r1.y, r1.z, l(0.050000), r1.y dp3_sat r1.z, l(1.000000, 1.000000, 1.000000, 0.000000), v0.xyzx mad r1.y, r1.z, l(0.050000), r1.y mul r1.z, r1.y, l(0.500000) dp3_sat r1.w, cb0[45].xyzx, v0.xyzx add r1.w, r1.w, r1.y mad r1.y, -r1.y, l(0.500000), r1.w mad r1.x, r1.x, r1.y, r1.z mul r1.xyzw, r2.xyzw, r1.xxxx mul o0.xyzw, r0.xyzw, r1.xyzw ret // Approximately 67 instruction slots used
UnknownText_0x1b4dc5: text "Hello. This is" line "@" text_ram wStringBuffer3 text "…" para "Good morning," line "<PLAY_G>!" done UnknownText_0x1b4ded: text "Hello. This is" line "@" text_ram wStringBuffer3 text "…" para "How's it going," line "<PLAY_G>?" done UnknownText_0x1b4e16: text "Hello. This is" line "@" text_ram wStringBuffer3 text "…" para "Good evening," line "<PLAY_G>!" done UnknownText_0x1b4e3e: text "<PLAY_G>, good" line "morning!" para "It's me, @" text_ram wStringBuffer3 text "." line "How are you doing?" done UnknownText_0x1b4e72: text "<PLAY_G>, howdy!" para "It's me, @" text_ram wStringBuffer3 text "." line "Isn't it nice out?" done UnknownText_0x1b4e9e: text "<PLAY_G>, good" line "evening!" para "It's me, @" text_ram wStringBuffer3 text "." line "Got a minute?" done UnknownText_0x1b4ecd: text "How are your" line "#MON doing?" para "My @" text_ram wStringBuffer4 text " is" line "so curious, it's a" para "problem. Maybe" line "it's like me…" done
; Generic MMC1 Template (NES 2.0) ; This template does not impose a specific "S*ROM" board layout. ;------------------------------------------------------------------------------; ; number of 16K PRG-ROM banks PRG_BANKS = $08 ; number of 8K CHR banks ($00 = CHR-RAM) CHR_BANKS = $02 ; MMC1 mirroring is mapper controlled. This just sets the default. ; If you want one-screen mapping, you will need to set it via MMC1 writes. ; %0000 = Horizontal ; %0001 = Vertical MIRRORING = %0001 ; Should the SRAM be battery backed or not? ; %0010 = battery backed ; %0000 = no battery SRAM_BATTERY = %0000 ; number of 8K PRG-RAM banks SRAM_SIZE = $00 ; Mapper 001 (MMC1 - generic) NES 2.0 header .byte "NES",$1A .byte PRG_BANKS ; 16K PRG-ROM banks .byte CHR_BANKS ; 8K CHR banks .byte $10|SRAM_BATTERY|MIRRORING ; flags 6 .byte $00 ; flags 7 .byte $00 ; Mapper Variant .byte $00 ; ROM size upper bits .byte $00 ; PRG-RAM size .byte $00 ; CHR-RAM size .byte $00 ; TV system .byte $00 ; Vs. Hardware .dsb 2, $00 ; clear the remaining bytes
_ln: 文件格式 elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 53 push %ebx e: 51 push %ecx f: 89 cb mov %ecx,%ebx if(argc != 3){ 11: 83 3b 03 cmpl $0x3,(%ebx) 14: 74 17 je 2d <main+0x2d> printf(2, "Usage: ln old new\n"); 16: 83 ec 08 sub $0x8,%esp 19: 68 18 08 00 00 push $0x818 1e: 6a 02 push $0x2 20: e8 3d 04 00 00 call 462 <printf> 25: 83 c4 10 add $0x10,%esp exit(); 28: e8 9e 02 00 00 call 2cb <exit> } if(link(argv[1], argv[2]) < 0) 2d: 8b 43 04 mov 0x4(%ebx),%eax 30: 83 c0 08 add $0x8,%eax 33: 8b 10 mov (%eax),%edx 35: 8b 43 04 mov 0x4(%ebx),%eax 38: 83 c0 04 add $0x4,%eax 3b: 8b 00 mov (%eax),%eax 3d: 83 ec 08 sub $0x8,%esp 40: 52 push %edx 41: 50 push %eax 42: e8 e4 02 00 00 call 32b <link> 47: 83 c4 10 add $0x10,%esp 4a: 85 c0 test %eax,%eax 4c: 79 21 jns 6f <main+0x6f> printf(2, "link %s %s: failed\n", argv[1], argv[2]); 4e: 8b 43 04 mov 0x4(%ebx),%eax 51: 83 c0 08 add $0x8,%eax 54: 8b 10 mov (%eax),%edx 56: 8b 43 04 mov 0x4(%ebx),%eax 59: 83 c0 04 add $0x4,%eax 5c: 8b 00 mov (%eax),%eax 5e: 52 push %edx 5f: 50 push %eax 60: 68 2b 08 00 00 push $0x82b 65: 6a 02 push $0x2 67: e8 f6 03 00 00 call 462 <printf> 6c: 83 c4 10 add $0x10,%esp exit(); 6f: e8 57 02 00 00 call 2cb <exit> 00000074 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 74: 55 push %ebp 75: 89 e5 mov %esp,%ebp 77: 57 push %edi 78: 53 push %ebx asm volatile("cld; rep stosb" : 79: 8b 4d 08 mov 0x8(%ebp),%ecx 7c: 8b 55 10 mov 0x10(%ebp),%edx 7f: 8b 45 0c mov 0xc(%ebp),%eax 82: 89 cb mov %ecx,%ebx 84: 89 df mov %ebx,%edi 86: 89 d1 mov %edx,%ecx 88: fc cld 89: f3 aa rep stos %al,%es:(%edi) 8b: 89 ca mov %ecx,%edx 8d: 89 fb mov %edi,%ebx 8f: 89 5d 08 mov %ebx,0x8(%ebp) 92: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 95: 90 nop 96: 5b pop %ebx 97: 5f pop %edi 98: 5d pop %ebp 99: c3 ret 0000009a <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 9a: 55 push %ebp 9b: 89 e5 mov %esp,%ebp 9d: 83 ec 10 sub $0x10,%esp char *os; os = s; a0: 8b 45 08 mov 0x8(%ebp),%eax a3: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) a6: 90 nop a7: 8b 45 08 mov 0x8(%ebp),%eax aa: 8d 50 01 lea 0x1(%eax),%edx ad: 89 55 08 mov %edx,0x8(%ebp) b0: 8b 55 0c mov 0xc(%ebp),%edx b3: 8d 4a 01 lea 0x1(%edx),%ecx b6: 89 4d 0c mov %ecx,0xc(%ebp) b9: 0f b6 12 movzbl (%edx),%edx bc: 88 10 mov %dl,(%eax) be: 0f b6 00 movzbl (%eax),%eax c1: 84 c0 test %al,%al c3: 75 e2 jne a7 <strcpy+0xd> ; return os; c5: 8b 45 fc mov -0x4(%ebp),%eax } c8: c9 leave c9: c3 ret 000000ca <strcmp>: int strcmp(const char *p, const char *q) { ca: 55 push %ebp cb: 89 e5 mov %esp,%ebp while(*p && *p == *q) cd: eb 08 jmp d7 <strcmp+0xd> p++, q++; cf: 83 45 08 01 addl $0x1,0x8(%ebp) d3: 83 45 0c 01 addl $0x1,0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) d7: 8b 45 08 mov 0x8(%ebp),%eax da: 0f b6 00 movzbl (%eax),%eax dd: 84 c0 test %al,%al df: 74 10 je f1 <strcmp+0x27> e1: 8b 45 08 mov 0x8(%ebp),%eax e4: 0f b6 10 movzbl (%eax),%edx e7: 8b 45 0c mov 0xc(%ebp),%eax ea: 0f b6 00 movzbl (%eax),%eax ed: 38 c2 cmp %al,%dl ef: 74 de je cf <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; f1: 8b 45 08 mov 0x8(%ebp),%eax f4: 0f b6 00 movzbl (%eax),%eax f7: 0f b6 d0 movzbl %al,%edx fa: 8b 45 0c mov 0xc(%ebp),%eax fd: 0f b6 00 movzbl (%eax),%eax 100: 0f b6 c0 movzbl %al,%eax 103: 29 c2 sub %eax,%edx 105: 89 d0 mov %edx,%eax } 107: 5d pop %ebp 108: c3 ret 00000109 <strlen>: uint strlen(char *s) { 109: 55 push %ebp 10a: 89 e5 mov %esp,%ebp 10c: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 10f: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 116: eb 04 jmp 11c <strlen+0x13> 118: 83 45 fc 01 addl $0x1,-0x4(%ebp) 11c: 8b 55 fc mov -0x4(%ebp),%edx 11f: 8b 45 08 mov 0x8(%ebp),%eax 122: 01 d0 add %edx,%eax 124: 0f b6 00 movzbl (%eax),%eax 127: 84 c0 test %al,%al 129: 75 ed jne 118 <strlen+0xf> ; return n; 12b: 8b 45 fc mov -0x4(%ebp),%eax } 12e: c9 leave 12f: c3 ret 00000130 <memset>: void* memset(void *dst, int c, uint n) { 130: 55 push %ebp 131: 89 e5 mov %esp,%ebp stosb(dst, c, n); 133: 8b 45 10 mov 0x10(%ebp),%eax 136: 50 push %eax 137: ff 75 0c pushl 0xc(%ebp) 13a: ff 75 08 pushl 0x8(%ebp) 13d: e8 32 ff ff ff call 74 <stosb> 142: 83 c4 0c add $0xc,%esp return dst; 145: 8b 45 08 mov 0x8(%ebp),%eax } 148: c9 leave 149: c3 ret 0000014a <strchr>: char* strchr(const char *s, char c) { 14a: 55 push %ebp 14b: 89 e5 mov %esp,%ebp 14d: 83 ec 04 sub $0x4,%esp 150: 8b 45 0c mov 0xc(%ebp),%eax 153: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 156: eb 14 jmp 16c <strchr+0x22> if(*s == c) 158: 8b 45 08 mov 0x8(%ebp),%eax 15b: 0f b6 00 movzbl (%eax),%eax 15e: 3a 45 fc cmp -0x4(%ebp),%al 161: 75 05 jne 168 <strchr+0x1e> return (char*)s; 163: 8b 45 08 mov 0x8(%ebp),%eax 166: eb 13 jmp 17b <strchr+0x31> } char* strchr(const char *s, char c) { for(; *s; s++) 168: 83 45 08 01 addl $0x1,0x8(%ebp) 16c: 8b 45 08 mov 0x8(%ebp),%eax 16f: 0f b6 00 movzbl (%eax),%eax 172: 84 c0 test %al,%al 174: 75 e2 jne 158 <strchr+0xe> if(*s == c) return (char*)s; return 0; 176: b8 00 00 00 00 mov $0x0,%eax } 17b: c9 leave 17c: c3 ret 0000017d <gets>: char* gets(char *buf, int max) { 17d: 55 push %ebp 17e: 89 e5 mov %esp,%ebp 180: 83 ec 18 sub $0x18,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 183: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 18a: eb 42 jmp 1ce <gets+0x51> cc = read(0, &c, 1); 18c: 83 ec 04 sub $0x4,%esp 18f: 6a 01 push $0x1 191: 8d 45 ef lea -0x11(%ebp),%eax 194: 50 push %eax 195: 6a 00 push $0x0 197: e8 47 01 00 00 call 2e3 <read> 19c: 83 c4 10 add $0x10,%esp 19f: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 1a2: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1a6: 7e 33 jle 1db <gets+0x5e> break; buf[i++] = c; 1a8: 8b 45 f4 mov -0xc(%ebp),%eax 1ab: 8d 50 01 lea 0x1(%eax),%edx 1ae: 89 55 f4 mov %edx,-0xc(%ebp) 1b1: 89 c2 mov %eax,%edx 1b3: 8b 45 08 mov 0x8(%ebp),%eax 1b6: 01 c2 add %eax,%edx 1b8: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1bc: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 1be: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1c2: 3c 0a cmp $0xa,%al 1c4: 74 16 je 1dc <gets+0x5f> 1c6: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1ca: 3c 0d cmp $0xd,%al 1cc: 74 0e je 1dc <gets+0x5f> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1ce: 8b 45 f4 mov -0xc(%ebp),%eax 1d1: 83 c0 01 add $0x1,%eax 1d4: 3b 45 0c cmp 0xc(%ebp),%eax 1d7: 7c b3 jl 18c <gets+0xf> 1d9: eb 01 jmp 1dc <gets+0x5f> cc = read(0, &c, 1); if(cc < 1) break; 1db: 90 nop buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1dc: 8b 55 f4 mov -0xc(%ebp),%edx 1df: 8b 45 08 mov 0x8(%ebp),%eax 1e2: 01 d0 add %edx,%eax 1e4: c6 00 00 movb $0x0,(%eax) return buf; 1e7: 8b 45 08 mov 0x8(%ebp),%eax } 1ea: c9 leave 1eb: c3 ret 000001ec <stat>: int stat(char *n, struct stat *st) { 1ec: 55 push %ebp 1ed: 89 e5 mov %esp,%ebp 1ef: 83 ec 18 sub $0x18,%esp int fd; int r; fd = open(n, O_RDONLY); 1f2: 83 ec 08 sub $0x8,%esp 1f5: 6a 00 push $0x0 1f7: ff 75 08 pushl 0x8(%ebp) 1fa: e8 0c 01 00 00 call 30b <open> 1ff: 83 c4 10 add $0x10,%esp 202: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 205: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 209: 79 07 jns 212 <stat+0x26> return -1; 20b: b8 ff ff ff ff mov $0xffffffff,%eax 210: eb 25 jmp 237 <stat+0x4b> r = fstat(fd, st); 212: 83 ec 08 sub $0x8,%esp 215: ff 75 0c pushl 0xc(%ebp) 218: ff 75 f4 pushl -0xc(%ebp) 21b: e8 03 01 00 00 call 323 <fstat> 220: 83 c4 10 add $0x10,%esp 223: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 226: 83 ec 0c sub $0xc,%esp 229: ff 75 f4 pushl -0xc(%ebp) 22c: e8 c2 00 00 00 call 2f3 <close> 231: 83 c4 10 add $0x10,%esp return r; 234: 8b 45 f0 mov -0x10(%ebp),%eax } 237: c9 leave 238: c3 ret 00000239 <atoi>: int atoi(const char *s) { 239: 55 push %ebp 23a: 89 e5 mov %esp,%ebp 23c: 83 ec 10 sub $0x10,%esp int n; n = 0; 23f: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 246: eb 25 jmp 26d <atoi+0x34> n = n*10 + *s++ - '0'; 248: 8b 55 fc mov -0x4(%ebp),%edx 24b: 89 d0 mov %edx,%eax 24d: c1 e0 02 shl $0x2,%eax 250: 01 d0 add %edx,%eax 252: 01 c0 add %eax,%eax 254: 89 c1 mov %eax,%ecx 256: 8b 45 08 mov 0x8(%ebp),%eax 259: 8d 50 01 lea 0x1(%eax),%edx 25c: 89 55 08 mov %edx,0x8(%ebp) 25f: 0f b6 00 movzbl (%eax),%eax 262: 0f be c0 movsbl %al,%eax 265: 01 c8 add %ecx,%eax 267: 83 e8 30 sub $0x30,%eax 26a: 89 45 fc mov %eax,-0x4(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 26d: 8b 45 08 mov 0x8(%ebp),%eax 270: 0f b6 00 movzbl (%eax),%eax 273: 3c 2f cmp $0x2f,%al 275: 7e 0a jle 281 <atoi+0x48> 277: 8b 45 08 mov 0x8(%ebp),%eax 27a: 0f b6 00 movzbl (%eax),%eax 27d: 3c 39 cmp $0x39,%al 27f: 7e c7 jle 248 <atoi+0xf> n = n*10 + *s++ - '0'; return n; 281: 8b 45 fc mov -0x4(%ebp),%eax } 284: c9 leave 285: c3 ret 00000286 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 286: 55 push %ebp 287: 89 e5 mov %esp,%ebp 289: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 28c: 8b 45 08 mov 0x8(%ebp),%eax 28f: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 292: 8b 45 0c mov 0xc(%ebp),%eax 295: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 298: eb 17 jmp 2b1 <memmove+0x2b> *dst++ = *src++; 29a: 8b 45 fc mov -0x4(%ebp),%eax 29d: 8d 50 01 lea 0x1(%eax),%edx 2a0: 89 55 fc mov %edx,-0x4(%ebp) 2a3: 8b 55 f8 mov -0x8(%ebp),%edx 2a6: 8d 4a 01 lea 0x1(%edx),%ecx 2a9: 89 4d f8 mov %ecx,-0x8(%ebp) 2ac: 0f b6 12 movzbl (%edx),%edx 2af: 88 10 mov %dl,(%eax) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 2b1: 8b 45 10 mov 0x10(%ebp),%eax 2b4: 8d 50 ff lea -0x1(%eax),%edx 2b7: 89 55 10 mov %edx,0x10(%ebp) 2ba: 85 c0 test %eax,%eax 2bc: 7f dc jg 29a <memmove+0x14> *dst++ = *src++; return vdst; 2be: 8b 45 08 mov 0x8(%ebp),%eax } 2c1: c9 leave 2c2: c3 ret 000002c3 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2c3: b8 01 00 00 00 mov $0x1,%eax 2c8: cd 40 int $0x40 2ca: c3 ret 000002cb <exit>: SYSCALL(exit) 2cb: b8 02 00 00 00 mov $0x2,%eax 2d0: cd 40 int $0x40 2d2: c3 ret 000002d3 <wait>: SYSCALL(wait) 2d3: b8 03 00 00 00 mov $0x3,%eax 2d8: cd 40 int $0x40 2da: c3 ret 000002db <pipe>: SYSCALL(pipe) 2db: b8 04 00 00 00 mov $0x4,%eax 2e0: cd 40 int $0x40 2e2: c3 ret 000002e3 <read>: SYSCALL(read) 2e3: b8 05 00 00 00 mov $0x5,%eax 2e8: cd 40 int $0x40 2ea: c3 ret 000002eb <write>: SYSCALL(write) 2eb: b8 10 00 00 00 mov $0x10,%eax 2f0: cd 40 int $0x40 2f2: c3 ret 000002f3 <close>: SYSCALL(close) 2f3: b8 15 00 00 00 mov $0x15,%eax 2f8: cd 40 int $0x40 2fa: c3 ret 000002fb <kill>: SYSCALL(kill) 2fb: b8 06 00 00 00 mov $0x6,%eax 300: cd 40 int $0x40 302: c3 ret 00000303 <exec>: SYSCALL(exec) 303: b8 07 00 00 00 mov $0x7,%eax 308: cd 40 int $0x40 30a: c3 ret 0000030b <open>: SYSCALL(open) 30b: b8 0f 00 00 00 mov $0xf,%eax 310: cd 40 int $0x40 312: c3 ret 00000313 <mknod>: SYSCALL(mknod) 313: b8 11 00 00 00 mov $0x11,%eax 318: cd 40 int $0x40 31a: c3 ret 0000031b <unlink>: SYSCALL(unlink) 31b: b8 12 00 00 00 mov $0x12,%eax 320: cd 40 int $0x40 322: c3 ret 00000323 <fstat>: SYSCALL(fstat) 323: b8 08 00 00 00 mov $0x8,%eax 328: cd 40 int $0x40 32a: c3 ret 0000032b <link>: SYSCALL(link) 32b: b8 13 00 00 00 mov $0x13,%eax 330: cd 40 int $0x40 332: c3 ret 00000333 <mkdir>: SYSCALL(mkdir) 333: b8 14 00 00 00 mov $0x14,%eax 338: cd 40 int $0x40 33a: c3 ret 0000033b <chdir>: SYSCALL(chdir) 33b: b8 09 00 00 00 mov $0x9,%eax 340: cd 40 int $0x40 342: c3 ret 00000343 <dup>: SYSCALL(dup) 343: b8 0a 00 00 00 mov $0xa,%eax 348: cd 40 int $0x40 34a: c3 ret 0000034b <getpid>: SYSCALL(getpid) 34b: b8 0b 00 00 00 mov $0xb,%eax 350: cd 40 int $0x40 352: c3 ret 00000353 <sbrk>: SYSCALL(sbrk) 353: b8 0c 00 00 00 mov $0xc,%eax 358: cd 40 int $0x40 35a: c3 ret 0000035b <sleep>: SYSCALL(sleep) 35b: b8 0d 00 00 00 mov $0xd,%eax 360: cd 40 int $0x40 362: c3 ret 00000363 <uptime>: SYSCALL(uptime) 363: b8 0e 00 00 00 mov $0xe,%eax 368: cd 40 int $0x40 36a: c3 ret 0000036b <getCuPos>: SYSCALL(getCuPos) 36b: b8 16 00 00 00 mov $0x16,%eax 370: cd 40 int $0x40 372: c3 ret 00000373 <setCuPos>: SYSCALL(setCuPos) 373: b8 17 00 00 00 mov $0x17,%eax 378: cd 40 int $0x40 37a: c3 ret 0000037b <getSnapshot>: SYSCALL(getSnapshot) 37b: b8 18 00 00 00 mov $0x18,%eax 380: cd 40 int $0x40 382: c3 ret 00000383 <clearScreen>: 383: b8 19 00 00 00 mov $0x19,%eax 388: cd 40 int $0x40 38a: c3 ret 0000038b <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 38b: 55 push %ebp 38c: 89 e5 mov %esp,%ebp 38e: 83 ec 18 sub $0x18,%esp 391: 8b 45 0c mov 0xc(%ebp),%eax 394: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 397: 83 ec 04 sub $0x4,%esp 39a: 6a 01 push $0x1 39c: 8d 45 f4 lea -0xc(%ebp),%eax 39f: 50 push %eax 3a0: ff 75 08 pushl 0x8(%ebp) 3a3: e8 43 ff ff ff call 2eb <write> 3a8: 83 c4 10 add $0x10,%esp } 3ab: 90 nop 3ac: c9 leave 3ad: c3 ret 000003ae <printint>: static void printint(int fd, int xx, int base, int sgn) { 3ae: 55 push %ebp 3af: 89 e5 mov %esp,%ebp 3b1: 53 push %ebx 3b2: 83 ec 24 sub $0x24,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 3b5: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 3bc: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 3c0: 74 17 je 3d9 <printint+0x2b> 3c2: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 3c6: 79 11 jns 3d9 <printint+0x2b> neg = 1; 3c8: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 3cf: 8b 45 0c mov 0xc(%ebp),%eax 3d2: f7 d8 neg %eax 3d4: 89 45 ec mov %eax,-0x14(%ebp) 3d7: eb 06 jmp 3df <printint+0x31> } else { x = xx; 3d9: 8b 45 0c mov 0xc(%ebp),%eax 3dc: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 3df: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 3e6: 8b 4d f4 mov -0xc(%ebp),%ecx 3e9: 8d 41 01 lea 0x1(%ecx),%eax 3ec: 89 45 f4 mov %eax,-0xc(%ebp) 3ef: 8b 5d 10 mov 0x10(%ebp),%ebx 3f2: 8b 45 ec mov -0x14(%ebp),%eax 3f5: ba 00 00 00 00 mov $0x0,%edx 3fa: f7 f3 div %ebx 3fc: 89 d0 mov %edx,%eax 3fe: 0f b6 80 94 0a 00 00 movzbl 0xa94(%eax),%eax 405: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1) }while((x /= base) != 0); 409: 8b 5d 10 mov 0x10(%ebp),%ebx 40c: 8b 45 ec mov -0x14(%ebp),%eax 40f: ba 00 00 00 00 mov $0x0,%edx 414: f7 f3 div %ebx 416: 89 45 ec mov %eax,-0x14(%ebp) 419: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 41d: 75 c7 jne 3e6 <printint+0x38> if(neg) 41f: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 423: 74 2d je 452 <printint+0xa4> buf[i++] = '-'; 425: 8b 45 f4 mov -0xc(%ebp),%eax 428: 8d 50 01 lea 0x1(%eax),%edx 42b: 89 55 f4 mov %edx,-0xc(%ebp) 42e: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 433: eb 1d jmp 452 <printint+0xa4> putc(fd, buf[i]); 435: 8d 55 dc lea -0x24(%ebp),%edx 438: 8b 45 f4 mov -0xc(%ebp),%eax 43b: 01 d0 add %edx,%eax 43d: 0f b6 00 movzbl (%eax),%eax 440: 0f be c0 movsbl %al,%eax 443: 83 ec 08 sub $0x8,%esp 446: 50 push %eax 447: ff 75 08 pushl 0x8(%ebp) 44a: e8 3c ff ff ff call 38b <putc> 44f: 83 c4 10 add $0x10,%esp buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 452: 83 6d f4 01 subl $0x1,-0xc(%ebp) 456: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 45a: 79 d9 jns 435 <printint+0x87> putc(fd, buf[i]); } 45c: 90 nop 45d: 8b 5d fc mov -0x4(%ebp),%ebx 460: c9 leave 461: c3 ret 00000462 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 462: 55 push %ebp 463: 89 e5 mov %esp,%ebp 465: 83 ec 28 sub $0x28,%esp char *s; int c, i, state; uint *ap; state = 0; 468: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 46f: 8d 45 0c lea 0xc(%ebp),%eax 472: 83 c0 04 add $0x4,%eax 475: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 478: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 47f: e9 59 01 00 00 jmp 5dd <printf+0x17b> c = fmt[i] & 0xff; 484: 8b 55 0c mov 0xc(%ebp),%edx 487: 8b 45 f0 mov -0x10(%ebp),%eax 48a: 01 d0 add %edx,%eax 48c: 0f b6 00 movzbl (%eax),%eax 48f: 0f be c0 movsbl %al,%eax 492: 25 ff 00 00 00 and $0xff,%eax 497: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 49a: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 49e: 75 2c jne 4cc <printf+0x6a> if(c == '%'){ 4a0: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 4a4: 75 0c jne 4b2 <printf+0x50> state = '%'; 4a6: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 4ad: e9 27 01 00 00 jmp 5d9 <printf+0x177> } else { putc(fd, c); 4b2: 8b 45 e4 mov -0x1c(%ebp),%eax 4b5: 0f be c0 movsbl %al,%eax 4b8: 83 ec 08 sub $0x8,%esp 4bb: 50 push %eax 4bc: ff 75 08 pushl 0x8(%ebp) 4bf: e8 c7 fe ff ff call 38b <putc> 4c4: 83 c4 10 add $0x10,%esp 4c7: e9 0d 01 00 00 jmp 5d9 <printf+0x177> } } else if(state == '%'){ 4cc: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 4d0: 0f 85 03 01 00 00 jne 5d9 <printf+0x177> if(c == 'd'){ 4d6: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 4da: 75 1e jne 4fa <printf+0x98> printint(fd, *ap, 10, 1); 4dc: 8b 45 e8 mov -0x18(%ebp),%eax 4df: 8b 00 mov (%eax),%eax 4e1: 6a 01 push $0x1 4e3: 6a 0a push $0xa 4e5: 50 push %eax 4e6: ff 75 08 pushl 0x8(%ebp) 4e9: e8 c0 fe ff ff call 3ae <printint> 4ee: 83 c4 10 add $0x10,%esp ap++; 4f1: 83 45 e8 04 addl $0x4,-0x18(%ebp) 4f5: e9 d8 00 00 00 jmp 5d2 <printf+0x170> } else if(c == 'x' || c == 'p'){ 4fa: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 4fe: 74 06 je 506 <printf+0xa4> 500: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 504: 75 1e jne 524 <printf+0xc2> printint(fd, *ap, 16, 0); 506: 8b 45 e8 mov -0x18(%ebp),%eax 509: 8b 00 mov (%eax),%eax 50b: 6a 00 push $0x0 50d: 6a 10 push $0x10 50f: 50 push %eax 510: ff 75 08 pushl 0x8(%ebp) 513: e8 96 fe ff ff call 3ae <printint> 518: 83 c4 10 add $0x10,%esp ap++; 51b: 83 45 e8 04 addl $0x4,-0x18(%ebp) 51f: e9 ae 00 00 00 jmp 5d2 <printf+0x170> } else if(c == 's'){ 524: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 528: 75 43 jne 56d <printf+0x10b> s = (char*)*ap; 52a: 8b 45 e8 mov -0x18(%ebp),%eax 52d: 8b 00 mov (%eax),%eax 52f: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 532: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 536: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 53a: 75 25 jne 561 <printf+0xff> s = "(null)"; 53c: c7 45 f4 3f 08 00 00 movl $0x83f,-0xc(%ebp) while(*s != 0){ 543: eb 1c jmp 561 <printf+0xff> putc(fd, *s); 545: 8b 45 f4 mov -0xc(%ebp),%eax 548: 0f b6 00 movzbl (%eax),%eax 54b: 0f be c0 movsbl %al,%eax 54e: 83 ec 08 sub $0x8,%esp 551: 50 push %eax 552: ff 75 08 pushl 0x8(%ebp) 555: e8 31 fe ff ff call 38b <putc> 55a: 83 c4 10 add $0x10,%esp s++; 55d: 83 45 f4 01 addl $0x1,-0xc(%ebp) } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 561: 8b 45 f4 mov -0xc(%ebp),%eax 564: 0f b6 00 movzbl (%eax),%eax 567: 84 c0 test %al,%al 569: 75 da jne 545 <printf+0xe3> 56b: eb 65 jmp 5d2 <printf+0x170> putc(fd, *s); s++; } } else if(c == 'c'){ 56d: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 571: 75 1d jne 590 <printf+0x12e> putc(fd, *ap); 573: 8b 45 e8 mov -0x18(%ebp),%eax 576: 8b 00 mov (%eax),%eax 578: 0f be c0 movsbl %al,%eax 57b: 83 ec 08 sub $0x8,%esp 57e: 50 push %eax 57f: ff 75 08 pushl 0x8(%ebp) 582: e8 04 fe ff ff call 38b <putc> 587: 83 c4 10 add $0x10,%esp ap++; 58a: 83 45 e8 04 addl $0x4,-0x18(%ebp) 58e: eb 42 jmp 5d2 <printf+0x170> } else if(c == '%'){ 590: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 594: 75 17 jne 5ad <printf+0x14b> putc(fd, c); 596: 8b 45 e4 mov -0x1c(%ebp),%eax 599: 0f be c0 movsbl %al,%eax 59c: 83 ec 08 sub $0x8,%esp 59f: 50 push %eax 5a0: ff 75 08 pushl 0x8(%ebp) 5a3: e8 e3 fd ff ff call 38b <putc> 5a8: 83 c4 10 add $0x10,%esp 5ab: eb 25 jmp 5d2 <printf+0x170> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 5ad: 83 ec 08 sub $0x8,%esp 5b0: 6a 25 push $0x25 5b2: ff 75 08 pushl 0x8(%ebp) 5b5: e8 d1 fd ff ff call 38b <putc> 5ba: 83 c4 10 add $0x10,%esp putc(fd, c); 5bd: 8b 45 e4 mov -0x1c(%ebp),%eax 5c0: 0f be c0 movsbl %al,%eax 5c3: 83 ec 08 sub $0x8,%esp 5c6: 50 push %eax 5c7: ff 75 08 pushl 0x8(%ebp) 5ca: e8 bc fd ff ff call 38b <putc> 5cf: 83 c4 10 add $0x10,%esp } state = 0; 5d2: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 5d9: 83 45 f0 01 addl $0x1,-0x10(%ebp) 5dd: 8b 55 0c mov 0xc(%ebp),%edx 5e0: 8b 45 f0 mov -0x10(%ebp),%eax 5e3: 01 d0 add %edx,%eax 5e5: 0f b6 00 movzbl (%eax),%eax 5e8: 84 c0 test %al,%al 5ea: 0f 85 94 fe ff ff jne 484 <printf+0x22> putc(fd, c); } state = 0; } } } 5f0: 90 nop 5f1: c9 leave 5f2: c3 ret 000005f3 <free>: static Header base; static Header *freep; void free(void *ap) { 5f3: 55 push %ebp 5f4: 89 e5 mov %esp,%ebp 5f6: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 5f9: 8b 45 08 mov 0x8(%ebp),%eax 5fc: 83 e8 08 sub $0x8,%eax 5ff: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 602: a1 b0 0a 00 00 mov 0xab0,%eax 607: 89 45 fc mov %eax,-0x4(%ebp) 60a: eb 24 jmp 630 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 60c: 8b 45 fc mov -0x4(%ebp),%eax 60f: 8b 00 mov (%eax),%eax 611: 3b 45 fc cmp -0x4(%ebp),%eax 614: 77 12 ja 628 <free+0x35> 616: 8b 45 f8 mov -0x8(%ebp),%eax 619: 3b 45 fc cmp -0x4(%ebp),%eax 61c: 77 24 ja 642 <free+0x4f> 61e: 8b 45 fc mov -0x4(%ebp),%eax 621: 8b 00 mov (%eax),%eax 623: 3b 45 f8 cmp -0x8(%ebp),%eax 626: 77 1a ja 642 <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 628: 8b 45 fc mov -0x4(%ebp),%eax 62b: 8b 00 mov (%eax),%eax 62d: 89 45 fc mov %eax,-0x4(%ebp) 630: 8b 45 f8 mov -0x8(%ebp),%eax 633: 3b 45 fc cmp -0x4(%ebp),%eax 636: 76 d4 jbe 60c <free+0x19> 638: 8b 45 fc mov -0x4(%ebp),%eax 63b: 8b 00 mov (%eax),%eax 63d: 3b 45 f8 cmp -0x8(%ebp),%eax 640: 76 ca jbe 60c <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 642: 8b 45 f8 mov -0x8(%ebp),%eax 645: 8b 40 04 mov 0x4(%eax),%eax 648: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 64f: 8b 45 f8 mov -0x8(%ebp),%eax 652: 01 c2 add %eax,%edx 654: 8b 45 fc mov -0x4(%ebp),%eax 657: 8b 00 mov (%eax),%eax 659: 39 c2 cmp %eax,%edx 65b: 75 24 jne 681 <free+0x8e> bp->s.size += p->s.ptr->s.size; 65d: 8b 45 f8 mov -0x8(%ebp),%eax 660: 8b 50 04 mov 0x4(%eax),%edx 663: 8b 45 fc mov -0x4(%ebp),%eax 666: 8b 00 mov (%eax),%eax 668: 8b 40 04 mov 0x4(%eax),%eax 66b: 01 c2 add %eax,%edx 66d: 8b 45 f8 mov -0x8(%ebp),%eax 670: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 673: 8b 45 fc mov -0x4(%ebp),%eax 676: 8b 00 mov (%eax),%eax 678: 8b 10 mov (%eax),%edx 67a: 8b 45 f8 mov -0x8(%ebp),%eax 67d: 89 10 mov %edx,(%eax) 67f: eb 0a jmp 68b <free+0x98> } else bp->s.ptr = p->s.ptr; 681: 8b 45 fc mov -0x4(%ebp),%eax 684: 8b 10 mov (%eax),%edx 686: 8b 45 f8 mov -0x8(%ebp),%eax 689: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 68b: 8b 45 fc mov -0x4(%ebp),%eax 68e: 8b 40 04 mov 0x4(%eax),%eax 691: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 698: 8b 45 fc mov -0x4(%ebp),%eax 69b: 01 d0 add %edx,%eax 69d: 3b 45 f8 cmp -0x8(%ebp),%eax 6a0: 75 20 jne 6c2 <free+0xcf> p->s.size += bp->s.size; 6a2: 8b 45 fc mov -0x4(%ebp),%eax 6a5: 8b 50 04 mov 0x4(%eax),%edx 6a8: 8b 45 f8 mov -0x8(%ebp),%eax 6ab: 8b 40 04 mov 0x4(%eax),%eax 6ae: 01 c2 add %eax,%edx 6b0: 8b 45 fc mov -0x4(%ebp),%eax 6b3: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6b6: 8b 45 f8 mov -0x8(%ebp),%eax 6b9: 8b 10 mov (%eax),%edx 6bb: 8b 45 fc mov -0x4(%ebp),%eax 6be: 89 10 mov %edx,(%eax) 6c0: eb 08 jmp 6ca <free+0xd7> } else p->s.ptr = bp; 6c2: 8b 45 fc mov -0x4(%ebp),%eax 6c5: 8b 55 f8 mov -0x8(%ebp),%edx 6c8: 89 10 mov %edx,(%eax) freep = p; 6ca: 8b 45 fc mov -0x4(%ebp),%eax 6cd: a3 b0 0a 00 00 mov %eax,0xab0 } 6d2: 90 nop 6d3: c9 leave 6d4: c3 ret 000006d5 <morecore>: static Header* morecore(uint nu) { 6d5: 55 push %ebp 6d6: 89 e5 mov %esp,%ebp 6d8: 83 ec 18 sub $0x18,%esp char *p; Header *hp; if(nu < 4096) 6db: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 6e2: 77 07 ja 6eb <morecore+0x16> nu = 4096; 6e4: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 6eb: 8b 45 08 mov 0x8(%ebp),%eax 6ee: c1 e0 03 shl $0x3,%eax 6f1: 83 ec 0c sub $0xc,%esp 6f4: 50 push %eax 6f5: e8 59 fc ff ff call 353 <sbrk> 6fa: 83 c4 10 add $0x10,%esp 6fd: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 700: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 704: 75 07 jne 70d <morecore+0x38> return 0; 706: b8 00 00 00 00 mov $0x0,%eax 70b: eb 26 jmp 733 <morecore+0x5e> hp = (Header*)p; 70d: 8b 45 f4 mov -0xc(%ebp),%eax 710: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 713: 8b 45 f0 mov -0x10(%ebp),%eax 716: 8b 55 08 mov 0x8(%ebp),%edx 719: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 71c: 8b 45 f0 mov -0x10(%ebp),%eax 71f: 83 c0 08 add $0x8,%eax 722: 83 ec 0c sub $0xc,%esp 725: 50 push %eax 726: e8 c8 fe ff ff call 5f3 <free> 72b: 83 c4 10 add $0x10,%esp return freep; 72e: a1 b0 0a 00 00 mov 0xab0,%eax } 733: c9 leave 734: c3 ret 00000735 <malloc>: void* malloc(uint nbytes) { 735: 55 push %ebp 736: 89 e5 mov %esp,%ebp 738: 83 ec 18 sub $0x18,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 73b: 8b 45 08 mov 0x8(%ebp),%eax 73e: 83 c0 07 add $0x7,%eax 741: c1 e8 03 shr $0x3,%eax 744: 83 c0 01 add $0x1,%eax 747: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 74a: a1 b0 0a 00 00 mov 0xab0,%eax 74f: 89 45 f0 mov %eax,-0x10(%ebp) 752: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 756: 75 23 jne 77b <malloc+0x46> base.s.ptr = freep = prevp = &base; 758: c7 45 f0 a8 0a 00 00 movl $0xaa8,-0x10(%ebp) 75f: 8b 45 f0 mov -0x10(%ebp),%eax 762: a3 b0 0a 00 00 mov %eax,0xab0 767: a1 b0 0a 00 00 mov 0xab0,%eax 76c: a3 a8 0a 00 00 mov %eax,0xaa8 base.s.size = 0; 771: c7 05 ac 0a 00 00 00 movl $0x0,0xaac 778: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 77b: 8b 45 f0 mov -0x10(%ebp),%eax 77e: 8b 00 mov (%eax),%eax 780: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 783: 8b 45 f4 mov -0xc(%ebp),%eax 786: 8b 40 04 mov 0x4(%eax),%eax 789: 3b 45 ec cmp -0x14(%ebp),%eax 78c: 72 4d jb 7db <malloc+0xa6> if(p->s.size == nunits) 78e: 8b 45 f4 mov -0xc(%ebp),%eax 791: 8b 40 04 mov 0x4(%eax),%eax 794: 3b 45 ec cmp -0x14(%ebp),%eax 797: 75 0c jne 7a5 <malloc+0x70> prevp->s.ptr = p->s.ptr; 799: 8b 45 f4 mov -0xc(%ebp),%eax 79c: 8b 10 mov (%eax),%edx 79e: 8b 45 f0 mov -0x10(%ebp),%eax 7a1: 89 10 mov %edx,(%eax) 7a3: eb 26 jmp 7cb <malloc+0x96> else { p->s.size -= nunits; 7a5: 8b 45 f4 mov -0xc(%ebp),%eax 7a8: 8b 40 04 mov 0x4(%eax),%eax 7ab: 2b 45 ec sub -0x14(%ebp),%eax 7ae: 89 c2 mov %eax,%edx 7b0: 8b 45 f4 mov -0xc(%ebp),%eax 7b3: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 7b6: 8b 45 f4 mov -0xc(%ebp),%eax 7b9: 8b 40 04 mov 0x4(%eax),%eax 7bc: c1 e0 03 shl $0x3,%eax 7bf: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 7c2: 8b 45 f4 mov -0xc(%ebp),%eax 7c5: 8b 55 ec mov -0x14(%ebp),%edx 7c8: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 7cb: 8b 45 f0 mov -0x10(%ebp),%eax 7ce: a3 b0 0a 00 00 mov %eax,0xab0 return (void*)(p + 1); 7d3: 8b 45 f4 mov -0xc(%ebp),%eax 7d6: 83 c0 08 add $0x8,%eax 7d9: eb 3b jmp 816 <malloc+0xe1> } if(p == freep) 7db: a1 b0 0a 00 00 mov 0xab0,%eax 7e0: 39 45 f4 cmp %eax,-0xc(%ebp) 7e3: 75 1e jne 803 <malloc+0xce> if((p = morecore(nunits)) == 0) 7e5: 83 ec 0c sub $0xc,%esp 7e8: ff 75 ec pushl -0x14(%ebp) 7eb: e8 e5 fe ff ff call 6d5 <morecore> 7f0: 83 c4 10 add $0x10,%esp 7f3: 89 45 f4 mov %eax,-0xc(%ebp) 7f6: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 7fa: 75 07 jne 803 <malloc+0xce> return 0; 7fc: b8 00 00 00 00 mov $0x0,%eax 801: eb 13 jmp 816 <malloc+0xe1> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 803: 8b 45 f4 mov -0xc(%ebp),%eax 806: 89 45 f0 mov %eax,-0x10(%ebp) 809: 8b 45 f4 mov -0xc(%ebp),%eax 80c: 8b 00 mov (%eax),%eax 80e: 89 45 f4 mov %eax,-0xc(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } 811: e9 6d ff ff ff jmp 783 <malloc+0x4e> } 816: c9 leave 817: c3 ret
// Copyright (c) 2013 The Chromium Embedded Framework 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 "libcef/browser/net/scheme_handler.h" #include <string> #include "libcef/browser/net/chrome_scheme_handler.h" #include "libcef/browser/net/devtools_scheme_handler.h" #include "libcef/common/net/scheme_registration.h" #include "base/memory/ptr_util.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/url_constants.h" #include "net/net_features.h" #include "net/url_request/data_protocol_handler.h" #include "net/url_request/file_protocol_handler.h" #include "net/url_request/ftp_protocol_handler.h" #include "net/url_request/url_request_job_factory_impl.h" #include "url/url_constants.h" namespace scheme { void InstallInternalProtectedHandlers( net::URLRequestJobFactoryImpl* job_factory, CefURLRequestManager* request_manager, content::ProtocolHandlerMap* protocol_handlers, net::HostResolver* host_resolver) { protocol_handlers->insert(std::make_pair( url::kDataScheme, linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( new net::DataProtocolHandler))); protocol_handlers->insert(std::make_pair( url::kFileScheme, linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( new net::FileProtocolHandler( content::BrowserThread::GetBlockingPool() ->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))))); #if !BUILDFLAG(DISABLE_FTP_SUPPORT) protocol_handlers->insert(std::make_pair( url::kFtpScheme, linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( net::FtpProtocolHandler::Create(host_resolver).release()))); #endif for (content::ProtocolHandlerMap::iterator it = protocol_handlers->begin(); it != protocol_handlers->end(); ++it) { const std::string& scheme = it->first; std::unique_ptr<net::URLRequestJobFactory::ProtocolHandler> protocol_handler; if (scheme == content::kChromeDevToolsScheme) { // Don't use the default "chrome-devtools" handler. continue; } else if (scheme == content::kChromeUIScheme) { // Filter the URLs that are passed to the default "chrome" handler so as // not to interfere with CEF's "chrome" handler. protocol_handler.reset( scheme::WrapChromeProtocolHandler( request_manager, base::WrapUnique(it->second.release())) .release()); } else { protocol_handler.reset(it->second.release()); } // Make sure IsInternalProtectedScheme() stays synchronized with what // Chromium is actually giving us. DCHECK(IsInternalProtectedScheme(scheme)); bool set_protocol = job_factory->SetProtocolHandler( scheme, base::WrapUnique(protocol_handler.release())); DCHECK(set_protocol); } } void RegisterInternalHandlers(CefURLRequestManager* request_manager) { scheme::RegisterChromeHandler(request_manager); scheme::RegisterChromeDevToolsHandler(request_manager); } void DidFinishLoad(CefRefPtr<CefFrame> frame, const GURL& validated_url) { if (validated_url.scheme() == content::kChromeUIScheme) scheme::DidFinishChromeLoad(frame, validated_url); } } // namespace scheme
/*++ Copyright (c) Microsoft Corporation Licensed under the MIT license. Module Name: - FontBuffer.hpp Abstract: - This manages the construction and storage of font definitions for the VT DECDLD control sequence. --*/ #pragma once #include "DispatchTypes.hpp" namespace Microsoft::Console::VirtualTerminal { class FontBuffer { public: FontBuffer() noexcept; ~FontBuffer() = default; bool SetEraseControl(const DispatchTypes::DrcsEraseControl eraseControl) noexcept; bool SetAttributes(const DispatchTypes::DrcsCellMatrix cellMatrix, const VTParameter cellHeight, const DispatchTypes::DrcsFontSet fontSet, const DispatchTypes::DrcsFontUsage fontUsage) noexcept; bool SetStartChar(const VTParameter startChar, const DispatchTypes::DrcsCharsetSize charsetSize) noexcept; void AddSixelData(const wchar_t ch); bool FinalizeSixelData(); gsl::span<const uint16_t> GetBitPattern() const noexcept; til::size GetCellSize() const noexcept; size_t GetTextCenteringHint() const noexcept; VTID GetDesignation() const noexcept; private: static constexpr size_t MAX_WIDTH = 16; static constexpr size_t MAX_HEIGHT = 32; static constexpr size_t MAX_CHARS = 96; void _buildCharsetId(const wchar_t ch); void _prepareCharacterBuffer(); void _prepareNextCharacter(); void _addSixelValue(const size_t value) noexcept; void _endOfSixelLine(); void _endOfCharacter(); std::tuple<size_t, size_t, size_t> _calculateDimensions() const; void _packAndCenterBitPatterns(); void _fillUnusedCharacters(); std::array<uint16_t, MAX_HEIGHT> _generateErrorGlyph(); DispatchTypes::DrcsCellMatrix _cellMatrix; DispatchTypes::DrcsCellMatrix _pendingCellMatrix; size_t _cellHeight; size_t _pendingCellHeight; bool _sizeDeclaredAsMatrix; size_t _declaredWidth; size_t _declaredHeight; size_t _usedWidth; size_t _usedHeight; size_t _fullWidth; size_t _fullHeight; size_t _textWidth; size_t _textOffset; size_t _textCenteringHint; DispatchTypes::DrcsFontSet _fontSet; DispatchTypes::DrcsFontSet _pendingFontSet; DispatchTypes::DrcsFontUsage _fontUsage; DispatchTypes::DrcsFontUsage _pendingFontUsage; size_t _linesPerPage; size_t _columnsPerPage; bool _isTextFont; DispatchTypes::DrcsCharsetSize _charsetSize; DispatchTypes::DrcsCharsetSize _pendingCharsetSize; VTID _charsetId{ 0 }; VTID _pendingCharsetId{ 0 }; bool _charsetIdInitialized; VTIDBuilder _charsetIdBuilder; size_t _startChar; size_t _lastChar; size_t _currentChar; using buffer_type = std::array<uint16_t, MAX_HEIGHT * MAX_CHARS>; buffer_type _buffer; buffer_type::iterator _currentCharBuffer; bool _bufferCleared; size_t _sixelColumn; size_t _sixelRow; }; }